D import idiom compilation time
Neia Neutuladh
neia at ikeran.org
Sat Jan 5 05:57:57 UTC 2019
On Fri, 04 Jan 2019 20:13:05 -0800, H. S. Teoh wrote:
> It doesn't have to be tied to a specific root package. Just call it
> "autoimport", or something short like "from":
>
> struct from {
> template opDispatch(string moduleName)
> {
> mixin("import opDispatch = " ~ moduleName ~ ";");
> }
> }
>
> Then just write:
>
> from.std.stdio.writeln("...");
Error: module `std` is in file 'std.d' which cannot be read
You need the opDispatch to take the module name rather than a qualified
package name. To fix that, you can write something like:
---
struct FromImpl(string prefix)
{
template opDispatch(string ident)
{
enum qualified = prefix == "" ? ident : prefix ~ "." ~ ident;
static if (__traits(compiles,
{mixin("import ", qualified, ";");}))
{
mixin("import opDispatch = ", qualified, ";");
}
else
{
enum opDispatch = FromImpl!(qualified)();
}
}
}
enum from = FromImpl!""();
---
This is greedy, so it doesn't work for everything. Let's say you have:
foo/
package.d
bar/
baz.d
In this case, from.foo.bar.baz.someFunc() will find foo/package.d and look
for a symbol it defines named bar. If it doesn't define that symbol,
you're out of luck.
Reader exercise: is there a way to make this second case work? How does
this interact with metaprogramming, and what sorts of precautions should
you take?
More information about the Digitalmars-d
mailing list