I have a simple enum, that has a method to “convert” it to a colored string, but whenever I try to use it, I get an error “unable to resolve comptime value”, though this code is not intended to be ran on comptime, but even if zig is calculating all possible return values at comptime (since there is a very finite number of those) of this function:
- I don’t remember asking to do so
- All values are actually comptime known, so there shouldn’t be any errors anyway.
Minimal example:
const std = @import("std");
const fmt = std.fmt.comptimePrint;
const ESC = "\x1B[";
const FORE: u8 = 38;
const BACK: u8 = 48;
const Field = enum {
A,
B,
fn to_string(self: Field) u8 {
return switch (self) {
.A => 'A',
.B => 'B',
};
}
fn to_colored_string(self: Field) []const u8 {
return switch (self) {
.A => setFore("A", "FF0000"),
.B => setFore("B", "0000FF"),
};
}
};
pub fn setFore(str: []const u8, comptime color: []const u8) []const u8 {
const x = convertHexColorToRGB(color);
return getRGB(FORE, x[0], x[1], x[2]) ++ str ++ getReset(FORE);
}
pub fn convertHexColorToRGB(comptime hex: []const u8) []u8 {
var result: [3]u8 = undefined;
for (0..3) |x| {
result[x] = hexStrToDec(hex[x * 2]) * 16 + hexStrToDec(hex[x * 2 + 1]);
}
return &result;
}
fn hexStrToDec(hex: u8) u8 {
if (hex >= 'A' and hex <= 'F') {
return hex - 'A' + 10;
} else if (hex >= 'a' and hex <= 'f') {
return hex - 'a' + 10;
} else if (hex >= '0' and hex <= '9') {
return hex - '0';
}
return 0;
}
fn getRGB(comptime mode: u8, r: u8, g: u8, b: u8) []const u8 {
return fmt("{s}{d};2;{d};{d};{d}m", .{ ESC, mode, r, g, b });
}
fn getReset(comptime mode: u8) []const u8 {
return fmt("{s}{d}m", .{ ESC, mode + 1 });
}
const stdout = std.io.getStdOut().writer();
pub fn main() void {
const field = Field.A;
// this works
stdout.print("{c}", .{field.to_string()}) catch return;
// and this doesn't
stdout.print("{s}", .{field.to_colored_string()}) catch return;
}
I also tried using comptimePrint instead of concat (since some errors explicitly mention concat as the main issue), but it didn’t change much. Replacing comptime operations with print that uses an allocator would probably fix the issue, but I don’t want to hassle with them in such a simple use-case.
Please help me understand why zig is trying to execute it at compile time, even though it shouldn’t, why it errors at comptime though all values are actually comptime-known in this example, atleast, and how to fix it for both when values are comptime known and when they aren’t.
I am new to zig, so bad code and stupid questions are definitely there, sorry for this .