Skip to content

std.Build: accept comptime string as option value #22135

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

thiago-negri
Copy link

Small quality of life improvement for std.Build interface: accept comptime string as option value without the need to cast it to []const u8.

Problem

On one project I have a build option declared as such:

const str_opt = b.option([]const u8, "str_opt", "my str opt");

Then on another project I want to set that option:

const dep = b.dependency("other-project", .{
    .str_opt = @as([]const u8, "the str value")
});

I'm forced to cast it to []const u8.

If I try this:

const dep = b.dependency("other-project", .{
    .str_opt = "the str value"
});

I get the error:

Build.zig:503:25: error: option 'opt_str' has unsupported type: *const [13:0]u8

Expectation

Zig compiler automatically casts comptime strings to []const u8 if they are, for example, declared as the type of a function argument. I'd expect the same here.

Diagnosis

std.Build.userInputOptionsFromArgs is a comptime function that evaluates its args using @TypeOf information. So the compiler has no way to know whether that requires an auto-cast or not.

Solution

This PR tries to address the issue by forcing the []const u8 type when it encounters a value that looks like a comptime string. As the inner UserValue.value uses a []const u8, I suppose the behavior does not change.

I'm not sure if that's the correct way to infer if a value can be considered a "comptime string". But it works for my use case.

@thiago-negri thiago-negri force-pushed the patch-1 branch 2 times, most recently from aa7fa1a to 40aae3f Compare December 9, 2024 15:35
@alexrp alexrp force-pushed the patch-1 branch 2 times, most recently from c4e19dd to 4cb7f4f Compare February 6, 2025 00:00
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

Successfully merging this pull request may close these issues.

1 participant