RE2C(1)

NAME
re2c - generate fast lexical analyzers for C/C++ and Go

SYNOPSIS

re2c [OPTIONS] INPUT [-o OUTPUT]

re2go [OPTIONS] INPUT [-o OUTPUT]

Note: This manual includes examples for Go, but it refers to re2c (rather than re2go) as the name of the program in general.

INTRODUCTION

Re2c works as a preprocessor. It reads the input file (which is usually a program in the target language, but can be anything) and looks for blocks of code enclosed in special-form comments. The text outside of these blocks is copied verbatim into the output file. The contents of the blocks are processed by re2c. It translates them to code in the target language and outputs the generated code in place of the block. There are different kinds of blocks; see the blocks and directives section for a full list of them. The main block kinds are the following:

/*!re2c[:<name>] ... */
    A global block that contains a mixture of named definitions, configurations, directives and rules (regular expressions with associated semantic actions). Re2c compiles regular expressions to a deterministic finite automaton, encodes it in the form of conditional jumps and replaces the block with the generated code. Names and configurations defined in the block are added to the global scope and become visible to subsequent blocks (at the start of the program global scope is initialized with the command-line options). The :<name> part is optional: if specified, the name can be used to refer to the block in another part of the program.

/*!local:re2c[:<name>] ... */
    A local block is like a global block, but the names and configurations defined in it have local scope (they do not affect other blocks).

/*!rules:re2c[:<name>] ... */
    A rules block is like a local block, but it does not generate any code and is meant to be reused in other blocks. This is a way of sharing code (more details in the reusable blocks section).

    A block may contain the following kinds of statements:

<name> = <regular expression>;
    A named definition binds a name to a regular expression. Names may contain alphanumeric characters and underscore. The regular expressions section gives an overview of re2c 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 re2c behavior and customize the generated code. For a full list of configurations supported by re2c 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 a regular expression to a semantic action (a block of code in the target language). If the regular expression matches, the associated semantic action 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 $. The 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. If start conditions are used, rules have more complex syntax.

!<directive>;
    A directive is one of the special predefined statements. Each directive has a unique purpose. For example, the !use directive merges a rules block into the current one (see the reusable blocks section), and the !include directive allows one to include an outer file (see the include files section).

    The generated code interfaces with the outer program with the help of primitives -- symbolic names that can be defined as variables, functions or macros in the target language (collectively referred to as the API). The primitives should be defined by the user. This approach gives the user freedom and flexibility in customizing the lexer, but it also requires some understanding of how the lexer works in order to implement the primitives correctly and efficiently. The manual provides examples for the most popular use cases. For the full list of primitives see the interface primitives section.

    There are two API flavours that define the set of primitives used by re2c:

Pointer API
    This API is also called default API, since it was historically the first, and for a long time the only one. This is a more restrictive API based on C pointer arithmetics. It consists of pointer-like primitives YYCURSOR, YYMARKER, YYCTXMARKER, YYLIMIT (which are normally defined as pointers of type YYCTYPE*) and YYFILL. Pointer API is enabled by default for the C backend, and it cannot be used with backends that do not support pointer arithmetics.

Generic API
    This is a more flexible API that does not assume pointer semantics. It consists of primitives YYPEEK, YYSKIP, YYBACKUP, YYBACKUPCTX, YYSTAGP, YYSTAGN, YYMTAGP, YYMTAGN, YYRESTORE, YYRESTORECTX, YYRESTORETAG, YYSHIFT, YYSHIFTSTAG, YYSHIFTMTAG, YYLESSTHAN and YYFILL. For the C backend generic API is enabled with --input custom option or re2c:flags:input = custom; configuration; for the Go backend it is enabled by default. Generic API was added in version 0.14. It is intentionally designed to give the user as much freedom as possible in redefining the input model and the semantics of different actions performed by the generated code.

    There are two API styles determine the form in which the primitives should be defined:

Free-form
    This style is enabled with re2c:api:style = free-form; configuration, and it is the default for the Go backend. Interface primitives should be defined as free-form pieces of code with interpolated variables of the form @@{name} or optionally just @@ if there is only one variable. The @@ text can be customized with the re2c:api:sigil configuration. In Go free-form style generic API can be defined in terms of integer variables cursor, limit, marker, ctxmarker and a string (or a byte slice) data as follows:

    /*!re2c
    re2c:define:YYPEEK       = "data[cursor]";
    re2c:define:YYSKIP       = "cursor++";
    re2c:define:YYBACKUP     = "marker = cursor";
    re2c:define:YYRESTORE    = "cursor = marker";
    re2c:define:YYBACKUPCTX  = "ctxmarker = cursor";
    re2c:define:YYRESTORECTX = "cursor = ctxmarker";
    re2c:define:YYRESTORETAG = "cursor = ${tag}";
    re2c:define:YYLESSTHAN   = "limit - cursor < @@{len}";
    re2c:define:YYSTAGP      = "@@{tag} = cursor";
    re2c:define:YYSTAGN      = "@@{tag} = -1";
    re2c:define:YYSHIFT      = "cursor += @@{shift}";
    re2c:define:YYSHIFTSTAG  = "@@{tag} += @@{shift}";
    */

Function-like
    This style is enabled with re2c:api:style = functions; configuration. Primitives should be defined as functions with parentheses, accepting the necessary number of arguments. This style can be used with the Go backend, but it is more restrictive than the free-form style and some primitives are problematic to define. Most of the primitives can be defined as closures in terms of integer variables cursor, limit, marker, ctxmarker and a string (or a byte slice) data:

    YYPEEK := func() byte { return data[cursor] }
    YYSKIP := func() { cursor++ }
    YYBACKUP := func() { marker = cursor }
    YYRESTORE := func() { cursor = marker }
    YYBACKUPCTX := func() { ctxmarker = cursor }
    YYRESTORECTX := func() { cursor = ctxmarker }
    YYLESSTHAN := func(n int) bool { return limit-cursor < n }
    YYSHIFT := func(n int) { cursor += n }

    For YYFILL definition and instructions how to customize or disable end-of-input checks see the handling the end of input and buffer refilling sections.

EXAMPLE

Here is a simple re2c program:

//go:generate re2go $INPUT -o $OUTPUT -i
package main                              //
                                          //
func lex(str string) {                    // Go code
    var cursor int                        //
                                          //
/*!re2c
    re2c:define:YYCTYPE = byte;           //
    re2c:define:YYPEEK = "str[cursor]";   //
    re2c:define:YYSKIP = "cursor += 1";   // configurations
    re2c:yyfill:enable = 0;               //
    re2c:flags:nested-ifs = 1;            //
                                          //
    number = [1-9][0-9]*;                 // named definition
                                          //
    number { return }                     // rules
    *      { panic("error!"); }           //
*/
}                                         //
                                          //
func main() {                             // Go code
    lex("1234\x00")                       //
}                                         //

The generated code looks like this:

// Code generated by re2c, DO NOT EDIT.
//go:generate re2go $INPUT -o $OUTPUT -i
package main                              //
                                          //
func lex(str string) {                    // Go code
    var cursor int                        //
                                          //
{
    var yych byte
    yych = str[cursor]
    if (yych <= '0') {
        goto yy2
    }
    if (yych <= '9') {
        goto yy4
    }
yy2:
    cursor += 1
    { panic("error!"); }
yy4:
    cursor += 1
    yych = str[cursor]
    if (yych <= '/') {
        goto yy6
    }
    if (yych <= '9') {
        goto yy4
    }
yy6:
    { return }
}
}                                         //
                                          //
func main() {                             // Go code
    lex("1234\x00")                       //
}                                         //

COMMAND-LINE OPTIONS

Command-line interface consists of options and warnings. Some of the options have corresponding configurations, others are global and cannot be changed after re2c starts reading the input file. Debug options generally require building re2c in debug configuration. Internal options are useful for experimenting with the algorithms used in re2c. Warnings can be invividually enabled, disabled and turned into an error.

-? -h --help
    Show help message.

-1 --single-pass
    Deprecated. Does nothing (single pass is the default now).

-8 --utf-8
    Generate a lexer that reads input in UTF-8 encoding. re2c assumes that character range is 0 -- 0x10FFFF and character size is 1 byte.

-b --bit-vectors
    Optimize conditional jumps using bit masks. Implies -s.

-c --conditions --start-conditions
    Enable support of Flex-like "conditions": multiple interrelated lexers within one block. Option --start-conditions is a legacy alias; use --conditions instead.

--case-insensitive
    Treat single-quoted and double-quoted strings as case-insensitive.

--case-inverted
    Invert the meaning of single-quoted and double-quoted strings: treat single-quoted strings as case-sensitive and double-quoted strings as case-insensitive.

--case-ranges
    Collapse consecutive cases in a switch statements into a range of the form case low ... high:. This syntax is an extension of the C/C++ language, supported by compilers like GCC, Clang and Tcc. The main advantage over using single cases is smaller generated C code and faster generation time, although for some compilers like Tcc it also results in smaller binary size. This option doesn't work for the Go backend.

--depfile FILE
    Write dependency information to FILE in the form of a Makefile rule <output-file> : <input-file> [include-file ...]. This allows to track build dependencies in the presence of /*!include:re2c*/ directives, so that updating include files triggers regeneration of the output file. This option requires that -o --output option is specified.

-e --ecb
    Generate a lexer that reads input in EBCDIC encoding. re2c assumes that character range is 0 -- 0xFF an character size is 1 byte.

--empty-class <match-empty | match-none | error>
    Define the way re2c treats empty character classes. With match-empty (the default) empty class matches empty input (which is illogical, but backwards-compatible). With match-none empty class always fails to match. With error empty class raises a compilation error.

--encoding-policy <fail | substitute | ignore>
    Define the way re2c treats Unicode surrogates. With fail re2c aborts with an error when a surrogate is encountered. With substitute re2c silently replaces surrogates with the error code point 0xFFFD. With ignore (the default) re2c treats surrogates as normal code points. The Unicode standard says that standalone surrogates are invalid, but real-world libraries and programs behave in different ways.

-f --storable-state
    Generate a lexer which can store its inner state. This is useful in push-model lexers which are stopped by an outer program when there is not enough input, and then resumed when more input becomes available. In this mode users should additionally define YYGETSTATE() and YYSETSTATE(state) macros and variables yych, yyaccept and state as part of the lexer state.

-F --flex-syntax
    Partial support for Flex syntax: in this mode named definitions don't need the equal sign and the terminating semicolon, and when used they must be surrounded by curly braces. Names without curly braces are treated as double-quoted strings.

-g --computed-gotos
    Optimize conditional jumps using non-standard "computed goto" extension (which must be supported by the compiler). re2c generates jump tables only in complex cases with a lot of conditional branches. Complexity threshold can be configured with cgoto:threshold configuration. This option implies -b. This option doesn't work for the Go backend.

-I PATH
    Add PATH to the list of locations which are used when searching for include files. This option is useful in combination with /*!include:re2c ... */ directive. Re2c looks for FILE in the directory of including file and in the list of include paths specified by -I option.

-i --no-debug-info
    Do not output #line information. This is useful when the generated code is tracked by some version control system or IDE.

--input <default | custom>
    Specify the API used by the generated code to interface with used-defined code. Option default is the C API based on pointer arithmetic (it is the default for the C backend). Option custom is the generic API (it is the default for the Go backend).

--input-encoding <ascii | utf8>
    Specify the way re2c parses regular expressions. With ascii (the default) re2c handles input as ASCII-encoded: any sequence of code units is a sequence of standalone 1-byte characters. With utf8 re2c handles input as UTF8-encoded and recognizes multibyte characters.

--lang <c | go>
    Specify the output language. Supported languages are C and Go (the default is C).

--location-format <gnu | msvc>
    Specify location format in messages. With gnu locations are printed as 'filename:line:column: ...'. With msvc locations are printed as 'filename(line,column) ...'. Default is gnu.

--no-generation-date
    Suppress date output in the generated file.

--no-version
    Suppress version output in the generated file.

-o OUTPUT --output=OUTPUT
    Specify the OUTPUT file.

-P --posix-captures
    Enable submatch extraction with POSIX-style capturing groups.

-r --reusable
    Deprecated since re2c version 2.2 (reusable blocks are allowed by default now).

-S --skeleton
    Ignore user-defined interface code and generate a self-contained "skeleton" program. Additionally, generate 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. This option doesn't work for the Go backend.

-s --nested-ifs
    Use nested if statements instead of switch statements in conditional jumps. This usually results in more efficient code with non-optimizing compilers.

-T --tags
    Enable submatch extraction with tags.

-t HEADER --type-header=HEADER
    Generate a HEADER file that contains enum with condition names. Requires -c option.

-u --unicode
    Generate a lexer that reads UTF32-encoded input. Re2c assumes that character range is 0 -- 0x10FFFF and character size is 4 bytes. This option implies -s.

-V --vernum
    Show version information in MMmmpp format (major, minor, patch).

--verbose
    Output a short message in case of success.

-v --version
    Show version information.

-w --wide-chars
    Generate a lexer that reads UCS2-encoded input. Re2c assumes that character range is 0 -- 0xFFFF and character size is 2 bytes. This option implies -s.

-x --utf-16
    Generate a lexer that reads UTF16-encoded input. Re2c assumes that character range is 0 -- 0x10FFFF and character size is 2 bytes. This option implies -s.

-D --emit-dot
    Instead of normal output generate 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).

-d --debug-output
    Emit YYDEBUG in the generated code. YYDEBUG should be defined by the user in the form of a void function with two parameters: state (lexer state or -1) and symbol (current input symbol of type YYCTYPE).

--dump-adfa
    Debug option: output DFA after tunneling (in .dot format).

--dump-cfg
    Debug option: output control flow graph of tag variables (in .dot format).

--dump-closure-stats
    Debug option: output statistics on the number of states in closure.

--dump-dfa-det
    Debug option: output DFA immediately after determinization (in .dot format).

--dump-dfa-min
    Debug option: output DFA after minimization (in .dot format).

--dump-dfa-tagopt
    Debug option: output DFA after tag optimizations (in .dot format).

--dump-dfa-tree
    Debug option: output DFA under construction with states represented as tag history trees (in .dot format).

--dump-dfa-raw
    Debug option: output DFA under construction with expanded state-sets (in .dot format).

--dump-interf
    Debug option: output interference table produced by liveness analysis of tag variables.

--dump-nfa
    Debug option: output NFA (in .dot format).

--dfa-minimization <moore | table>
    Internal option: DFA minimization algorithm used by re2c. The moore option is the Moore algorithm (it is the default). The table option 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.

--eager-skip
    Internal option: make the generated lexer advance the input position eagerly -- immediately after reading the input symbol. This changes the default behavior when the input position is advanced lazily -- after transition to the next state. This option is implied by --no-lookahead.

--no-lookahead
    Internal option: use TDFA(0) instead of TDFA(1). This option has effect only with --tags or --posix-captures options.

--no-optimize-tags
    Internal optionL: suppress optimization of tag variables (useful for debugging).

--posix-closure <gor1 | gtop>
    Internal option: specify shortest-path algorithm used for the construction of epsilon-closure with POSIX disambiguation semantics: gor1 (the default) stands for Goldberg-Radzik algorithm, and gtop stands for "global topological order" algorithm.

--posix-prectable <complex | naive>
    Internal option: specify the algorithm used to compute POSIX precedence table. The complex algorithm computes precedence table in one traversal of 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 is much simpler than complex and may be slightly faster in non-pathological cases.

--stadfa
    Internal option: use staDFA algorithm for submatch extraction. The main difference with TDFA is that tag operations in staDFA are placed in states, not on transitions.

--fixed-tags <none | toplevel | all>
    Internal option: specify whether the fixed-tag optimization should be applied to all tags (all), none of them (none), or only those in toplevel concatenation (toplevel). The default is all. "Fixed" tags are those that are located within a fixed distance to some other tag (called "base"). In such cases only tha base tag needs to be tracked, and the value of the fixed tag can be computed as the value of the base tag plus a static offset. For tags that are under alternative or repetition it is also necessary to check if the base tag has a no-match value (in that case fixed tag should also be set to no-match, disregarding the offset). For tags in top-level concatenation the check is not needed, because they always match.

-W  Turn on all warnings.

-Werror
    Turn warnings into errors. Note that this option alone doesn't turn on any warnings; it only affects those warnings that have been turned on so far or will be turned on later.

-W<warning>
    Turn on warning.

-Wno-<warning>
    Turn off warning.

-Werror-<warning>
    Turn on warning and treat it as an error (this implies -W<warning>).

-Wno-error-<warning>
    Don't treat this particular warning as an error. This doesn't turn off the warning itself.

-Wcondition-order
    Warn if the generated program makes implicit assumptions about condition numbering. One should use either the -t, --type-header option or the /*!types:re2c*/ directive to generate a mapping of condition names to numbers and then use the autogenerated condition names.

-Wempty-character-class
    Warn if a regular expression contains an empty character class. Trying to match an empty character class makes no sense: it should always fail. However, for backwards compatibility reasons re2c allows empty character classes and treats them as empty strings. Use the --empty-class option to change the default behavior.

-Wmatch-empty-string
    Warn if a rule is nullable (matches an empty string). If the lexer runs in a loop and the empty match is unintentional, the lexer may unexpectedly hang in an infinite loop.

-Wswapped-range
    Warn if the lower bound of a range is greater than its upper bound. The default behavior is to silently swap the range bounds.

-Wundefined-control-flow
    Warn if some input strings cause undefined control flow in the lexer (the faulty patterns are reported). This is the most dangerous and most common mistake. It can be easily fixed by adding the default rule * which has the lowest priority, matches any code unit, and consumes exactly one code unit.

-Wunreachable-rules
    Warn about rules that are shadowed by other rules and will never match.

-Wuseless-escape
    Warn if a symbol is escaped when it shouldn't be. By default, re2c silently ignores such escapes, but this may as well indicate a typo or an error in the escape sequence.

-Wnondeterministic-tags
    Warn if a tag has n-th degree of nondeterminism, where n is greater than 1.

-Wsentinel-in-midrule
    Warn if the sentinel symbol occurs in the middle of a rule --- 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.

BLOCKS AND DIRECTIVES

Below is the list of re2c directives (syntactic constructs that mark the beginning and end of the code that should be processed by re2c). Named blocks were added in re2c version 2.2. They are exactly the same as unnamed blocks, except that the name can be used to reference a block in other parts of the program. More information on each directive can be found in the related sections.

/*!re2c[:<name>] ... */
    A global re2c block with an optional name. The block may contain named definitions, configurations and rules in any order. Named definitions and configurations are defined in the global scope, so they are inherited by subsequent blocks. The code for a global block is generated at the point where the block is specified.

/*!local:re2c[:<name>] ... */
    A local re2c block with an optional name. Unlike global blocks, definitions and configurations inside of a local block are not added into the global scope. In all other respects local blocks are the same as global blocks.

/*!rules:re2c[:<name>] ... */
    A reusable block with an optional name. Rules blocks have the same structure as local or global blocks, but they do not produce any code and they can be reused multiple times in other blocks with the help of a !use:<name>; directive or a /*!use:re2c[:<name>] ... */ block. A rules block on its own does not add any definitions into the global scope. The code for it is generated at the point of use. Prior to re2c version 2.2 rules blocks required -r --reusable option.

/*!use:re2c[:<name>] ... */
    A use block that references a previously defined rules block. If the name is specified, re2c 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 re2c version 2.2 use blocks required -r --reusable option.

!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.

/*!max:re2c[:<name1>[:<name2>...]] ... */
    A directive 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:re2c[:<name1>[:<name2>...]] ... */
    A directive 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.

/*!stags:re2c[:<name1>[:<name2>...]] ... */, /*!mtags:re2c[:<name1>[:<name2>...]] ... */
    Directives that specify a template piece of code that is expanded for each s-tag/m-tag variable generated by re2c. 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.

/*!getstate:re2c[:<name1>[:<name2>...]] ... */
    A directive that generates conditional dispatch on the lexer state (it requires -f --storable-state option). An optional list of block names specifies 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.

/*!types:re2c[:<name1>[:<name2>...]] ... */
    A directive that generates condition enumeration (it requires -c --conditions option). An optional list of block names specifies which blocks should be included when computing the set of conditions (if the list is empty, all blocks are included). By default the generated code is an enumeration YYCONDTYPE. It can be customized with optional configurations format and separator. Configuration format specifies 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. Configuration separator specifies a piece of code used to join the generated format pieces for different conditions.

/*!include:re2c <file> */
    This directive allows one to include <file>, which must be a double-quoted file path. The contents of the file are literally substituted in place of the directive, in the same way as #include works in C/C++. This directive can be used together with the --depfile option to generate build system dependencies on the included files.

!include <file>;
    This directive is the same as /*!include:re2c <file> */, except that it should be used inside of a re2c block.

/*!header:re2c:on*/
    This directive marks the start of header file. Everything after it and up to the following /*!header:re2c:off*/ directive is processed by re2c and written to the header file specified with -t --type-header option.

/*!header:re2c:off*/
    This directive marks the end of header file started with /*!header:re2c:on*/.

/*!ignore:re2c ... */
    A block which contents are ignored and removed from the output file.

%{ ... %}
    A global re2c block in -F --flex-support mode. This is deprecated and exists for backward compatibility.

INTERFACE PRIMITIVES

Here is a list of API primitives that may be used by the generated code in order to interface with the outer program. Which primitives are needed depends on multiple factors, including the complexity of regular expressions, input representation, buffering, the use of various features and so on. All the necessary primitives should be defined by the user in the form of macros, functions, variables, free-form pieces of code or any other suitable form. Re2c does not (and cannot) check the definitions, so if anything is missing or defined incorrectly the generated code will not compile.

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.

YYCURSOR
    A pointer-like l-value that stores the current input position (usually a pointer of type YYCTYPE*). Initially YYCURSOR should point to the first input character. It is advanced by the generated code. When a rule matches, YYCURSOR points to the one after the last matched character. It is used only in the default C API.

YYLIMIT
    A pointer-like r-value that stores the end of input position (usually a pointer of type YYCTYPE*). Initially YYLIMIT should point to the one after the last available input character. It is not changed by the generated code. Lexer compares YYCURSOR to YYLIMIT in order to determine if there is enough input characters left. YYLIMIT is used only in the default C API.

YYMARKER
    A pointer-like l-value (usually a pointer of type YYCTYPE*) that stores the position of the latest matched rule. It is used to restores YYCURSOR position if the longer match fails and lexer needs to rollback. Initialization is not needed. YYMARKER is used only in the default C API.

YYCTXMARKER
    A pointer-like l-value that stores the position of the trailing context (usually a pointer of type YYCTYPE*). No initialization is needed. It is used only in the default C API, and only with the lookahead operator /.

YYFILL
    API primitive with one argument len. The meaning of YYFILL is to provide at least len more input characters or fail. If EOF rule is used, YYFILL should always return to the calling function; the return value should be zero on success and non-zero on failure. If EOF rule is not used, YYFILL return value is ignored and it should not return on failure. Maximal value of len is YYMAXFILL, which can be generated with /*!max:re2c*/ directive. The definition of YYFILL can be either function-like or free-form depending on the API style (see re2c:api:style and re2c:define:YYFILL:naked).

YYMAXFILL
    An integral constant equal to the maximal value of YYFILL argument. It can be generated with /*!max:re2c*/ directive.

YYLESSTHAN
    A generic API primitive with one argument len. It should be defined as an r-value of boolean type that equals true if and only if there is less than len input characters left. The definition can be either function-like or free-form depending on the API style (see re2c:api:style).

YYPEEK
    A generic API primitive with no arguments. It should be defined as an r-value of type YYCTYPE that is equal to the character at the current input position. The definition can be either function-like or free-form depending on the API style (see re2c:api:style).

YYSKIP
    A generic API primitive with no arguments. The meaning of YYSKIP is to advance the current input position by one character. The definition can be either function-like or free-form depending on the API style (see re2c:api:style).

YYBACKUP
    A generic API primitive with no arguments. The meaning of YYBACKUP is to save the current input position, which is later restored with YYRESTORE. The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYRESTORE
    A generic API primitive with no arguments. The meaning of YYRESTORE is to restore the current input position to the value saved by YYBACKUP. The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYBACKUPCTX
    A generic API primitive with zero arguments. The meaning of YYBACKUPCTX is to save the current input position as the position of the trailing context, which is later restored by YYRESTORECTX. The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYRESTORECTX
    A generic API primitive with no arguments. The meaning of YYRESTORECTX is to restore the trailing context position saved with YYBACKUPCTX. The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYRESTORETAG
    A generic API primitive with one argument tag. The meaning of YYRESTORETAG is to restore the trailing context position to the value of tag. The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYSTAGP
    A generic API primitive with one argument tag. The meaning of YYSTAGP is to set tag value to the current input position. The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYSTAGN
    A generic API primitive with one argument tag. The meaning of YYSTAGN is to set tag value to null (or some default value). The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYMTAGP
    A generic API primitive with one argument tag. The meaning of YYMTAGP is to append the current position to the history of tag. The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYMTAGN
    A generic API primitive with one argument tag. The meaning of YYMTAGN is to append null (or some other default) value to the history of tag. The definition can be either function-like or free-form depending on the API style (see re2c:api:style).

YYSHIFT
    A generic API primitive with one argument shift. The meaning of YYSHIFT is to shift the current input position by shift characters (the shift value may be negative). The definition can be either function-like or free-form depending on the API style (see re2c:api:style).

YYSHIFTSTAG
    A generic API primitive with two arguments, tag and shift. The meaning of YYSHIFTSTAG is to shift tag by shift characters (the shift value may be negative). The definition can be either function-like or free-form depending on the API style (see re2c:api:style).

YYSHIFTMTAG
    A generic API primitive with two arguments, tag and shift. The meaning of YYSHIFTMTAG is to shift the latest value in the history of tag by shift characters (the shift value may be negative). The definition should be either function-like or free-form depending on the API style (see re2c:api:style).

YYMAXNMATCH
    An integral constant equal to the maximal number of POSIX capturing groups in a rule. It is generated with /*!maxnmatch:re2c*/ directive.

YYCONDTYPE
    The type of the condition enum. It should be generated either with /*!types:re2c*/ directive or -t --type-header option.

YYGETCONDITION
    An API primitive with zero arguments. It should be defined as an r-value of type YYCONDTYPE that is equal to the current condition identifier. The definition can be either function-like or free-form depending on the API style (see re2c:api:style and re2c:define:YYGETCONDITION:naked).

YYSETCONDITION
    An API primitive with one argument cond. The meaning of YYSETCONDITION is to set the current condition identifier to cond. The definition should be either function-like or free-form depending on the API style (see re2c:api:style and re2c:define:YYSETCONDITION@cond).

YYGETSTATE
    An API primitive with zero arguments. It should be defined as an r-value of integer type that is equal to the current lexer state. Should be initialized to -1. The definition can be either function-like or free-form depending on the API style (see re2c:api:style and re2c:define:YYGETSTATE:naked).

YYSETSTATE
    An API primitive with one argument state. The meaning of YYSETSTATE is to set the current lexer state to state. The definition should be either function-like or free-form depending on the API style (see re2c:api:style and re2c:define:YYSETSTATE@state).

YYDEBUG
    A debug API primitive with two arguments. It can be used to debug the generated code (with -d --debug-output option). YYDEBUG should return no value and accept two arguments: state (either a DFA state index or -1) and symbol (the current input symbol).

yych
    An l-value of type YYCTYPE that stores the current input character. User definition is necessary only with -f --storable-state option.

yyaccept
    An l-value of unsigned integral type that stores the number of the latest matched rule. User definition is necessary only with -f --storable-state option.

yynmatch
    An l-value of unsigned integral type that stores the number of POSIX capturing groups in the matched rule. Used only with -P --posix-captures option.

yypmatch
    An array of l-values that are used to hold the tag values corresponding to the capturing parentheses in the matching rule. Array length must be at least yynmatch * 2 (usually YYMAXNMATCH * 2 is a good choice). Used only with -P --posix-captures option.

CONFIGURATIONS

re2c:flags:t, re2c:flags:type-header
    Specify the name of the generated header file relative to the directory of the output file. (Same as -t, --type-header command-line option except that the filepath is relative.)

re2c:flags:input
    Same as --input command-line option.

re2c:api:style
    Allows one to specify the style of generic API. Possible values are functions and free-form. With functions style (the default for the C backend) API primitives behave like functions, and re2c generates parentheses with an argument list after the name of each primitive. With free-form style (the default for the Go backend) re2c treats API definitions as interpolated strings and substitutes argument placeholders with the actual argument values. This option can be overridden by options for individual API primitives, e.g. re2c:define:YYFILL:naked for YYFILL.

re2c:api:sigil
    Allows one to specify the "sigil" symbol (or string) that is used to recognize argument placeholders in the definitions of generic API primitives. The default value is @@. Placeholders start with sigil, followed by the argument name in curly braces. For example, if 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:define:YYFILL@len for YYFILL.

re2c:define:YYCTYPE
    Defines YYCTYPE (see the user interface section).

re2c:define:YYCURSOR
    Defines C API primitive YYCURSOR (see the user interface section).

re2c:define:YYLIMIT
    Defines C API primitive YYLIMIT (see the user interface section).

re2c:define:YYMARKER
    Defines C API primitive YYMARKER (see the user interface section).

re2c:define:YYCTXMARKER
    Defines C API primitive YYCTXMARKER (see the user interface section).

re2c:define:YYFILL
    Defines API primitive YYFILL (see the user interface section).

re2c:define:YYFILL@len
    Specifies the sigil used for argument substitution in YYFILL definition. Defaults to @@. Overrides the more generic re2c:api:sigil configuration.

re2c:define:YYFILL:naked
    Allows one to override re2c:api:style for YYFILL. Value 0 corresponds to free-form API style.

re2c:yyfill:enable
    Defaults to 1 (YYFILL is enabled). Set this to zero to suppress the generation of YYFILL. Use warnings (-W option) and re2c:sentinel configuration to verify that the generated lexer cannot read past the end of input, as this might introduce severe security issues to your programs.

re2c:yyfill:parameter
    Controls the argument in the parentheses that follow YYFILL. Defaults to 1, which means that the argument is generated. If zero, the argument is omitted. Can be overridden with re2c:define:YYFILL:naked or re2c:api:style.

re2c:eof
    Specifies the sentinel symbol used with EOF rule $ to check for the end of input in the generated lexer. The default value is -1 (EOF rule is not used). Other possible values include all valid code units. Only decimal numbers are recognized.

re2c:sentinel
    Specifies the sentinel symbol used with the sentinel method of checking for the end of input in the generated lexer (the case when bounds checking is disabled with re2c:yyfill:enable = 0; and EOF rule $ is not used). This configuration does not affect code generation. It is used by re2c to verify that the sentinel symbol is not allowed in the middle of the rule, and prevent possible reads past the end of buffer in the generated lexer. The default value is -1 (re2c assumes that the sentinel symbol is 0, which is the most common case). Other possible values include all valid code units. Only decimal numbers are recognized.

re2c:define:YYLESSTHAN
    Defines generic API primitive YYLESSTHAN (see the user interface section).

re2c:yyfill:check
    Setting this to zero allows to suppress the generation of YYFILL check (YYLESSTHAN in generic API of YYLIMIT-based comparison in default C API). This configuration is useful when the necessary input is always available. it defaults to 1 (the check is generated).

re2c:label:yyFillLabel
    Allows one to change the prefix of YYFILL labels (used with EOF rule or with storable states).

re2c:define:YYPEEK
    Defines generic API primitive YYPEEK (see the user interface section).

re2c:define:YYSKIP
    Defines generic API primitive YYSKIP (see the user interface section).

re2c:define:YYBACKUP
    Defines generic API primitive YYBACKUP (see the user interface section).

re2c:define:YYBACKUPCTX
    Defines generic API primitive YYBACKUPCTX (see the user interface section).

re2c:define:YYRESTORE
    Defines generic API primitive YYRESTORE (see the user interface section).

re2c:define:YYRESTORECTX
    Defines generic API primitive YYRESTORECTX (see the user interface section).

re2c:define:YYRESTORETAG
    Defines generic API primitive YYRESTORETAG (see the user interface section).

re2c:define:YYSHIFT
    Defines generic API primitive YYSHIFT (see the user interface section).

re2c:define:YYSHIFTMTAG
    Defines generic API primitive YYSHIFTMTAG (see the user interface section).

re2c:define:YYSHIFTSTAG
    Defines generic API primitive YYSHIFTSTAG (see the user interface section).

re2c:define:YYSTAGN
    Defines generic API primitive YYSTAGN (see the user interface section).

re2c:define:YYSTAGP
    Defines generic API primitive YYSTAGP (see the user interface section).

re2c:define:YYMTAGN
    Defines generic API primitive YYMTAGN (see the user interface section).

re2c:define:YYMTAGP
    Defines generic API primitive YYMTAGP (see the user interface section).

re2c:flags:T, re2c:flags:tags
    Same as -T --tags command-line option.

re2c:flags:P, re2c:flags:posix-captures
    Same as -P --posix-captures command-line option.

re2c:tags:expression
    Allows one to customize the way re2c addresses tag variables. By default re2c generates expressions of the form yyt<N>. This might be inconvenient, for example if tag variables are defined as fields in a struct. Re2c recognizes placeholder of the form @@{tag} or @@ and replaces it with the actual tag name. Sigil @@ can be redefined with re2c:api:sigil configuration. For example, setting re2c:tags:expression = "p->@@"; results in expressions of the form p->yyt<N> in the generated code.

re2c:tags:prefix
    Allows one to override the prefix of tag variables (defaults to yyt).

re2c:flags:lookahead
    Same as inverted --no-lookahead command-line option.

re2c:flags:optimize-tags
    Same as inverted --no-optimize-tags command-line option.

re2c:define:YYCONDTYPE
    Defines YYCONDTYPE (see the user interface section).

re2c:define:YYGETCONDITION
    Defines API primitive YYGETCONDITION (see the user interface section).

re2c:define:YYGETCONDITION:naked
    Allows one to override re2c:api:style for YYGETCONDITION. Value 0 corresponds to free-form API style.

re2c:define:YYSETCONDITION
    Defines API primitive YYSETCONDITION (see the user interface section).

re2c:define:YYSETCONDITION@cond
    Specifies the sigil used for argument substitution in YYSETCONDITION definition. The default value is @@. Overrides the more generic re2c:api:sigil configuration.

re2c:define:YYSETCONDITION:naked
    Allows one to override re2c:api:style for YYSETCONDITION. Value 0 corresponds to free-form API style.

re2c:cond:goto
    Allows one to customize the goto statements used with the shortcut :=> rules in conditions. The default value is goto @@;. Placeholders are substituted with condition name (see re2c:api;sigil and re2c:cond:goto@cond).

re2c:cond:goto@cond
    Specifies the sigil used for argument substitution in 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 condition name (see re2c:api;sigil and re2c:cond:divider@cond).

re2c:cond:divider@cond
    Specifies the sigil used for argument substitution in re2c:cond:divider definition. The default value is @@. Overrides the more generic re2c:api:sigil configuration.

re2c:condprefix
    Specifies the prefix used for condition labels. The default value is yyc_.

re2c:condenumprefix
    Specifies the prefix used for condition identifiers. The default value is yyc.

re2c:define:YYGETSTATE
    Defines API primitive YYGETSTATE (see the user interface section).

re2c:define:YYGETSTATE:naked
    Allows one to override re2c:api:style for YYGETSTATE. Value 0 corresponds to free-form API style.

re2c:define:YYSETSTATE
    Defines API primitive YYSETSTATE (see the user interface section).

re2c:define:YYSETSTATE@state
    Specifies the sigil used for argument substitution in YYSETSTATE definition. The default value is @@. Overrides the more generic re2c:api:sigil configuration.

re2c:define:YYSETSTATE:naked
    Allows one to override re2c:api:style for YYSETSTATE. Value 0 corresponds to free-form API style.

re2c:state:abort
    If set to a positive integer value, changes the form of the YYGETSTATE switch: instead of using default case to jump to the beginning of the lexer block, a -1 case is used, and the default case aborts the program.

re2c:state:nextlabel
    With storable states, allows to control if the YYGETSTATE block is followed by a yyNext label (the default value is zero, which corresponds to no label). Instead of using yyNext it is possible to use re2c:startlabel to force the generation of a specific start label. Instead of using labels it is often more convenient to generate YYGETSTATE code using /*!getstate:re2c*/.

re2c:label:yyNext
    Allows one to change the name of the yyNext label.

re2c:startlabel
    Controls the generation of start label for the next lexer block. The default value is zero, which means that the start label is generated only if it is used. An integer value greater than zero forces the generation of start label even if it is unused by the lexer. A string value also forces start label generation and sets the label name to the specified string. This configuration applies only to the current block (it is reset to default for the next block).

re2c:flags:s, re2c:flags:nested-ifs
    Same as -s --nested-ifs command-line option.

re2c:flags:b, re2c:flags:bit-vectors
    Same as -b --bit-vectors command-line option.

re2c:variable:yybm
    Overrides the name of the yybm variable.

re2c:yybm:hex
    Defaults to zero (a decimal bitmap table is generated). If set to nonzero, a hexadecimal table is generated.

re2c:flags:g, re2c:flags:computed-gotos
    Same as -g --computed-gotos command-line option.

re2c:cgoto:threshold
    With -g --computed-gotos option this value specifies the complexity threshold that triggers the generation of jump tables instead of nested if statements and bitmaps. The default value is 9.

re2c:flags:case-ranges
    Same as --case-ranges command-line option.

re2c:flags:e, re2c:flags:ecb
    Same as -e --ecb command-line option.

re2c:flags:8, re2c:flags:utf-8
    Same as -8 --utf-8 command-line option.

re2c:flags:w, re2c:flags:wide-chars
    Same as -w --wide-chars command-line option.

re2c:flags:x, re2c:flags:utf-16
    Same as -x --utf-16 command-line option.

re2c:flags:u, re2c:flags:unicode
    Same as -u --unicode command-line option.

re2c:flags:encoding-policy
    Same as --encoding-policy command-line option.

re2c:flags:empty-class
    Same as --empty-class command-line option.

re2c:flags:case-insensitive
    Same as --case-insensitive command-line option.

re2c:flags:case-inverted
    Same as --case-inverted command-line option.

re2c:indent:string
    Specifies the string to use for indentation. The default value is "\t". Indent string should contain only whitespace characters. To disable indentation entirely, set this configuration to 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:labelprefix
    Allows one to change the prefix of DFA state labels. The default value is yy.

re2c:yych:emit
    Set this to zero to suppress the generation of yych definition. Defaults to 1 (the definition is generated).

re2c:variable:yych
    Overrides the name of the yych variable.

re2c:yych:conversion
    If set to nonzero, re2c automatically generates a cast to YYCTYPE every time yych is read. Defaults to zero (no cast).

re2c:variable:yyaccept
    Overrides the name of the yyaccept variable.

re2c:variable:yytarget
    Overrides the name of the yytarget variable.

re2c:variable:yystable
    Deprecated.

re2c:variable:yyctable
    When both -c --conditions and -g --computed-gotos are active, re2c will use this variable to generate a static jump table for YYGETCONDITION.

re2c:define:YYDEBUG
    Defines YYDEBUG (see the user interface section).

re2c:flags:d, re2c:flags:debug-output
    Same as -d --debug-output command-line option.

re2c:flags:dfa-minimization
    Same as --dfa-minimization command-line option.

re2c:flags:eager-skip
    Same as --eager-skip command-line option.

REGULAR EXPRESSIONS

re2c uses the following syntax for regular expressions:

•   "foo" case-sensitive string literal

•   'foo' case-insensitive string literal

•   [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 or for POSIX-style submatch

•   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

•   name the regular expression defined as name (or literal string "name" in Flex compatibility mode)

•   {name} the 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

    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.

HANDLING THE END OF INPUT

One of the main problems for the lexer is to know when to stop. There are a few terminating conditions:

•   the lexer may match some rule (including 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

    The first two conditions terminate the lexer in a "natural" way: it comes to a state with no outgoing transitions, and the matching automatically stops. The third condition, end of input, is different: 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, therefore it is necessary to minimize the number of such checks. re2c supports a few different methods for end of input handling. Which one to use depends on the complexity of regular expressions, the need for buffering, performance considerations and other factors. Here is a list of all methods:

•   Sentinel character. This method eliminates the need for the end of input checks altogether. It is 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 is not allowed by the regular expressions, except perhaps as the last character of a rule. The sentinel character is appended at the end of input and serves as a stop signal: when the lexer reads it, it must be either the end of input, or a syntax error. In both cases the lexer stops. This method is used if YYFILL is disabled with re2c:yyfill:enable = 0; and re2c:eof has the default value -1.

•   Sentinel character with bounds checks. This method is generic: it allows to 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 character" 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 character 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 will resume matching and handle the sentinel character as a regular one. Otherwise it will try to get more input with YYFILL (unless YYFILL is disabled). If more input is available, the lexer will rematch the last character and continue as if the sentinel never occurred. Otherwise it is the real end of input, and the lexer will stop. This method is used if re2c:eof has non-negative value (it should be set to the ordinal of the sentinel character). YYFILL must be either defined or disabled with re2c:yyfill:enable = 0;.

•   Bounds checks with padding. This method is the default one. It is generic, and it is usually faster than the "sentinel character with bounds checks" method, but also more complex to use. The idea is to partition the underlying finite-state automaton into strongly connected components (SCCs), and generate only one bounds check per SCC, but make it check for multiple characters at once (enough to cover the longest non-looping path in the SCC). This way the checks are less frequent, which makes the lexer run much faster. If a check shows that there is not enough input, the lexer will invoke YYFILL, which may either supply enough input or else it should not return (in the latter case the lexer will stop). This approach has a problem with matching short lexemes at the end of input, because the multi-character check requires enough characters to cover the longest possible lexeme. To fix this problem, it is necessary to append a few fake characters at the end of input. The padding should not form a valid lexeme suffix to avoid fooling the lexer into matching it as part of the input. The minimum sufficient length of padding is YYMAXFILL and it is autogenerated by re2c with /*!max:re2c*/. This method is used if re2c:yyfill:enable has the default nonzero value, and re2c:eof has the default value -1. YYFILL must be defined.

•   Custom methods with generic API. Generic API allows to override basic operations like reading a character, which makes it possible to include the end of input checks as part of them. Such methods are error-prone and should be used with caution, only if other methods cannot be used. These methods are used if generic API is enabled with --input custom or re2c:flags:input = custom; and default bounds checks are disabled with re2c:yyfill:enable = 0;. Note that the use of generic API does not imply the use of custom methods, it merely allows it.

    The following subsections contain an example of each method.

  Sentinel character

In this example the lexer uses a sentinel character to handle the end of input. The program counts space-separated words in a null-terminated string. Configuration re2c:yyfill:enable = 0; suppresses the generation of bounds checks and YYFILL invocations. The sentinel character is null. It is 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 is not included in the character ranges, where it is easy to overlook). If a null occurs in the middle of a string, it is a syntax error and the lexer will match default rule *, but it won't read past the end of input or crash. -Wsentinel-in-midrule warning verifies that the rules do not allow sentinel in the middle (it is possible to tell re2c which character is used as a sentinel with re2c:sentinel configuration --- the default assumption is null, since this is the most common case).

//go:generate re2go $INPUT -o $OUTPUT
package main
import "testing"
// expect a null-terminated string
func lex(str string) int {
    var cursor int
    count := 0
loop:
    /*!re2c
    re2c:yyfill:enable = 0;
    re2c:define:YYCTYPE = byte;
    re2c:define:YYPEEK = "str[cursor]";
    re2c:define:YYSKIP = "cursor += 1";
    *      { return -1 }
    [\x00] { return count }
    [a-z]+ { count += 1; goto loop }
    [ ]+   { goto loop }
    */
}
func TestLex(t *testing.T) {
    var tests = []struct {
        res int
        str string
    }{
        {0, "\000"},
        {3, "one two three\000"},
        {-1, "f0ur\000"},
    }
    for _, x := range tests {
        t.Run(x.str, func(t *testing.T) {
            res := lex(x.str)
            if res != x.res {
                t.Errorf("got %d, want %d", res, x.res)
            }
        })
    }
}

  Sentinel character with bounds checks

In this example the lexer uses sentinel character with bounds checks to handle the end of input (this method was added in version 1.2). The program counts single-quoted strings separated with spaces. The sentinel character is null, which is specified with re2c:eof = 0; configuration. Null is the last character of each input string --- this is essential to detect the end of input. Null, as well as any other character, is 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 has a switch on an input character, in the conditional branch that corresponds to null (that branch may also cover other characters --- re2c does not split out a separate branch for sentinel, because increasing the number of branches degrades performance more than bounds checks do). Bounds checks are of the form YYLIMIT <= YYCURSOR or YYLESSTHAN(1) with generic API. If a bounds check succeeds, the lexer will continue matching. If a bounds check fails, the lexer has reached the end of input, and it should stop. In this example YYFILL is disabled with re2c:yyfill:enable = 0; and the lexer does not attempt to get more input (see another example that uses YYFILL in the YYFILL with sentinel character section). When the end of input has been reached, there are three possibilities: if the lexer is in the initial state, it will match the end of input rule $, otherwise it will either fallback to a previously matched rule (including default rule *) or go to a default state, causing -Wundefined-control-flow.

//go:generate re2go $INPUT -o $OUTPUT
package main
import "testing"
// Expects a null-terminated string.
func lex(str string) int {
    var cursor, marker int
    limit := len(str) - 1 // limit points at the terminating null
    count := 0
loop:
    /*!re2c
    re2c:yyfill:enable = 0;
    re2c:eof = 0;
    re2c:define:YYCTYPE    = byte;
    re2c:define:YYPEEK     = "str[cursor]";
    re2c:define:YYSKIP     = "cursor += 1";
    re2c:define:YYBACKUP   = "marker = cursor";
    re2c:define:YYRESTORE  = "cursor = marker";
    re2c:define:YYLESSTHAN = "limit <= cursor";
    *                           { return -1 }
    $                           { return count }
    ['] ([^'\\] | [\\][^])* ['] { count += 1; goto loop }
    [ ]+                        { goto loop }
    */
}
func TestLex(t *testing.T) {
    var tests = []struct {
        res int
        str string
    }{
        {0, "\000"},
        {3, "'qu\000tes' 'are' 'fine: \\'' \000"},
        {-1, "'unterminated\\'\000"},
    }
    for _, x := range tests {
        t.Run(x.str, func(t *testing.T) {
            res := lex(x.str)
            if res != x.res {
                t.Errorf("got %d, want %d", res, x.res)
            }
        })
    }
}

  Bounds checks with padding

In this example the lexer uses bounds checking with padding to handle the end of input (it is the default method). The program counts single-quoted strings separated with spaces. There is a padding of YYMAXFILL null characters appended at the end of input, where YYMAXFILL value is autogenerated with /*!max:re2c*/ directive. It is 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 is a "stop" rule that matches the first padding character (null) and terminates the lexer (it returns success only if it has matched at the beginning of padding, otherwise a stray null is syntax error). Bounds checks are generated only in some states that depend on the strongly connected components of the underlying automaton. They are of 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 a bounds check succeeds, the lexer will continue matching. If a bounds check fails, the lexer has reached the end of input and will invoke YYFILL(n), which should either supply at least n input characters, or it should not return. In this example YYFILL always fails and terminates the lexer with an error. This is fine, because in this example YYFILL can only be called when the lexer has advanced into the padding, which means that is has encountered an unterminated string and should return a syntax error. See the YYFILL with padding section for an example that refills the input buffer with YYFILL.

//go:generate re2go $INPUT -o $OUTPUT
package main
import (
    "strings"
    "testing"
)
/*!max:re2c*/
// Expects YYMAXFILL-padded string.
func lex(str string) int {
    var cursor int
    limit := len(str)
    count := 0
loop:
    /*!re2c
    re2c:define:YYCTYPE    = byte;
    re2c:define:YYPEEK     = "str[cursor]";
    re2c:define:YYSKIP     = "cursor += 1";
    re2c:define:YYLESSTHAN = "limit - cursor < @@{len}";
    re2c:define:YYFILL     = "return -1";
    * {
        return -1
    }
    [\x00] {
        if limit - cursor == YYMAXFILL - 1 {
            return count
        } else {
            return -1
        }
    }
    ['] ([^'\\] | [\\][^])* ['] {
        count += 1;
        goto loop
    }
    [ ]+ {
        goto loop
    }
    */
}
// Pad string with YYMAXFILL zeroes at the end.
func pad(str string) string {
    return str + strings.Repeat("\000", YYMAXFILL)
}
func TestLex(t *testing.T) {
    var tests = []struct {
        res int
        str string
    }{
        {0, ""},
        {3, "'qu\000tes' 'are' 'fine: \\'' "},
        {-1, "'unterminated\\'"},
    }
    for _, x := range tests {
        t.Run(x.str, func(t *testing.T) {
            res := lex(pad(x.str))
            if res != x.res {
                t.Errorf("got %d, want %d", res, x.res)
            }
        })
    }
}

  Custom methods with generic API

In this example the lexer uses a custom end of input handling method based on generic API. The program counts single-quoted strings separated with spaces. It is the same as the sentinel character with bounds checks example, except that the input is not null-terminated (so this method can be used if it's not possible to have any padding at all, not even a single sentinel character). To cover up for the absence of 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 succeeds, YYPEEK returns the real character, otherwise it returns a fake sentinel character.

//go:generate re2go $INPUT -o $OUTPUT
package main
import "testing"
// Returns "fake" terminating null if cursor has reached limit.
func peek(str string, cursor int, limit int) byte {
    if cursor >= limit {
        return 0 // fake null
    } else {
        return str[cursor]
    }
}
// Expects a string without terminating null.
func lex(str string) int {
    var cursor, marker int
    limit := len(str)
    count := 0
loop:
    /*!re2c
    re2c:yyfill:enable = 0;
    re2c:eof = 0;
    re2c:define:YYCTYPE    = byte;
    re2c:define:YYLESSTHAN = "cursor >= limit";
    re2c:define:YYPEEK     = "peek(str, cursor, limit)";
    re2c:define:YYSKIP     = "cursor += 1";
    re2c:define:YYBACKUP   = "marker = cursor";
    re2c:define:YYRESTORE  = "cursor = marker";
    *                           { return -1 }
    $                           { return count }
    ['] ([^'\\] | [\\][^])* ['] { count += 1; goto loop }
    [ ]+                        { goto loop }
    */
}
func TestLex(t *testing.T) {
    var tests = []struct {
        res int
        str string
    }{
        {0, ""},
        {3, "'qu\000tes' 'are' 'fine: \\'' "},
        {-1, "'unterminated\\'"},
    }
    for _, x := range tests {
        t.Run(x.str, func(t *testing.T) {
            res := lex(x.str)
            if res != x.res {
                t.Errorf("got %d, want %d", res, x.res)
            }
        })
    }
}

BUFFER REFILLING

The need for buffering arises 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 posiitons:

•   cursor: the next input character to be read (YYCURSOR in default API or YYSKIP/YYPEEK in generic API)

•   limit: the position after the last available input character (YYLIMIT in default 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 re2c 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 default API or YYBACKUPCTX/YYRESTORECTX in generic API)

•   tag variables: submatch positions (defined with /*!stags:re2c*/ and /*!mtags:re2c*/ directives and YYSTAGP/YYSTAGN/YYMTAGP/YYMTAGN in generic API)

    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 (desrbed in the section about storable state).

  YYFILL with sentinel character

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 default 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.

//go:generate re2go $INPUT -o $OUTPUT
package main
import (
    "os"
    "testing"
)
// Intentionally small to trigger buffer refill.
const SIZE int = 16
type Input struct {
    file   *os.File
    data   []byte
    cursor int
    marker int
    token  int
    limit  int
    eof    bool
}
func fill(in *Input) int {
    // If nothing can be read, fail.
    if in.eof {
        return 1
    }
    // Check if at least some space can be freed.
    if in.token == 0 {
        // In real life can reallocate a larger buffer.
        panic("fill error: lexeme too long")
    }
    // Discard everything up to the start of the current lexeme,
    // shift buffer contents and adjust offsets.
    copy(in.data[0:], in.data[in.token:in.limit])
    in.cursor -= in.token
    in.marker -= in.token
    in.limit -= in.token
    in.token = 0
    // Read new data (as much as possible to fill the buffer).
    n, _ := in.file.Read(in.data[in.limit:SIZE])
    in.limit += n
    in.data[in.limit] = 0
    // If read less than expected, this is the end of input.
    in.eof = in.limit < SIZE
    // If nothing has been read, fail.
    if n == 0 {
        return 1
    }
    return 0
}
func lex(in *Input) int {
    count := 0
loop:
    in.token = in.cursor
    /*!re2c
    re2c:eof = 0;
    re2c:define:YYCTYPE    = byte;
    re2c:define:YYPEEK     = "in.data[in.cursor]";
    re2c:define:YYSKIP     = "in.cursor += 1";
    re2c:define:YYBACKUP   = "in.marker = in.cursor";
    re2c:define:YYRESTORE  = "in.cursor = in.marker";
    re2c:define:YYLESSTHAN = "in.limit <= in.cursor";
    re2c:define:YYFILL     = "fill(in) == 0";
    *                           { return -1 }
    $                           { return count }
    ['] ([^'\\] | [\\][^])* ['] { count += 1; goto loop }
    [ ]+                        { goto loop }
    */
}
// Prepare a file with the input text and run the lexer.
func test(data string) (result int) {
    tmpfile := "input.txt"
    f, _ := os.Create(tmpfile)
    f.WriteString(data)
    f.Seek(0, 0)
    defer func() {
        if r := recover(); r != nil {
            result = -2
        }
        f.Close()
        os.Remove(tmpfile)
    }()
    in := &Input{
        file:   f,
        data:   make([]byte, SIZE+1),
        cursor: SIZE,
        marker: SIZE,
        token:  SIZE,
        limit:  SIZE,
        eof:    false,
    }
    return lex(in)
}
func TestLex(t *testing.T) {
    var tests = []struct {
        res int
        str string
    }{
        {0, ""},
        {2, "'one' 'two'"},
        {3, "'qu\000tes' 'are' 'fine: \\'' "},
        {-1, "'unterminated\\'"},
        {-2, "'loooooooooooong'"},
    }
    for _, x := range tests {
        t.Run(x.str, func(t *testing.T) {
            res := test(x.str)
            if res != x.res {
                t.Errorf("got %d, want %d", res, x.res)
            }
        })
    }
}

  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 default 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.

//go:generate re2go $INPUT -o $OUTPUT
package main
import (
    "fmt"
    "os"
    "testing"
)
/*!max:re2c*/
// Intentionally small to trigger buffer refill.
const SIZE int = 16
type Input struct {
    file   *os.File
    data   []byte
    cursor int
    marker int
    token  int
    limit  int
    eof    bool
}
func fill(in *Input, need int) int {
    // End of input has already been reached, nothing to do.
    if in.eof {
        return -1 // Error: unexpected EOF
    }
    // Check if after moving the current lexeme to the beginning
    // of buffer there will be enough free space.
    if SIZE-(in.cursor-in.token) < need {
        return -2 // Error: lexeme too long
    }
    // Discard everything up to the start of the current lexeme,
    // shift buffer contents and adjust offsets.
    copy(in.data[0:], in.data[in.token:in.limit])
    in.cursor -= in.token
    in.marker -= in.token
    in.limit -= in.token
    in.token = 0
    // Read new data (as much as possible to fill the buffer).
    n, _ := in.file.Read(in.data[in.limit:SIZE])
    in.limit += n
    // If read less than expected, this is the end of input.
    in.eof = in.limit < SIZE
    // If end of input, add padding so that the lexer can read
    // the remaining characters at the end of buffer.
    if in.eof {
        for i := 0; i < YYMAXFILL; i += 1 {
            in.data[in.limit+i] = 0
        }
        in.limit += YYMAXFILL
    }
    return 0
}
func lex(in *Input) int {
    count := 0
loop:
    in.token = in.cursor
    /*!re2c
    re2c:define:YYCTYPE    = byte;
    re2c:define:YYPEEK     = "in.data[in.cursor]";
    re2c:define:YYSKIP     = "in.cursor += 1";
    re2c:define:YYBACKUP   = "in.marker = in.cursor";
    re2c:define:YYRESTORE  = "in.cursor = in.marker";
    re2c:define:YYLESSTHAN = "in.limit-in.cursor < @@{len}";
    re2c:define:YYFILL     = "if r := fill(in, @@{len}); r != 0 { return r }";
    * {
        return -1
    }
    [\x00] {
        if in.limit - in.cursor == YYMAXFILL - 1 {
            return count
        } else {
            return -1
        }
    }
    ['] ([^'\\] | [\\][^])* ['] {
        count += 1;
        goto loop
    }
    [ ]+ {
        goto loop
    }
    */
}
// Prepare a file with the input text and run the lexer.
func test(data string) (result int) {
    tmpfile := "input.txt"
    f, _ := os.Create(tmpfile)
    f.WriteString(data)
    f.Seek(0, 0)
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
            result = -2
        }
        f.Close()
        os.Remove(tmpfile)
    }()
    in := &Input{
        file:   f,
        data:   make([]byte, SIZE+YYMAXFILL),
        cursor: SIZE,
        marker: SIZE,
        token:  SIZE,
        limit:  SIZE,
        eof:    false,
    }
    return lex(in)
}
func TestLex(t *testing.T) {
    var tests = []struct {
        res int
        str string
    }{
        {0, ""},
        {2, "'one' 'two'"},
        {3, "'qu\000tes' 'are' 'fine: \\'' "},
        {-1, "'unterminated\\'"},
        {-2, "'loooooooooooong'"},
    }
    for _, x := range tests {
        t.Run(x.str, func(t *testing.T) {
            res := test(x.str)
            if res != x.res {
                t.Errorf("got %d, want %d", res, x.res)
            }
        })
    }
}

INCLUDE FILES

re2c allows one to include other files using directive /*!include:re2c FILE */ or !include FILE ;, where FILE is a path to the file to be included. The first form should be used outside of re2c blocks, and the second form allows one to include a file in the middle of a re2c block. re2c looks for included files in the directory of the including file and in include locations, which can be specified with -I option. Include directives in re2c work in the same way as C/C++ #include: the contents of FILE are copy-pasted verbatim in place of the directive. Include files may have further includes of their own. Use --depfile option to track build dependencies of the output file on include files. re2c provides some predefined include files that can be found in the include/ subdirectory of the project. These files contain definitions that can be useful to other projects (such as Unicode categories) and form something like a standard library for re2c. Below is an example of using include directive.

  Include file 1 (definitions.go)

const (
    ResultOk = iota
    ResultFail
)
/*!re2c
    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 ResultOk }

  Input file

//go:generate re2go -c $INPUT -o $OUTPUT -i
package main
import "testing"
/*!include:re2c "definitions.go" */
func lex(str string) int {
    var cursor, marker int
    /*!re2c
    re2c:define:YYCTYPE   = byte;
    re2c:define:YYPEEK    = "str[cursor]";
    re2c:define:YYSKIP    = "cursor += 1";
    re2c:define:YYBACKUP  = "marker = cursor";
    re2c:define:YYRESTORE = "cursor = marker";
    re2c:yyfill:enable    = 0;
    number { return ResultOk }
    !include "extra_rules.re.inc";
    * { return ResultFail }
    */
}
func TestLex(t *testing.T) {
    if lex("123\000") != ResultOk {
        t.Errorf("error")
    }
    if lex("123.4567\000") != ResultOk {
        t.Errorf("error")
    }
}

HEADER FILES

Re2c allows one to generate header file from the input .re file using option -t, --type-header or configuration re2c:flags:type-header and directives /*!header:re2c:on*/ and /*!header:re2c:off*/. The first directive marks the beginning of header file, and the second directive marks the end of it. Everything between these directives is processed by re2c, and the generated code is written to the file specified by the -t --type-header option (or stdout if this option was not used). Autogenerated header file may be needed in cases when re2c is used to generate definitions of constants, variables and structs that must be visible from other translation units.

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

  Input file

//go:generate re2go $INPUT -o $OUTPUT -i --type-header src/lexer/lexer.go
package main
import (
    "lexer" // generated by re2c
    "testing"
)
/*!header:re2c:on*/
package lexer
type State struct {
    Data string
    Cur, Mar, /*!stags:re2c format="@@{tag}"; separator=", "; */ int
}
/*!header:re2c:off*/
func lex(st *lexer.State) int {
    /*!re2c
    re2c:flags:type-header = "src/lexer/lexer.go";
    re2c:yyfill:enable = 0;
    re2c:flags:tags = 1;
    re2c:define:YYCTYPE      = byte;
    re2c:define:YYPEEK       = "st.Data[st.Cur]";
    re2c:define:YYSKIP       = "st.Cur++";
    re2c:define:YYBACKUP     = "st.Mar = st.Cur";
    re2c:define:YYRESTORE    = "st.Cur = st.Mar";
    re2c:define:YYRESTORETAG = "st.Cur = @@{tag}";
    re2c:define:YYSTAGP      = "@@{tag} = st.Cur";
    re2c:tags:expression     = "st.@@{tag}";
    re2c:tags:prefix         = "Tag";
    [x]{1,4} / [x]{3,5} { return 0 } // ambiguous trailing context
    *                   { return 1 }
    */
}
func TestLex(t *testing.T) {
    st := &lexer.State{
        Data: "xxxxxxxx\x00",
    }
    if !(lex(st) == 0 && st.Cur == 4) {
        t.Error("failed")
    }
}

  Header file

// Code generated by re2c, DO NOT EDIT.
package lexer
type State struct {
    Data string
    Cur, Mar, Tag1, Tag2, Tag3 int
}

SUBMATCH EXTRACTION

Re2c has two options for submatch extraction.

The first option is -T --tags. With this option one can use standalone tags of the form @stag and #mtag, where stag and mtag are arbitrary used-defined names. Tags can be used anywhere inside of a regular expression; semantically they are just position markers. Tags of the form @stag are called s-tags: they denote a single submatch value (the last input position where this tag matched). Tags of the form #mtag are called m-tags: they denote multiple submatch values (the whole history of repetitions of this tag). All tags should be defined by the user as variables with the corresponding names. With standalone tags re2c uses leftmost greedy disambiguation: submatch positions correspond to the leftmost matching path through the regular expression.

The second option is -P --posix-captures: it enables POSIX-compliant capturing groups. In this mode parentheses in regular expressions denote the beginning and the end of capturing groups; the whole regular expression is group number zero. The number of groups for the matching rule is stored in a variable yynmatch, and submatch results are stored in yypmatch array. Both yynmatch and yypmatch should be defined by the user, and yypmatch size must be at least [yynmatch * 2]. Re2c provides a directive /*!maxnmatch:re2c*/ that defines YYMAXNMATCH: a constant equal to the maximal value of yynmatch among all rules. Note that re2c implements POSIX-compliant disambiguation: each subexpression matches as long as possible, and subexpressions that start earlier in regular expression have priority over those starting later. Capturing groups are translated into s-tags under the hood, therefore we use the word "tag" to describe them as well.

With both -P --posix-captures and T --tags options re2c uses efficient submatch extraction algorithm described in the Tagged Deterministic Finite Automata with Lookahead paper. The overhead on submatch extraction in the generated lexer grows with the number of tags --- if this number is moderate, the overhead is barely noticeable. In the lexer tags are implemented using a number of tag variables generated by re2c. There is no one-to-one correspondence between tag variables and tags: a single variable may be reused for different tags, and one tag may require multiple variables to hold all its ambiguous values. Eventually ambiguity is resolved, and only one final variable per tag survives. When a rule matches, all its tags are set to the values of the corresponding tag variables. The exact number of tag variables is unknown to the user; this number is determined by re2c. However, tag variables should be defined by the user as a part of the lexer state and updated by YYFILL, therefore re2c provides directives /*!stags:re2c*/ and /*!mtags:re2c*/ that can be used to declare, initialize and manipulate tag variables. These directives have two optional configurations: format = "@@"; (specifies the template where @@ is substituted with the name of each tag variable), and separator = ""; (specifies the piece of code used to join the generated pieces for different tag variables).

S-tags support the following operations:

•   save input position to an s-tag: t = YYCURSOR with default API or a user-defined operation YYSTAGP(t) with generic API

•   save default value to an s-tag: t = NULL with default API or a user-defined operation YYSTAGN(t) with 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 default and generic API

•   append default value to an m-tag: a user-defined operation YYMTAGN(t) with both default and 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 array of nodes (v, p), where v is tag value and p is a pointer to parent node.

    Here is a simple example of using s-tags to parse an IPv4 address (see below for a more complex example that uses YYFILL).

    //go:generate re2go $INPUT -o $OUTPUT
    package main
    import (
        "errors"
        "testing"
    )
    var eBadIP error = errors.New("bad IP")
    func lex(str string) (int, error) {
        var cursor, marker, o1, o2, o3, o4 int
        /*!stags:re2c format = 'var @@ int'; separator = "\n\t"; */
        num := func(pos int, end int) int {
            n := 0
            for ; pos < end; pos++ {
                n = n*10 + int(str[pos]-'0')
            }
            return n
        }
        /*!re2c
        re2c:flags:tags = 1;
        re2c:yyfill:enable = 0;
        re2c:define:YYCTYPE   = byte;
        re2c:define:YYPEEK    = "str[cursor]";
        re2c:define:YYSKIP    = "cursor += 1";
        re2c:define:YYBACKUP  = "marker = cursor";
        re2c:define:YYRESTORE = "cursor = marker";
        re2c:define:YYSTAGP   = "@@{tag} = cursor";
        re2c:define:YYSTAGN   = "@@{tag} = -1";
        octet = [0-9] | [1-9][0-9] | [1][0-9][0-9] | [2][0-4][0-9] | [2][5][0-5];
        dot = [.];
        end = [\x00];
        @o1 octet dot @o2 octet dot @o3 octet dot @o4 octet end {
            return num(o4, cursor-1)+
                (num(o3, o4-1) << 8)+
                (num(o2, o3-1) << 16)+
                (num(o1, o2-1) << 24), nil
        }
        * { return 0, eBadIP }
        */
    }
    func TestLex(t *testing.T) {
        var tests = []struct {
            str string
            res int
            err error
        }{
            {"1.2.3.4\000", 0x01020304, nil},
            {"127.0.0.1\000", 0x7f000001, nil},
            {"255.255.255.255\000", 0xffffffff, nil},
            {"1.2.3.\000", 0, eBadIP},
            {"1.2.3.256\000", 0, eBadIP},
        }
        for _, x := range tests {
            t.Run(x.str, func(t *testing.T) {
                res, err := lex(x.str)
                if !(res == x.res && err == x.err) {
                    t.Errorf("got %d, want %d", res, x.res)
                }
            })
        }
    }

    Here is a more complex example of using s-tags with YYFILL to parse a file with IPv4 addresses. 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 buffer, which may be the case with m-tags.

    //go:generate re2go $INPUT -o $OUTPUT --tags
    package main
    import (
        "fmt"
        "os"
        "reflect"
        "testing"
    )
    const SIZE int = 4096
    type Input struct {
        file   *os.File
        data   []byte
        cursor int
        marker int
        token  int
        limit  int
        // 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:re2c format = "\t@@ int\n"; */
        eof    bool
    }
    func fill(in *Input) int {
        // If nothing can be read, fail.
        if in.eof {
            return 1
        }
        // Check if at least some space can be freed.
        if in.token == 0 {
            // In real life can reallocate a larger buffer.
            panic("fill error: lexeme too long")
        }
        // Discard everything up to the start of the current lexeme,
        // shift buffer contents and adjust offsets.
        copy(in.data[0:], in.data[in.token:in.limit])
        in.cursor -= in.token
        in.marker -= in.token
        in.limit -= in.token
        // Tag variables need to be shifted like other input positions. The
        // check for -1 is only needed if some tags are nested inside of
        // alternative or repetition, so that they can have -1 value.
        /*!stags:re2c
            format = "\tif in.@@ != -1 { in.@@ -= in.token }\n";
        */
        in.token = 0
        // Read new data (as much as possible to fill the buffer).
        n, _ := in.file.Read(in.data[in.limit:SIZE])
        in.limit += n
        in.data[in.limit] = 0
        // If read less than expected, this is the end of input.
        in.eof = in.limit < SIZE
        // If nothing has been read, fail.
        if n == 0 {
            return 1
        }
        return 0
    }
    func lex(in *Input) []int {
        // User-defined local variables that store final tag values. They are
        // different from tag variables autogenerated with `stags:re2c`, as
        // they are set at the end of match and used only in semantic actions.
        var o1, o2, o3, o4 int
        var ips []int
        num := func(pos int, end int) int {
            n := 0
            for ; pos < end; pos++ {
                n = n*10 + int(in.data[pos]-'0')
            }
            return n
        }
    loop:
        in.token = in.cursor
        /*!re2c
        re2c:eof = 0;
        re2c:define:YYCTYPE    = byte;
        re2c:define:YYPEEK     = "in.data[in.cursor]";
        re2c:define:YYSKIP     = "in.cursor += 1";
        re2c:define:YYBACKUP   = "in.marker = in.cursor";
        re2c:define:YYRESTORE  = "in.cursor = in.marker";
        re2c:define:YYLESSTHAN = "in.limit <= in.cursor";
        re2c:define:YYFILL     = "fill(in) == 0";
        re2c:define:YYSTAGP    = "@@{tag} = in.cursor";
        re2c:define:YYSTAGN    = "@@{tag} = -1";
        // The way tag variables are accessed from the lexer (not needed if tag
        // variables are defined as local variables).
        re2c:tags:expression = "in.@@";
        octet = [0-9] | [1-9][0-9] | [1][0-9][0-9] | [2][0-4][0-9] | [2][5][0-5];
        dot = [.];
        eol = [\n];
        @o1 octet dot @o2 octet dot @o3 octet dot @o4 octet eol {
            ips = append(ips, num(o4, in.cursor-1)+
                (num(o3, o4-1) << 8)+
                (num(o2, o3-1) << 16)+
                (num(o1, o2-1) << 24))
            goto loop
        }
        $ { return ips }
        * { return nil }
        */
    }
    func TestLex(t *testing.T) {
        tmpfile := "input.txt"
        var want, have []int
        // Write a few IPv4 addresses to the input file and save them to compare
        // against parse results.
        f, _ := os.Create(tmpfile)
        for i := 0; i < 256; i++ {
            fmt.Fprintf(f, "%d.%d.%d.%d\n", i, i, i, i)
            want = append(want, i + (i<<8) + (i<<16) + (i<<24));
        }
        f.Seek(0, 0)
        defer func() {
            if r := recover(); r != nil {
                have = nil
            }
            f.Close()
            os.Remove(tmpfile)
        }()
        in := &Input{
            file:   f,
            data:   make([]byte, SIZE+1),
            cursor: SIZE,
            marker: SIZE,
            token:  SIZE,
            limit:  SIZE,
            eof:    false,
        }
        have = lex(in)
        if !reflect.DeepEqual(have, want) {
            t.Errorf("have %d, want %d", have, want)
        }
    }

    Here is an example of using POSIX capturing groups to parse an IPv4 address.

    //go:generate re2go $INPUT -o $OUTPUT
    package main
    import (
        "errors"
        "testing"
    )
    /*!maxnmatch:re2c*/
    var eBadIP error = errors.New("bad IP")
    func lex(str string) (int, error) {
        var cursor, marker, yynmatch int
        yypmatch := make([]int, YYMAXNMATCH*2)
        /*!stags:re2c format = '\tvar @@ int\n'; */
        num := func(pos int, end int) int {
            n := 0
            for ; pos < end; pos++ {
                n = n*10 + int(str[pos]-'0')
            }
            return n
        }
        /*!re2c
        re2c:flags:posix-captures = 1;
        re2c:yyfill:enable = 0;
        re2c:define:YYCTYPE     = byte;
        re2c:define:YYPEEK      = "str[cursor]";
        re2c:define:YYSKIP      = "cursor += 1";
        re2c:define:YYBACKUP    = "marker = cursor";
        re2c:define:YYRESTORE   = "cursor = marker";
        re2c:define:YYSTAGP     = "@@{tag} = cursor";
        re2c:define:YYSTAGN     = "@@{tag} = -1";
        re2c:define:YYSHIFTSTAG = "@@{tag} += @@{shift}";
        octet = [0-9] | [1-9][0-9] | [1][0-9][0-9] | [2][0-4][0-9] | [2][5][0-5];
        dot = [.];
        end = [\x00];
        (octet) dot (octet) dot (octet) dot (octet) end {
            if yynmatch != 5 {
                panic("expected 5 submatch groups")
            }
            return num(yypmatch[8], yypmatch[9])+
                (num(yypmatch[6], yypmatch[7]) << 8)+
                (num(yypmatch[4], yypmatch[5]) << 16)+
                (num(yypmatch[2], yypmatch[3]) << 24), nil
        }
        * { return 0, eBadIP }
        */
    }
    func TestLex(t *testing.T) {
        var tests = []struct {
            str string
            res int
            err error
        }{
            {"1.2.3.4\000", 0x01020304, nil},
            {"127.0.0.1\000", 0x7f000001, nil},
            {"255.255.255.255\000", 0xffffffff, nil},
            {"1.2.3.\000", 0, eBadIP},
            {"1.2.3.256\000", 0, eBadIP},
        }
        for _, x := range tests {
            t.Run(x.str, func(t *testing.T) {
                res, err := lex(x.str)
                if !(res == x.res && err == x.err) {
                    t.Errorf("got %d, want %d", res, x.res)
                }
            })
        }
    }

    Here is an example of using m-tags to parse a semicolon-separated sequence of words (C++). Tag variables are stored in a tree that is packed in a vector.

    //go:generate re2go $INPUT -o $OUTPUT
    package main
    import (
        "reflect"
        "testing"
    )
    const (
        mtagRoot int = -1
        mtagNil int = -2
    )
    type mtagElem struct {
        val  int
        pred int
    }
    type mtagTrie = []mtagElem
    func createTrie(capacity int) mtagTrie {
        return make([]mtagElem, 0, capacity)
    }
    func mtag(trie *mtagTrie, tag int, val int) int {
        *trie = append(*trie, mtagElem{val, tag})
        return len(*trie) - 1
    }
    // Recursively unwind both tag histories and consruct submatches.
    func unwind(trie mtagTrie, x int, y int, str string) []string {
        if x == mtagRoot && y == mtagRoot {
            return []string{}
        } else if x == mtagRoot || y == mtagRoot {
            panic("tag histories have different length")
        } else {
            xval := trie[x].val
            yval := trie[y].val
            ss := unwind(trie, trie[x].pred, trie[y].pred, str)
            // Either both tags should be nil, or none of them.
            if xval == mtagNil && yval == mtagNil {
                return ss
            } else if xval == mtagNil || yval == mtagNil {
                panic("tag histories positive/negative tag mismatch")
            } else {
                s := str[xval:yval]
                return append(ss, s)
            }
        }
    }
    func lex(str string) []string {
        var cursor, marker int
        trie := createTrie(256)
        x := mtagRoot
        y := mtagRoot
        /*!mtags:re2c format = "\t@@ := mtagRoot\n"; */
        /*!re2c
        re2c:flags:tags = 1;
        re2c:yyfill:enable = 0;
        re2c:define:YYCTYPE   = byte;
        re2c:define:YYPEEK    = "str[cursor]";
        re2c:define:YYSKIP    = "cursor += 1";
        re2c:define:YYBACKUP  = "marker = cursor";
        re2c:define:YYRESTORE = "cursor = marker";
        re2c:define:YYMTAGP   = "@@{tag} = mtag(&trie, @@{tag}, cursor)";
        re2c:define:YYMTAGN   = "@@{tag} = mtag(&trie, @@{tag}, mtagNil)";
        end = [\x00];
        (#x [a-z]+ #y [;])* end { return unwind(trie, x, y, str) }
        *                       { return nil }
        */
    }
    func TestLex(t *testing.T) {
        var tests = []struct {
            str string
            res []string
        }{
            {"\000", []string{}},
            {"one;two;three;\000", []string{"one", "two", "three"}},
            {"one;two\000", nil},
        }
        for _, x := range tests {
            t.Run(x.str, func(t *testing.T) {
                res := lex(x.str)
                if !reflect.DeepEqual(res, x.res) {
                    t.Errorf("got %v, want %v", res, x.res)
                }
            })
        }
    }

STORABLE STATE

With -f --storable-state option re2c generates a lexer that can store its current state, return to the caller, and later resume operations exactly where it left off. The default mode of operation in re2c is a "pull" model, in which the lexer "pulls" more input whenever it needs it. This may be unacceptable in cases when the input becomes available piece by piece (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). Storable state feature is intended exactly for such cases: it allows one to 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. There are a few changes necessary compared to the "pull" model:

•   Define YYSETSTATE() and YYGETSTATE(state) promitives.

•   Define yych, yyaccept 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.

•   Use /*!getstate:re2c*/ directive if it is necessary to execute any code before entering the lexer.

•   Use configurations state:abort and state:nextlabel to further tweak the generated code.

    Here is an example of a "push"-model lexer that reads input from stdin and expects a sequence of words separated by spaces and newlines. The lexer loops forever, waiting for more input. It can be terminated by sending a special EOF token --- a word "stop", in which case the lexer terminates successfully and prints the number of words it has seen. Abnormal termination happens in case of a syntax error, premature end of input (without the "stop" word) or in case the buffer is too small to hold a lexeme (for example, if one of the words exceeds buffer size). Premature end of input happens in case the lexer fails to read any input while being in the initial state --- this is the only case when EOF rule matches. Note that the lexer may call YYFILL twice before terminating (and thus require hitting Ctrl+D a few times). First time YYFILL is called when the lexer expects continuation of the current greedy lexeme (either a word or a whitespace sequence). If YYFILL fails, the lexer knows that it has reached the end of the current lexeme and executes the corresponding semantic action. The action jumps to the beginning of the loop, the lexer enters the initial state and calls YYFILL once more. If it fails, the lexer matches EOF rule. (Alternatively EOF rule can be used for termination instead of a special EOF lexeme.)

  Example

//go:generate re2go -f $INPUT -o $OUTPUT
package main
import (
    "fmt"
    "os"
    "testing"
)
// Intentionally small to trigger buffer refill.
const SIZE int = 16
type Input struct {
    file     *os.File
    data     []byte
    cursor   int
    marker   int
    token    int
    limit    int
    state    int
    yyaccept int
}
const (
    lexEnd = iota
    lexReady
    lexWaitingForInput
    lexPacketBroken
    lexPacketTooBig
    lexCountMismatch
)
func fill(in *Input) int {
    if in.token == 0 {
        // Error: no space can be freed.
        // In real life can reallocate a larger buffer.
        return lexPacketTooBig
    }
    // Discard everything up to the start of the current lexeme,
    // shift buffer contents and adjust offsets.
    copy(in.data[0:], in.data[in.token:in.limit])
    in.cursor -= in.token
    in.marker -= in.token
    in.limit -= in.token
    in.token = 0
    // Read new data (as much as possible to fill the buffer).
    n, _ := in.file.Read(in.data[in.limit:SIZE])
    in.limit += n
    in.data[in.limit] = 0 // append sentinel symbol
    return lexReady
}
func lex(in *Input, recv *int) int {
    var yych byte
    /*!getstate:re2c*/
loop:
    in.token = in.cursor
    /*!re2c
    re2c:eof = 0;
    re2c:define:YYPEEK     = "in.data[in.cursor]";
    re2c:define:YYSKIP     = "in.cursor += 1";
    re2c:define:YYBACKUP   = "in.marker = in.cursor";
    re2c:define:YYRESTORE  = "in.cursor = in.marker";
    re2c:define:YYLESSTHAN = "in.limit <= in.cursor";
    re2c:define:YYFILL     = "return lexWaitingForInput";
    re2c:define:YYGETSTATE = "in.state";
    re2c:define:YYSETSTATE = "in.state = @@{state}";
    packet = [a-z]+[;];
    *      { return lexPacketBroken }
    $      { return lexEnd }
    packet { *recv = *recv + 1; goto loop }
    */
}
func test(packets []string) int {
    fname := "pipe"
    fw, _ := os.Create(fname);
    fr, _ := os.Open(fname);
    in := &Input{
        file:   fr,
        data:   make([]byte, SIZE+1),
        cursor: SIZE,
        marker: SIZE,
        token:  SIZE,
        limit:  SIZE,
        state:  -1,
    }
    // data is zero-initialized, no need to write sentinel
    var status int
    send := 0
    recv := 0
loop:
    for {
        status = lex(in, &recv)
        if status == lexEnd {
            if send != recv {
                status = lexCountMismatch
            }
            break loop
        } else if status == lexWaitingForInput {
            if send < len(packets) {
                fw.WriteString(packets[send])
                send += 1
            }
            status = fill(in)
            if status != lexReady {
                break loop
            }
        } else if status == lexPacketBroken {
            break loop
        } else {
            panic("unexpected status")
        }
    }
    fr.Close()
    fw.Close()
    os.Remove(fname)
    return status
}
func TestLex(t *testing.T) {
    var tests = []struct {
        status  int
        packets []string
    }{
        {lexEnd, []string{}},
        {lexEnd, []string{"zero;", "one;", "two;", "three;", "four;"}},
        {lexPacketBroken, []string{"??;"}},
        {lexPacketTooBig, []string{"looooooooooooong;"}},
    }
    for i, x := range tests {
        t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
            status := test(x.packets)
            if status != x.status {
                t.Errorf("got %d, want %d", status, x.status)
            }
        })
    }
}

REUSABLE BLOCKS

Reusable blocks are re2c blocks that can be reused any number of times and combined with other re2c blocks. They are defined with /*!rules:re2c[:<name>] ... */ (the <name> is optional). A rules block can be used in two contexts: either in a use block, or in a use directive inside of another block. The code for a rules block is generated at every point of use.

Use blocks are defined with /*!use:re2c[:<name>] ... */. The <name> is optional; if 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).

In-block use directive !use:<name>; can be used from inside of a re2c block. It merges the referenced block <name> into the current one. If some of the merged rules and configurations overlap with the previously defined ones, conflicts are resolved in the usual way: the earliest rule takes priority, and latest configuration overrides preceding ones. One exception are the special rules *, $ and (in condition mode) <!>, for which a block-local definition overrides any inherited ones. Use directive allows one to combine different re2c blocks together in one block (see the example below).

Named blocks and in-block use directive were added in re2c version 2.2. Since that version reusable blocks are allowed by default (no special option is needed). Before version 2.2 reuse mode was enabled with -r --reusable option. Before version 1.2 reusable blocks could not be mixed with normal blocks.

  Example of a !use directive

//go:generate re2go $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.
package main
import "testing"
const (
    Color = iota
    Fish
    Dunno
)
/*!rules:re2c:colors
    *                            { panic("eh!") }
    "red" | "salmon" | "magenta" { return Color }
*/
/*!rules:re2c:fish
    *                            { panic("oh!") }
    "haddock" | "salmon" | "eel" { return Fish }
*/
func lex(str string) int {
    var cursor, marker int
    /*!re2c
    re2c:yyfill:enable = 0;
    re2c:define:YYCTYPE   = byte;
    re2c:define:YYPEEK    = "str[cursor]";
    re2c:define:YYSKIP    = "cursor += 1";
    re2c:define:YYBACKUP  = "marker = cursor";
    re2c:define:YYRESTORE = "cursor = marker";
    !use:fish;
    !use:colors;
    * { return Dunno }
    */
}
func TestLex(t *testing.T) {
    if lex("salmon") != Fish || lex("what?") != Dunno {
        t.Errorf("lex failed")
    }
}

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

//go:generate re2go $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.
package main
import "testing"
/*!rules:re2c
    re2c:yyfill:enable = 0;
    re2c:define:YYPEEK    = "str[cursor]";
    re2c:define:YYSKIP    = "cursor += 1";
    re2c:define:YYBACKUP  = "marker = cursor";
    re2c:define:YYRESTORE = "cursor = marker";
    "∀x ∃y" { return 0; }
    *       { return 1; }
*/
func lexUTF8(str []uint8) int {
    var cursor, marker int
    /*!use:re2c
    re2c:flags:8 = 1;
    re2c:define:YYCTYPE = uint8;
    */
}
func lexUTF32(str []uint32) int {
    var cursor, marker int
    /*!use:re2c
    re2c:flags:u = 1;
    re2c:define:YYCTYPE = uint32;
    */
}
func TestLex(t *testing.T) {
    s8 := []uint8{0xe2, 0x88, 0x80, 0x78, 0x20, 0xe2, 0x88, 0x83, 0x79};
    if lexUTF8(s8) != 0 {
        t.Errorf("utf8 failed")
    }
    s32 := []uint32{0x2200, 0x78, 0x20, 0x2203, 0x79};
    if lexUTF32(s32) != 0 {
        t.Errorf("utf32 failed")
    }
}

ENCODING SUPPORT

Speaking of encodings, it is necessary to understand the difference between code points and code units. Code point is an abstract symbol. Code unit is the smallest atomic unit of storage in the encoded text. A single code point may be represented with one or more code units. In a fixed-length encoding all code points are represented with the same number of code units. In a variable-length encoding code points may be represented with a different number of code units. Note that the "any" rule [^] matches any code point, but not necessarily any code unit. The only way to match any code unit regardless of the encoding it the default rule *. YYCTYPE size should be equal to the size of code unit.

Re2c supports the following encodings: ASCII, EBCDIC, UCS2, UTF8, UTF16 and UTF32.

•   ASCII is enabled by default. It is a fixed-length encoding with code space [0-255] and 1-byte code points and code units.

•   EBCDIC is enabled with -e, --ecb option. It a fixed-length encoding with code space [0-255] and 1-byte code points and code units.

•   UCS2 is enabled with -w, --wide-chars option. It is a fixed-length encoding with code space [0-0xFFFF] and 2-byte code points and code units.

•   UTF8 is enabled with -8, --utf-8 option. It is a variable-length Unicode encoding with code space [0-0x10FFFF]. Code points are represented with one, two, three or four 1-byte code units.

•   UTF16 is enabled with -x, --utf-16 option. It is a variable-length Unicode encoding with code space [0-0x10FFFF]. Code points are represented with one or two 2-byte code units.

•   UTF32 is enabled with -u, --unicode option. It is a fixed-length Unicode encoding with code space [0-0x10FFFF] and 4-byte code points and code units.

    Encodings can also be set or unset using re2c:flags configuration, for example re2c:flags:8 = 1; enables UTF8.

    Include file include/unicode_categories.re provides re2c definitions for the standard Unicode categories.

    Option --input-encoding utf8 enables Unicode literals in regular expressions.

    Option --encoding-policy <fail | substitute | ignore> specifies the way re2c handles Unicode surrogates: code points in the range [0xD800-0xDFFF].

  Example

//go:generate re2go $INPUT -o $OUTPUT -8 -s -i
//
// Simplified "Unicode Identifier and Pattern Syntax"
// (see https://unicode.org/reports/tr31)
package main
import "testing"
/*!include:re2c "unicode_categories.re" */
func lex(str string) int {
    var cursor, marker int
    /*!re2c
    re2c:yyfill:enable    = 0;
    re2c:define:YYCTYPE   = byte;
    re2c:define:YYPEEK    = "str[cursor]";
    re2c:define:YYSKIP    = "cursor += 1";
    re2c:define:YYBACKUP  = "marker = cursor";
    re2c:define:YYRESTORE = "cursor = marker";
    id_start    = L | Nl | [$_];
    id_continue = id_start | Mn | Mc | Nd | Pc | [\u200D\u05F3];
    identifier  = id_start id_continue*;
    identifier { return 0 }
    *          { return 1 }
    */
}
func TestLex(t *testing.T) {
    if lex("_Ыдентификатор\000") != 0 {
        t.Errorf("failed")
    }
}

START CONDITIONS

Conditions are enabled with -c --conditions. This option allows one to encode multiple interrelated lexers within the same re2c block.

Each lexer corresponds to a single condition. It starts with a label of the form yyc_name, where name is condition name and yyc prefix can be adjusted with configuration re2c:condprefix. Different lexers are separated with a comment /* *********************************** */ which can be adjusted with configuration re2c:cond:divider.

Furthermore, each condition has a unique identifier of the form yycname, where name is condition name and yyc prefix can be adjusted with configuration re2c:condenumprefix. Identifiers have the type YYCONDTYPE and should be generated with /*!types:re2c*/ directive or -t --type-header option. Users shouldn't define these identifiers manually, as the order of conditions is not specified.

Before all conditions re2c generates entry code that checks the current condition identifier and transfers control flow to the start label of the active condition. After matching some rule of this condition, lexer may either transfer control flow back to the entry code (after executing the associated action and optionally setting another condition with =>), or use :=> shortcut and transition directly to the start label of another condition (skipping the action and the entry code). Configuration re2c:cond:goto allows one to change the default behavior.

Syntactically each rule must be preceded with a list of comma-separated condition names or a wildcard * enclosed in angle brackets < and >. Wildcard means "any condition" and is semantically equivalent to listing all condition names. Here regexp is a regular expression, default refers to the default rule *, and action is a block of code.

•   <conditions-or-wildcard> regexp-or-default action

•   <conditions-or-wildcard> regexp-or-default => condition action

•   <conditions-or-wildcard> regexp-or-default :=> condition

    Rules with an exclamation mark ! in front of condition list have a special meaning: they have no regular expression, and the associated action is merged as an entry code to actions of normal rules. This might be a convenient place to peform a routine task that is common to all rules.

•   <!conditions-or-wildcard> action

    Another special form of rules with an empty condition list <> and no regular expression allows one to specify an "entry condition" that can be used to execute code before entering the lexer. It is semantically equivalent to a condition with number zero, name 0 and an empty regular expression.

•   <> action

•   <> => condition action

•   <> :=> condition

  Example

//go:generate re2go -c $INPUT -o $OUTPUT -i
package main
import (
    "errors"
    "testing"
)
var (
    eSyntax   = errors.New("syntax error")
    eOverflow = errors.New("overflow error")
)
/*!types:re2c*/
const u32Limit uint64 = 1<<32
func parse_u32(str string) (uint32, error) {
    var cursor, marker int
    result := uint64(0)
    cond := yycinit
    add_digit := func(base uint64, offset byte) {
        result = result * base + uint64(str[cursor-1] - offset)
        if result >= u32Limit {
            result = u32Limit
        }
    }
    /*!re2c
    re2c:yyfill:enable = 0;
    re2c:define:YYCTYPE        = byte;
    re2c:define:YYPEEK         = "str[cursor]";
    re2c:define:YYSKIP         = "cursor += 1";
    re2c:define:YYSHIFT        = "cursor += @@{shift}";
    re2c:define:YYBACKUP       = "marker = cursor";
    re2c:define:YYRESTORE      = "cursor = marker";
    re2c:define:YYGETCONDITION = "cond";
    re2c:define:YYSETCONDITION = "cond = @@";
    <*> * { return 0, eSyntax }
    <init> '0b' / [01]        :=> bin
    <init> "0"                :=> oct
    <init> ""   / [1-9]       :=> dec
    <init> '0x' / [0-9a-fA-F] :=> hex
    <bin, oct, dec, hex> "\x00" {
        if result < u32Limit {
            return uint32(result), nil
        } else {
            return 0, eOverflow
        }
    }
    <bin> [01]  { add_digit(2, '0');     goto yyc_bin }
    <oct> [0-7] { add_digit(8, '0');     goto yyc_oct }
    <dec> [0-9] { add_digit(10, '0');    goto yyc_dec }
    <hex> [0-9] { add_digit(16, '0');    goto yyc_hex }
    <hex> [a-f] { add_digit(16, 'a'-10); goto yyc_hex }
    <hex> [A-F] { add_digit(16, 'A'-10); goto yyc_hex }
    */
}
func TestLex(t *testing.T) {
    var tests = []struct {
        num uint32
        str string
        err error
    }{
        {1234567890, "1234567890\000", nil},
        {13, "0b1101\000", nil},
        {0x7fe, "0x007Fe\000", nil},
        {0644, "0644\000", nil},
        {0, "9999999999\000", eOverflow},
        {0, "123??\000", eSyntax},
    }
    for _, x := range tests {
        t.Run(x.str, func(t *testing.T) {
            num, err := parse_u32(x.str)
            if !(num == x.num && err == x.err) {
                t.Errorf("got %d, want %d", num, x.num)
            }
        })
    }
}

SKELETON PROGRAMS

With the -S, --skeleton option, re2c ignores all non-re2c 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) re2c 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 re2c 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). Re2c 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, re2c 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) re2c 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 (re2c writes data to file as soon as it is generated).

VISUALIZATION AND DEBUG

With the -D, --emit-dot option, re2c does not generate code. Instead, it dumps the generated DFA in DOT format. One 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

Re2c was originaly written by Peter Bumbulis in 1993. Since then it has been developed and maintained by multiple volunteers; mots notably, Brain Young, Marcus Boerger, Dan Nuffer and Ulya Trofimovich.