Skip to content

Commit

Permalink
Treat import("file") as hex string
Browse files Browse the repository at this point in the history
  • Loading branch information
dkorpel authored and adamdruppe committed Jun 30, 2024
1 parent 96a2729 commit a50339d
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 29 deletions.
12 changes: 12 additions & 0 deletions changelog/dmd.import-exp-hexstring.dd
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Import expressions are now treated as hex strings

While [Import expressions](https://dlang.org/spec/expression.html#import_expressions) are typed as `string`, they are also used to embed binary files.
By treating them the same as hex strings, they will implicitly convert to arrays of integral types other than `char`.

---
// Formerly, a cast was required:
immutable ubyte[] iconImg = cast(immutable ubyte[]) import("icon.png");

// Now, it implicitly converts to integral arrays:
immutable ubyte[] iconImg = import("icon.png");
---
1 change: 1 addition & 0 deletions compiler/src/dmd/expressionsem.d
Original file line number Diff line number Diff line change
Expand Up @@ -7668,6 +7668,7 @@ private extern (C++) final class ExpressionSemanticVisitor : Visitor
if (auto fmResult = global.fileManager.lookup(fileName))
{
se = new StringExp(e.loc, fmResult);
se.hexString = true;
}
else
{
Expand Down
36 changes: 36 additions & 0 deletions compiler/test/compilable/import_exp.d
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// REQUIRED_ARGS: -Jcompilable/imports/
// EXTRA_FILES: imports/imp16088.d imports/test21227/a..b.txt imports/test21227/a.txt imports/test21227/..foo/a.txt

// https://issues.dlang.org/show_bug.cgi?id=16088

void bar(string x) {}
auto foo()
{
import("imp16088.d").bar;
}


// https://issues.dlang.org/show_bug.cgi?id=21227

void test21227()
{
import("./test21227/a.txt").bar;
import("test21227//a..b.txt").bar;
import("test21227/..foo/a.txt").bar;

version(Windows)
{
import(r".\test21227\a.txt").bar;
import(r"test21227\\a..b.txt").bar;
import(r"test21227\..foo\a.txt").bar;
}
}

// Test that it's treated like a hex string, allowing implicit conversion to byte array

// Can't test whole contents because line endings may vary
enum expectedStart = "module imports.imp16088;";

immutable ubyte[] s0 = import("imp16088.d");

static assert(s0[0 .. expectedStart.length] == "module imports.imp16088;");
10 changes: 0 additions & 10 deletions compiler/test/compilable/test16088.d

This file was deleted.

19 changes: 0 additions & 19 deletions compiler/test/compilable/test21227.d

This file was deleted.

0 comments on commit a50339d

Please sign in to comment.