Pathological import symbol shadowing

Timon Gehr timon.gehr at gmx.ch
Wed Nov 18 13:42:18 UTC 2020


On 18.11.20 11:14, FeepingCreature wrote:
> On Friday, 13 November 2020 at 22:57:03 UTC, H. S. Teoh wrote:
>> Just ran into this today:
>>
>>     void main() {
>>         int[string] aa;
>>         int x;
>>
>>         x = aa.get("abc", 123);    // OK
>>
>>         import std;
>>         x = aa.get("abc", 123);    // Error: template std.net.curl.get 
>> cannot deduce function from argument types ...
>>
>>         import std, object;
>>         x = aa.get("abc", 123);    // OK
>>     }
>>
>> I know there's technically an explanation of this in terms of how the 
>> compiler implements import, but seriously, this is extremely annoying 
>> and confusing behaviour.  Especially because the symbol being hijacked 
>> comes from the implicitly-imported object.d.  Newbies wouldn't even 
>> *know* where to look if they encountered this error.
>>
>> D's import implementation was supposed to be designed to prevent 
>> symbol hijacking, but in this case it's falling flat on its face.
>>
>> Why can't we make it so that symbols that aren't explicitly named on 
>> the import line would add to existing overload sets instead of 
>> replacing them?
>>
>>
>> T
> 
> This is why our style guide doesn't allow unqualified imports in 
> functions. The more I think about it, the more I suspect function local 
> imports were just a mistake to begin with.
> 
> Bouncing back from module scope into import scope is just fundamentally 
> bad for understandability. The set of relevant symbols goes from "all 
> the ones imported" to "all the ones in the module" back to "all the ones 
> imported" again, with imports shadowing local functions, which is 
> exactly the opposite of what should happen.
> ...

The shadowing is bad, not local imports...

> Putting aside how Walter is completely correct that "import std" was a 
> mistake, I'd go further and also remove unqualified module imports 
> completely. There's a set of features that are good for writing but bad 
> for reading. Generally as time goes on, people discover those features 
> are bad ideas, but because writing comes before reading, everyone thinks 
> they're a good idea at first, so languages are doomed to reinvent them.

I'd hate that. It would make D less viable for writing small scripts.
If you are actively wondering, it's trivially easy to figure out where a 
symbol came from, and listing all imported symbols screws with reading 
as well as writing. (It's just bloat, nobody would actually look at the 
list, except when wondering where some specific symbol came from). The 
compiler should just ensure that there are no surprises, i.e., 
anti-hijacking is enough. If it makes sense to enforce additional style 
guidelines in your own code base, that's simple to do too, no need to 
break everyone else's code for no benefit.


More information about the Digitalmars-d mailing list