liveBook · Manning

@compileError

As explained in Systems Programming with Zig

@compileError is a Zig compile-time builtin that emits a compilation error with a specified message.

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

How Systems Programming with Zig covers it

How deep it goes
Demonstrates the builtin in a parser and formats its error message with std.fmt.comptimePrint.
Examples
Uses a four-byte wordlist parser and invites readers to trigger its diagnostic with an invalid word.
What you can do after
Apply it in Zig to reject invalid compile-time input with a formatted diagnostic.
How it connects
Connects compile-time execution with parsing, error handling, and compile-time debugging.

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.