When a wordlist is parsed at compile time, a malformed word can stop the build instead of slipping into the finished program. Zig’s @compileError builtin stops compilation and displays a supplied error string. Compile-time code can also use ordinary errors, but @compileError makes a direct diagnostic convenient. section 4.1.3
Listing 4.4 Parsing the wordlist into an array
fn parseWordlist(
comptime wordlist: []const u8, #1
) [countWordlist(wordlist)][4]u8 { #2
var list: [countWordlist(wordlist)][4]u8 = undefined;
var i: usize = 0;
var word_iter = std.mem.tokenizeScalar(u8, wordlist, '\n');
while (word_iter.next()) |word| : (i += 1) { #3
if (word.len != 4) {
@compileError(std.fmt.comptimePrint( #4
"the word '{s}' is not four characters long.",
.{word},
));
}
list[i] = word[0..4].*; #5
}
return list;
}
The parser checks each word’s length before copying it into a four-byte array. For an invalid word, std.fmt.comptimePrint formats a message containing that word, and @compileError stops compilation. section 4.1.3
To trigger the diagnostic, put a word whose length is not four bytes in the compile-time wordlist. The parser’s message identifies the offending word. section 4.1.3
