Bug 12059 – Smarter error messages when a module contains a namespace with the same name
Status
RESOLVED
Resolution
DUPLICATE
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-02-02T02:35:00Z
Last change time
2017-07-02T17:13:20Z
Keywords
diagnostic
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2014-02-02T02:35:15Z
This is just one example of a problem in D code that I have seen seen several times in D.learn and elsewhere:
http://forum.dlang.org/thread/[email protected]
-------------
> I am having troubles to use the enum defined in the separate
> module.
> When I try to access it, I am getting "Undefined symbol" error:
>
>
> // CodeEnum.d
>
> enum CodeEnum
> {
> OK = 200,
> FAIL = 400
> }
>
> unittest
> {
> auto e = CodeEnum.OK; // Works!
> }
>
>
> // Reply.d
> import CodeEnum;
>
> unittest
> {
> auto.e = CodeEnum.OK; // Error: undefined identifier 'OK'
> }
>
>
> What I am doing wrong?
-------------
The answer that explains the problem:
> The module and your enum have the same name. When the compiler sees
> the `CodeEnum` symbol, it considers you're referring to the module.
> This module does not have an `OK` member, hence the error.
> In D, do not use the same symbol for a module and one of its inner symbols.
-------------
Lot of time ago I was hit by a similar problem defining a "set.d" module with inside a "Set" struct plus a "set()" helper function.
There are various ways to avoid this problem. One way is to always forbid to define the name "foo" inside the module named "foo", with an error message (Like: "Error: module foo contains a member named foo. Module members cannot shadow module names" as suggested by Philippe Sigaud).
I like that idea, but it's a significant breaking change, and it looks quite restrictive.
An alternative solution that is much less disruptive change is to just improve the error message. Instead of just giving "Error: undefined identifier 'OK'" a more descriptive error message can tell the programmer what the problem exactly is and how to fix:
Error: undefined identifier 'OK' inside module 'CodeEnum.d'. Did you mean to use 'CodeEnum.CodeEnum.OK'?
This error message does not avoid the problems, so it's less good than forbidding the name duplication, but it could be enough.
Comment #1 by andrej.mitrovich — 2014-02-02T06:07:52Z
The first option would break code, if someone actually wants to write code this way. So a simple diagnostic change would be preferred IMO.
Comment #2 by dlang-bugzilla — 2017-07-02T17:13:20Z