Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

compileLog can print 'runtime_value' even when its not #1752

Closed
daurnimator opened this issue Nov 19, 2018 · 3 comments
Closed

compileLog can print 'runtime_value' even when its not #1752

daurnimator opened this issue Nov 19, 2018 · 3 comments

Comments

@daurnimator
Copy link
Collaborator

const std = @import("std");

fn parseFile(contents:[]const u8) u8 {
    var acc:u8 = 0;
    for (contents) |byte| {
        acc |= byte;
    }
    return acc;
}

fn compileTimeParseFile(comptime filename:[]const u8) u8 {
    comptime {
        const contents = @embedFile(filename);
        return parseFile(contents[0..contents.len]);
    }
}

pub fn main() void {
    const x = compileTimeParseFile("sample-file");
    @compileLog(x);
    std.debug.warn("FILE={}\n", x);
}
$ zig build-exe embedfile-test.zig 
| (runtime value)
embedfile-test.zig:20:5: error: found compile log statement
    @compileLog(x);
    ^

Now I comment out the @compileLog line:

$ echo foo >> sample-file
$ zig build-exe embedfile-test.zig 
$ ./embedfile-test 
FILE=111
$ strings embedfile-test | grep foo
@ghost
Copy link

ghost commented Nov 19, 2018

If you want it to work now you could change the one line to this:

const x = comptime compileTimeParseFile("sample-file");

@andrewrk
Copy link
Member

This is working as designed. Function calls are executed at runtime, unless the type signature requires a comptime execution, or unless the function call is in a comptime scope. @dbandstra's suggestion puts the function call into a comptime scope, which is why it solves the problem.

I think the somewhat counter-intuitive thing here is that return control flow is unaffected by whether it is in a comptime scope or not. However the return expression is comptime evaluated. So your compileTimeParseFile ends up being code generated to return 42 (or whatever the result of the computation is) which is then called at runtime from main.

A related issue is #425.

I'm happy to consider proposals to adjust semantics if you have a clear idea of how to improve this.

@daurnimator
Copy link
Collaborator Author

Thankyou for the explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants