Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog/fix16002.dd
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
fix Issue 16002 - Add `is(sym == module)` and `is(sym == package)`

This enhancement adds two new forms of the `is()`, expression, which
determine whether a given symbol represents a module or package.

It also adds `__traits(isModule, sym)` and `__traits(isPackage, sym)`, which
do the same thing.
145 changes: 88 additions & 57 deletions src/dmd/dmodule.d
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,71 @@ void semantic3OnDependencies(Module m)
semantic3OnDependencies(m.aimports[i]);
}

/**
* Converts a chain of identifiers to the filename of the module
*
* Params:
* packages = the names of the "parent" packages
* ident = the name of the child package or module
*
* Returns:
* the filename of the child package or module
*/
private const(char)[] getFilename(Identifiers* packages, Identifier ident)
{
const(char)[] filename = ident.toString();

if (packages == null || packages.dim == 0)
return filename;

OutBuffer buf;
OutBuffer dotmods;
auto modAliases = &global.params.modFileAliasStrings;

void checkModFileAlias(const(char)[] p)
{
/* Check and replace the contents of buf[] with
* an alias string from global.params.modFileAliasStrings[]
*/
dotmods.writestring(p);
foreach_reverse (const m; *modAliases)
{
const q = strchr(m, '=');
assert(q);
if (dotmods.offset == q - m && memcmp(dotmods.peekChars(), m, q - m) == 0)
{
buf.reset();
auto rhs = q[1 .. strlen(q)];
if (rhs.length > 0 && (rhs[$ - 1] == '/' || rhs[$ - 1] == '\\'))
rhs = rhs[0 .. $ - 1]; // remove trailing separator
buf.writestring(rhs);
break; // last matching entry in ms[] wins
}
}
dotmods.writeByte('.');
}

foreach (pid; *packages)
{
const p = pid.toString();
buf.writestring(p);
if (modAliases.dim)
checkModFileAlias(p);
version (Windows)
enum FileSeparator = '\\';
else
enum FileSeparator = '/';
buf.writeByte(FileSeparator);
}
buf.writestring(filename);
if (modAliases.dim)
checkModFileAlias(filename);
buf.writeByte(0);
filename = buf.extractSlice()[0 .. $ - 1];

return filename;
}

enum PKG : int
{
unknown, // not yet determined whether it's a package.d or not
Expand Down Expand Up @@ -281,6 +346,27 @@ extern (C++) class Package : ScopeDsymbol
}
return null;
}

/**
* Checks for the existence of a package.d to set isPkgMod appropriately
* if isPkgMod == PKG.unknown
*/
final void resolvePKGunknown()
{
if (isModule())
return;
if (isPkgMod != PKG.unknown)
return;

Identifiers packages;
for (Dsymbol s = this.parent; s; s = s.parent)
packages.insert(0, s.ident);

if (lookForSourceFile(getFilename(&packages, ident)))
Module.load(Loc(), &packages, this.ident);
else
isPkgMod = PKG.package_;
}
}

/***********************************************************
Expand Down Expand Up @@ -462,63 +548,8 @@ extern (C++) final class Module : Package
// foo.bar.baz
// into:
// foo\bar\baz
const(char)[] filename = ident.toString();
if (packages && packages.dim)
{
OutBuffer buf;
OutBuffer dotmods;
auto ms = global.params.modFileAliasStrings;
const msdim = ms ? ms.dim : 0;

void checkModFileAlias(const(char)[] p)
{
/* Check and replace the contents of buf[] with
* an alias string from global.params.modFileAliasStrings[]
*/
dotmods.writestring(p);
Lmain:
for (size_t j = msdim; j--;)
{
const m = (*ms)[j];
const q = strchr(m, '=');
assert(q);
if (dotmods.offset == q - m && memcmp(dotmods.peekChars(), m, q - m) == 0)
{
buf.reset();
auto qlen = strlen(q + 1);
if (qlen && (q[qlen] == '/' || q[qlen] == '\\'))
--qlen; // remove trailing separator
buf.writestring(q[1 .. qlen + 1]);
break Lmain; // last matching entry in ms[] wins
}
}
dotmods.writeByte('.');
}

foreach (pid; *packages)
{
const p = pid.toString();
buf.writestring(p);
if (msdim)
checkModFileAlias(p);
version (Windows)
{
buf.writeByte('\\');
}
else
{
buf.writeByte('/');
}
}
buf.writestring(filename);
if (msdim)
checkModFileAlias(filename);
buf.writeByte(0);
filename = buf.extractData().toDString();
}

/* Look for the source file
*/
const(char)[] filename = getFilename(packages, ident);
// Look for the source file
if (const result = lookForSourceFile(filename))
filename = result; // leaks

Expand Down
68 changes: 58 additions & 10 deletions src/dmd/expressionsem.d
Original file line number Diff line number Diff line change
Expand Up @@ -2308,6 +2308,36 @@ private bool functionParameters(const ref Loc loc, Scope* sc,
return (err || olderrors != global.errors);
}

/**
* Determines whether a symbol represents a module or package
* (Used as a helper for is(type == module) and is(type == package))
*
* Params:
* sym = the symbol to be checked
*
* Returns:
* the symbol which `sym` represents (or `null` if it doesn't represent a `Package`)
*/
Package resolveIsPackage(Dsymbol sym)
{
Package pkg;
if (Import imp = sym.isImport())
{
if (imp.pkg is null)
{
.error(sym.loc, "Internal Compiler Error: unable to process forward-referenced import `%s`",
imp.toChars());
assert(0);
}
pkg = imp.pkg;
}
else
pkg = sym.isPackage();
if (pkg)
pkg.resolvePKGunknown();
return pkg;
}

private Module loadStdMath()
{
__gshared Import impStdMath = null;
Expand Down Expand Up @@ -5098,16 +5128,34 @@ private extern (C++) final class ExpressionSemanticVisitor : Visitor
}

Type tded = null;
Scope* sc2 = sc.copy(); // keep sc.flags
sc2.tinst = null;
sc2.minst = null;
sc2.flags |= SCOPE.fullinst;
Type t = e.targ.trySemantic(e.loc, sc2);
sc2.pop();
if (!t)
goto Lno;
// errors, so condition is false
e.targ = t;
if (e.tok2 == TOK.package_ || e.tok2 == TOK.module_) // These is() expressions are special because they can work on modules, not just types.
{
Dsymbol sym = e.targ.toDsymbol(sc);
if (sym is null)
goto Lno;
Package p = resolveIsPackage(sym);
if (p is null)
goto Lno;
if (e.tok2 == TOK.package_ && p.isModule()) // Note that isModule() will return null for package modules because they're not actually instances of Module.
goto Lno;
else if(e.tok2 == TOK.module_ && !(p.isModule() || p.isPackageMod()))
goto Lno;
tded = e.targ;
goto Lyes;
}

{
Scope* sc2 = sc.copy(); // keep sc.flags
sc2.tinst = null;
sc2.minst = null;
sc2.flags |= SCOPE.fullinst;
Type t = e.targ.trySemantic(e.loc, sc2);
sc2.pop();
if (!t) // errors, so condition is false
goto Lno;
e.targ = t;
}

if (e.tok2 != TOK.reserved)
{
switch (e.tok2)
Expand Down
2 changes: 1 addition & 1 deletion src/dmd/globals.d
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ struct Param
uint errorLimit = 20;

const(char)[] argv0; // program name
Array!(const(char)*)* modFileAliasStrings; // array of char*'s of -I module filename alias strings
Array!(const(char)*) modFileAliasStrings; // array of char*'s of -I module filename alias strings
Array!(const(char)*)* imppath; // array of char*'s of where to look for import modules
Array!(const(char)*)* fileImppath; // array of char*'s of where to look for file import modules
const(char)* objdir; // .obj/.lib file output directory
Expand Down
2 changes: 1 addition & 1 deletion src/dmd/globals.h
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ struct Param
unsigned errorLimit;

DArray<const char> argv0; // program name
Array<const char *> *modFileAliasStrings; // array of char*'s of -I module filename alias strings
Array<const char *> modFileAliasStrings; // array of char*'s of -I module filename alias strings
Array<const char *> *imppath; // array of char*'s of where to look for import modules
Array<const char *> *fileImppath; // array of char*'s of where to look for file import modules
const char *objdir; // .obj/.lib file output directory
Expand Down
2 changes: 2 additions & 0 deletions src/dmd/id.d
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,8 @@ immutable Msgtable[] msgtable =
{ "isFinalFunction" },
{ "isOverrideFunction" },
{ "isStaticFunction" },
{ "isModule" },
{ "isPackage" },
{ "isRef" },
{ "isOut" },
{ "isLazy" },
Expand Down
2 changes: 0 additions & 2 deletions src/dmd/mars.d
Original file line number Diff line number Diff line change
Expand Up @@ -2251,8 +2251,6 @@ bool parseCommandLine(const ref Strings arguments, const size_t argc, ref Param
{
if (p[4] && strchr(p + 5, '='))
{
if (!params.modFileAliasStrings)
params.modFileAliasStrings = new Strings();
params.modFileAliasStrings.push(p + 4);
}
else
Expand Down
5 changes: 3 additions & 2 deletions src/dmd/parse.d
Original file line number Diff line number Diff line change
Expand Up @@ -7974,8 +7974,9 @@ final class Parser(AST) : Lexer
nextToken();
if (tok == TOK.equal && (token.value == TOK.struct_ || token.value == TOK.union_
|| token.value == TOK.class_ || token.value == TOK.super_ || token.value == TOK.enum_
|| token.value == TOK.interface_ || token.value == TOK.argumentTypes
|| token.value == TOK.parameters || token.value == TOK.const_ && peek(&token).value == TOK.rightParentheses
|| token.value == TOK.interface_ || token.value == TOK.package_ || token.value == TOK.module_
|| token.value == TOK.argumentTypes || token.value == TOK.parameters
|| token.value == TOK.const_ && peek(&token).value == TOK.rightParentheses
|| token.value == TOK.immutable_ && peek(&token).value == TOK.rightParentheses
|| token.value == TOK.shared_ && peek(&token).value == TOK.rightParentheses
|| token.value == TOK.inout_ && peek(&token).value == TOK.rightParentheses || token.value == TOK.function_
Expand Down
28 changes: 27 additions & 1 deletion src/dmd/traits.d
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import dmd.canthrow;
import dmd.dclass;
import dmd.declaration;
import dmd.denum;
import dmd.dimport;
import dmd.dmodule;
import dmd.dscope;
import dmd.dsymbol;
import dmd.dsymbolsem;
Expand Down Expand Up @@ -107,6 +109,8 @@ shared static this()
"isFinalFunction",
"isOverrideFunction",
"isStaticFunction",
"isModule",
"isPackage",
"isRef",
"isOut",
"isLazy",
Expand Down Expand Up @@ -480,7 +484,7 @@ Expression semanticTraits(TraitsExp e, Scope* sc)
return null;
}

IntegerExp isX(T)(bool function(T) fp)
IntegerExp isX(T)(bool delegate(T) fp)
{
if (!dim)
return False();
Expand Down Expand Up @@ -516,6 +520,14 @@ Expression semanticTraits(TraitsExp e, Scope* sc)
alias isFuncX = isX!FuncDeclaration;
alias isEnumMemX = isX!EnumMember;

Expression isPkgX(bool function(Package) fp)
{
return isDsymX((Dsymbol sym) {
Package p = resolveIsPackage(sym);
return (p !is null) && fp(p);
});
}

if (e.ident == Id.isArithmetic)
{
return isTypeX(t => t.isintegral() || t.isfloating());
Expand Down Expand Up @@ -672,6 +684,20 @@ Expression semanticTraits(TraitsExp e, Scope* sc)

return isFuncX(f => !f.needThis() && !f.isNested());
}
if (e.ident == Id.isModule)
{
if (dim != 1)
return dimError(1);

return isPkgX(p => p.isModule() || p.isPackageMod());
}
if (e.ident == Id.isPackage)
{
if (dim != 1)
return dimError(1);

return isPkgX(p => p.isModule() is null);
}
if (e.ident == Id.isRef)
{
if (dim != 1)
Expand Down
3 changes: 3 additions & 0 deletions test/compilable/imports/pkgmodule/package.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/// Used to test is(x == package) and is(x == module)

module imports.pkgmodule;
2 changes: 2 additions & 0 deletions test/compilable/imports/pkgmodule/plainmodule.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/// Used to test is(x == module)
module imports.pkgmodule.plainmodule;
4 changes: 4 additions & 0 deletions test/compilable/imports/plainpackage/plainmodule.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/// Used to test is(x == module)

module imports.plainpackage.plainmodule;

Loading