Search code examples
compiler-constructiondlanguage-design

Why are modules explicitly named in files?


From the D language reference:

Modules have a one-to-one correspondence with source files. The module name is the file name with the path and extension stripped off.

Module names are still specified in files explicitly, though.

module foo;

What's the point of this? If modules correspond to files, why can't the compiler infer what they're called from the file names?


Solution

  • same page a bit down (emph mine)

    The ModuleDeclaration sets the name of the module and what package it belongs to. If absent, the module name is taken to be the same name (stripped of path and extension) of the source file name.

    this means that if you want to put a module in a package you have to explicitly specify it is (like Java's package declaration) and given the strange propensity of people to use odd/foreign directory names you can't rely on checking for source/src/import in the path

    the reason that filename and module name don't have to be the same can be so you can use a .di for import and use several versions of the actual code using -c switch to create the .obj file for linking of the different versions (though fiddling with the import path is handier for that)