Skip to content

make @import require a string literal rather than a comptime expression #2206

Closed
@andrewrk

Description

@andrewrk

Zig's comptime evaluation is already powerful enough to allows conditional importing without having to have the @import target be a comptime expression. For example:

const target = if (builtin.mode == .Debug) "debug_mutex.zig" else "release_mutex.zig";
const mutex = @import(target);

This could be rewritten - and I would even say would be preferred to be rewritten - as:

const debug_mutex = @import("debug_mutex.zig");
const release_mutex = @import("release_mutex.zig");
const mutex = if (builtin.mode == .Debug) debug_mutex else release_mutex;

If import syntax is required to be trivially resolvable to either a file or a package name, then Zig can find all the source files for testing without this kind of thing:

comptime {
_ = @import("behavior/align.zig");
_ = @import("behavior/alignof.zig");
_ = @import("behavior/array.zig");
_ = @import("behavior/asm.zig");
_ = @import("behavior/atomics.zig");
_ = @import("behavior/bit_shifting.zig");
_ = @import("behavior/bitcast.zig");
_ = @import("behavior/bitreverse.zig");
_ = @import("behavior/bool.zig");
_ = @import("behavior/bswap.zig");
_ = @import("behavior/bugs/1025.zig");
_ = @import("behavior/bugs/1076.zig");
_ = @import("behavior/bugs/1111.zig");
_ = @import("behavior/bugs/1120.zig");
_ = @import("behavior/bugs/1277.zig");
_ = @import("behavior/bugs/1322.zig");
_ = @import("behavior/bugs/1381.zig");
_ = @import("behavior/bugs/1421.zig");

There is still a problem though, because if zig ran all tests indiscriminately, this would stop working:

zig/std/os/linux.zig

Lines 1537 to 1541 in 7c38651

test "import" {
if (builtin.os == builtin.Os.linux) {
_ = @import("linux/test.zig");
}
}

The general problem here is that @import has compile-time side effects:

  • changes the set of unit tests
  • causes additional symbols to be exported, with export or @export - potentially conflicting.
  • could cause @compileError to trigger based on build mode or something else in top level comptime blocks.
  • could cause a @cImport which causes a compile error

It would be weird to activate these side effects for tests but not for other builds. And these side effects are important; they're not going away.

So I think the benefits of this proposal are not clear. But I think this is a sort of important topic in Zig so it deserves an issue that we can reference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions