import from subdir

Jonathan M Davis jmdavisProg at gmx.com
Thu Dec 23 12:54:42 PST 2010


On Thursday 23 December 2010 05:59:37 spir wrote:
> On Thu, 23 Dec 2010 05:26:57 -0800
> 
> Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > On Thursday 23 December 2010 04:38:56 spir wrote:
> > > Hello,
> > > 
> > > Say I have a project with the following tree structure:
> > > 
> > > [app]
> > > 
> > > 	app.d
> > > 	util.d
> > > 	[test]
> > > 	
> > > 		test.d
> > > 	
> > > 	[data]
> > > 	
> > > 		data.d
> > > 
> > > Is there a way to import util & data from test?
> > 
> > Use the -I flag when compiling. Presumably, you'd do something like -I../
> > so that it would also search for files starting at the parent directory.
> > 
> > - Jonathan M Davis
> 
> Thank you, I'll try this solution. So, there is no syntax? (I tried "import
> ..util;" and import "..data.data;" without any success ;-)
> 
> What about proposing that each _single_ leading dot moves up one dir? In my
> case, this would give "import .util;" and "import .data.data;". I find
> this simple, practical and very useful.

Packages and modules follow the file system's structure, but they're _not_ 
intended to be traversing the file system. So, if you have the module a.b.c, then 
it will be the file a/b/c.d where a is either in the base directory of 
compilation or in a directory given to dmd with the -I flag. But from the 
module's perspective, it doesn't care that packages equate to directories on 
disk or that module equate to files on disk. It's giving the compiler a module 
name, and the compiler finds it with the assumption that packages equate to 
directories and modules equate to files. But there's nothing stopping D from 
changing things so that having a file name a.b.c.d would be the module a.b.c. 
That change definitely won't be made, but the point is that in D, module names 
are effectively divorced from the file system as far as the language is concerned. 
It's just that the language specifies that packages equate to directories and 
modules equate to files in order to simplify the compilation process and simplify 
the job of any D-related tools.

What you're trying to do is pretty abnormal really, as far as your average 
module goes. I assume that you're writing a test app which needs access to the 
main body of code and are trying to find a way to point it to that code without 
mixing the two. The normal way to deal with that would be -I. The same goes for 
C++ actually. Not to mention, you probably don't want your tests to rely on 
where they are on disk in comparison to the rest of your code. If you later want 
to change where you put your test code, it could be a big hassle to have to go 
change all of your imports. Just use -I. It makes your test code properly 
portable and is really the intended way to do the sort of thing that you're 
trying to do.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list