Symbol lookup rules and imports

Rainer Schuetze via Digitalmars-d digitalmars-d at puremagic.com
Thu Dec 4 15:25:49 PST 2014



On 02.12.2014 23:00, H. S. Teoh via Digitalmars-d wrote:
> 4) This isn't the end of the story. There's also this lovely bug:
>
> 	https://issues.dlang.org/show_bug.cgi?id=1238
>
> which, as its number should tell you, has been around for a LONG time.
> Executive summary:
>
> 	// mymod.d
> 	module mymod;
> 	private int impl;
>
> 	// main.d
> 	module main;
> 	import mymod;
>
> 	void impl() { ... }
>
> 	void main() {
> 		impl(); // Error: main.impl conflicts with mymod.impl (WAT?)
> 	}

This compiles as expected. I guess you rather mean to import impl from 
two modules, one with a public impl, the other with a private impl. I 
don't think this belongs to the same set of issues as the other examples 
(though I agree private symbols from imports should not be considered in 
overload sets).

Here is another bad example of local import symbol hijacking:

module base;

class Base
{
	import std.conv;
}

module derived;
import base;
import std.stdio;

string text = "123";

class Derived : Base
{
	static void foo()
	{
		writeln(text);
	}
}

void main()
{
	Derived.foo();
}

This prints an empty line!

The documentation isn't very specific about symbol lookup rules, I found 
the import rules on dlang.org/modules.html: "How basic imports work is 
that first a name is searched for in the current namespace. If it is not 
found, then it is looked for in the imports. If it is found uniquely 
among the imports, then that is used. If it is in more than one import, 
an error occurs."

I don't think "namespace" here is chosen to mean something like "C++ 
namespace". If you replace it with "module", most of the problems 
described go away.

The contradicting specification follows for scoped imports offending 
part: "The imports are looked up to satisfy any unresolved symbols at 
that scope. Imported symbols may hide symbols from outer scopes."

This defeats one of the major goals of the module system: avoiding 
symbol hijacking (http://dlang.org/hijack.html). Removing that last 
sentence would be in line with the paragraph above. I.e. local imports 
just add to the imports. This does not make the rules any more 
difficult. (The implementation would be a tad more involved, though.)


More information about the Digitalmars-d mailing list