D import idiom compilation time
H. S. Teoh
hsteoh at quickfur.ath.cx
Sat Jan 5 14:52:14 UTC 2019
On Sat, Jan 05, 2019 at 05:57:57AM +0000, Neia Neutuladh via Digitalmars-d wrote:
> On Fri, 04 Jan 2019 20:13:05 -0800, H. S. Teoh wrote:
[...]
> > 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.
Hmph. But in that case, doesn't that mean that the original definition
of _std doesn't work with Phobos subpackages, like std.algorithm,
because it would be trying to lookup the symbol in the package rather
than the module? So something like _std.algorithm.searching.find would
fail, because `searching.find` cannot be found in
std/algorithm/package.d.
[...]
> ---
> 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!""();
> ---
Interesting.
> 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?
Hmm. Couldn't you make it work by making it lazy? I.e., have opDispatch
return a struct that encapsulates a partial package path, and that
contains a further opDispatch to resolve the next component in the
qualified name, and that only resolves to the actual symbol when it
actually references an actual symbol?
T
--
There's light at the end of the tunnel. It's the oncoming train.
More information about the Digitalmars-d
mailing list