How to check that import module will succeed?

Andrey Zherikov andrey.zherikov at gmail.com
Fri Jul 26 14:56:37 UTC 2019


On Friday, 26 July 2019 at 06:24:18 UTC, evilrat wrote:
> On Friday, 26 July 2019 at 03:42:58 UTC, Andrey Zherikov wrote:
>> Is there a way to check whether some module, say "foo", is 
>> available for import before doing "import foo"?
>
> I did some really retarded utility like this in the past, 
> worked for me, but I can't say it is that well tested and there 
> might be a better way (after all it just assumes that template 
> instantiation failure can only mean there is no such module), 
> so in short template allowed to fail, and we check if it is 
> failed or not to test if desired module exists. Don't remember 
> if static is really necessary or you can just return directly.
>
>     bool isModuleAvailable(alias modName)() {
>         mixin("import " ~ modName ~ ";");
>         static if (__traits(compiles, mixin(modName).stringof))
>             return true;
>         else
>             return false;
>     }
>
>     // use like this
>     static if (__traits(compiles, isModuleAvailable!"mymod" ))
>         import mymod;

This works, thanks!

But when I try to wrap usage as a single call to something I get 
slightly different result of import:

// mymod.d
module mymod;
void myfunc() { import std.stdio; writeln("myfunc"); }

// use1.d
static if (__traits(compiles, isModuleAvailable!"mymod" )) import 
mymod;
pragma(msg,fullyQualifiedName!(myfunc));       // mymod.myfunc
pragma(msg,fullyQualifiedName!(mymod.myfunc)); // mymod.myfunc

// use2.d
mixin template my_import(alias modName)
{
static if (__traits(compiles, isModuleAvailable!modName ))
     mixin("import " ~ modName ~ ";");
}
mixin my_import!"mymod";
pragma(msg,fullyQualifiedName!(myfunc));       // Error: 
undefined identifier myfunc
pragma(msg,fullyQualifiedName!(mymod.myfunc)); // mymod.myfunc


Even without static if I get the same result:
mixin template my_import(alias modName)
{
     mixin("import " ~ modName ~ ";");
}
mixin my_import!"mymod";
pragma(msg,fullyQualifiedName!(myfunc));       // Error: 
undefined identifier myfunc
pragma(msg,fullyQualifiedName!(mymod.myfunc)); // mymod.myfunc

If I understood template mixin doc correctly this happens because 
of "The declarations in a mixin are placed in a nested scope". So 
is there a way to make two use cases above to work the same way, 
i.e. "myfunc" to be available without "mymod." prefix?


More information about the Digitalmars-d-learn mailing list