Skip to content

Function only called at comptime is emitted to binary #6256

Closed

Description

@cr1901

Consider the following code sample, with the source name comptime-test.zig (this is minimized, so no comptime yet :)):

const std = @import("std");

pub fn Foo() []const []const u8 {
    var rows: []const []const u8 = &[_][]const u8{};
    rows = rows ++ [_][]const u8{&[_]u8{'1', '2', '3'}, &[_]u8{'4', '5', '6'}};
    rows = rows ++ [_][]const u8{&[_]u8{'1', '2', '3'}, &[_]u8{'4', '5', '6'}};

    return rows;
}

pub fn Bar() type {
    var rows: []const []const u8 = &[_][]const u8{};
    rows = rows ++ [_][]const u8{&[_]u8{'1', '2', '3'}, &[_]u8{'4', '5', '6'}};

    return struct {
        rows: []const []const u8 = rows
    };
}

test "foo" {
    const stdout = std.io.getStdOut().writer();

    var foo = Foo();
    try stdout.print("{}\n", .{foo[0]});
}

test "bar" {
    const stdout = std.io.getStdOut().writer();

    var bar = Bar(){};
    try stdout.print("{}\n", .{bar.rows[0]});
}

zig test comptime-test.zig --test-filter foo will reject the above source code with error: unable to evaluate constant expression. I'm not certain what syntactic changes I need to make for the compiler to accept this array concatenation.

william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$ zig test comptime-test.zig --test-filter foo
./comptime-test.zig:5:12: error: unable to evaluate constant expression
    rows = rows ++ [_][]const u8{&[_]u8{'1', '2', '3'}, &[_]u8{'4', '5', '6'}};
           ^
./comptime-test.zig:5:17: note: referenced here
    rows = rows ++ [_][]const u8{&[_]u8{'1', '2', '3'}, &[_]u8{'4', '5', '6'}};

On the other hand, zig test comptime-test.zig --test-filter bar will succeed, and the test will print out the contents of [_]u8{'1', '2', '3'} as a string (I assume the lack of null terminator doesn't matter here because the array length is encoded in the type):

william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$ zig test comptime-test.zig --test-filter bar
Test [1/1] test "bar"... 123
All 1 tests passed.

I'm not certain which behavior is desirable, but I don't think these two functions should have diverging behavior based on whether the return type is generic or not. bar does what I intended, so it feels like the array concatenation in foo should work as well?

Other Information

Version:

william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$ zig version
0.6.0+cff14dc2c

OS:

william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$ uname -a
Linux xubuntu-dtrain 4.15.0-66-generic #75~16.04.1-Ubuntu SMP Tue Oct 1 14:01:08 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

Activity

  1. fengb commented on Sep 4, 2020

    @fengb
    Contributor

    I think this is expected behavior. Any function that returns type is implied to be comptime only and thus works, even though you didn't explicitly mark it as such.

  2. cr1901 commented on Sep 5, 2020

    @cr1901
    Author

    Looks like I made my example too simple. Indeed, if I rewrite Foo as:

    pub fn Foo() []const []const u8 {
        comptime var rows: []const []const u8 = &[_][]const u8{};
        rows = rows ++ [_][]const u8{&[_]u8{'1', '2', '3'}, &[_]u8{'4', '5', '6'}};
        rows = rows ++ [_][]const u8{&[_]u8{'1', '2', '3'}, &[_]u8{'4', '5', '6'}};
    
        return rows;
    }

    the tests succeed:

    william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$ zig test comptime-test.zig
    Test [1/2] test "foo"... 123
    Test [2/2] test "bar"... 123
    All 2 tests passed.
    

    A less-reduced example, more in line with the code I was trying to study:

    const std = @import("std");
    const assert = std.debug.assert;
    
    pub fn Foo(comptime map: []const u8) []const []const u8 {
        comptime var rows: []const []const u8 = &[_][]const u8{};
        comptime var it = std.mem.tokenize(map, "\n");
        inline while (it.next()) |row| {
            rows = rows ++ [_][]const u8{row};
        }
    
        return rows;
    }
    
    pub fn Bar(comptime map: []const u8) type {
        var rows: []const []const u8 = &[_][]const u8{};
        var it = std.mem.tokenize(map, "\n");
        while (it.next()) |row| {
            rows = rows ++ [_][]const u8{row};
        }
    
        return struct {
            rows: []const []const u8 = rows
        };
    }
    
    test "foo" {
        const stdout = std.io.getStdOut().writer();
    
        var foo = Foo("123\n456\n789");
        try stdout.print("{}\n", .{foo[0]});
    }
    
    test "bar" {
        const stdout = std.io.getStdOut().writer();
    
        var bar = Bar("123\n456\n789"){};
        try stdout.print("{}\n", .{bar.rows[0]});
    }

    Is there any reason why Foo should fail to compile even when I add the comptime and inline qualifiers, when Bar succeeds?

    william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$ zig test comptime-test.zig --test-filter foo
    ./comptime-test.zig:7:26: error: unable to evaluate constant expression
        inline while (it.next()) |row| {
                             ^
    ./comptime-test.zig:29:18: note: called from here
        var foo = Foo("123\n456\n789");
                     ^
    ./comptime-test.zig:26:12: note: called from here
    test "foo" {
               ^
    ./comptime-test.zig:29:18: note: referenced here
        var foo = Foo("123\n456\n789");
                     ^
    william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$ zig test comptime-test.zig --test-filter bar
    Test [1/1] test "bar"... 123
    All 1 tests passed.
    william@xubuntu-dtrain:~/Projects/zig/aoc-2016/comptime-test$
    
  3. pfgithub commented on Sep 5, 2020

    @pfgithub
    Contributor

    Right now the best way to do this is by wrapping the body of the function in a comptime block, or using comptime when calling the function

    pub fn Foo(comptime map: []const u8) []const []const u8 {
        comptime {
            var rows: []const []const u8 = &[_][]const u8{};
            var it = std.mem.tokenize(map, "\n");
            while (it.next()) |row| {
                rows = rows ++ [_][]const u8{row};
            }
    
            return rows;
        }
    }

    or

    test "foo" {
        const stdout = std.io.getStdOut().writer();
    
        var foo = comptime Foo("123\n456\n789");
        try stdout.print("{}\n", .{foo[0]});
    }

    In the future, #425 or something like it might get accepted and implemented and that will make things easier

  4. cr1901 commented on Sep 5, 2020

    @cr1901
    Author

    For the sake of completeness, the following also works:

    pub fn Foo(comptime map: []const u8) []const []const u8 {
        comptime var rows: []const []const u8 = &[_][]const u8{};
        comptime var it = std.mem.tokenize(map, "\n");
        inline while (comptime it.next()) |row| {
            rows = rows ++ [_][]const u8{row};
        }
    
        return rows;
    }

    My issue is that I didn't know KEYWORD_comptime Expr was accepted by the grammar, and in fact is accepted in many places that KEYWORD_comptime BlockExprStatement is not. Such as inside the condition of an if-statement or while-loop :).

    This can probably be closed then. I think my final follow-up is: why isn't the call to it.next() already comptime since it has been declared as comptime?

  5. modified the milestones: 0.7.0, 0.8.0 on Oct 4, 2020
  6. andrewrk commented on Oct 4, 2020

    @andrewrk
    Member

    Related: #4094

    There is definitely a problem here. Zig sometimes tries to generate runtime versions of functions that are only ever called at comptime. It's unclear how to solve yet. Will leave this open until either there is a solution or it becomes an acknowledged and permanent flaw in the language.

  7. modified the milestones: 0.8.0, 0.9.0 on Nov 6, 2020
  8. added
    use case
    on Mar 21, 2021
  9. modified the milestones: 0.9.0, 0.10.0 on May 19, 2021
  10. changed the title [-]Zig Compiler rejects or accepts array concatenation based on return type.[/-] [+]Function only called at comptime is emitted to binary[/+] on Mar 13, 2022
  11. added 6 commits that reference this issue on May 29, 2023
    85ff300
    f8f95eb
    93a8cb5
    1df228c
    1125a02
    4976b58
  12. modified the milestones: 0.13.0, 0.11.0 on Jun 15, 2023
  13. added a commit that references this issue on May 9, 2024
    919d9e6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    use case

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions