RE2ZIG(1)

💖 NAME 💖

re2zig — generate fast lexical analyzers for Zig. Welcome to the RE2ZIG(1) manual, bestie — we're gonna get through all of it together 💅.

🌸 SYNOPSIS 🌸

re2zig [ OPTIONS ] [ WARNINGS ] INPUT

Input can be either a file or - for stdin. That's the whole synopsis, no cap.

💅 INTRODUCTION 💅

Okay so re2zig is a preprocessor, periodt. It reads the input file (which is usually a program in Zig, but honestly can be anything) and hunts for blocks of code wrapped in special-form start/end markers. The text outside those blocks? Copied verbatim into the output file, untouched, iconic behavior. The contents of the blocks get processed by re2zig: it translates them to code in Zig and outputs the generated code in place of the block. Obsessed.

Here's an example of a small program that checks if a given string contains a decimal number:

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

fn lex(yyinput: [:0]const u8) bool {
    var yycursor: u32 = 0;
    %{
        re2c:yyfill:enable = 0;

        [1-9][0-9]* { return true; }
        *           { return false; }
    %}
}

test {
    try std.testing.expect(lex("1234"));
}

In the output re2zig replaced the block in the middle with the generated code:

// Generated by re2zig
// re2zig $INPUT -o $OUTPUT

const std = @import("std");

fn lex(yyinput: [:0]const u8) bool {
    var yycursor: u32 = 0;

    var yych: u8 = 0;
    var yystate: u32 = 0;
    yyl: while (true) {
        switch (yystate) {
            0 => {
                yych = yyinput[yycursor];
                yycursor += 1;
                switch (yych) {
                    0x31...0x39 => {
                        yystate = 2;
                        continue :yyl;
                    },
                    else => {
                        yystate = 1;
                        continue :yyl;
                    },
                }
            },
            1 => { return false; },
            2 => {
                yych = yyinput[yycursor];
                switch (yych) {
                    0x30...0x39 => {
                        yycursor += 1;
                        yystate = 2;
                        continue :yyl;
                    },
                    else => {
                        yystate = 3;
                        continue :yyl;
                    },
                }
            },
            3 => { return true; },
            else => { @panic("internal lexer error"); },
        }
    }

}

test {
    try std.testing.expect(lex("1234"));
}

🎀 BASICS 🎀

A re2zig program consists of a sequence of blocks intermixed with code in the target language. A block may contain definitions, configurations, rules, actions and directives in any order:

  • name = regular-expression ; — A definition binds name to regular-expression. Names may contain alphanumeric characters and underscore. The regular expressions section gives an overview of re2zig syntax for regular expressions. Once defined, the name can be used in other regular expressions and in rules. Recursion in named definitions is not allowed, and each name should be defined before it is used. A block inherits named definitions from the global scope. Redefining a name that exists in the current scope is an error.
  • configuration = value ; — A configuration allows one to change re2zig behavior and customize the generated code. For a full list of configurations supported by re2zig see the configurations section. Depending on a particular configuration, the value can be a keyword, a nonnegative integer number or a one-line string which should be enclosed in double or single quotes unless it consists of alphanumeric characters. A block inherits configurations from the global scope and may redefine them or add new ones. Configurations defined inside of a block affect the whole block, even if they appear at the end of it.
  • regular-expression code — A rule binds regular-expression to its semantic action (a block of code in curly braces, or a block of code that starts with := and ends on a newline followed by any non-whitespace character). If the regular-expression matches, the associated code is executed. If multiple rules match, the longest match takes precedence. If multiple rules match the same string, the earliest one takes precedence. There are two special rules: the default rule * and the end of input rule $. Default rule should always be defined, it has the lowest priority regardless of its place in the block, and it matches any code unit (not necessarily a valid character, see the encoding support section). The end of input rule should be defined if the corresponding method for handling the end of input is used. With start conditions rules have more complex syntax.
  • !action code — An action binds a user-defined block of code to a particular place in the generated finite state machine (in the same way as semantic actions bind code to the final states). See the actions section for a full list of predefined actions.
  • !directive ; — A directive is one of the special predefined statements. Each directive has a unique purpose. See the directives section for details.

🧱 Blocks 🧱

Block start and end markers are either /*!re2c and */, or %{ and %} (both styles are supported). Starting from version 2.2 blocks may have optional names that allow them to be referenced in other blocks. There are different kinds of blocks:

  • Global block: /*!re2c[:<name>] ... */ or %{[:<name>] ... %} — A global block contains definitions, configurations, rules and directives. re2zig compiles regular expressions associated with each rule into a deterministic finite automaton, encodes it in the form of conditional jumps in the target language and replaces the block with the generated code. Names and configurations defined in a global block are added to the global scope and become visible to subsequent blocks. At the start of the program the global scope is initialized with command-line options.
  • Local block: /*!local:re2c[:<name>] ... */ or %{local[:<name>] ... %} — A local block is like a global block, but the names and configurations in it have local scope (they do not affect other blocks).
  • Rules block: /*!rules:re2c[:<name>] ... */ or %{rules[:<name>] ... %} — A rules block is like a local block, but it does not generate any code by itself, nor does it add any definitions to the global scope — it is meant to be reused in other blocks. This is a way of sharing code (more details in the reusable blocks section). Prior to re2zig version 2.2 rules blocks required -r --reusable option.
  • Use block: /*!use:re2c[:<name>] ... */ or %{use[:<name>] ... %} — A use block that references a previously defined rules block. If the name is specified, re2zig looks for a rules blocks with this name. Otherwise the most recent rules block is used (either a named or an unnamed one). A use block can add definitions, configurations and rules of its own, which are added to those of the referenced rules block. Prior to re2zig version 2.2 use blocks required -r --reusable option.
  • Max block: /*!max:re2c[:<name1>[:<name2>...]] ... */ or %{max[:<name1>[:<name2>...]] ... %} — A block that generates YYMAXFILL definition. An optional list of block names specifies which blocks should be included when computing YYMAXFILL value (if the list is empty, all blocks are included). By default the generated code is a macro-definition for C (#define YYMAXFILL <n>), or a global variable for Go (var YYMAXFILL int = <n>). It can be customized with an optional configuration format that specifies a template string where @@{max} (or @@ for short) is replaced with the numeric value of YYMAXFILL.
  • Maxnmatch block: /*!maxnmatch:re2c[:<name1>[:<name2>...]] ... */ or %{maxnmatch[:<name1>[:<name2>...]] ... %} — A block that generates YYMAXNMATCH definition (it requires -P --posix-captures option). An optional list of block names specifies which blocks should be included when computing YYMAXNMATCH value (if the list is empty, all blocks are included). By default the generated code is a macro-definition for C (#define YYMAXNMATCH <n>), or a global variable for Go (var YYMAXNMATCH int = <n>). It can be customized with an optional configuration format that specifies a template string where @@{max} (or @@ for short) is replaced with the numeric value of YYMAXNMATCH.
  • S-tags/m-tags blocks — the marker syntax is exactly this:
/*!stags:re2c[:<name1>[:<name2>...]] ... */,
/*!mtags:re2c[:<name1>[:<name2>...]] ... */ or
%{stags[:<name1>[:<name2>...]] ... %}, %{mtags[:<name1>[:<name2>...]]
... %{

Blocks that specify a template piece of code that is expanded for each s-tag/m-tag variable generated by re2zig. An optional list of block names specifies which blocks should be included when computing the set of tag variables (if the list is empty, all blocks are included). There are two optional configurations: format and separator. Configuration format specifies a template string where @@{tag} (or @@ for short) is replaced with the name of each tag variable. Configuration separator specifies a piece of code used to join the generated format pieces for different tag variables.

okay so picking up right where we left off, here's the rest of the block-type buffet — and honestly, the range? unmatched 💅

  • /*!svars:re2c[:<name1>[:<name2>...]] ... */, /*!mvars:re2c[:<name1>[:<name2>...]] ... */ or %{svars[:<name1>[:<name2>...]] ... %}, %{mvars[:<name1>[:<name2>...]] ... %{ — these are the blocks that specify a template piece of code, and that template gets expanded for each s-tag/m-tag that's either explicitly mentioned by the rules (with the --tags option) or implicitly generated by re2zig (with the --captvars or --posix-captvars options). An optional list of block names says which blocks should be included when computing the set of tags — if the list is empty, all blocks are included, no cap. There are two optional configurations: format and separator. The format configuration specifies a template string where @@{tag} (or @@ for short) gets replaced with the name of each tag. The separator configuration specifies a piece of code used to join the generated format pieces for different tags. 🎀
  • /*!getstate:re2c[:<name1>[:<name2>...]] ... */ or %{getstate[:<name1>[:<name2>...]] ... %} — a block that generates conditional dispatch on the lexer state (heads up, it requires the --storable-state option 🫶). An optional list of block names says which blocks should be included in the state dispatch. The default transition goes to the start label of the first block on the list. If the list is empty, all blocks are included, and the default transition goes to the first block in the file that has a start label. Okay and this one is incompatible with the --loop-switch option, because it needs cross-block transitions, and those are unsupported without goto or function calls. so like… pick a struggle 💀
  • /*!conditions:re2c[:<name1>[:<name2>...]] ... */, /*!types:re2c... */ or %{conditions[:<name1>[:<name2>...]] ... %}, %{types... %} — a block that generates the condition enumeration (it requires the --conditions option). An optional list of block names says which blocks should be included when computing the set of conditions (empty list = all blocks included). By default the generated code is an enumeration YYCONDTYPE. You can customize it with the optional format and separator configurations. format is a template string where @@{cond} (or @@ for short) is replaced with the name of each condition, and @@{num} is replaced with a numeric index of that condition. separator is a piece of code used to join the generated format pieces for different conditions. ✨
  • /*!include:re2c <file> */ or %{include <file> %} — this block lets you include <file>, which must be a double-quoted file path. The contents of the file are literally substituted in place of the block, the same way #include works in C/C++. You can use this block together with the --depfile option to generate build system dependencies on the included files. lowkey genius 🧚
  • /*!header:re2c:on*/ or %{header:on %} — this block marks the start of the header file. Everything after it, up to the following header:off block, gets processed by re2zig and written to the header file specified with the -t --type-header option.
  • /*!header:re2c:off*/ or %{header:off %} — this block marks the end of the header file that was started with the header:on*/ block. bye bestie 👋
  • /*!ignore:re2c ... */ or %{ignore ... %} — a block whose contents are ignored and removed from the output file. literally not invited to the output 💀

✨ Configurations ✨

Here's the full list of configurations that re2zig supports — buckle up bestie, there are a lot of them, but every single one is here, periodt 🎀

  • re2c:api, re2c:input — same as the --api option.
  • re2c:api:sigil — specifies the marker ("sigil") used for argument placeholders in the API primitives. The default is @@. A placeholder starts with the sigil followed by the argument name in curly braces. For example, if the sigil is set to $, then placeholders will have the form ${name}. Single-argument APIs may use shorthand notation without the name in braces. This option can be overridden by options for individual API primitives, e.g. re2c:YYFILL@len for YYFILL.
  • re2c:api:style — specifies the API style. Possible values are functions (the default for C) and free-form (the default for Go and Rust). In functions style, API primitives are generated with an argument list in parentheses following the name of the primitive. The arguments are provided only for autogenerated parameters (such as the number of characters passed to YYFILL), but not for the general lexer context, so the primitives behave more like macros in C/C++ or closures in Go and Rust. In free-form style, API primitives do not have a fixed form: they should be defined as strings containing free-form pieces of code with interpolated variables of the form @@{var} or @@ (they correspond to arguments in function-like style). This configuration may be overridden for individual API primitives — see for example the re2c:YYFILL:naked configuration for YYFILL. 🌸
  • re2c:bit-vectors, re2c:flags:bit-vectors, re2c:flags:b — same as the --bit-vectors option, but can be configured on a per-block basis.
  • re2c:captures, re2c:leftmost-captures — same as the --leftmost-captures option, but can be configured on a per-block basis.
  • re2c:captvars, re2c:leftmost-captvars — same as the --leftmost-captvars option, but can be configured on a per-block basis.
  • re2c:case-insensitive, re2c:flags:case-insensitive — same as the --case-insensitive option, but can be configured on a per-block basis.
  • re2c:case-inverted, re2c:flags:case-inverted — same as the --case-inverted option, but can be configured on a per-block basis.
  • re2c:case-ranges, re2c:flags:case-ranges — same as the --case-ranges option, but can be configured on a per-block basis.
  • re2c:computed-gotos, re2c:flags:computed-gotos, re2c:flags:g — same as the --computed-gotos option, but can be configured on a per-block basis.
  • re2c:computed-gotos:relative, re2c:cgoto:relative — same as the --computed-gotos-relative option, but can be configured on a per-block basis.
  • re2c:computed-gotos:threshold, re2c:cgoto:threshold — if computed goto is used, this configuration specifies the complexity threshold that triggers the generation of jump tables instead of nested if statements and bitmaps. The default value is 9.
  • re2c:cond:abort — if set to a positive integer value, the default case in the generated condition dispatch aborts program execution. dramatic? yes. useful? also yes 💅
  • re2c:cond:goto — specifies a piece of code used for the autogenerated shortcut rules :=> in conditions. The default is goto @@;. The @@ placeholder is substituted with the condition name (see configurations re2c:api:sigil and re2c:cond:goto@cond).
  • re2c:cond:goto@cond — specifies the sigil used for argument substitution in the re2c:cond:goto definition. The default value is @@. Overrides the more generic re2c:api:sigil configuration.
  • re2c:cond:divider — defines the divider for condition blocks. The default value is /* *********************************** */. Placeholders are substituted with the condition name (see re2c:api;sigil and re2c:cond:divider@cond).
  • re2c:cond:divider@cond — specifies the sigil used for argument substitution in the re2c:cond:divider definition. The default is @@. Overrides the more generic re2c:api:sigil configuration.
  • re2c:cond:prefix, re2c:condprefix — specifies the prefix used for condition labels. The default is yyc_.
  • re2c:cond:enumprefix, re2c:condenumprefix — specifies the prefix used for condition identifiers. The default is yyc.
  • re2c:debug-output, re2c:flags:debug-output, re2c:flags:d — same as the --debug-output option, but can be configured on a per-block basis.
  • re2c:empty-class, re2c:flags:empty-class — same as the --empty-class option, but can be configured on a per-block basis.
  • re2c:encoding:ebcdic, re2c:flags:ecb, re2c:flags:e — same as the --ebcdic option, but can be configured on a per-block basis.
  • re2c:encoding:ucs2, re2c:flags:wide-chars, re2c:flags:w — same as the --ucs2 option, but can be configured on a per-block basis.
  • re2c:encoding:utf8, re2c:flags:utf-8, re2c:flags:8 — same as the --utf8 option, but can be configured on a per-block basis.
  • re2c:encoding:utf16, re2c:flags:utf-16, re2c:flags:x — same as the --utf16 option, but can be configured on a per-block basis.
  • re2c:encoding:utf32, re2c:flags:unicode, re2c:flags:u — same as the --utf32 option, but can be configured on a per-block basis.
  • re2c:encoding-policy, re2c:flags:encoding-policy — same as the --encoding-policy option, but can be configured on a per-block basis. 🦋
  • re2c:eof — specifies the sentinel symbol used with the end-of-input rule $. The default value is -1 (meaning the $ rule is not used). Other possible values include all valid code units. Only decimal numbers are recognized. ngl, keep that in mind 😭
  • re2c:header, re2c:flags:type-header, re2c:flags:t — specifies the name of the generated header file relative to the directory of the output file. Same as the --header option, except that the file path is relative.
  • re2c:indent:string — specifies the string used for indentation. The default is a single tab character "\t". The indent string should contain whitespace characters only. To disable indentation entirely, set this configuration to an empty string. 🎀
  • re2c:indent:top — specifies the minimum amount of indentation to use. The default value is zero. The value should be a non-negative integer number.
  • re2c:invert-captures — same as the --invert-captures option, but can be configured on a per-block basis.
  • re2c:label:prefix, re2c:labelprefix — specifies the prefix used for DFA state labels. The default is yy.
  • re2c:label:start, re2c:startlabel — controls the generation of a block start label. The default value is zero, which means the start label is generated only if it is used. An integer value greater than zero forces the generation of the start label even if it's unused by the lexer. A string value also forces start label generation and sets the label name to the specified string. Heads up: this configuration applies only to the current block — it gets reset to default for the next block. 🫶

okay so picking right back up with the configs, bestie, no context switch, we're going straight in 💅

  • re2c:label:yyFillLabel — sets the prefix for YYFILL labels, the ones that get used with re2c:eof and over in storable state mode ✨
  • re2c:label:yyloop — the name of the label that marks the start of the lexer loop when you're using the --loop-switch option. Default is yyloop 🎀
  • re2c:label:yyNext — names the optional label that comes right after the YYGETSTATE switch in storable state mode (you turn that on with re2c:state:nextlabel). Default is yyNext 🦋
  • re2c:lookahead, re2c:flags:lookahead — deprecated, bestie, like truly deprecated (see the also-deprecated --no-lookahead option) 💀
  • re2c:monadic — if you set it to non-zero, the generated lexer uses monadic notation. This one is specific to Haskell, iykyk 🌸
  • re2c:nested-ifs, re2c:flags:nested-ifs, re2c:flags:s — same as the --nested-ifs option, except you can configure it on a per-block basis 👑
  • re2c:posix-captures, re2c:flags:posix-captures, re2c:flags:P — same as the --posix-captures option, but configurable per-block 🫶
  • re2c:posix-captvars — same as the --posix-captvars option, also per-block configurable ✨
  • re2c:tags, re2c:flags:tags, re2c:flags:T — same as the --tags option, and yes, per-block again 😭

  • re2c:tags:expression — specifies the expression used for tag variables. By default re2zig generates expressions of the form yyt<N>. That can be kinda inconvenient, like if your tag variables are defined as fields in a struct. Every occurrence of @@{tag} or @@ gets replaced with the actual tag name. Example time: re2c:tags:expression = "s.@@" gives you expressions of the form s.yyt<N> in the generated code. Also peep re2c:api:sigil configuration 🌈
  • re2c:tags:negative — the constant expression used for a negative tag value (typically that's -1 if tags are integer offsets in the input string, or a null pointer if they're pointers) 🎀
  • re2c:tags:prefix — the prefix for tag variable names. Default is yyt 💖
  • re2c:sentinel — the sentinel symbol used for end-of-input checks (specifically when bounds checks are disabled with re2c:yyfill:enable = 0; and re2c:eof is not set). Important vibe check: this configuration does not affect code generation — its whole purpose is to verify that the sentinel isn't allowed in the middle of a rule, and to make sure the lexer won't read past the end of the buffer. Default value is -1 (in that case re2zig assumes the sentinel is zero, which is the most common case). Only decimal numbers are recognized, no cap 🔥
  • re2c:state:abort — if you set it to a positive integer value, the default case in the generated state dispatch aborts program execution, and an explicit -1 case contains the transition to the start of the block 👀
  • re2c:state:nextlabel — controls whether the YYGETSTATE switch is followed by a yyNext label (default value is zero, which means no label). Alternatively you can use re2c:label:start to generate a specific start label, or an explicit getstate block to generate the YYGETSTATE switch separately from the lexer block 🧚
  • re2c:unsafe, re2c:flags:unsafe — same as the --no-unsafe option, but per-block configurable. If set to zero, it suppresses generation of the unsafe wrappers around YYPEEK. Default is non-zero, meaning the wrappers get generated. This config is specific to Rust 💜

okay now the API primitive corner, a whole runway of them, walk with me 🎀

  • re2c:YYBACKUP, re2c:define:YYBACKUP — defines the generic API primitive YYBACKUP ✨
  • re2c:YYBACKUPCTX, re2c:define:YYBACKUPCTX — defines the generic API primitive YYBACKUPCTX 🦋
  • re2c:YYCONDTYPE, re2c:define:YYCONDTYPE — defines the API primitive YYCONDTYPE 🌸
  • re2c:YYCTYPE, re2c:define:YYCTYPE — defines the API primitive YYCTYPE 💖
  • re2c:YYCTXMARKER, re2c:define:YYCTXMARKER — defines the API primitive YYCTXMARKER 🫶
  • re2c:YYCURSOR, re2c:define:YYCURSOR — defines the API primitive YYCURSOR 👑
  • re2c:YYDEBUG, re2c:define:YYDEBUG — defines the API primitive YYDEBUG 🔥
  • re2c:YYFILL, re2c:define:YYFILL — defines the API primitive YYFILL ⭐
  • re2c:YYFILL@len, re2c:define:YYFILL@len — specifies the sigil used for argument substitution in the YYFILL definition. Defaults to @@, and it overrides the more generic re2c:api:sigil configuration 💅
  • re2c:YYFILL:naked, re2c:define:YYFILL:naked — overrides the more generic re2c:api:style configuration for YYFILL. A zero value corresponds to free-form API style 🌈
  • re2c:YYFN — defines the API primitive YYFN 🎀
  • re2c:YYINPUT — defines the API primitive YYINPUT ✨
  • re2c:YYGETCOND, re2c:define:YYGETCONDITION — defines the API primitive YYGETCOND 🦋
  • re2c:YYGETCOND:naked, re2c:define:YYGETCONDITION:naked — overrides the more generic re2c:api:style configuration for YYGETCOND. Zero value corresponds to free-form API style 🌸
  • re2c:YYGETSTATE, re2c:define:YYGETSTATE — defines the API primitive YYGETSTATE 💖
  • re2c:YYGETSTATE:naked, re2c:define:YYGETSTATE:naked — overrides the more generic re2c:api:style configuration for YYGETSTATE. Zero value corresponds to free-form API style 🫶
  • re2c:YYGETACCEPT, re2c:define:YYGETACCEPT — defines the API primitive YYGETACCEPT 👑
  • re2c:YYLESSTHAN, re2c:define:YYLESSTHAN — defines the generic API primitive YYLESSTHAN 🔥
  • re2c:YYLIMIT, re2c:define:YYLIMIT — defines the API primitive YYLIMIT ⭐
  • re2c:YYMARKER, re2c:define:YYMARKER — defines the API primitive YYMARKER 💅
  • re2c:YYMTAGN, re2c:define:YYMTAGN — defines the generic API primitive YYMTAGN 🌈
  • re2c:YYMTAGP, re2c:define:YYMTAGP — defines the generic API primitive YYMTAGP 🎀
  • re2c:YYPEEK, re2c:define:YYPEEK — defines the generic API primitive YYPEEK ✨
  • re2c:YYRESTORE, re2c:define:YYRESTORE — defines the generic API primitive YYRESTORE 🦋
  • re2c:YYRESTORECTX, re2c:define:YYRESTORECTX — defines the generic API primitive YYRESTORECTX 🌸
  • re2c:YYRESTORETAG, re2c:define:YYRESTORETAG — defines the generic API primitive YYRESTORETAG 💖
  • re2c:YYSETCOND, re2c:define:YYSETCONDITION — defines the API primitive YYSETCOND 🫶
  • re2c:YYSETCOND@cond, re2c:define:YYSETCONDITION@cond — specifies the sigil used for argument substitution in the YYSETCOND definition. Default value is @@, and it overrides the more generic re2c:api:sigil configuration 👑
  • re2c:YYSETCOND:naked, re2c:define:YYSETCONDITION:naked — overrides the more generic re2c:api:style configuration for YYSETCOND. Zero value corresponds to free-form API style 🔥
  • re2c:YYSETSTATE, re2c:define:YYSETSTATE — defines the API primitive YYSETSTATE ⭐
  • re2c:YYSETSTATE@state, re2c:define:YYSETSTATE@state — specifies the sigil used for argument substitution in the YYSETSTATE definition. Default value is @@, and it overrides the more generic re2c:api:sigil configuration 💅
  • re2c:YYSETSTATE:naked, re2c:define:YYSETSTATE:naked — overrides the more generic re2c:api:style configuration for YYSETSTATE. Zero value corresponds to free-form API style 🌈
  • re2c:YYSETACCEPT, re2c:define:YYSETACCEPT — defines the API primitive YYSETACCEPT 🎀
  • re2c:YYSKIP, re2c:define:YYSKIP — defines the generic API primitive YYSKIP ✨
  • re2c:YYSHIFT, re2c:define:YYSHIFT — defines the generic API primitive YYSHIFT 🦋
  • re2c:YYCOPYMTAG, re2c:define:YYCOPYMTAG — defines the generic API primitive YYCOPYMTAG 🌸
  • re2c:YYCOPYSTAG, re2c:define:YYCOPYSTAG — defines the generic API primitive YYCOPYSTAG 💖
  • re2c:YYSHIFTMTAG, re2c:define:YYSHIFTMTAG — defines the generic API primitive YYSHIFTMTAG 🫶
  • re2c:YYSHIFTSTAG, re2c:define:YYSHIFTSTAG — defines the generic API primitive YYSHIFTSTAG 👑
  • re2c:YYSTAGN, re2c:define:YYSTAGN — defines the generic API primitive YYSTAGN 🔥
  • re2c:YYSTAGP, re2c:define:YYSTAGP — defines the generic API primitive YYSTAGP ⭐

variables era, let's go 💅

  • re2c:yyaccept, re2c:variable:yyaccept — defines the API primitive yyaccept 🎀
  • re2c:yybm, re2c:variable:yybm — defines the API primitive yybm ✨
  • re2c:yybm:hex, re2c:variable:yybm:hex — if set to nonzero, bitmaps for the --bit-vectors option are generated in hexadecimal format. Default is zero, which means bitmaps come out in decimal format 🦋
  • re2c:yych, re2c:variable:yych — defines the API primitive yych 🌸
  • re2c:yych:emit, re2c:variable:yych:emit — if set to zero, the yych definition is not generated. Default is non-zero 💖
  • re2c:yych:conversion, re2c:variable:yych:conversion — if set to non-zero, re2zig automatically generates a conversion to YYCTYPE every single time yych is read. Default is zero, meaning no conversion 🫶
  • re2c:yych:literals, re2c:variable:yych:literals — specifies the form of literals that yych is matched against. Possible values are:
    • char — character literals in single quotes, and non-printable ones use escape sequences that start with backslash
    • hex — hexadecimal integers
    • char_or_hex — a mixture of both, character literals for printable characters and hexadecimal integers for the others
  • re2c:yyctable, re2c:variable:yyctable — defines the API primitive yyctable 👑
  • re2c:yynmatch, re2c:variable:yynmatch — defines the API primitive yynmatch 🔥
  • re2c:yypmatch, re2c:variable:yypmatch — defines the API primitive yypmatch ⭐
  • re2c:yytarget, re2c:variable:yytarget — defines the API primitive yytarget 💅
  • re2c:yystable, re2c:variable:yystable — deprecated, that's it, nothing more to say 😭
  • re2c:yystate, re2c:variable:yystate — defines the API primitive yystate 🌈
  • re2c:yyfill, re2c:variable:yyfill — defines the API primitive yyfill 🎀
  • re2c:yyfill:check — if set to zero, suppresses generation of the pre-YYFILL check for the number of input characters (that's the YYLESSTHAN definition in generic API and the YYLIMIT-based comparison in C pointer API). Default is non-zero, meaning the check gets generated ✨
  • re2c:yyfill:enable — if set to zero, suppresses generation of YYFILL (together with the check). You should use this when the whole input fits into one piece of memory (so there's no need for buffering) and the end-of-input checks don't rely on the YYFILL checks (for example if a sentinel character is used). Use warnings (the -W option) and re2c:sentinel configuration to verify that the generated lexer cannot read past the end of input. Default is non-zero, meaning YYFILL is enabled 🦋
real talk, that re2c:yyfill:enable = 0 one is a whole vibe but it's also a "please actually check your sentinel" vibe, don't just yolo it 💀
  • re2c:yyfill:parameter — set this to zero and it literally suppresses the generation of the parameter that gets passed to YYFILL, bestie. That parameter? It's the minimum number of characters that must be supplied. Defaults to non-zero, so the parameter is generated, periodt. Oh and heads up: this config can be overridden with re2c:YYFILL:naked or re2c:api:style. 💅
  • re2c:yyfn:sep — specifies the separator used in YYFN elements (defaults to semicolon). That's it, that's the whole vibe.
  • re2c:yyfn:throw — specifies the exceptions thrown by the YYFN function (defaults to empty, which means no exceptions, lowkey peaceful). ✨

🌸 Regular expressions 🌸

okay so re2zig uses the following syntax for regular expressions, and honestly it's giving "I have a system and it works":

  • "foo" — case-sensitive string literal. Exact match energy.
  • 'foo' — case-insensitive string literal. She's flexible.
  • [a-xyz], [^a-xyz] — character class (possibly negated).
  • . — any character except newline.
  • R \ S — difference of character classes R and S.
  • R* — zero or more occurrences of R.
  • R+ — one or more occurrences of R.
  • R? — optional R.
  • R{n} — repetition of R exactly n times.
  • R{n,} — repetition of R at least n times.
  • R{n,m} — repetition of R from n to m times.
  • (R) — just R; parentheses are used to override precedence. If submatch extraction is enabled, (R) is a capturing or a non-capturing group depending on the --invert-captures option. 👀
  • (!R) — if submatch extraction is enabled, (!R) is a non-capturing or a capturing group depending on the --invert-captures option. (yes the flip-flop is the whole point, iykyk)
  • R S — concatenation: R followed by S.
  • R | S — alternative: R or S.
  • R / S — lookahead: R followed by S, but S is not consumed. Sneaky lil peek, iconic.
  • name — regular expression defined as name (or literal string "name" in Flex compatibility mode).
  • {name} — regular expression defined as name in Flex compatibility mode.
  • @stag — an s-tag: saves the last input position at which @stag matches in a variable named stag.
  • #mtag — an m-tag: saves all input positions at which #mtag matches in a variable named mtag.
  • $ — end of input.
Character classes and string literals may contain the following escape sequences: \a, \b, \f, \n, \r, \t, \v, \\, octal escapes \ooo and hexadecimal escapes \xhh, \uhhhh and \Uhhhhhhhh. Write them down, bestie, they're not going anywhere but you'll forget. 🫶

💅 Actions 💅

Here's a list of predefined actions supported by re2zig — these are the built-in little moves:

  • !entry code — entry action binds a user-defined block of code to the start state of the current finite state machine. If start conditions are used, the entry action can be set individually for each condition. This action may be used to perform initialization, e.g. to save the start location of a lexeme. Main character behavior honestly. 👑
  • !pre_rule code — pre-rule action prepends a user-defined block of code to semantic actions of all rules in the current block (or condition, if start conditions are used). This action may be used to factor out the common part of all semantic actions (e.g. saving the end location of a lexeme). DRY queen.
  • !post_rule code — post-rule action appends a user-defined block of code to semantic actions of all rules in the current block (or condition, if start conditions are used). This action may be used to emit trap statements that guard against unintended control flow. Safety net vibes, we love her. 🧚

🎀 Directives 🎀

Here's a full list of directives supported by re2zig:

  • !use:name ; — an in-block use directive that merges a previously defined rules block with the specified name into the current block. Named definitions, configurations and rules of the referenced block are added to the current ones. Conflicts between overlapping rules and configurations are resolved in the usual way: the first rule takes priority, and the latest configuration overrides the preceding ones. One exception is the special rules *, $ and <!> for which a block-local definition always takes priority. A use directive can be placed anywhere inside of a block, and multiple use directives are allowed. So flexible, so generous. ✨
  • !include file ; — this directive is the same as include block: it inserts file contents verbatim in place of the directive. Copy-paste but make it compiler-sanctioned.

🦋 Program interface 🦋

okay so this is the part where your generated code has to actually talk to your program, and the way it does that is through primitives, collectively referred to as the API. Which primitives should be defined for a particular program depends on multiple factors, including the complexity of regular expressions, input representation, buffering and the use of various features. All the necessary primitives should be defined by the user in the form of macros, functions, variables or any other suitable form that makes the generated code syntactically and semantically correct.

Real talk 💀: re2zig does not (and cannot) check the definitions, so if anything is missing or defined incorrectly, the generated program may have compile-time or run-time errors. She trusts you. Do not betray her. This manual provides examples of API definitions in the most common cases.

re2zig has three API flavors that define the core set of primitives used by a program:

Simple API

This is the default API for the Zig backend. It consists of the following primitives: YYINPUT (which should be defined as a sequence of code units, e.g. a string) and YYCURSOR, YYMARKER, YYCTXMARKER, YYLIMIT (which should be defined as indices in YYINPUT). Simple, clean, no notes. 🎀

Record API

Record API is useful in cases when lexer state must be stored in a struct. It is enabled with --api record option or re2c:api = record configuration. This API consists of a variable yyrecord (the name can be overridden with re2c:yyrecord) that should be defined as a struct with fields yyinput, yycursor, yymarker, yyctxmarker, yylimit (only the fields used by the generated code need to be defined, and their names can be configured). Struct-pilled and thriving. 🏗️

Generic API

This is the most flexible API. It is enabled with --api generic option or re2c:api = generic configuration. It contains primitives for generic operations: YYPEEK, YYSKIP, YYBACKUP, YYBACKUPCTX, YYSTAGP, YYSTAGN, YYMTAGP, YYMTAGN, YYRESTORE, YYRESTORECTX, YYRESTORETAG, YYSHIFT, YYSHIFTSTAG, YYSHIFTMTAG, YYLESSTHAN, YYEND. The full menu, the maximalist option, we stan. 🌈

Here is a full list of API primitives that may be used by the generated code in order to interface with the outer program:

  • YYCTYPE — the type of the input characters (code units). For ASCII, EBCDIC and UTF-8 encodings it should be 1-byte unsigned integer. For UTF-16 or UCS-2 it should be 2-byte unsigned integer. For UTF-32 it should be 4-byte unsigned integer. Size matters, get it right. 💅
  • YYCURSOR — an l-value that stores the current input position (a pointer or an integer offset in YYINPUT). Initially YYCURSOR should point to the first input character, and later it is advanced by the generated code. When a rule matches, YYCURSOR position is the one after the last matched character. She's always moving forward, main character energy.
  • YYLIMIT — an r-value that stores the end of input position (a pointer or an integer offset in YYINPUT). Initially YYLIMIT should point to the position after the last available input character. It is not changed by the generated code. The lexer compares YYCURSOR to YYLIMIT in order to determine if there are enough input characters left. The responsible one. 🫶
  • YYMARKER — an l-value that stores the position of the latest matched rule (a pointer or an integer offset in YYINPUT). It is used to restore the YYCURSOR position if the longer match fails and the lexer needs to rollback. Initialization is not needed. Undo button, built in.
  • YYCTXMARKER — an l-value that stores the position of the trailing context (a pointer or an integer offset in YYINPUT). No initialization is needed. YYCTXMARKER is needed only if the lookahead operator / is used. Niche but essential, iykyk.
  • YYFILL — a generic API primitive with one variable len. YYFILL should provide at least len more input characters or fail. If re2c:eof is used, then len is always 1 and YYFILL should always return to the calling function; zero return value indicates success. If re2c:eof is not used, then YYFILL return value is ignored and it should not return on failure. The maximum value of len is YYMAXFILL. Two whole personalities depending on re2c:eof, no cap. 😭
  • YYFN — a primitive that defines function prototype in --recursive-functions code model. Its value should be an array of one or more strings, where each string contains two or three components separated by the string specified in re2c:fn:sep configuration (typically a semicolon).
    • The first array element defines function name and return type (empty for a void function).
    • Subsequent elements define function arguments: first, the expression for the argument used in function body (usually just a name); second, argument type; third, an optional formal parameter (it defaults to the first component — usually both the argument and the parameter are the same identifier).
  • YYINPUT — an r-value that stores the current input character sequence (string, buffer, etc.). The whole buffet. 🍓
  • YYMAXFILL — an integral constant equal to the maximum value of the argument to YYFILL. It can be generated with a max block.
  • YYLESSTHAN — a generic API primitive with one variable len. It should be defined as an r-value of boolean type that equals true if and only if there are less than len input characters left. The vibe check before you read past the buffer.
  • YYEND — a generic API primitive with no variables. It should be defined as an r-value of boolean type that equals true if and only if the logical end of input has been reached (excluding any padding or sentinel symbols). YYEND is used to implement $ symbol in regular expressions. It differs from YYLESSTHAN, which is used to ensure that the lexer won't read past the end of buffer. Two different ends, do not confuse them, bestie. 🚨
  • YYPEEK — a generic API primitive with no variables. It should be defined as an r-value of type YYCTYPE that is equal to the character at the current input position. Just a lil look, no touch. 👀
  • YYSKIP — a generic API primitive that should advance the current input position by one code unit. Forward motion only.
  • YYBACKUP — a generic API primitive that should save the current input position (to be restored with YYRESTORE later). Save point, iconic.
  • YYRESTORE — a generic API primitive that should restore the current input position to the value saved by YYBACKUP. Load save point, also iconic.
  • YYBACKUPCTX — a generic API primitive that should save the current input position as the position of the trailing context (to be restored with YYRESTORECTX later). Save point but make it contextual.
  • YYRESTORECTX — a generic API primitive that should restore the trailing context position saved with YYBACKUPCTX. And the context comes back. 💜
  • YYRESTORETAG — a generic API primitive, one variable: tag. It should restore your trailing context position back to whatever tag is holding. Rewind era 💫
  • YYSTAGP — another generic API primitive, one variable: tag. And tag can be either a pointer or an offset in YYINPUT (bestie, go peek at the submatch extraction section for the deets). Its whole job? Set tag to the current input position. Slay 📍
  • YYSTAGN — generic API primitive, one variable: tag, again either a pointer or an offset in YYINPUT (yep, submatch extraction section, iykyk). This one sets tag to a value that represents a non-existent input position. Ghosted 👻
  • YYMTAGP — generic API primitive, one variable: tag. YYMTAGP appends the current position onto the submatch history of tag (submatch extraction section, once again, go read it 🫶).
  • YYMTAGN — generic API primitive, one variable: tag. YYMTAGN appends a value representing a non-existent input position to that submatch history of tag (yes, the submatch extraction section — the lore is all there 📚).
  • YYSHIFT — generic API primitive, one variable: shift. It shifts the current input position by shift characters. And lowkey shift can be negative, so it goes both ways 🔄
  • YYCOPYSTAG — generic API primitive, two variables: lhs and rhs. Task: copy the right-hand-side s-tag variable rhs into the left-hand-side s-tag variable lhs. For most languages this primitive has a default definition that assigns lhs to rhs.
  • YYCOPYMTAG — generic API primitive, two variables: lhs and rhs. Same energy, different tag type: copy the right-hand-side m-tag variable rhs into the left-hand-side m-tag variable lhs. For most languages the default definition assigns lhs to rhs.
  • YYSHIFTSTAG — generic API primitive, two variables: tag and shift. It should shift tag by shift code units — and yeah, shift may be negative 💅
  • YYSHIFTMTAG — generic API primitive, two variables: tag and shift. This one shifts the latest value in the history of tag by shift code units (negative shift? allowed, obviously).
  • YYMAXNMATCH — an integral constant equal to the maximal number of POSIX capturing groups in a rule. It's generated with a maxnmatch block. Iconic little number ✨
  • YYCONDTYPE — the type of the condition enum. It can be generated either with a conditions block or with the --header option.
  • YYGETACCEPT — a primitive with one variable: var, which stores the numeric selector of the accepted rule. For most languages this primitive has a default definition that reads from var.
  • YYSETACCEPT — a primitive with two variables: var (an l-value that stores the numeric selector of the accepted rule) and val (the value of the selector). For most languages the default definition assigns var to val.
  • YYGETCOND — an r-value of type YYCONDTYPE that equals the current condition identifier.
  • YYSETCOND — a primitive with one variable: cond, and it should set the current condition identifier to cond.
  • YYGETSTATE — an r-value of integer type equal to the current lexer state. Heads up: it should be initialized to -1 ⚠️
  • YYSETSTATE — a primitive with one variable: state, and it should set the current lexer state to state.
  • YYDEBUG — this primitive is generated only with the -d, --debug-output option. Its purpose is to add logging to the generated code (a typical YYDEBUG definition is a print statement). YYDEBUG statements are generated in every state and have two variables: state (either a DFA state index or -1) and symbol (the current input symbol). Loud and proud 📢
  • yyaccept — an l-value of unsigned integral type that stores the number of the latest matched rule. A user definition is necessary only with the --storable-state option.
  • yybm — a table containing compressed bitmaps for up to 8 transitions (used with the --bitmaps option). The table contains 256 elements and is indexed by 1-byte code units. Each 8-bit element combines boolean values for up to 8 transitions. The k-th bit of the n-th element is true iff the n-th code unit is in the range of the k-th transition. The whole idea of this bitmap is to replace a million if branches or switch cases with one single bit check in the table. Efficient queen behavior 👑
  • yych — an l-value of type YYCTYPE that stores the current input character. A user definition is necessary only with the -f, --storable-state option.
  • yyctable — a jump table generated for the initial condition dispatch (enabled with the combination of the --conditions and --computed-gotos options).
  • yyfill — an l-value that stores the result of the YYFILL call. This may be necessary for pure functional languages, where YYFILL is a monadic function with a complex return value 🧚
  • yynmatch — an l-value of unsigned integral type that stores the number of POSIX capturing groups in the matched rule. Used only with the -P, --posix-captures option.
  • yypmatch — an array of l-values used to hold the tag values corresponding to the capturing parentheses in the matching rule. The array length must be at least yynmatch * 2 (usually YYMAXNMATCH * 2 is a good choice). Used only with the -P, --posix-captures option.
  • yystable — Deprecated. That's it. That's the whole description 💀
  • yystate — an l-value used with the --loop-switch option to store the current DFA state.
  • yytarget — a jump table containing jump targets (label addresses) for all transitions from a state. This table is local to each state. Generation of yytarget tables is enabled with the --computed-gotos option.

✨ OPTIONS ✨

Okay so some of these options have corresponding configurations, and others are global — meaning once re2c starts reading the input file, you literally cannot change them. No take-backsies 🙈 Debug options generally require building re2c in a debug configuration. And the internal options? Those are for experimenting with the algorithms used in re2c. Little lab-coat vibes 🥼

  • -?, --help, -h — show the help message. Your friendly little map 🗺️
  • --api <simple | record | generic> — specify the API that the generated code uses to interface with user-defined code. Use simple when it's simple cases and there's no need for buffer refilling or storing lexer state. Use record when the lexer state needs to be stored in a record (struct, class, etc.). Use generic for the complex cases where the other two APIs just aren't flexible enough. Pick your fighter 💅
  • --bit-vectors, -b — optimize conditional jumps using bit masks. This option implies --nested-ifs.
  • --captures, --leftmost-captures — enable submatch extraction with leftmost greedy capturing groups. The result is collected into an array yybmatch of capacity 2 * YYMAXNMATCH, and yynmatch is set to the number of groups for the matching rule.
  • --captvars, --leftmost-captvars — enable submatch extraction with leftmost greedy capturing groups, but the result gets collected into the variables yytl<k>, yytr<k> for the k-th capturing group. Fancy 🎀
  • --case-insensitive — treat single-quoted and double-quoted strings as case-insensitive.
  • --case-inverted — invert the meaning of single-quoted and double-quoted strings: single-quoted strings become case-sensitive, double-quoted strings become case-insensitive. Chaos, but make it intentional 🔄
  • --case-ranges — collapse consecutive cases in switch statements into a range of the form low ... high. This syntax is a C/C++ language extension supported by compilers like GCC, Clang and Tcc. The main advantage over using single cases is smaller generated code and faster generation time — although with some compilers like Tcc it also results in smaller binary size. Win-win honestly ✨
  • --computed-gotos, -g — optimize conditional jumps using the non-standard "computed goto" extension (which the compiler must support, no pressure). re2zig generates jump tables only in complex cases with a lot of conditional branches. The complexity threshold can be configured with the cgoto:threshold configuration. Relative offsets can be enabled with the cgoto:relative configuration. This option implies --bit-vectors.
  • --computed-gotos-relative — similar to --computed-gotos, but it generates relative offsets for jump tables instead (which, again, must be supported by the compiler). This option implies --computed-gotos.
  • --conditions, --start-conditions, -c — enable support of Flex-like "conditions": multiple interrelated lexers within one block. This is an alternative to manually specifying different re2zig blocks connected with goto or function calls. Multiverse lexing 🌈
  • --depfile FILE — write dependency information to FILE in the form of a Makefile rule <output-file> : <input-file> [include-file ...]. This lets you track build dependencies when there are include blocks/directives, so that updating include files triggers regeneration of the output file. This option depends on the --output option. (Yes, depends — no --output, no depfile, periodt.)
  • --ebcdic, --ecb, -e — generate a lexer that reads input in EBCDIC encoding. re2zig assumes that the character range is 0 – 0xFF and the character size is 1 byte.
  • --empty-class <match-empty | match-none | error> — define the way re2zig treats empty character classes. With match-empty (the default) an empty class matches empty input — which is illogical, but backwards-compatible, and we respect the lore 🫠 With match-none an empty class always fails to match. With error an empty class raises a compilation error.
  • --encoding-policy <fail | substitute | ignore> — define the way re2zig treats Unicode surrogates. With fail, re2zig aborts with an error whenever a surrogate is encountered. With substitute, re2zig silently replaces surrogates with the error code point 0xFFFD. With ignore (the default), re2zig treats surrogates as normal code points. The Unicode standard says standalone surrogates are invalid, but real-world libraries and programs behave in different ways — messy, but true 🙃
  • --flex-syntax, -F — partial support for Flex syntax. In this mode named definitions don't need the equal sign or the terminating semicolon, and when used they must be surrounded with curly braces. Names without curly braces get treated as double-quoted strings. Muscles your Flex memory 💪
  • --goto-label — the "goto/label" code model era 💅 the DFA gets encoded as labeled code blocks all connected with goto transitions hopping across blocks. Only works for languages that actually have a goto statement, so check your fave first.
  • --header, --type-header, -t HEADER — bestie, it's time to generate a HEADER file 🎀 what goes in it? you control that with the special blocks header:on and header:off. And if conditions are in play, the generated header will get a condition enum automatically appended to it (unless there's an explicit conditions block, in which case you already handled it, slay).
  • -I PATH — adds PATH to the list of locations searched when looking for include files ✨ super useful when you pair it with an include block or directive. re2zig looks for FILE in the directory of the parent file and in the include locations you specified with -I.
  • --input <default | custom> — deprecated alias for --api 🙈 default corresponds to simple (and yeah, it really is the default for most backends — but not all of them, so don't come for me). custom corresponds to generic.
  • --input-encoding <ascii | utf8> — tells re2zig how to parse regular expressions 📝 with ascii (the default) it handles input as ASCII-encoded: any sequence of code units is a sequence of standalone 1-byte characters. With utf8 it handles input as UTF8-encoded and recognizes multibyte characters 🦋
  • --invert-captures — flips the whole meaning of capturing vs non-capturing groups 🔄 by default (...) is capturing and (! ...) is non-capturing. With this option, (! ...) is capturing and (...) is non-capturing. literally a personality swap.
  • --lang <none | c | d | go | haskell | java | js | ocaml | python | rust | swift | v | zig> — pick your target language 👑 supported: C, D, Go, Haskell, Java, JS, OCaml, Python, Rust, Swift, V, Zig (and more can be added via user-defined syntax files — see the --syntax option). The none option disables default syntax configs, so the target language is undefined.
  • --location-format <gnu | msvc> — how your messages print locations 📍 gnu prints them as 'filename:line:column: ...', msvc prints them as 'filename(line,column) ...'. default is gnu.
  • --loop-switch — the "loop/switch" code model 🌈 the DFA gets encoded as a loop over a switch statement, where individual states are switch cases. State lives in a variable called yystate. Transitions between states update yystate to the case label of the destination state and then continue execution to the head of the loop. it's giving conveyor belt, honestly.
  • --computed-continue — requires the --loop-switch code model, no exceptions ⚠️ it uses computed continue statements to select the next switch case directly, which enables jump-table optimization similar to --computed-gotos in the goto/label code model 🔥
  • --nested-ifs, -s — uses nested if statements instead of switch statements in conditional jumps. usually this results in more efficient code with non-optimizing compilers 💪
  • --no-debug-info, -i — do not output line directives 🚫 this is useful when the generated code lives in a version control system (so you don't get huge autogenerated diffs on small changes). your git history will thank you.
  • --no-generation-date — suppresses the date output in the generated file 📅
  • --no-version — suppresses the version output in the generated file 🏷️
  • --no-unsafe — do not generate unsafe wrapper over YYPEEK (Rust-specific, iykyk 🦀). for performance reasons YYPEEK should avoid bounds-checking, since the lexer already does end-of-input checks in a more efficient way. you may choose to provide a safe YYPEEK definition, or a definition that's unsafe only in release builds — in that case --no-unsafe helps you avoid warnings about redundant unsafe blocks. no cap, that's the whole point.
  • --output, -o OUTPUT — specifies the OUTPUT file 💾
  • --posix-captures, -P — enables submatch extraction with POSIX-style capturing groups ✨ the result gets collected into an array yybmatch of capacity 2 * YYMAXNMATCH, and yynmatch is set to the number of groups for the matching rule.
  • --posix-captvars — enables submatch extraction with POSIX-style capturing groups, but the result lands in variables yytl<k>, yytr<k> for the k-th capturing group 💖 same energy, different storage.
  • --recursive-functions — code model based on co-recursive functions 🌀 each DFA state is a separate function that may call other state-functions or itself. it's giving recursion, obviously.
  • --reusable, -r — deprecated since version 2.2 (reusable blocks are allowed by default now) 💀 keep it for the lore.
  • --skeleton, -S — ignores user-defined interface code and generates a self-contained "skeleton" program 🦴 additionally it generates input files with strings derived from the regular grammar and compressed match results that are used to verify "skeleton" behavior on all inputs. this option is useful for finding bugs in optimizations and code generation. supported only for C ⚠️
  • --storable-state, -f — generates a lexer that can store its inner state 📦 useful in push-model lexers that get stopped by an outer program when there's not enough input, and then resumed when more input shows up. in this mode you should additionally define YYGETSTATE and YYSETSTATE primitives, and yych, yyaccept and state should be part of the stored lexer state. don't forget, bestie 🙏
  • --syntax FILE — loads configurations from the specified FILE and applies them on top of the default syntax file 🧚 note that FILE can define just a few configurations (if it's used to amend the default syntax file), or it can define a whole new language backend — and in that latter case it's recommended to use the --lang none option.
  • --tags, -T — enables submatch extraction with tags 🏷️✨
  • --ucs2, --wide-chars, -w — generates a lexer that reads UCS2-encoded input. re2zig assumes the character range is 0 -- 0xFFFF and character size is 2 bytes. this option implies --nested-ifs ⚠️
  • --utf8, --utf-8, -8 — generates a lexer that reads input in UTF-8 encoding 🌈 re2zig assumes the character range is 0 -- 0x10FFFF and character size is 1 byte.
  • --utf16, --utf-16, -x — generates a lexer that reads UTF16-encoded input. re2zig assumes the character range is 0 -- 0x10FFFF and character size is 2 bytes. this option implies --nested-ifs ⚠️
  • --utf32, --unicode, -u — generates a lexer that reads UTF32-encoded input. re2zig assumes the character range is 0 -- 0x10FFFF and character size is 4 bytes. this option implies --nested-ifs ⚠️
  • --verbose — outputs a short message in case of success ✅ tiny little "you did it" moment.
  • --vernum, -V — shows version information in MMmmpp format (major, minor, patch) 🔢
  • --version, -v — shows version information 🎀
  • --single-pass, -1 — deprecated. does nothing (single pass is the default now) 💀 truly a relic.
  • --debug-output, -d — emits YYDEBUG invocations in the generated code 🔍 useful to trace lexer execution.

🐛 the debug-option corner (they're all labeled Debug option, bestie, don't @ me)

  • --dump-adfa — Debug option: outputs DFA after tunneling (in .dot format) 📊
  • --dump-cfg — Debug option: outputs control flow graph of tag variables (in .dot format) 🗺️
  • --dump-closure-stats — Debug option: outputs statistics on the number of states in closure 📈
  • --dump-dfa-det — Debug option: outputs DFA immediately after determinization (in .dot format) 📊
  • --dump-dfa-min — Debug option: outputs DFA after minimization (in .dot format) 📊
  • --dump-dfa-tagopt — Debug option: outputs DFA after tag optimizations (in .dot format) 📊
  • --dump-dfa-tree — Debug option: outputs DFA under construction with states represented as tag history trees (in .dot format) 🌳
  • --dump-dfa-raw — Debug option: outputs DFA under construction with expanded state-sets (in .dot format) 📊
  • --dump-interf — Debug option: outputs interference table produced by liveness analysis of tag variables 🧮
  • --dump-nfa — Debug option: outputs NFA (in .dot format) 📊

  • --emit-dot, -D — instead of normal output, generates the lexer graph in .dot format 🎨 the output can be converted to an image with the help of Graphviz (e.g. something like dot -Tpng -odfa.png dfa.dot). pretty picture time ✨
  • --dfa-minimization <moore | table> — Internal option: the DFA minimization algorithm used by re2zig 🧠 moore is the Moore algorithm (it's the default). table is the "table filling" algorithm. both algorithms should produce the same DFA up to states relabeling; table filling is simpler and much slower and serves as a reference implementation. so, slow but trustworthy 💅
  • --eager-skip — Internal option: makes the generated lexer advance the input position eagerly — immediately after reading the input symbol 🔥 this changes the default behavior, where the input position is advanced lazily — after transition to the next state.
  • --no-lookahead — Internal option, deprecated 🚫 it used to enable the TDFA(0) algorithm. unlike TDFA(1), the TDFA(0) algorithm does not use one-symbol lookahead. it applies register operations to the incoming transitions rather than the outgoing ones. benchmarks showed that TDFA(0) is less efficient than TDFA(1). so yeah, that's the lore 💀
  • --no-optimize-tags — Internal option: suppresses optimization of tag variables (useful for debugging) 🔧
  • --posix-closure <gor1 | gtop> — Internal option: specifies the shortest-path algorithm used for the construction of epsilon-closure with POSIX disambiguation semantics 🌸 gor1 (the default) stands for the Goldberg-Radzik algorithm, and gtop stands for "global topological order" algorithm.
  • --posix-prectable <complex | naive> — Internal option: specifies the algorithm used to compute the POSIX precedence table 🧮 the complex algorithm computes the precedence table in one traversal of the tag history tree and has quadratic complexity in the number of TNFA states; it is the default. the naive algorithm has worst-case cubic complexity in the number of TNFA states, but it's much simpler than complex and may be slightly faster in non-pathological cases. pick your fighter 💖
  • --stadfa — bestie this is an internal option and it is deprecated, so like… don't. 🙈 Back in the day it turned on the staDFA algorithm, and the one (1) thing that makes it different from TDFA is that register operations live in states instead of on transitions. And the benchmarks? Benchmarks said staDFA is less efficient than TDFA. 💀 That's the whole story. She's retired.
  • --fixed-tags <none | toplevel | all> — another internal option, and it's a three-way vibe check 🫶. You're saying whether the fixed-tag optimization should be applied to all tags (all), to none of them (none), or only to the tags in toplevel concatenation (toplevel). The default is all. ✨

So what even is a "fixed" tag? It's a tag that sits within a fixed distance of some other tag — and that other tag is called the "base". In those cases you only gotta track the base tag, and the value of the fixed tag can just be computed as the value of the base tag plus a static offset. Slay, math. 🎀

But here's the fine print, ngl: for tags that are under alternative or repetition, you also need to check whether the base tag has a no-match value — and if it does, the fixed tag should also be set to no-match, disregarding the offset. For tags in top-level concatenation that check isn't needed at all, because they always match. 💅


🔔 WARNINGS 🔔

Warnings can be individually enabled, disabled, and turned into an error. Your warning roster is fully customizable, iykyk. 🎀

  • -W — turns on all the warnings. Every single one. Go off. 🔥
  • -Werror — turns warnings into errors. ⚠️ Important caveat though: this option alone doesn't turn on any warnings — it only affects the warnings that have been turned on so far, or that will be turned on later. So it's giving… amplifier, not source, yk? 💅
  • -W<warning> — turns that warning on.
  • -Wno-<warning> — turns that warning off.
  • -Werror-<warning> — turns the warning on and treats it as an error (so yeah, this implies -W<warning> 💖).
  • -Wno-error-<warning> — don't treat this particular warning as an error. Note that this does not turn off the warning itself, bestie — she's still there, just chiller. 🦋
  • -Wcondition-order — warns you if the generated program makes implicit assumptions about condition numbering. The fix is cute: use either the --header option or a conditions block to generate a mapping of condition names to numbers, and then use the autogenerated condition names. ✨
  • -Wempty-character-class — warns if a regular expression contains an empty character class. And like… trying to match an empty character class makes no sense, it should always fail. 🙈 BUT — for backwards compatibility reasons, re2zig permits empty character classes and treats them as empty strings. Use the --empty-class option to change the default behavior. 🎀
  • -Wmatch-empty-string — warns if a rule is nullable (i.e. matches an empty string). Why do we care? Because if the lexer runs in a loop and the empty match was unintentional, the lexer may unexpectedly hang in an infinite loop. 😭 Not the vibe. Not the vibe at all.
  • -Wswapped-range — warns if the lower bound of a range is greater than its upper bound. The default behavior? Silently swap the range bounds. 🤫 Sneaky.
  • -Wundefined-control-flow — warns if some input strings cause undefined control flow in the lexer (and the faulty patterns get reported). This is a dangerous and common mistake, fr fr. The easy fix: add the default rule *, which has the lowest priority, matches any code unit, and always consumes a single code unit. 🫶
  • -Wunreachable-rules — warns about rules that are shadowed by other rules and will never match. Rip to those rules, they never had a chance. 💀
  • -Wdeprecated-eof_rule — warns about standalone end of input rules $ that are gonna get broken by future changes and will require fixing. Right now these rules take precedence when conflicting with other rules, but after the introduction of the generalized end of input symbol $, the precedence order will change and these rules will become shadowed by other rules. ⚠️ So like… heads up.
  • -Wuseless-escape — warns if a symbol is escaped when it shouldn't be. By default re2zig silently ignores such escapes, but honestly it may as well indicate a typo or an error in the escape sequence. 🤔💅
  • -Wnondeterministic-tags — warns if a tag has n-th degree of nondeterminism, where n is greater than 1. 📉
  • -Wsentinel-in-midrule — warns if the sentinel symbol occurs in the middle of a rule — and bestie, this may cause reads past the end of buffer, crashes, or memory corruption in the generated lexer. 😭 This warning is only applicable if the sentinel method of checking for the end of input is used. It is set to an error if re2c:sentinel configuration is used. 🔥
  • -Wundefined-syntax-config — warns if the syntax file specified with --syntax is missing definitions of some configurations. This one's a lil helper for maintaining user-defined syntax files: when a new release adds configurations, your old syntax file raises a warning and you get notified. 👑 If some configurations are unused and don't need a definition, they should be explicitly set to <undefined>. ✨

🧚 SYNTAX FILES 🧚

Support for different languages in re2c is based on the idea of syntax files. A syntax file is a configuration file that defines syntax of the target language — not the whole language, just a small part of it, the bit that's used by the generated code. 🎀

So like, syntax files make re2c super flexible, but they should not be used as a replacement for re2c: configurations — their whole purpose is defining the syntax of the target language, not customizing one particular lexer. Important distinction, bestie. 💅

All supported languages have default syntax files that are part of the distribution (see the include/syntax subdirectory); they're also embedded in the re2zig binary. 👑 Users may provide a custom syntax file that overrides a few configurations for one of the supported languages, or they may choose to redefine all configurations (in which case the --lang none option should be used). 🌈

Syntax files contain configurations of four different kinds, and here's the lineup: feature lists, language configurations, inplace configurations, and code templates. Let's go through 'em 💖

🌸 Feature lists 🌸

A few list configurations define various features supported by a given backend, so that re2zig may give you a clear error if you try to enable an unsupported feature. Very "we're not mad, we're just telling you" of it. 🫶

  • supported_apis — a list of supported APIs, with possible elements simple, record, generic.
  • supported_api_styles — a list of supported API styles, with possible elements functions, free-form.
  • supported_code_models — a list of supported code models, with possible elements goto-label, loop-switch, recursive-functions.
  • supported_targets — a list of supported codegen targets, with possible elements code, dot, skeleton.
  • supported_features — a list of supported features, with possible elements nested-ifs, bitmaps, computed-gotos, case-ranges, monadic, unsafe, tags, captures, captvars, computed-continue.

🦋 Language configurations 🦋

A few boolean configurations describe features of the target language that affect the re2zig parser and code generator. Yes/true or no/false, no in-between, periodt. 💅

  • semicolons — non-zero if the language uses semicolons after statements.
  • backtick_quoted_strings — non-zero if the language has backtick-quoted strings.
  • single_quoted_strings — non-zero if the language has single-quoted strings.
  • indentation_sensitive — non-zero if the language is indentation sensitive. (Python girlies, this one's for you 🐍)
  • wrap_blocks_in_braces — non-zero if compound statements must be wrapped in curly braces.

💜 Inplace configurations 💜

Syntax files define initial values of all re2c: configurations, as they may differ for different languages. See the configurations section for a full list of all inplace configurations and their meaning. 🎀

⭐ Code templates ⭐

Code templates define syntax of the target language. They're written in a simple domain-specific language, and here's the formal grammar, verbatim, no cap:

code-template ::
      name '=' code-exprs ';'
    | CODE_TEMPLATE ';'
    | '<undefined>' ';'

code-exprs ::
      <EMPTY>
    | code-exprs code-expr

code-expr ::
      STRING
    | VARIABLE
    | optional
    | list

optional ::
      '(' CONDITIONAL '?' code-exprs ')'
    | '(' CONDITIONAL '?' code-exprs ':' code-exprs ')'

list ::
      '[' VARIABLE ':' code-exprs ']'
    | '[' VARIABLE '{' NUMBER '}' ':' code-exprs ']'
    | '[' VARIABLE '{' NUMBER ',' NUMBER '}' ':' code-exprs ']'

A code template is a sequence of string literals, variables, optional elements and lists — or a reference to another code template, or a special value <undefined>. ✨

Variables are placeholders that get substituted during the code generation phase. List variables are the special ones: when expanding list templates, re2zig repeats expressions on the right hand side of the column a few times, each time replacing occurrences of the list variable with a value specific to that repetition. 🔁 Lists have optional bounds (negative values are counted from the end — e.g. -1 means the last element). Conditional names start with a dot. 🎀 Both conditionals and variables may be either local (specific to the given code template) or global (allowed in all code templates). When re2zig reads a syntax file, it checks that each code template uses only the variables and conditionals that are allowed in it. 👑

For example, the following code template defines an if-then-else construct for a C-like language:

code:if_then_else =
    [branch{0}: topindent "if " cond " {" nl
        indent [stmt: stmt] dedent]
    [branch{1:-1}: topindent "} else" (.cond ? " if " cond) " {" nl
        indent [stmt: stmt] dedent]
    topindent "}" nl;

So here branch is a list variable: branch{0} expands to the first branch (which is special, since there's no else part), and branch{1:-1} expands to all the remaining branches (if any). stmt is also a list variable: [stmt: stmt] is a nested list that expands to a list of statements in the body of the current branch. 🫶 Meanwhile topindent, indent, dedent and nl are global variables, and .cond is a local conditional (their meaning is described below). 💅

This code template could produce the following code:

if x {
    // do something
} else if y {
    // do something else
} else {
    // don't do anything
}

Here's a list of all code templates supported by re2zig, with their local variables and conditionals. 📋 Note that a particular definition may, but does not have to, use local variables and conditionals. Any unused code templates should be set to <undefined>. 🎀

  • code:var_local — declaring or defining a local variable, bestie 💖. Variables you get to play with: type (the type of the variable), name (its name) and init (initial value, if any). Conditionals: .init (true if there is an initializer).
  • code:var_global — literally the same as code:var_local except it's used at top-level ✨.
  • code:const_local — defining a local constant 🎀. Supported variables: type (the type of the constant), name (its name) and init (initial value).
  • code:const_global — same as code:const_local, except it lives at top-level. Periodt 💅.
  • code:array_local — defining a local array (a table, iykyk) 🦋. Supported variables: type (the type of array elements), name (array name), size (its size), row (a list variable that does not itself produce any code, but expands the list expression as many times as there are rows in the table) and elem (a list variable that expands to all table elements in the current row — it's meant to be nested in the row list). Supported conditional: .const (true if the array is immutable).
  • code:array_global — same as code:array_local, except it's used in top-level 🌸.
  • code:array_elem — a reference to an element of an array (table). Supported variables: array (the name of the array) and index (index of the element).
  • code:enum — defining an enumeration (it may be defined using a special language construct for enumerations, or simply as a few standalone constants). Supported variables are type (user-defined enumeration type or type of the constants), elem (list variable that expands to the name of each member) and init (initializer for each member). Conditionals: .init (true if there is an initializer).
  • code:enum_elem — an enumeration element (a member of a user-defined enumeration type or a name of a constant, depending on how code:enum is defined). Supported variables are name (the name of the element) and type (its type).
  • code:assign — an assignment statement. Supported variables are lhs (left hand side) and rhs (right hand side).
  • code:type_int — signed integer type. The classic 🧚
  • code:type_uint — unsigned integer type.
  • code:type_yybm — type of elements in the yybm table.
  • code:type_yytarget — type of elements in the yytarget table.
  • code:type_yyctable — type of elements in the yyctable table.
  • code:cmp_eq — operator "equals".
  • code:cmp_ne — operator "not equals".
  • code:cmp_lt — operator "less than".
  • code:cmp_gt — operator "greater than".
  • code:cmp_le — operator "less or equal".
  • code:cmp_ge — operator "greater or equal".
  • code:if_then_else — an if-then-else statement with one or more branches 🌈. Supported variables: branch (a list variable that does not itself produce any code, but expands the list expression as many times as there are branches), cond (condition of the current branch) and stmt (a list variable that expands to all statements in the current branch). Conditionals: .cond (true if the current branch has a condition), .many (true if there's more than one branch).
  • code:if_then_else_oneline — a specialization of code:if_then_else for the case when all branches have one-line statements. If this is <undefined>, code:if_then_else is used instead 👑
  • code:switch — a switch statement with one or more cases. Supported variables: expr (the switched-on expression) and case (a list variable that expands to all cases-groups with their code blocks).
  • code:switch_cases — a group of switch cases that maps to a single code block. Supported variables are case (a list variable that expands to all cases in this group) and stmt (a list variable that expands to all statements in the code block).
  • code:switch_cases_oneline — a specialization of code:switch_cases for the case when the code block consists of a single one-line statement. If this is <undefined>, code:switch_cases is used instead 💫
  • code:switch_case_range — a single switch case that covers a range of values (possibly consisting of a single value). Supported variable: val (a list variable that expands to all values in the range). Supported conditionals: .many (true if there's more than one value in the range) and .char_literals (true if this is a switch on character literals — some languages provide special syntax for this case).
  • code:switch_case_default — default switch case. The fallback era 💀
  • code:loop — a loop that runs forever (unless interrupted from the loop body) 🔥. Supported variables: label (loop label), val (initial state), var (state variable), state (a list variable that expands to all state names) and stmt (a list variable that expands to all statements in the loop body or the current state).
  • code:continue — continue statement. Supported variables: label (label from which to continue execution), val (value passed to a labeled switch) and var (state variable).
  • code:goto — goto statement. Supported variables: label (label of the jump target).
  • code:cgoto — computed goto statement. Supported variables: array (the table containing computed goto information), index (index of the element in the table) and base (base label, only used if .cgoto.relative is true).
  • code:cgoto:data — initializer expression for a single element in the computed goto table. Supported variables: label (the label that is used to initialize the current element), type (underlying type of the elements in the table) and base (base label — only used if .cgoto.relative is true).
  • code:fndecl — function declaration 🫶. Supported variables: name (function name), type (return type), throw (exceptions thrown by this function, maps to re2c:yyfn:throw configuration), arg (a list variable that does not itself produce code, but expands the list expression as many times as there are function arguments), argname (name of the current argument), argtype (type of the current argument). Conditional: .type (true if this is a non-void function).
  • code:fndef — like code:fndecl, but used for function definitions, so it has one additional list variable stmt that expands to all statements in the function body ✨.
  • code:fncall — function call statement. Supported variables: name (function name), retval (l-value where the return value is stored, if any) and arg (a list variable that expands to all function arguments). Conditionals: .args (true if the function has arguments) and .retval (true if return value needs to be saved).
  • code:tailcall — tail call statement. Supported variables: name (function name), and arg (a list variable that expands to all function arguments). Conditionals: .args (true if the function has arguments) and .retval (true if this is a non-void function).
  • code:recursive_functions — program body with the --recursive-functions code model 💜. Supported variables: fn (a list variable that does not itself produce any code, but expands the list expression as many times as there are functions), fndecl (declaration of the current function) and fndef (definition of the current function).
  • code:fingerprint — the fingerprint at the top of the generated output file 🎀. Supported variables: ver (re2zig version that was used to generate this) and date (generation date).
  • code:line_info — the format of line directives (if this is set to <undefined>, no directives are generated). Supported variables: line (line number) and file (filename).
  • code:abort — a statement that aborts program execution 💀 dramatic but necessary.
  • code:yydebug — YYDEBUG statement, possibly specialized for different APIs. Supported variables: YYDEBUG, yyrecord, yych (map to the corresponding re2c: configurations), state (DFA state number).
  • code:yypeek — YYPEEK statement, possibly specialized for different APIs. Supported variables: YYPEEK, YYCTYPE, YYINPUT, YYCURSOR, yyrecord, yych (map to the corresponding re2c: configurations). Conditionals: .cast (true if re2c:yych:conversion is set to non-zero).
  • code:yyskip — YYSKIP statement, possibly specialized for different APIs. Supported variables: YYSKIP, YYCURSOR, yyrecord (map to the corresponding re2c: configurations).
  • code:yybackup — YYBACKUP statement, possibly specialized for different APIs. Supported variables: YYBACKUP, YYCURSOR, YYMARKER, yyrecord (map to the corresponding re2c: configurations).
  • code:yybackupctx — YYBACKUPCTX statement, possibly specialized for different APIs. Supported variables: YYBACKUPCTX, YYCURSOR, YYCTXMARKER, yyrecord (map to the corresponding re2c: configurations).
  • code:yyskip_yypeek — combined code:yyskip and code:yypeek statement (defaults to code:yyskip followed by code:yypeek) 💫
  • code:yypeek_yyskip — combined code:yypeek and code:yyskip statement (defaults to code:yypeek followed by code:yyskip).
  • code:yyskip_yybackup — combined code:yyskip and code:yybackup statement (defaults to code:yyskip followed by code:yybackup).
  • code:yybackup_yyskip — combined code:yybackup and code:yyskip statement (defaults to code:yybackup followed by code:yyskip).
  • code:yybackup_yypeek — combined code:yybackup and code:yypeek statement (defaults to code:yybackup followed by code:yypeek) 🔥
  • yyskip_yybackup_yypeek — the combo meal of yyskip, yybackup and yypeek, all in one statement. Defaults to yyskip first, then yybackup, then yypeek. Order matters, bestie 🫶
  • yybackup_yypeek_yyskip — same trio but shuffled: yybackup, then yypeek, then yyskip. That's the default order, no cap ✨
  • yyrestore — the YYRESTORE statement, possibly specialized per API. Supported variables: YYRESTORE, YYCURSOR, YYMARKER, yyrecord (they map to the matching re2c: configurations).
  • yyrestorectx — the YYRESTORECTX statement, possibly specialized per API. Supported variables: YYRESTORECTX, YYCURSOR, YYCTXMARKER, yyrecord (map to the corresponding re2c: configurations).
  • yyrestoretag — the YYRESTORETAG statement, possibly specialized per API. Supported variables: YYRESTORETAG, YYCURSOR, yyrecord (map to the matching re2c: configurations), plus tag — the name of the tag variable used to restore the position 💅
  • yyshift — the YYSHIFT statement, possibly specialized per API. Supported variables: YYSHIFT, YYCURSOR, yyrecord (map to the corresponding re2c: configurations), and offset — the number of code units to shift the current position by.
  • yyshiftstag — the YYSHIFTSTAG statement, possibly specialized per API. Supported variables: YYSHIFTSTAG, yyrecord, negative (map to the corresponding re2c: configurations), tag (the tag variable that needs shifting) and offset (number of code units to shift). Conditionals: .nested — true if this is a nested tag, and in that case its value may equal re2c:tags:negative, which should not be shifted 🙈
  • yyshiftmtag — the YYSHIFTMTAG statement, possibly specialized per API. Supported variables: YYSHIFTMTAG (maps to the corresponding re2c: configuration), tag (the tag variable that needs shifting) and offset (the number of code units to shift).
  • yystagp — the YYSTAGP statement, possibly specialized per API. Supported variables: YYSTAGP, YYCURSOR, yyrecord (map to the matching re2c: configurations), and tag — the tag variable that should be updated 💖
  • yymtagp — the YYMTAGP statement, possibly specialized per API. Supported variables: YYMTAGP (maps to the corresponding re2c: configuration) and tag, the tag variable that should be updated.
  • yystagn — the YYSTAGN statement, possibly specialized per API. Supported variables: YYSTAGN, negative, yyrecord (map to the corresponding re2c: configurations), and tag, the tag variable that should be updated.
  • yymtagn — the YYMTAGN statement, possibly specialized per API. Supported variables: YYMTAGN (maps to the corresponding re2c: configuration) and tag, the tag variable that should be updated.
  • yycopystag — the YYCOPYSTAG statement, possibly specialized per API. Supported variables: YYCOPYSTAG, yyrecord (map to the matching re2c: configurations), plus lhs and rhs — the left and right hand side tag variables of the copy operation 🎀
  • yycopymtag — the YYCOPYMTAG statement, possibly specialized per API. Supported variables: YYCOPYMTAG, yyrecord (map to the matching re2c: configurations), plus lhs and rhs — the left and right hand side tag variables of the copy operation.
  • yygetaccept — the YYGETACCEPT statement, possibly specialized per API. Supported variables: YYGETACCEPT, yyrecord (map to the corresponding re2c: configurations), and var (maps to the re2c:yyaccept configuration).
  • yysetaccept — the YYSETACCEPT statement, possibly specialized per API. Supported variables: YYSETACCEPT, yyrecord (map to the matching re2c: configurations), var (maps to re2c:yyaccept) and val — the numeric value of the accepted rule.
  • yygetcond — the YYGETCOND statement, possibly specialized per API. Supported variables: YYGETCOND, yyrecord (map to the corresponding re2c: configurations), and var (maps to the re2c:yycond configuration).
  • yysetcond — the YYSETCOND statement, possibly specialized per API. Supported variables: YYSETCOND, yyrecord (map to the corresponding re2c: configurations), var (maps to re2c:yycond) and val — the numeric condition identifier.
  • yygetstate — the YYGETSTATE statement, possibly specialized per API. Supported variables: YYGETSTATE, yyrecord (map to the corresponding re2c: configurations), and var (maps to the re2c:yystate configuration).
  • yysetstate — the YYSETSTATE statement, possibly specialized per API. Supported variables: YYSETSTATE, yyrecord (map to the corresponding re2c: configurations), var (maps to re2c:yystate) and val — the state number.
  • yylessthan — the YYLESSTHAN statement, possibly specialized per API. Supported variables: YYLESSTHAN, YYCURSOR, YYLIMIT, yyrecord (map to the corresponding re2c: configurations), and need — the number of code units to check against. Conditional: .many — true when the need is more than one 🦋
  • yyend — the YYEND expression, possibly specialized per API. Supported variables: YYEND, YYCURSOR, YYLIMIT.
  • yybm_filter — a condition used to filter out yych values that the yybm table doesn't cover (used together with the --bitmaps option). Supported variable: yych (maps to the re2c:yych configuration).
  • yybm_match — the format of the yybm table check (generated with the --bitmaps option). Supported variables: yybm, yych (map to the corresponding re2c: configurations), offset (the offset in the yybm table that needs to be added to yych) and mask (the bit mask applied to the table entry to get the boolean value that needs checking) 🔥
  • yytarget_filter — a condition used to filter out yych values that the yytarget table doesn't cover (used with the --computed-gotos option). Supported variable: yych (maps to the re2c:yych configuration).

Okay so here's the full guest list of global variables you're allowed to use in syntax files, iykyk:

  • nl — literally just a newline. That's it. That's the whole variable 🌸
  • indent — doesn't produce any code at all, it's purely a vibe shift: it bumps the indentation level up one.
  • dedent — same deal, no code, just lowers the indentation level back down.
  • topindent — the indentation string for the current statement. The code generator tracks the indentation level and updates this automatically, so you don't have to 💅

And here's the list of every global conditional allowed in syntax files:

  • .api.simple — true when the simple API is in play (--api simple or re2c:api = simple).
  • .api.generic — true when the generic API is in play (--api generic or re2c:api = generic).
  • .api.record — true when the record API is in play (--api record or re2c:api = record).
  • .api_style.functions — true when the function-like API style is used (re2c:api-style = functions).
  • .api_style.freeform — true when the free-form API style is used (re2c:api-style = free-form).
  • .case_ranges — true when the case ranges feature is enabled (--case-ranges or re2c:case-ranges = 1).
  • .cgoto.relative — true when the relative form of computed goto is used (--computed-gotos-relative or re2c:cgoto:relative = 1).
  • .computed_continue — true when the loop/switch model uses labeled-switch transitions (--computed-continue).
  • .code_model.goto_label — true when the code model based on goto/label is used (--goto-label).
  • .code_model.loop_switch — true when the code model based on loop/switch is used (--loop-switch).
  • .code_model.recursive_functions — true when the code model based on recursive functions is used (--recursive-function).
  • .date — true when the generated fingerprint should contain the generation date 🗓️
  • .loop_label — true when the loops generated by re2zig must have a label (re2c:label:yyloop is set to a nonempty string).
  • .monadic — true when the generated code should be monadic (re2c:monadic = 1). Heads up: this only matters for pure functional languages ✨
  • .start_conditions — true when start conditions are enabled (--start-conditions).
  • .storable_state — true when storable state is enabled (--storable-state).
  • .unsafe — true when re2zig should use "unsafe" blocks to generate faster code (--unsafe, re2c:unsafe = 1). Only relevant for languages that actually have an "unsafe" feature.
  • .version — true when the generated fingerprint should contain the re2zig version.
  • .yyfill.enable — true when YYFILL is enabled (re2c:yyfill:enable = 1).
  • .yyfn.throw — true when the re2c:yyfn:throw configuration is defined to a nonempty string.

🌈 HANDLING THE END OF INPUT 🌈

Okay so this is like, the classic lexer dilemma, bestie: how do you know when to stop? 😭 There are a few terminating conditions:

  • the lexer may match some rule (including the default rule *) and come to a final state
  • the lexer may fail to match any rule and come to a default state
  • the lexer may reach the end of input 📍

okay so bestie, the first two conditions terminate the lexer in a totally "natural" way: it comes to a state with no outgoing transitions, and the matching automatically stops. the third condition — end of input — is a whole different beast: it may happen in any state, and the lexer should be able to handle it. checking for the end of input interrupts the normal lexer workflow and adds conditional branches to the generated program, so it is necessary to minimize the number of such checks. re2zig supports a few different methods for handling the end of input. which one to use depends on the complexity of regular expressions, the need for buffering, performance considerations and other factors. here's the lineup, bestie:

  • Sentinel. this method eliminates the need for the end of input checks altogether. it's simple and efficient, but limited to the case when there is a natural "sentinel" character that can never occur in valid input. this character may still occur in invalid input, but it should not be allowed by the regular expressions, except perhaps as the last character of a rule. the sentinel is appended at the end of input and serves as a stop signal: when the lexer reads this character, it is either a syntax error or the end of input. in both cases the lexer should stop. this method is used if YYFILL is disabled with re2c:yyfill:enable = 0; and re2c:eof has the default value -1.
  • Sentinel with bounds checks. this one is generic: it lets you handle any input without restrictions on the regular expressions. the idea is to reduce the number of end of input checks by performing them only on certain characters. similar to the "sentinel" method, one of the characters is chosen as a "sentinel" and appended at the end of input. however, there is no restriction on where the sentinel may occur (in fact, any character can be chosen for a sentinel). when the lexer reads this character, it additionally performs a bounds check. if the current position is within bounds, the lexer resumes matching and handles the sentinel as a regular character. otherwise it invokes YYFILL (unless it is disabled). if more input is supplied, the lexer will rematch the last character and continue as if the sentinel wasn't there. otherwise it must be the real end of input, and the lexer stops. this method is used when re2c:eof has a non-negative value (it should be set to the numeric value of the sentinel). YYFILL is optional.
  • Bounds checks with padding. this method is generic, and it may be faster than the "sentinel with bounds checks" method, but it is also more complex. the idea is to partition DFA states into strongly connected components (SCCs) and generate a single check per SCC for enough characters to cover the longest non-looping path in this SCC. this reduces the number of checks, but there is a problem with short lexemes at the end of input, as the check requires enough characters to cover the longest lexeme. this can be fixed by padding the input with a few fake characters that do not form a valid lexeme suffix (so that the lexer cannot match them). the length of padding should be YYMAXFILL, generated with a max block. if there is not enough input, the lexer invokes YYFILL which should supply at least the required number of characters or not return. this method is used if YYFILL is enabled and re2c:eof is -1 (this is the default configuration).
  • Custom checks. the generic API allows one to override basic operations like reading a character, which makes it possible to include the end-of-input checks as part of them. this approach is error-prone and should be used with caution. to use a custom method, enable generic API with --api custom or re2c:api = custom; and disable default bounds checks with re2c:yyfill:enable = 0; or re2c:yyfill:check = 0;.

the following subsections contain an example of each method. 💅


🛡️ Sentinel 🛡️

this example uses a sentinel character to handle the end of input. the program counts space-separated words in a null-terminated string. the sentinel is null: it's the last character of each input string, and it is not allowed in the middle of a lexeme by any of the rules (in particular, it's not included in character ranges where it's easy to overlook). if a null occurs in the middle of a string, it's a syntax error and the lexer will match default rule *, but it won't read past the end of input or crash (use -Wsentinel-in-midrule warning and re2c:sentinel configuration to verify this). configuration re2c:yyfill:enable = 0; suppresses the generation of bounds checks and YYFILL invocations. slay.

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

// Expects a null-terminated string.
fn lex(yyinput: [:0]const u8) i32 {
    var yycursor: u32 = 0;
    var count: i32 = 0;

    loop: while (true) {
        %{
            re2c:yyfill:enable = 0;

            *      { return -1; }
            [\x00] { return count; }
            [a-z]+ { count += 1; continue :loop; }
            [ ]+   { continue :loop; }
        %}
    }
}

test {
    try std.testing.expectEqual(lex(""), 0);
    try std.testing.expectEqual(lex("one two three"), 3);
    try std.testing.expectEqual(lex("f0ur"), -1);
}

🔍 Sentinel with bounds checks 🔍

this example uses sentinel with bounds checks to handle the end of input (this method was added in version 1.2). the program counts space-separated single-quoted strings. the sentinel character is null, which is specified with re2c:eof = 0; configuration. as in the sentinel method, null is the last character of each input string, but it's allowed in the middle of a rule (for example, 'aaa\0aa'\0 is valid input, but 'aaa\0 is a syntax error). bounds checks are generated in each state that matches an input character, but they're scoped to the branch that handles null. bounds checks are of the form YYLIMIT <= YYCURSOR or YYLESSTHAN(1) with generic API. if the check condition is true, lexer has reached the end of input and should stop (YYFILL is disabled with re2c:yyfill:enable = 0; as the input fits into one buffer — see the YYFILL with sentinel section for an example that uses YYFILL). reaching the end of input opens three possibilities: if the lexer is in the initial state it will match the end-of-input rule $, otherwise it may fallback to a previously matched rule (including default rule *) or go to a default state, causing -Wundefined-control-flow. iykyk 😭

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

// Expects a null-terminated string.
fn lex(yyinput: [:0]const u8) i32 {
    var yycursor: usize = 0;
    var yymarker: usize = 0;
    const yylimit: usize = yyinput.len; // points at the terminating null
    var count: i32 = 0;

    loop: while (true) {
        %{
            re2c:yyfill:enable = 0;
            re2c:eof = 0;

            str = ['] ([^'\\] | [\\][^])* ['];

            *    { return -1; }
            $    { return count; }
            str  { count += 1; continue :loop; }
            [ ]+ { continue :loop; }
        %}
    }
}

test {
    try std.testing.expectEqual(lex(""), 0);
    try std.testing.expectEqual(lex("'qu\x00tes' 'are' 'fine: \\'' "), 3);
    try std.testing.expectEqual(lex("'unterminated\\'"), -1);
}

📏 Bounds checks with padding 📏

this example uses bounds checks with padding to handle the end of input (this method is enabled by default, periodt). the program counts space-separated single-quoted strings. there's a padding of YYMAXFILL null characters appended at the end of input, where the YYMAXFILL value is autogenerated with a max block. it's not necessary to use null for padding — any characters can be used as long as they do not form a valid lexeme suffix (in this example padding should not contain single quotes, as they may be mistaken for a suffix of a single-quoted string). there's a "stop" rule that matches the first padding character (null) and terminates the lexer (note that it checks if null is at the beginning of padding, otherwise it's a syntax error). bounds checks are generated only in some states that are determined by the strongly connected components of the underlying automaton. checks have the form (YYLIMIT - YYCURSOR) < n or YYLESSTHAN(n) with generic API, where n is the minimum number of characters that are needed for the lexer to proceed (it also means that the next bounds check will occur in at most n characters). if the check condition is true, the lexer has reached the end of input and will invoke YYFILL(n) that should either supply at least n input characters or not return. in this example YYFILL always fails and terminates the lexer with an error (which is fine because the input fits into one buffer). see the YYFILL with padding section for an example that refills the input buffer with YYFILL. obsessed with this one ngl 🧚

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

%{max %}

fn lex(str: []const u8) !i32 {
    // Create a copy of the input string padded with yymaxfill zeroes at the end.
    var yyinput = try std.testing.allocator.alloc(u8, str.len + yymaxfill);
    defer std.testing.allocator.free(yyinput);
    std.mem.copyForwards(u8, yyinput[0..], str);
    std.mem.copyForwards(u8, yyinput[str.len..], &[_]u8{0} ** yymaxfill); // zero padding

    var yycursor: usize = 0;
    const yylimit: usize = yyinput.len;
    var count: i32 = 0;

    loop: while (true) {
        %{
            re2c:YYFILL = "return -1;";

            str = ['] ([^'\\] | [\\][^])* ['];

            [\x00] {
                // Check that it is the sentinel, not some unexpected null.
                return if (yycursor - 1 == str.len) count else -1;
            }
            str  { count += 1; continue :loop; }
            [ ]+ { continue :loop; }
            *    { return -1; }
        %}
    }
}

test {
    try std.testing.expectEqual(lex(""), 0);
    try std.testing.expectEqual(lex("'qu\x00tes' 'are' 'fine: \\'' "), 3);
    try std.testing.expectEqual(lex("'unterminated\\'"), -1);
    try std.testing.expectEqual(lex("'unexpected \x00 null\\'"), -1);
}

✨ Custom checks ✨

Okay bestie, this example is giving custom end-of-input handling method based on generic API realness. The program counts space-separated single-quoted strings. It’s literally the same as the sentinel example, except that the input is not null-terminated. To cover up for the absence of a sentinel character at the end of input, YYPEEK is redefined to perform a bounds check before it reads the next input character. This is inefficient because checks are done very often. If the check condition fails, YYPEEK returns the real character, otherwise it returns a fake sentinel character. 🫶

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

// Expects a string without terminating null.
fn lex(str: []const u8) i32 {
    var cur: usize = 0;
    var count: i32 = 0;

    loop: while (true) {
        %{
            re2c:api = generic;
            re2c:yyfill:enable = 0;
            // YYPEEK returns "fake" terminating null if cursor has reached limit.
            re2c:YYPEEK = "if (cur >= str.len) 0 else str[cur]";
            re2c:YYSKIP = "cur += 1;";

            *      { return -1; }
            [\x00] { return count; }
            [a-z]+ { count += 1; continue :loop; }
            [ ]+   { continue :loop; }
        %}
    }
}

test {
    try std.testing.expectEqual(lex(""), 0);
    try std.testing.expectEqual(lex("one two three"), 3);
    try std.testing.expectEqual(lex("f0ur"), -1);
}

🫧 BUFFER REFILLING 🫧

So the need for buffering pops up when the input cannot be mapped in memory all at once: either it is too large, or it comes in a streaming fashion (like reading from a socket). The usual technique in such cases is to allocate a fixed-sized memory buffer and process input in chunks that fit into the buffer. When the current chunk is processed, it is moved out and new data is moved in. In practice it is somewhat more complex, because lexer state consists not of a single input position, but a set of interrelated positions:

  • cursor — the next input character to be read (YYCURSOR in C pointer API or YYSKIP/YYPEEK in generic API)
  • limit — the position after the last available input character (YYLIMIT in C pointer API, implicitly handled by YYLESSTHAN in generic API)
  • marker — the position of the most recent match, if any (YYMARKER in default API or YYBACKUP/YYRESTORE in generic API)
  • token — the start of the current lexeme (implicit in re2zig API, as it is not needed for the normal lexer operation and can be defined and updated by the user)
  • context marker — the position of the trailing context (YYCTXMARKER in C pointer API or YYBACKUPCTX/YYRESTORECTX in generic API)
  • tag variables — submatch positions (defined with stags and mtags blocks and generic API primitives YYSTAGP/YYSTAGN/YYMTAGP/YYMTAGN)

Not all these are used in every case, but if used, they must be updated by YYFILL. All active positions are contained in the segment between token and cursor, therefore everything between buffer start and token can be discarded, the segment from token and up to limit should be moved to the beginning of buffer, and the free space at the end of buffer should be filled with new data. In order to avoid frequent YYFILL calls it is best to fill in as many input characters as possible (even though fewer characters might suffice to resume the lexer). The details of YYFILL implementation are slightly different depending on which EOF handling method is used: the case of EOF rule is somewhat simpler than the case of bounds-checking with padding. Also note that if -f --storable-state option is used, YYFILL has slightly different semantics (described in the section about storable state).

🌟 YYFILL with sentinel 🌟

If EOF rule is used, YYFILL is a function-like primitive that accepts no arguments and returns a value which is checked against zero. YYFILL invocation is triggered by condition YYLIMIT <= YYCURSOR in C pointer API and YYLESSTHAN() in generic API. A non-zero return value means that YYFILL has failed. A successful YYFILL call must supply at least one character and adjust input positions accordingly. Limit must always be set to one after the last input position in buffer, and the character at the limit position must be the sentinel symbol specified by re2c:eof configuration. The pictures below show the relative locations of input positions in buffer before and after YYFILL call (sentinel symbol is marked with #, and the second picture shows the case when there is not enough input to fill the whole buffer). 💖

                         <-- shift -->
                       >-A------------B---------C-------------D#-----------E->
                       buffer       token    marker         limit,
                                                            cursor
          >-A------------B---------C-------------D------------E#->
                       buffer,  marker        cursor        limit
                       token

                         <-- shift -->
                       >-A------------B---------C-------------D#--E (EOF)
                       buffer       token    marker         limit,
                                                            cursor
          >-A------------B---------C-------------D---E#........
                       buffer,  marker       cursor limit
                       token

Here is an example of a program that reads input file input.txt in chunks of 4096 bytes and uses EOF rule.

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

const bufsize = 4095;

const State = struct {
    file: *std.Io.Reader,
    yyinput: [bufsize + 1]u8,
    yycursor: usize,
    yymarker: usize,
    yylimit: usize,
    token: usize,
    eof: bool
};

fn fill(st: *State) i32 {
    if (st.eof) { return -1; } // unexpected EOF

    // Error: lexeme too long. In real life can reallocate a larger buffer.
    if (st.token < 1) { return -2; }

    // Shift buffer contents (discard everything up to the current token).
    std.mem.copyBackwards(
        u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]);
    st.yycursor -= st.token;
    st.yymarker = @subWithOverflow(st.yymarker, st.token)[0];
    st.yylimit -= st.token;
    st.token = 0;

    // Fill free space at the end of buffer with new data from file.
    st.yylimit += st.file.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0;
    st.yyinput[st.yylimit] = 0; // append sentinel symbol

    // If read less than expected, this is the end of input.
    st.eof = st.yylimit < bufsize;

    return 0;
}

fn lex(yyrecord: *State) i32 {
    var count: i32 = 0;
    loop: while (true) {
        yyrecord.token = yyrecord.yycursor;
        %{
            re2c:api = record;
            re2c:eof = 0;
            re2c:YYFILL = "fill(yyrecord) == 0";

            str = ['] ([^'\\] | [\\][^])* ['];

            *    { return -1; }
            $    { return count; }
            str  { count += 1; continue :loop; }
            [ ]+ { continue :loop; }
        %}
    }
}

test {
    const fname = "input";
    const content = "'qu\x00tes' 'are' 'fine: \\'' " ** bufsize;
    const count = 3 * bufsize; // number of quoted strings written to file

    // Prepare input file: a few times the size of the buffer, containing
    // strings with zeroes and escaped quotes.
    var fw = try std.fs.cwd().createFile(fname, .{});
    try fw.writeAll(content);
    fw.close();

    // Prepare lexer state: all offsets are at the end of buffer.
    // Use unbuffered reader - lexer does its own buffering.
    const zerobuf: [0]u8 = undefined;
    var fr = try std.fs.cwd().openFile(fname, .{.mode = .read_only});
    var reader = fr.reader(&zerobuf);
    var st = State{
        .file = &reader.interface,
        .yyinput = undefined,
        .yycursor = bufsize,
        .yymarker = bufsize,
        .yylimit = bufsize,
        .token = bufsize,
        .eof = false,
    };
    // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL.
    st.yyinput[st.yylimit] = 0;

    // Run the lexer.
    try std.testing.expectEqual(lex(&st), count);

    // Cleanup: remove input file.
    fr.close();
    try std.fs.cwd().deleteFile(fname);
}

🌈 YYFILL with padding 🌈

In the default case (when EOF rule is not used) YYFILL is a function-like primitive that accepts a single argument and does not return any value. YYFILL invocation is triggered by condition (YYLIMIT - YYCURSOR) < n in C pointer API and YYLESSTHAN(n) in generic API. The argument passed to YYFILL is the minimal number of characters that must be supplied. If it fails to do so, YYFILL must not return to the lexer (for that reason it is best implemented as a macro that returns from the calling function on failure). In case of a successful YYFILL invocation the limit position must be set either to one after the last input position in buffer, or to the end of YYMAXFILL padding (in case YYFILL has successfully read at least n characters, but not enough to fill the entire buffer). The pictures below show the relative locations of input positions in buffer before and after YYFILL invocation (YYMAXFILL padding on the second picture is marked with # symbols). 🦋

                         <-- shift -->                 <-- need -->
                       >-A------------B---------C-----D-------E---F--------G->
                       buffer       token    marker cursor  limit

          >-A------------B---------C-----D-------E---F--------G->
                       buffer,  marker cursor               limit
                       token

                         <-- shift -->                 <-- need -->
                       >-A------------B---------C-----D-------E-F        (EOF)
                       buffer       token    marker cursor  limit

          >-A------------B---------C-----D-------E-F###############
                       buffer,  marker cursor                   limit
                       token                        <- YYMAXFILL ->

Here is an example of a program that reads input file input.txt in chunks of 4096 bytes and uses bounds-checking with padding.

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

%{max %}
const bufsize = 4096;

const State = struct {
    file: *std.Io.Reader,
    yyinput: [bufsize + yymaxfill]u8,
    yycursor: usize,
    yymarker: usize,
    yylimit: usize,
    token: usize,
    eof: bool
};

okay so, picking up mid-code, no cap — here’s the rest of that chunk exactly as it lives:

          fn fill(st: *State, need: usize) i32 {
              if (st.eof) { return -1; } // unexpected EOF

              // Error: lexeme too long. In real life can reallocate a larger buffer.
              if (st.token < need) { return -2; }

              // Shift buffer contents (discard everything up to the current token).
              std.mem.copyBackwards(
                  u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]);
              st.yycursor -= st.token;
              st.yymarker = @subWithOverflow(st.yymarker, st.token)[0];
              st.yylimit -= st.token;
              st.token = 0;

              // Fill free space at the end of buffer with new data from file.
              st.yylimit += st.file.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0;

              // If read less than expected, this is the end of input.
              if (st.yylimit < bufsize) {
                  st.eof = true;
                  @memset(st.yyinput[st.yylimit..st.yylimit + yymaxfill], 0);
                  st.yylimit += yymaxfill;
              }

              return 0;
          }

          fn lex(yyrecord: *State) i32 {
              var count: i32 = 0;
              loop: while (true) {
                  yyrecord.token = yyrecord.yycursor;
                  %{
                      re2c:api = record;
                      re2c:YYFILL = "{ if (fill(yyrecord, @@) != 0) return -2; }";

                      str = ['] ([^'\\] | [\\][^])* ['];

                      [\x00] {
                          // Check that it is the sentinel, not some unexpected null.
                          return if (yyrecord.token == yyrecord.yylimit - yymaxfill) count else -1;
                      }
                      str  { count += 1; continue :loop; }
                      [ ]+ { continue :loop; }
                      *    { return -1; }
                  %}
              }
          }

          test {
              const fname = "input";
              const content = "'qu\x00tes' 'are' 'fine: \\'' " ** bufsize;
              const count = 3 * bufsize; // number of quoted strings written to file

              // Prepare input file: a few times the size of the buffer, containing
              // strings with zeroes and escaped quotes.
              var fw = try std.fs.cwd().createFile(fname, .{});
              try fw.writeAll(content);
              fw.close();

              // Prepare lexer state: all offsets are at the end of buffer.
              // This immediately triggers YYFILL, as the YYLESSTHAN condition is true.
              // Use unbuffered reader - lexer does its own buffering.
              const zerobuf: [0]u8 = undefined;
              var fr = try std.fs.cwd().openFile(fname, .{.mode = .read_only});
              var reader = fr.reader(&zerobuf);
              var st = State{
                  .file = &reader.interface,
                  .yyinput = undefined,
                  .yycursor = bufsize,
                  .yymarker = bufsize,
                  .yylimit = bufsize,
                  .token = bufsize,
                  .eof = false,
              };
              @memset(st.yyinput[st.yylimit..st.yylimit + yymaxfill], 0); // zero-padding at the end

              // Run the lexer.
              try std.testing.expectEqual(lex(&st), count);

              // Cleanup: remove input file.
              fr.close();
              try std.fs.cwd().deleteFile(fname);
          }

🌈 FEATURES 🌈

🎀 Multiple blocks 🎀

bestie, sometimes you literally need multiple interrelated lexers — like when there’s a high-level state machine doing transitions between lexer modes. That’s so real. You can do it with multiple connected re2zig blocks. Another option? Start conditions. Both iconic. 💅

How you wire connections between blocks depends on the target language. In languages that have a goto statement — yes, C/C++ and Go, we see you — one can have all blocks in one function, each of them prefixed with a label. Transition from one block to another is a simple goto. In languages that do not have goto (looking at you, Rust), it is necessary to use a loop with a switch on a state variable, similar to the yystate loop/switch generated by re2zig, or else wrap each block in a function and use function calls. Iykyk. 🦋

The example below uses multiple blocks to parse binary, octal, decimal and hexadecimal numbers. Each base has its own block. The initial block determines base and dispatches to other blocks. Common configurations are defined in a separate block at the beginning of the program; they are inherited by the other blocks. slay. ✨

          // re2zig $INPUT -o $OUTPUT

          const std = @import("std");

          // Store u32 number in u64 during parsing to simplify overflow handling.
          const State = struct {
              yyinput: [:0]const u8,
              yycursor: usize,
              yymarker: usize,
              num: u64,
          };

          // Common re2c definitions shared between all functions.
          %{
              re2c:api = record;
              re2c:yyrecord = st;
              re2c:yyfill:enable = 0;
          %}

          const ERROR: u64 = @as(u64, std.math.maxInt(u32)) + 1; // overflow

          // Add digit with the given base, checking for overflow.
          fn add(st: *State, offs: u8, base: u64) void {
              const digit = st.yyinput[st.yycursor - 1] - offs;
              st.num = @min(st.num * base + digit, ERROR);
          }

          // Convert u64 to optional u32 (null meaning overflow or parse error).
          fn maybeU32(num: u64) ?u32 {
              return if (num < ERROR) @intCast(num) else null;
          }

          fn parse_u32(s: [:0]const u8) ?u32 {
              var st = State {.yyinput = s, .yycursor = 0, .yymarker = 0, .num = 0};
              %{
                  '0b' / [01]        { return parse_bin(&st); }
                  "0"                { return parse_oct(&st); }
                  "" / [1-9]         { return parse_dec(&st); }
                  '0x' / [0-9a-fA-F] { return parse_hex(&st); }
                  *                  { return null; }
              %}
          }

          fn parse_bin(st: *State) ?u32 {
              bin: while (true) {%{
                  [01] { add(st, 48, 2); continue :bin; }
                  *    { return maybeU32(st.num); }
              %}}
          }

          fn parse_oct(st: *State) ?u32 {
              oct: while (true) {%{
                  [0-7] { add(st, 48, 8); continue :oct; }
                  *     { return maybeU32(st.num); }
              %}}
          }

          fn parse_dec(st: *State) ?u32 {
              dec: while (true) {%{
                  [0-9] { add(st, 48, 10); continue :dec; }
                  *     { return maybeU32(st.num); }
              %}}
          }

          fn parse_hex(st: *State) ?u32 {
              hex: while (true) {%{
                  [0-9] { add(st, 48, 16); continue :hex; }
                  [a-f] { add(st, 87, 16); continue :hex; }
                  [A-F] { add(st, 55, 16); continue :hex; }
                  *     { return maybeU32(st.num); }
              %}}
          }

          test {
              try std.testing.expectEqual(parse_u32(""), null);
              try std.testing.expectEqual(parse_u32("1234567890"), 1234567890);
              try std.testing.expectEqual(parse_u32("0b1101"), 13);
              try std.testing.expectEqual(parse_u32("0x7Fe"), 2046);
              try std.testing.expectEqual(parse_u32("0644"), 420);
              try std.testing.expectEqual(parse_u32("9999999999"), null);
          }

🦋 Start conditions 🦋

Start conditions are enabled with --start-conditions option. They provide a way to encode multiple interrelated automata within the same re2zig block. obsessed. 🫶

Each condition corresponds to a single automaton and has a unique name specified by the user and a unique internal number defined by re2zig. The numbers are used to switch between conditions: the generated code uses YYGETCOND and YYSETCOND primitives to get the current condition or set it to the given number. Use conditions block, --header option or re2c:header configuration to generate numeric condition identifiers. Configuration re2c:cond:enumprefix specifies the generated identifier prefix. 📌

In condition mode every rule must be prefixed with a list of comma-separated condition names in angle brackets, or a wildcard <*> to denote all conditions. The rule syntax is extended as follows:

          < condition-list > regular-expression code
                 A rule that is merged to every condition on the
                 condition-list.  It matches regular-expression and executes
                 the associated code.

          < condition-list > regular-expression => condition code
                 A rule that is merged to every condition on the
                 condition-list.  It matches regular-expression, sets the
                 current condition to condition and executes the associated
                 code.

          < condition-list > regular-expression :=> condition
                 A rule that is merged to every condition on the
                 condition-list.  It matches regular-expression and immediately
                 transitions to condition (there is no semantic action).

          < condition-list > !action code
                 A rule that binds code to the place defined by action in every
                 condition on the condition-list (see the actions section for
                 various types of actions).

          <! condition-list > code
                 A rule that prepends code to semantic actions of all rules for
                 every condition on the condition-list. This syntax is
                 deprecated and the !pre_rule action should be used instead (it
                 does exactly the same).

          < > code
                 A rule that creates a special entry condition with number zero
                 and name "0" that executes code before jumping to other
                 conditions.  This syntax is deprecated, and the !entry action
                 should be used instead (it provides a more fine-grained
                 control, as the code can be specified on a per-condition
                 basis, and one can jump directly to condition start without
                 going through condition dispatch).

          < > => condition code
                 Same as the previous rule, except that it sets the next
                 condition.

          < > :=> condition
                 Same as the previous rule, except that it has no associated
                 code and immediately jumps to condition.

The code re2zig generates for conditions depends on whether re2zig uses goto/label approach or loop/switch approach to encode the automata. 🔥

In languages that have goto statement (such as C/C++ and Go) conditions are naturally implemented as blocks of code prefixed with labels of the form yyc_<cond>, where cond is a condition name (label prefix can be changed with re2c:cond:prefix). Transitions between conditions are implemented using goto and condition labels. Before all conditions re2zig generates an initial switch on YYGETSTATE that jumps to the start state of the current condition. The shortcut rules :=> bypass the initial switch and jump directly to the specified condition (re2c:cond:goto can be used to change the default behavior). The rules with semantic actions do not automatically jump to the next condition; this should be done by the user-defined action code. periodt. 💖

okay so in languages that do NOT have goto (looking at you, Rust 👀), re2zig just reuses the yystate variable to stash condition numbers. each condition gets a numeric identifier equal to the number of its start state, and switching between conditions is literally no different from switching between DFA states of a single condition. so there's no need for a separate initial condition switch — it's giving efficiency 💅 (and heads up: since the same approach is used to implement storable states, YYGETCOND/YYSETCOND are redundant if you're using both storable states and conditions, iykyk).

the program below uses start conditions to parse binary, octal, decimal and hexadecimal numbers 🔢 there's a single block where each base has its own condition, and the initial condition is connected to all of them. the user-defined variable cond stores the current condition number; it's initialized to the number of the initial condition generated with the conditions block. slay.

// re2zig $INPUT -o $OUTPUT -c

const std = @import("std");

%{conditions %}

const ERROR: u64 = @as(u64, std.math.maxInt(u32)) + 1; // overflow

// Add digit with the given base, checking for overflow.
fn add(num: *u64, str: [:0]const u8, cur: usize, offs: u8, base: u64) void {
    num.* = @min(num.* * base + (str[cur - 1] - offs), ERROR);
}

fn parse_u32(yyinput: [:0]const u8) ?u32 {
    var yycursor: usize = 0;
    var yymarker: usize = 0;
    var yycond = yycinit;
    var num: u64 = 0; // Store number in u64 to simplify overflow checks.

    loop: while(true) {
    %{
        re2c:yyfill:enable = 0;

        <init> '0b' / [01]        :=> bin
        <init> "0"                :=> oct
        <init> "" / [1-9]         :=> dec
        <init> '0x' / [0-9a-fA-F] :=> hex
        <init> * { return null; }

        <bin> [01]  { add(&num, yyinput, yycursor, 48, 2);  continue :loop; }
        <oct> [0-7] { add(&num, yyinput, yycursor, 48, 8);  continue :loop; }
        <dec> [0-9] { add(&num, yyinput, yycursor, 48, 10); continue :loop; }
        <hex> [0-9] { add(&num, yyinput, yycursor, 48, 16); continue :loop; }
        <hex> [a-f] { add(&num, yyinput, yycursor, 87, 16); continue :loop; }
        <hex> [A-F] { add(&num, yyinput, yycursor, 55, 16); continue :loop; }

        <bin, oct, dec, hex> * {
            return if (num < ERROR) @intCast(num) else null;
        }
    %}}
}

test {
    try std.testing.expectEqual(parse_u32(""), null);
    try std.testing.expectEqual(parse_u32("1234567890"), 1234567890);
    try std.testing.expectEqual(parse_u32("0b1101"), 13);
    try std.testing.expectEqual(parse_u32("0x7Fe"), 2046);
    try std.testing.expectEqual(parse_u32("0644"), 420);
    try std.testing.expectEqual(parse_u32("9999999999"), null);
}

🎀 Storable state

with the --storable-state option, re2zig generates a lexer that can store its current state, return to the caller, and later resume operations exactly where it left off 😭✨

so the default mode of operation in re2zig is a "pull" model, where the lexer "pulls" more input whenever it needs it. that's lowkey unacceptable in cases where the input becomes available piece by piece — like, for example, if the lexer is invoked by the parser, or if the lexer program communicates via a socket protocol with some other program that must wait for a reply from the lexer before it transmits the next message. the Storable state feature is intended exactly for such cases: it lets you generate lexers that work in a "push" model 🫶 when the lexer needs more input, it stores its state and returns to the caller. later, when more input becomes available, the caller resumes the lexer exactly where it stopped. periodt.

there are a few changes necessary compared to the "pull" model:

  • Define YYSETSTATE() and YYGETSTATE(state) primitives.
  • Define yych, yyaccept (if used) and state variables as a part of persistent lexer state. the state variable should be initialized to -1.
  • YYFILL should return to the outer program instead of trying to supply more input. return code should indicate that lexer needs more input.
  • the outer program should recognize situations when lexer needs more input and respond appropriately.
  • optionally use getstate block to generate YYGETSTATE switch detached from the main lexer. this only works for languages that have goto (not in --loop-switch mode).
  • use re2c:eof and the sentinel with bounds checks method to handle the end of input. the padding-based method may not work because it is unclear when to append padding: the current end of input may not be the ultimate end of input, and appending padding too early may cut off a partially read greedy lexeme 😬 furthermore, due to high-level program logic, getting more input may depend on processing the lexeme at the end of buffer (which already is blocked due to the end-of-input condition).

here's an example of a "push" model lexer that simulates reading packets from a socket 🔌 the lexer loops until it encounters the end of input and returns to the calling function. the calling function provides more input by "sending" the next packet and resumes lexing. this process stops when all the packets have been sent, or when there's an error 💀

// re2zig $INPUT -o $OUTPUT -f

const std = @import("std");

const Status = enum {
    end,
    ready,
    waiting,
    bad_packet,
    big_packet
};

// Use a small buffer to cover the case when a lexeme doesn't fit.
// In real world use a larger buffer.
const bufsize = 10;

const State = struct {
    file: std.fs.File.Reader,
    yyinput: [bufsize + 1]u8,
    yycursor: usize,
    yymarker: usize,
    yylimit: usize,
    token: usize,
    yystate: i32,
    received: usize,
};

fn fill(st: *State) Status {
    // Error: lexeme too long. In real life can reallocate a larger buffer.
    if (st.token < 1) { return Status.big_packet; }

    // Shift buffer contents (discard everything up to the current token).
    std.mem.copyBackwards(
        u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]);
    st.yycursor -= st.token;
    st.yymarker = @subWithOverflow(st.yymarker, st.token)[0];
    st.yylimit -= st.token;
    st.token = 0;

    // Fill free space at the end of buffer with new data from file.
    st.yylimit += st.file.interface.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0;
    st.yyinput[st.yylimit] = 0; // append sentinel symbol

    return Status.ready;
}

fn lex(yyrecord: *State) Status {
    var yych: u8 = 0;
    loop: while (true) {
        yyrecord.token = yyrecord.yycursor;
        %{
            re2c:api = record;
            re2c:eof = 0;
            re2c:YYFILL = "return Status.waiting;";

            packet = [a-z]+[;];

            *      { return Status.bad_packet; }
            $      { return Status.end; }
            packet { yyrecord.received += 1; continue :loop; }
        %}
    }
}

fn run(expect: Status, packets: []const []const u8) !void {
    // Create a "pipe" (open the same file for reading and writing).
    const fname = "input";
    var fw = try std.fs.cwd().createFile(fname, .{});
    var fr = try std.fs.cwd().openFile(fname, .{ .mode = .read_only});

    // Initialize lexer state: `state` value is -1, all offsets are at the end
    // of buffer. Use unbuffered reader - lexer does its own buffering.
    const zerobuf: [0]u8 = undefined;
    var st = State{
        .file = fr.reader(&zerobuf),
        .yyinput = undefined,
        .yycursor = bufsize,
        .yymarker = bufsize,
        .yylimit = bufsize,
        .token = bufsize,
        .yystate = -1,
        .received = 0,
    };
    // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL.
    st.yyinput[st.yylimit] = 0;

    // Main loop. The buffer contains incomplete data which appears packet by
    // packet. When the lexer needs more input it saves its internal state and
    // returns to the caller which should provide more input and resume lexing.
    var status = Status.ready;
    var send: usize = 0;
    while (true) {
        status = lex(&st);
        if (status == Status.end) {
            break;
        } else if (status == Status.waiting) {
            if (send < packets.len) {
                std.log.debug("sending packet {}", .{send});
                try fw.writeAll(packets[send]);
                send += 1;
            }
            status = fill(&st);
            std.log.debug("filled buffer [{s}], status {}", .{st.yyinput, status});
            if (status != Status.ready) {
                break;
            }
        } else if (status == Status.bad_packet) {
            break;
        }
    }

    // Check results.
    try std.testing.expectEqual(status, expect);
    if (status == Status.end) { try std.testing.expectEqual(st.received, send); }

    // Cleanup: remove input file.
    fw.close();
    fr.close();
    try std.fs.cwd().deleteFile(fname);
}

test {
    try run(Status.end, &[_][]const u8{});
    try run(Status.end, &[_][]const u8{"zero;", "one;", "two;", "three;", "four;"});
    try run(Status.bad_packet, &[_][]const u8{"??;"});
    try run(Status.big_packet, &[_][]const u8{"looooooooooooong;"});
}

🧚 Reusable blocks

reusable blocks of the form /*!rules:re2c[:<name>] ... */ or %{rules[:<name>] ... %} can be reused any number of times and combined with other re2zig blocks ✨ the <name> is optional. a rules block can be used in a use block or directive. the code for a rules block is generated at every point of use — so it's literally copy-paste energy but make it compiler 💅

use blocks are defined with /*!use:re2c[:<name>] ... */ or %{use[:<name>] ... %}. the <name> is optional: if it's not specified, the associated rules block is the most recent one (whether named or unnamed). a use block can add named definitions, configurations and rules of its own 🎀 an important use case for use blocks is a lexer that supports multiple input encodings: the same rules block is reused multiple times with encoding-specific configurations (see the example below). iconic.

okay so the in-block use directive !use:<name>; is literally the friendship bracelet of re2zig — you use it from inside a re2zig block to merge the referenced block <name> into the current one 🫶. And when merged rules and configs overlap with stuff you already defined, the conflict gets resolved the usual way: earliest rule takes priority, and the latest configuration overrides the preceding ones. The one exception (iconic behavior, honestly) are the special rules *, $ and — in condition mode — <!>, where a block-local definition overrides any inherited ones. Basically the use directive lets you combine different re2zig blocks together in one block, see the example below 💅.

Named blocks and the in-block use directive were added in re2zig version 2.2. Since that version, reusable blocks are allowed by default — no special option needed, we love a low-maintenance queen ✨. Before version 2.2, reuse mode was enabled with the -r, --reusable option. And before version 1.2, reusable blocks could not be mixed with normal blocks. History, bestie 📜.

Example of a !use directive 🌸

// re2zig $INPUT -o $OUTPUT

// This example shows how to combine reusable re2c blocks: two blocks
// ('colors' and 'fish') are merged into one. The 'salmon' rule occurs
// in both blocks; the 'fish' block takes priority because it is used
// earlier. Default rule * occurs in all three blocks; the local (not
// inherited) definition takes priority.

const std = @import("std");

const Ans = enum {color, fish, dunno};

%{rules:colors
    *                            { @panic("ah"); }
    "red" | "salmon" | "magenta" { return Ans.color; }
%}

%{rules:fish
    *                            { @panic("oh"); }
    "haddock" | "salmon" | "eel" { return Ans.fish; }
%}

fn lex(yyinput: [:0]const u8) Ans {
    var yycursor: usize = 0;
    var yymarker: usize = 0;
    %{
        re2c:yyfill:enable = 0;

        !use:fish;
        !use:colors;
        * { return Ans.dunno; } // overrides inherited '*' rules
    %}
}

test {
    try std.testing.expectEqual(lex("salmon"), Ans.fish);
    try std.testing.expectEqual(lex("what?"), Ans.dunno);
}

Example of a /*!use:re2c ... */ block 🦋

// re2zig $INPUT -o $OUTPUT --input-encoding utf8

// This example supports multiple input encodings: UTF-8 and UTF-32.
// Both lexers are generated from the same rules block, and the use
// blocks add only encoding-specific configurations.

const std = @import("std");

%{rules
    re2c:yyfill:enable = 0;

    "∀x ∃y" { return yycursor; }
    *       { return null; }
%}

fn lex_utf8(yyinput: []const u8) ?usize {
    var yycursor: usize = 0;
    var yymarker: usize = 0;
    %{use
        re2c:encoding:utf8 = 1;
        re2c:YYCTYPE = u8; // the default
    %}
}

fn lex_utf32(yyinput: []const u32) ?usize {
    var yycursor: usize = 0;
    var yymarker: usize = 0;
    %{use
        re2c:encoding:utf32 = 1;
        re2c:YYCTYPE = u32;
    %}
}

test {
    const s8 = [_]u8{0xe2, 0x88, 0x80, 0x78, 0x20, 0xe2, 0x88, 0x83, 0x79};
    try std.testing.expectEqual(lex_utf8(&s8), s8.len);

    const s32 = [_]u32{0x2200, 0x78, 0x20, 0x2203, 0x79};
    try std.testing.expectEqual(lex_utf32(&s32), s32.len);
}

Submatch extraction 🎀

re2zig has two options for submatch extraction, and honestly? both ate. Pick your fighter:

Tags — The first option is to use standalone tags of the form @stag or #mtag, where stag and mtag are arbitrary user-defined names. Tags are enabled with the -T, --tags option or the re2c:tags = 1 configuration. Semantically, tags are position markers: they can be inserted anywhere in a regular expression, and they bind to the corresponding position (or multiple positions) in the input string. S-tags bind to the last matching position, and m-tags bind to a list of positions — they may be used in repetition subexpressions, where a single position in a regular expression corresponds to multiple positions in the input string, which is giving multiverse energy 🌈. All tags should be defined by the user, either manually or with the help of svars and mvars blocks. If there is more than one way tags can be matched against the input, the ambiguity is resolved using the leftmost greedy disambiguation strategy. Periodt.

Captures — The second option is to use capturing groups. They're enabled with the --captures option or the re2c:captures = 1 configuration. There are two flavours for different disambiguation policies: --leftmost-captures (the default) is for the leftmost greedy policy, and --posix-captures is for the POSIX longest-match policy. In this mode all parenthesized subexpressions are considered capturing groups, and a bang can be used to mark non-capturing groups: (! ... ). With the --invert-captures option or the re2c:invert-captures = 1 configuration the meaning of bang is inverted 🔄. The number of groups for the matching rule is stored in a variable yynmatch (the whole regular expression is group number zero), and submatch results are stored in the yypmatch array. Both yynmatch and yypmatch should be defined by the user, and yypmatch size must be at least [yynmatch * 2]. Use the maxnmatch block to define YYMAXNMATCH, a constant that equals the maximum value of yynmatch among all rules. no cap, write that size down 📝.

Captvars — Another way to use capturing groups is the --captvars option or the re2c:captvars = 1 configuration. The only difference with --captures is in the way the generated code stores submatch results: instead of yynmatch and yypmatch, re2zig generates variables yytl<k> and yytr<k> for the k-th capturing group (the user should declare these using an svars block). Captures with variables support two disambiguation policies: --leftmost-captvars or re2c:leftmost-captvars = 1 for the leftmost greedy policy (the default one), and --posix-captvars or re2c:posix-captvars for the POSIX longest-match policy 💅.

Under the hood all these options translate into tags and Tagged Deterministic Finite Automata with Lookahead. The core idea of TDFA is to minimize the overhead on submatch extraction. In the extreme, if there're no tags or captures in a regular expression, TDFA is just an ordinary DFA — it's giving minimalism ✨. If the number of tags is moderate, the overhead is barely noticeable. The generated TDFA uses a number of tag variables which do not map directly to tags: a single variable may be used for different tags, and a tag may require multiple variables to hold all its possible values. Eventually ambiguity is resolved, and only one final variable per tag survives 👑. Tag variables should be defined using stags or mtags blocks. If lexer state is stored, tag variables should be part of it. They also need to be updated by YYFILL.

S-tags support the following operations:

  • save input position to an s-tag: t = YYCURSOR with the C pointer API or a user-defined operation YYSTAGP(t) with the generic API
  • save default value to an s-tag: t = NULL with the C pointer API or a user-defined operation YYSTAGN(t) with the generic API
  • copy one s-tag to another: t1 = t2

M-tags support the following operations:

  • append input position to an m-tag: a user-defined operation YYMTAGP(t) with both the default and the generic API
  • append default value to an m-tag: a user-defined operation YYMTAGN(t) with both the default and the generic API
  • copy one m-tag to another: t1 = t2

S-tags can be implemented as scalar values (pointers or offsets). M-tags need a more complex representation, as they need to store a sequence of tag values. The most naive and inefficient representation of an m-tag is a list (array, vector) of tag values; a more efficient representation is to store all m-tags in a prefix-tree represented as an array of nodes (v, p), where v is the tag value and p is a pointer to the parent node 🌳.

Here is a simple example of using s-tags to parse semantic versions consisting of three numeric components: major, minor, patch (the latter is optional). See below for a more complex example that uses YYFILL 💖.

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

const SemVer = struct {
    major: u32,
    minor: u32,
    patch: u32,
};

const none = std.math.maxInt(usize);

fn s2n(str: []const u8) u32 { // convert a pre-parsed string to a number
    var n: u32 = 0;
    for (str) |c| { n = n * 10 + (c - 48); }
    return n;
}

fn parse(yyinput: [:0]const u8) ?SemVer {
    var yycursor: usize = 0;
    var yymarker: usize = 0;

    // Final tag variables available in semantic action.
    %{svars format = "var @@: usize = none;"; %}

    // Intermediate tag variables used by the lexer (must be autogenerated).
    %{stags format = "var @@: usize = none;"; %}

    %{
        re2c:yyfill:enable = 0;
        re2c:tags = 1;

        num = [0-9]+;

        @t1 num @t2 "." @t3 num @t4 ("." @t5 num)? [\x00] {
            return SemVer {
                .major = s2n(yyinput[t1..t2]),
                .minor = s2n(yyinput[t3..t4]),
                .patch = if (t5 == none) 0 else s2n(yyinput[t5..yycursor - 1]),
            };
        }
        * { return null; }
    %}
}

test {
    try std.testing.expectEqual(parse("23.34"), SemVer{.major = 23, .minor = 34, .patch = 0});
    try std.testing.expectEqual(parse("1.2.99999"), SemVer{.major = 1, .minor = 2, .patch = 99999});
    try std.testing.expectEqual(parse("1.a"), null);
}

Here is a more complex example of using s-tags with YYFILL to parse a file with newline-separated semantic versions. Tag variables are part of the lexer state, and they are adjusted in YYFILL like other input positions. Note that it is necessary for s-tags because their values are invalidated after shifting buffer contents 😭 — it may not be necessary in a custom implementation where tag variables store offsets relative to the start of the input string rather than the buffer, which may be the case with m-tags 🌸.

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

const bufsize = 4095;
const none = std.math.maxInt(usize);

const err = error.SyntaxError;

const SemVer = struct {
    major: u32,
    minor: u32,
    patch: u32,
};

fn s2n(str: []const u8) u32 { // convert a pre-parsed string to a number
    var n: u32 = 0;
    for (str) |c| { n = n * 10 + (c - 48); }
    return n;
}

...and we were right in the middle of the State struct, bestie, so no re-introducing, just vibes and code:

          const State = struct {
              file: *std.Io.Reader,
              yyinput: [bufsize + 1]u8,
              yycursor: usize,
              yymarker: usize,
              yylimit: usize,
              token: usize,
              // Intermediate tag variables must be part of the lexer state passed to YYFILL.
              // They don't correspond to tags and should be autogenerated by re2c.
              %{stags format = "@@: usize,\n"; %}
              eof: bool
          };

          fn fill(st: *State) i32 {
              if (st.eof) { return -1; } // unexpected EOF

              // Error: lexeme too long. In real life can reallocate a larger buffer.
              if (st.token < 1) { return -2; }

              // Shift buffer contents (discard everything up to the current token).
              std.mem.copyBackwards(
                  u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]);
              st.yycursor -= st.token;
              st.yymarker = @subWithOverflow(st.yymarker, st.token)[0];
              st.yylimit -= st.token;
              // Tag variables need to be shifted like other input positions. The check
              // for NONE is only needed if some tags are nested inside of alternative or
              // repetition, so that they can have NONE value.
              %{stags format = "if (st.@@ != none) st.@@ = @subWithOverflow(st.@@, st.token)[0];\n"; %}
              st.token = 0;

              // Fill free space at the end of buffer with new data from file.
              st.yylimit += st.file.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0;
              st.yyinput[st.yylimit] = 0; // append sentinel symbol

              // If read less than expected, this is the end of input.
              st.eof = st.yylimit < bufsize;

              return 0;
          }

          fn parse(st: *State) !std.ArrayList(SemVer) {
              var vers = try std.ArrayList(SemVer).initCapacity(std.testing.allocator, 0);

              // Final tag variables available in semantic action.
              %{svars format = "var @@: usize = 0;\n"; %}

              loop: while (true) {
                  st.token = st.yycursor;
                  %{
                      re2c:api = record;
                      re2c:eof = 0;
                      re2c:tags = 1;
                      re2c:yyrecord = st;
                      re2c:YYFILL = "fill(st) == 0";

                      num = [0-9]+;

                      num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] {
                          try vers.append(std.testing.allocator, SemVer {
                              .major = s2n(st.yyinput[st.token..t1]),
                              .minor = s2n(st.yyinput[t2..t3]),
                              .patch = if (t4 == none) 0 else s2n(st.yyinput[t4..st.yycursor - 1]),
                          });
                          continue :loop;
                      }
                      $ { return vers; }
                      * { return error.SyntaxError; }
                  %}
              }
          }

          test {
              const fname = "input";
              const content = "1.22.333\n" ** bufsize;

              // Prepare input file: a few times the size of the buffer, containing
              // strings with zeroes and escaped quotes.
              var fw = try std.fs.cwd().createFile(fname, .{});
              try fw.writeAll(content);
              fw.close();

              // Prepare lexer state: all offsets are at the end of buffer.
              // Use unbuffered reader - lexer does its own buffering.
              const zerobuf: [0]u8 = undefined;
              var fr = try std.fs.cwd().openFile(fname, .{.mode = .read_only});
              var reader = fr.reader(&zerobuf);
              var st = State{
                  .file = &reader.interface,
                  .yyinput = undefined,
                  .yycursor = bufsize,
                  .yymarker = bufsize,
                  .yylimit = bufsize,
                  .token = bufsize,
                  %{stags format = ".@@ = none,\n"; %}
                  .eof = false,
              };
              // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL.
              st.yyinput[st.yylimit] = 0;

              // Manually construct expected result.
              var expect = [_]SemVer{SemVer{.major = 1, .minor = 22, .patch = 333}} ** bufsize;

              // Run the lexer.
              var result = try parse(&st);
              try std.testing.expectEqualDeep(&expect, result.items);

              // Cleanup: free memory and remove input file.
              result.deinit(std.testing.allocator);
              fr.close();
              try std.fs.cwd().deleteFile(fname);
          }

okay so real talk — that fill function is doing the most important little dance ever: it shifts the buffer contents to throw away everything up to the current token, and then it shifts the tag variables too 😭 because tags are literally input positions, so if the buffer moves, they gotta move with it. That's why the stags format string gets its own if (st.@@ != none) guard — the check is only needed if some tags are nested inside an alternative or repetition, so they can hold a NONE value. Very demure, very mindful. 💅

And st.eof = st.yylimit < bufsize — if we read less than expected, that's the end of input, periodt. 🦋


Here is an example of using capturing groups to parse semantic versions.

          // re2zig $INPUT -o $OUTPUT

          const std = @import("std");

          const none = std.math.maxInt(usize);

          const SemVer = struct {
              major: u32,
              minor: u32,
              patch: u32,
          };

          fn s2n(str: []const u8) u32 { // convert pre-parsed string to a number
              var n: u32 = 0;
              for (str) |c| { n = n * 10 + (c - 48); }
              return n;
          }

          fn parse(yyinput: [:0]const u8) ?SemVer {
              var yycursor: usize = 0;
              var yymarker: usize = 0;

              // Final tag variables available in semantic action.
              %{svars format = "var @@: usize = none;"; %}

              // Intermediate tag variables used by the lexer (must be autogenerated).
              %{stags format = "var @@: usize = none;"; %}

              %{
                  re2c:yyfill:enable = 0;
                  re2c:captvars = 1;

                  num = [0-9]+;

                  (num) "." (num) ("." num)? [\x00] {
                      return SemVer {
                          .major = s2n(yyinput[yytl1..yytr1]),
                          .minor = s2n(yyinput[yytl2..yytr2]),
                          .patch = if (yytl3 == none) 0 else s2n(yyinput[yytl3 + 1..yytr3])
                      };
                  }
                  * { return null; }
              %}
          }

          test {
              try std.testing.expectEqual(parse("23.34"), SemVer{.major = 23, .minor = 34, .patch = 0});
              try std.testing.expectEqual(parse("1.2.99999"), SemVer{.major = 1, .minor = 2, .patch = 99999});
              try std.testing.expectEqual(parse("1.a"), null);
          }

okay the re2c:captvars = 1 thing is giving main character energy ✨ — it hands you the yytl1/yytr1 style variables (left/right of each capture group), and you're just slicing yyinput with them. Note the absolutely iconic .patch = if (yytl3 == none) 0 else s2n(yyinput[yytl3 + 1..yytr3]) — there's a + 1 in there because the third capture is the number after the dot, and the dot itself is not invited to the number party 🙈.

Also parse("1.a") returns null — the fallback rule * { return null; } said no thank you. 🫶


Here is an example of using m-tags to parse a version with a variable number of components. Tag variables are stored in a trie.

          // re2zig $INPUT -o $OUTPUT

          const std = @import("std");

          const none = std.math.maxInt(usize);
          const mtag_root = none - 1;

          const err = error.SyntaxError;

          // An m-tag tree is a way to store histories with an O(1) copy operation.
          // Histories naturally form a tree, as they have common start and fork at some
          // point. The tree is stored as an array of pairs (tag value, link to parent).
          // An m-tag is represented with a single link in the tree (array index).
          const MtagElem = struct {
              elem: usize, // tag value
              pred: usize, // index of the predecessor node or root
          };

          // Append a single value to an m-tag history.
          fn add_mtag(trie: *std.ArrayList(MtagElem), mtag: usize, value: usize) !usize {
              try trie.append(std.testing.allocator, MtagElem{.elem = value, .pred = mtag});
              return trie.items.len - 1;
          }

          // Recursively unwind tag histories and collect version components.
          fn unwind(trie: *std.ArrayList(MtagElem),
                    x: usize,
                    y: usize,
                    str: []const u8,
                    ver: *std.ArrayList(u32)) !void {
              // Reached the root of the m-tag tree, stop recursion.
              if (x == mtag_root and y == mtag_root) return;

              // Unwind history further.
              try unwind(trie, trie.items[x].pred, trie.items[y].pred, str, ver);

              // Get tag values. Tag histories must have equal length.
              std.debug.assert(x != mtag_root and y != mtag_root);
              const ex = trie.items[x].elem;
              const ey = trie.items[y].elem;

              if (ex != none and ey != none) {
                  // Both tags are valid string indices, extract component.
                  try ver.append(std.testing.allocator, s2n(str[ex..ey]));
              } else {
                  // Both tags are none (this corresponds to zero repetitions).
                  std.debug.assert(ex == none and ey == none);
              }
          }

          fn s2n(str: []const u8) u32 { // convert a pre-parsed string to a number
              var n: u32 = 0;
              for (str) |c| { n = n * 10 + (c - 48); }
              return n;
          }

          fn parse(yyinput: [:0]const u8) !std.ArrayList(u32) {
              var yycursor: usize = 0;
              var yymarker: usize = 0;
              var mt = try std.ArrayList(MtagElem).initCapacity(std.testing.allocator, 0);
              defer mt.deinit(std.testing.allocator);

              // Final tag variables available in semantic action.
              %{svars format = "var @@: usize = none;"; %}
              %{mvars format = "var @@: usize = mtag_root;"; %}

              // Intermediate tag variables used by the lexer (must be autogenerated).
              %{stags format = "var @@: usize = none;"; %}
              %{mtags format = "var @@: usize = mtag_root;"; %}

              %{
                  re2c:YYMTAGP = "@@ = add_mtag(&mt, @@, yycursor) catch none;";
                  re2c:YYMTAGN = "@@ = add_mtag(&mt, @@, none) catch none;";
                  re2c:yyfill:enable = 0;
                  re2c:tags = 1;

                  num = [0-9]+;

                  @t1 num @t2 ("." #t3 num #t4)* [\x00] {
                      var ver = try std.ArrayList(u32).initCapacity(std.testing.allocator, 0);
                      try ver.append(std.testing.allocator, s2n(yyinput[t1..t2]));
                      try unwind(&mt, t3, t4, yyinput, &ver);
                      return ver;
                  }
                  * { return error.SyntaxError; }
              %}
          }

          test {
              var result = try parse("1");
              var expect = [_]u32{1};
              try std.testing.expectEqualDeep(&expect, result.items);
              result.deinit(std.testing.allocator);
          }

          test {
              var result = try parse("1.2.3.4.5.6.7");
              var expect = [_]u32{1, 2, 3, 4, 5, 6, 7};
              try std.testing.expectEqualDeep(&expect, result.items);
              result.deinit(std.testing.allocator);
          }

          test {
              const result = parse("1.2.") catch null;
              try std.testing.expectEqualDeep(result, null);
          }

okay this one is genuinely so smart it hurts 😭 the whole point of the m-tag tree is that histories can be copied in O(1) — instead of cloning a whole list every time, you just store a pair of (tag value, link to parent) and point at your predecessor. Histories naturally form a tree because they all start from the same root and fork somewhere along the way 🌸.

And notice the difference in syntax bestie: @t1 / @t2 are the plain tags, but #t3 / #t4 — the ones with the little hash — are the m-tags, the ones living in the trie. The re2c:YYMTAGP and re2c:YYMTAGN hooks are what actually push a value onto the history (yycursor when it's a real position, none when the repetition didn't happen, hence the "N"). The unwind function then walks both chains in lockstep, and it asserts that both histories must have equal length — no cap, that's a hard requirement. 🧚

The var err = error.SyntaxError; doesn't even get used in this snippet btw, it's just chilling there like a background character 💀.

and the tests ate, honestly:

  • parse("1") → {1}
  • parse("1.2.3.4.5.6.7") → {1, 2, 3, 4, 5, 6, 7}
  • parse("1.2.") → caught into null because that trailing dot is a whole crime scene 🚨

still more coming, don't go anywhere — we're only getting started on the good stuff 💜

🌈 Encoding support 🌈

Okay bestie, before we talk encodings, we gotta clock the difference between code points and code units — this is the lore. A code point is the numeric ID of a symbol. A code unit is the smallest unit of storage in encoded text. One code point can be represented by one or more code units. In a fixed-length encoding, every code point uses the same number of code units. In a variable-length encoding, code points can use different numbers of code units.

Also note: the "any" rule [^] matches any code point, but not necessarily any code unit — the only way to match any code unit no matter the encoding is the default rule *. The generated lexer works with a stream of code units: yych stores a code unit, and YYCTYPE is the code unit type. Regexes, on the other hand, are specified in terms of code points. When re2zig compiles regexes to automata, it translates code points to code units. This is generally not a simple mapping: in variable-length encodings a single code point range may get translated to a complex code unit graph. The following encodings are supported:

  • ASCII — enabled by default. It's a fixed-length encoding with code space [0-255] and 1-byte code points and code units.
  • EBCDIC — enabled with --ebcdic or re2c:encoding:ebcdic. It's a fixed-length encoding with code space [0-255] and 1-byte code points and code units.
  • UCS2 — enabled with --ucs2 or re2c:encoding:ucs2. It's a fixed-length encoding with code space [0-0xFFFF] and 2-byte code points and code units.
  • UTF8 — enabled with --utf8 or re2c:encoding:utf8. It's a variable-length Unicode encoding. Code unit size is 1 byte. Code points are represented with 1 -- 4 code units.
  • UTF16 — enabled with --utf16 or re2c:encoding:utf16. It's a variable-length Unicode encoding. Code unit size is 2 bytes. Code points are represented with 1 -- 2 code units.
  • UTF32 — enabled with --utf32 or re2c:encoding:utf32. It's a fixed-length Unicode encoding with code space [0-0x10FFFF] and 4-byte code points and code units.

The include files include/unicode_blocks.re, include/unicode_categories.re and include/unicode_properties.re provide re2zig definitions for blocks, categories and properties described in the Unicode standard.

Option --input-encoding specifies source file encoding, which can be used to enable Unicode literals in regular expressions. For example --input-encoding utf8 tells re2zig that the source file is in UTF8 (it differs from --utf8, which sets input text encoding). Option --encoding-policy specifies the way re2zig handles Unicode surrogates (code points in range [0xD800-0xDFFF]).

Below is an example of a lexer for UTF8 encoded Unicode identifiers.

// re2zig $INPUT -o $OUTPUT --utf8

const std = @import("std");

%{include "unicode_categories.re" %}

fn lex(yyinput: [:0]const u8) bool {
    var yycursor: u32 = 0;
    var yymarker: u32 = 0;

    %{
        re2c:yyfill:enable = 0;

        // Simplified "Unicode Identifier and Pattern Syntax"
        // (see https://unicode.org/reports/tr31)
        id_start    = L | Nl | [$_];
        id_continue = id_start | Mn | Mc | Nd | Pc | [\u200D\u05F3];
        identifier  = id_start id_continue*;

        identifier { return true; }
        *          { return false; }
    %}
}

test {
    try std.testing.expect(lex("_Ыдентификатор"));
}

🎀 Include files 🎀

re2zig lets you include other files using a block like /*!include:re2c FILE */ or %{include FILE %}, or an in-block directive !include FILE ;, where FILE is a path to the file to be included. re2zig looks for include files in the directory of the including file and in include locations, which you can specify with the -I option.

Include blocks/directives in re2zig work the same way as C/C++ #include: FILE contents are copy-pasted verbatim in place of the block/directive. Include files may have further includes of their own. Use the --depfile option to track build dependencies of the output file on include files. re2zig provides some predefined include files that can be found in the include/ subdirectory of the project. These files contain definitions that may be useful to other projects (such as Unicode categories) and form something like a standard library for re2zig. Below is an example of using include files.

✨ Include file 1 (definitions.zig) ✨

const Num = enum { integer, floating, nan };

%{
    number = [1-9][0-9]*;
%}

✨ Include file 2 (extra_rules.re.inc) ✨

// floating-point numbers
frac  = [0-9]* "." [0-9]+ | [0-9]+ ".";
exp   = 'e' [+-]? [0-9]+;
float = frac exp? | [0-9]+ exp;

float { return Num.floating; }

✨ Input file ✨

// re2zig $INPUT -o $OUTPUT

const std = @import("std");

%{include "definitions.zig" %}

fn lex(yyinput: [:0]const u8) Num {
    var yycursor: u32 = 0;
    var yymarker: u32 = 0;
    %{
        re2c:yyfill:enable = 0;

        *      { return Num.nan; }
        number { return Num.integer; }
        !include "extra_rules.re.inc";
    %}
}

test {
    try std.testing.expectEqual(lex("123"), Num.integer);
    try std.testing.expectEqual(lex("123.4567"), Num.floating);
}

🦋 Header files 🦋

re2zig can generate a header file from the input .re file using the --header option or re2c:header configuration, and block pairs of the form /*!header:re2c:on*/ and /*!header:re2c:off*/, or %{header:on%} and %{header:off%}. The first block marks the beginning of the header file, and the second block marks the end of it. Everything between these blocks is processed by re2zig, and the generated code is written to the file specified with --header option or re2c:header configuration (or stdout if neither option nor configuration is used). An autogenerated header file may be needed in cases when re2zig is used to generate definitions that must be visible from other translation units.

Here's an example of generating a header file that contains the definition of the lexer state with tag variables (the number of variables depends on the regular grammar and is unknown to the programmer).

✨ Input file ✨

// re2zig $INPUT -o $OUTPUT --header lexer/state.zig

const std = @import("std");
const state = @import("lexer/state.zig"); // the module is generated by re2c

%{header:on %}
pub const State = struct {
    yyinput: [:0]const u8,
    yycursor: usize,
    %{stags format = "@@: usize,"; %}
};
%{header:off %}

fn lex(yyrecord: *state.State) usize {
    var t: usize = 0;
    %{
        re2c:header = "lexer/state.zig";
        re2c:api = record;
        re2c:yyfill:enable = 0;
        re2c:tags = 1;

        [a]* @t [b]* { return t; }
    %}
}

test {
    var st = state.State {
        .yyinput = "ab",
        .yycursor = 0,
        %{stags format = ".@@ = 0,"; %}
    };
    try std.testing.expectEqual(lex(&st), 1);
}

✨ Header file ✨

// Generated by re2c

pub const State = struct {
    yyinput: [:0]const u8,
    yycursor: usize,
    yyt1: usize,
};

💅 Skeleton programs 💅

With the -S, --skeleton option, re2zig ignores all non-re2zig code and generates a self-contained C program that can be further compiled and executed. The program consists of lexer code and input data. For each constructed DFA (block or condition) re2zig generates a standalone lexer and two files: an .input file with strings derived from the DFA and a .keys file with expected match results. The program runs each lexer on the corresponding .input file and compares results with the expectations. Skeleton programs are very useful for a number of reasons:

  • They can check correctness of various re2zig optimizations (the data is generated early in the process, before any DFA transformations have taken place).
  • Generating a set of input data with good coverage may be useful for both testing and benchmarking.
  • Generating self-contained executable programs allows one to get minimized test cases (the original code may be large or have a lot of dependencies).

The difficulty with generating input data is that for all but the most trivial cases the number of possible input strings is too large (even if the string length is limited). re2zig solves this difficulty by generating sufficiently many strings to cover almost all DFA transitions. It uses the following algorithm. First, it constructs a skeleton of the DFA. For encodings with 1-byte code unit size (such as ASCII, UTF-8 and EBCDIC) skeleton is just an exact copy of the original DFA. For encodings with multibyte code units skeleton is a copy of DFA with certain transitions omitted: namely, re2zig takes at most 256 code units for each disjoint continuous range that corresponds to a DFA transition. The chosen values are evenly distributed and include range bounds. Instead of trying to cover all possible paths in the skeleton (which is infeasible) re2zig generates sufficiently many paths to cover all skeleton transitions, and thus trigger the corresponding conditional jumps in the lexer. The algorithm implementation is limited by ~1Gb of transitions and consumes constant amount of memory (re2zig writes data to file as soon as it is generated).

🔥 Visualization and debug 🔥

With the -D, --emit-dot option, re2zig does not generate code. Instead, it dumps the generated DFA in DOT format. You can convert this dump to an image of the DFA using Graphviz or another library. Note that this option shows the final DFA after it has gone through a number of optimizations and transformations. Earlier stages can be dumped with various debug options, such as --dump-nfa, --dump-dfa-raw etc. (see the full list of options).

💖 SEE ALSO 💖

You can find more information about re2c at the official website: http://re2c.org. Similar programs are flex(1), lex(1), quex(‐ http://quex.sourceforge.net).

👑 AUTHORS 👑

re2zig was originally written by Peter Bumbulis (peter@csg.uwaterloo.ca) in 1993. Marcus Boerger and Dan Nuffer spent several years to turn the original idea into a production ready code generator. Since then it has been maintained and developed by multiple volunteers, most notably, Brian Young (bayoung@acm.org), Marcus Boerger, Dan Nuffer (nuffer@users.sourceforge.net), Ulya Trofimovich (skvadrik@gmail.com), Serghei Iakovlev, Sergei Trofimovich, Petr Skocik, ligfx raekye and PolarGoose.

Okay, that’s the whole RE2ZIG(1) page, bestie — footer/source/version/date energy is giving “mysterious manpage footer,” but this cute sign-off is the real main character. Go lex something iconic. 💖✨🫶

📦 where this page comes from