Local imports hide local symbols

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 23 13:08:42 PDT 2014


On Tue, Sep 23, 2014 at 07:47:59PM +0000, monarch_dodra via Digitalmars-d wrote:
> On Tuesday, 23 September 2014 at 19:18:08 UTC, H. S. Teoh via Digitalmars-d
> wrote:
> >But this would cause a compile error:
> >
> >	----mod.d----
> >	module mod;
> >	string x, y;
> >
> >	----main.d----
> >	void main() {
> >		int x, y, z;
> >		import mod;
> >
> >		x++;	// Error: ambiguous symbol 'x', could be local
> >			// variable 'x' or mod.x
> >	}
> >
> >
> >T
> 
> How do you disambiguate to say "the x I want is the local one" ?
> 
> IMO, simply make it that local imports work like global ones, but
> scoped.  Global imports don't have this issue, why should local
> imports have special rules?

Sounds reasonable. How would that be implemented, though? Currently, in
the compiler, lookup is implemented via a linked list of Scope objects
that contain, among other things, a symbol table for the symbols
declared in that scope. A local import achieves locality by adding
symbols to the current (i.e., innermost) Scope, since doing otherwise
would cause those symbols to "spill" into the outer scopes and they will
persist past the lifetime of the current scope.

OTOH, it's this importing into the innermost scope that causes this
issue to begin with, since by definition, the innermost scope takes
precedence over outer scopes, so the imported symbols would shadow
symbols declared in outer scopes.

Implementing what you suggest would either involve treating imported
symbols separately (by having multiple parents per scope, which quickly
devolves into a mess, or otherwise having sibling pointers to imported
scopes, which also greatly complicates lookup logic), or sticking
symbols into outer scopes and keeping track of which symbols were
imported where so that they can be removed after we leave the current
scope -- which is fragile and would again add tons of complications to
the compiler.


T

-- 
What do you get if you drop a piano down a mineshaft? A flat minor.


More information about the Digitalmars-d mailing list