0.14.0 usingnamespace doesn't work for std import

Hi there,

AK does not allow me to post issue in github, so I asked here. The following code works fine under 0.13 public release, however, it failed under 0.14.0 public release:
$ zig test src/main.zig
src\main.zig:16:9: error: dependency loop detected
pub usingnamespace mixin(@This());
^~~~~~~~~~~~~~~~~~~~~~~~~

const std = @import("std");

pub fn mixin(comptime T: type) type {
    if (std.meta.hasMethod(T, "deinit") == true) {
        @compileError("error here");
    }

    return struct {
        pub fn func() void {}
    };
}

pub const MyNode = struct {
    val: u8 = 5,

    pub usingnamespace mixin(@This());
};

test "aaaaaaa" {
    const a = MyNode{};

    std.debug.print("{}\n", .{a.val});
}

By digging around, I guess it is due to the std usage in mixin function. By removing std.meta.hasMethod usage the compilation is passed.

Is it a bug in 0.14.0? Thanks.

Hi @nine-fox , welcome to Ziggit.

I think you will have a hard time making the case that this is a bug. The main thing here is that usingnamespace has been slated for the chopping block. I would avoid it from now on. See Remove `usingnamespace` · Issue #20663 · ziglang/zig · GitHub for the compiler team conversation. You can find some of the conversation from ziggit here: POLL: Remove usingnamespace

Besides that, dependency loop detection improvements would not be a bug. Zig is moving fast and implementation details of the compiler should not be relied upon. It would be hard to explain that an improvement in dependency loop detection is a bug.

I am curious though: does the same error happen if you put mixin in it’s own file with it’s own? What about if you move MyNode into it’s own file as well? You might have found a perfect storm kind of issue.

This error is correct. Calling hasMethod requires using @hasDecl on MyNode, and because of the usingnamespace, we don’t know whether MyNode has that declaration until we’ve finished evaluating mixin(MyNode); but we can’t finish evaluating mixin(MyNode) until we’ve finished calling hasMethod. That’s a dependency loop.

As mentioned in the 0.14.0 release notes (and in the comment above), users are encouraged to avoid usingnamespace as much as possible.

10 Likes

@mlugg : Just curious why the code was working in zig-0.13?

Hi, thanks for your reply. I can understand why it happened now. Also, I can do alternative way you suggested to do rework, however, the several parts may contain duplicate code.

But its fine to me, to keep it as much as simpler.

Hi @Southporter , thanks very much for your detailed reply. By reading the posts you attached, I can understand the choice zig community made, which is fine to me.

BTW, the same will happen even if I put the mixin into another file(also MyNode).

Thanks,
nine-fox

2 Likes