RE2D(1)
โจ NAME โจ
okay bestie, welcome to RE2D(1) โ the manual page for re2d, which is here to generate fast lexical analyzers for D. Thatโs the whole NAME vibe. iconic. ๐
๐ธ SYNOPSIS ๐ธ
re2d [ OPTIONS ] [ WARNINGS ] INPUT
INPUT can be either a file or - for stdin. yes bestie, - really is the stdin shortcut. ๐ซถ
๐ฆ INTRODUCTION ๐ฆ
okay so re2d works as a preprocessor. It reads the input file (which is usually a program in D, but can be anything) and looks for blocks of code enclosed in special-form start/end markers. The text outside of these blocks is copied verbatim into the output file. The contents of the blocks are processed by re2d. It translates them to code in D and outputs the generated code in place of the block. literally the main character of your build pipeline. โจ
Here is an example of a small program that checks if a given string contains a decimal number:
// re2d $INPUT -o $OUTPUT -i
module main;
private bool lex(const(char)* yycursor) {
/*!re2c
re2c:YYCTYPE = char;
re2c:yyfill:enable = 0;
[1-9][0-9]* { return true; }
* { return false; }
*/
}
void main() {
assert(lex("1234"));
}
In the output re2d replaced the block in the middle with the generated code:
/* Generated by re2d */
// re2d $INPUT -o $OUTPUT -i
module main;
private bool lex(const(char)* yycursor) {
{
char yych;
yych = *yycursor;
switch (yych) {
case '1': .. case '9': goto yy2;
default: goto yy1;
}
yy1:
++yycursor;
{ return false; }
yy2:
yych = *++yycursor;
switch (yych) {
case '0': .. case '9': goto yy2;
default: goto yy3;
}
yy3:
{ return true; }
}
}
void main() {
assert(lex("1234"));
}
๐ BASICS ๐
A re2d program consists of a sequence of blocks intermixed with code in the target language. A block may contain definitions, configurations, rules, actions and directives in any order:
name = regular-expression ;โ a definition binds name to regular-expression. Names may contain alphanumeric characters and underscore. The regular expressions section gives an overview ofre2dsyntax 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 changere2dbehavior and customize the generated code. For a full list of configurations supported byre2dsee 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. sneaky but slay. ๐regular-expression codeโ a rule binds regular-expression to its semantic action (a block of code in curly braces, or a block of code that starts with:=and ends on a newline followed by any non-whitespace character). If the regular-expression matches, the associated code is executed. If multiple rules match, the longest match takes precedence. If multiple rules match the same string, the earliest one takes precedence. There are two special rules: the default rule*and the end of input rule$. Default rule should always be defined, it has the lowest priority regardless of its place in the block, and it matches any code unit (not necessarily a valid character, see the encoding support section). The end of input rule should be defined if the corresponding method for handling the end of input is used. With start conditions rules have more complex syntax. ๐!action codeโ an action binds a user-defined block of code to a particular place in the generated finite state machine (in the same way as semantic actions bind code to the final states). See the actions section for a full list of predefined actions.!directive ;โ a directive is one of the special predefined statements. Each directive has a unique purpose. See the directives section for details.
๐ง Blocks ๐ง
Block start and end markers are either /*!re2c and */, or %{ and %} (both styles are supported). Starting from version 2.2 blocks may have optional names that allow them to be referenced in other blocks. There are different kinds of blocks:
/*!re2c[:<name>] ... */or%{[:<name>] ... %}โ a global block contains definitions, configurations, rules and directives.re2dcompiles regular expressions associated with each rule into a deterministic finite automaton, encodes it in the form of conditional jumps in the target language and replaces the block with the generated code. Names and configurations defined in a global block are added to the global scope and become visible to subsequent blocks. At the start of the program the global scope is initialized with command-line options. ๐/*!local:re2c[:<name>] ... */or%{local[:<name>] ... %}โ a local block is like a global block, but the names and configurations in it have local scope (they do not affect other blocks). cozy and contained. ๐/*!rules:re2c[:<name>] ... */or%{rules[:<name>] ... %}โ a rules block is like a local block, but it does not generate any code by itself, nor does it add any definitions to the global scope โ it is meant to be reused in other blocks. This is a way of sharing code (more details in the reusable blocks section). Prior tore2dversion 2.2 rules blocks required-r --reusableoption. sharing is caring fr fr. ๐ซถ/*!use:re2c[:<name>] ... */or%{use[:<name>] ... %}โ a use block that references a previously defined rules block. If the name is specified,re2dlooks 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 tore2dversion 2.2 use blocks required-r --reusableoption. reuse era. โป๏ธ/*!max:re2c[:<name1>[:<name2>...]] ... */or%{max[:<name1>[:<name2>...]] ... %}โ a block that generatesYYMAXFILLdefinition. An optional list of block names specifies which blocks should be included when computingYYMAXFILLvalue (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 configurationformatthat specifies a template string where@@{max}(or@@for short) is replaced with the numeric value ofYYMAXFILL. ๐/*!maxnmatch:re2c[:<name1>[:<name2>...]] ... */or%{maxnmatch[:<name1>[:<name2>...]] ... %}โ a block that generatesYYMAXNMATCHdefinition (it requires-P --posix-capturesoption). An optional list of block names specifies which blocks should be included when computingYYMAXNMATCHvalue (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 configurationformatthat specifies a template string where@@{max}(or@@for short) is replaced with the numeric value ofYYMAXNMATCH. ๐ข/*!stags:re2c[:<name1>[:<name2>...]] ... */,/*!mtags:re2c[:<name1>[:<name2>...]] ... */or%{stags[:<name1>[:<name2>...]] ... %},%{mtags[:<name1>[:<name2>...]] ... %{โ blocks that specify a template piece of code that is expanded for each s-tag/m-tag variable generated byre2d. 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:formatandseparator. Configurationformatspecifies a template string where@@{tag}(or@@for short) is replaced with the name of each tag variable. Configurationseparatorspecifies a piece of code used to join the generated format pieces for different tag variables. ๐ท๏ธ/*!svars:re2c[:<name1>[:<name2>...]] ... */,/*!mvars:re2c[:<name1>[:<name2>...]] ... */or%{svars[:<name1>[:<name2>...]] ... %},%{mvars[:<name1>[:<name2>...]] ... %{โ blocks that specify a template piece of code that is expanded for each s-tag/m-tag that is either explicitly mentioned by the rules (with--tagsoption) or implicitly generated byre2d(with--captvarsor--posix-captvarsoptions). An optional list of block names specifies which blocks should be included when computing the set of tags (if the list is empty, all blocks are included). There are two optional configurations:formatandseparator. Configurationformatspecifies a template string where@@{tag}(or@@for short) is replaced with the name of each tag. Configurationseparatorspecifies a piece of code used to join the generated format pieces for different tags. ๐/*!getstate:re2c[:<name1>[:<name2>...]] ... */or%{getstate[:<name1>[:<name2>...]] ... %}โ a block that generates conditional dispatch on the lexer state (it requires--storable-stateoption). 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. This block type is incompatible with the--loop-switchoption, as it requires cross-block transitions that are unsupported withoutgotoor function calls. ๐ฆ/*!conditions:re2c[:<name1>[:<name2>...]] ... */,/*!types:re2c... */or%{conditions[:<name1>[:<name2>...]] ... %},%{types... %}โ okay so this block literally generates the condition enumeration, but only if you've got the--conditionsoption on (it requires it, no cap). You can optionally drop a list of block names after it to say which blocks get counted when it's figuring out the set of conditions โ and if you leave the list empty, bestie, it just includes all the blocks. By default the generated code is an enumeration calledYYCONDTYPE. Wanna customize it? There's optional configsformatandseparatorfor that.formatis a template string where@@{cond}(or just@@if you're feeling lazy) gets swapped for each condition's name, and@@{num}gets swapped for that condition's numeric index.separatoris the bit of code used to glue the generatedformatpieces together for different conditions. โจ/*!include:re2c <file> */or%{include <file> %}โ this one lets you include<file>, and heads up, it must be a double-quoted file path. The contents of that file get literally substituted right where the block is, exactly the way#includeworks in C/C++. You can pair this with the--depfileoption to generate build system dependencies on those included files. ๐ซถ/*!header:re2c:on*/or%{header:on %}โ marks the start of the header file. Everything after this, all the way up to the nextheader:offblock, gets processed byre2dand written out to the header file you specified with the-t/--type-headeroption. ๐/*!header:re2c:off*/or%{header:off %}โ and this marks the end of the header file section that got started by theheader:onblock. That's it, that's the whole job. ๐/*!ignore:re2c ... */or%{ignore ... %}โ a block where the contents get straight-up ignored and yeeted from the output file. Not in the output, not your problem. ๐
๐ฆ Configurations ๐ฆ
Here's the full list of configurations re2d supports โ I'm not skipping a single one, bestie, we're going the whole way:
re2c:api,re2c:inputโ same as the--apioption.re2c:api:sigilโ sets the marker ("sigil") used for argument placeholders in the API primitives. Default is@@. A placeholder starts with the sigil followed by the argument name in curly braces โ so like, if you set the sigil to$, placeholders look like${name}. Single-argument APIs are allowed to use a shorthand without the name in braces. You can override this one with options for individual API primitives, e.g.re2c:YYFILL@lenforYYFILL. ๐ฏre2c:api:styleโ picks the API style. Possible values arefunctions(the default for C) andfree-form(the default for Go and Rust). Infunctionsstyle, API primitives get generated with an argument list in parentheses right after the primitive's name. Those arguments are only provided for autogenerated parameters (like the number of characters passed toYYFILL), not for the general lexer context, so the primitives behave more like macros in C/C++ or closures in Go and Rust. Infree-formstyle the API primitives don't have a fixed form at all โ they're defined as strings containing free-form pieces of code with interpolated variables of the form@@{var}or@@, and those correspond to the arguments in function-like style. You can override this per-primitive โ see for example there2c:YYFILL:nakedconfiguration forYYFILL. ๐re2c:bit-vectors,re2c:flags:bit-vectors,re2c:flags:bโ same as the--bit-vectorsoption, except you can configure it per-block. ๐งre2c:captures,re2c:leftmost-capturesโ same as the--leftmost-capturesoption, but per-block. ๐re2c:captvars,re2c:leftmost-captvarsโ same as the--leftmost-captvarsoption, but per-block. ๐re2c:case-insensitive,re2c:flags:case-insensitiveโ same as the--case-insensitiveoption, but per-block.re2c:case-inverted,re2c:flags:case-invertedโ same as the--case-invertedoption, but per-block.re2c:case-ranges,re2c:flags:case-rangesโ same as the--case-rangesoption, but per-block.re2c:computed-gotos,re2c:flags:computed-gotos,re2c:flags:gโ same as the--computed-gotosoption, but per-block. ๐ฅre2c:computed-gotos:relative,re2c:cgoto:relativeโ same as the--computed-gotos-relativeoption, but configurable per-block.re2c:computed-gotos:threshold,re2c:cgoto:thresholdโ if computed goto is being used, this sets the complexity threshold that triggers generation of jump tables instead of nestedifstatements and bitmaps. Default value is9. ๐re2c:cond:abortโ if you set it to a positive integer value, the default case in the generated condition dispatch aborts program execution. Yeah. Dramatic but real. ๐re2c:cond:gotoโ a piece of code used for the autogenerated shortcut rules:=>in conditions. Default isgoto @@;. That@@placeholder gets substituted with the condition name (see configurationsre2c:api:sigilandre2c:cond:goto@cond).re2c:cond:goto@condโ sets the sigil used for argument substitution inside there2c:cond:gotodefinition. Default value is@@. This overrides the more genericre2c:api:sigilconfiguration.re2c:cond:dividerโ defines the divider for condition blocks. Default value is/* *********************************** */. Placeholders get substituted with the condition name (seere2c:api;sigilandre2c:cond:divider@cond).re2c:cond:divider@condโ sets the sigil used for argument substitution inside there2c:cond:dividerdefinition. Default is@@. Overrides the more genericre2c:api:sigilconfiguration.re2c:cond:prefix,re2c:condprefixโ the prefix used for condition labels. Default isyyc_.re2c:cond:enumprefix,re2c:condenumprefixโ the prefix used for condition identifiers. Default isyyc.re2c:debug-output,re2c:flags:debug-output,re2c:flags:dโ same as the--debug-outputoption, but per-block.re2c:empty-class,re2c:flags:empty-classโ same as the--empty-classoption, but per-block.re2c:encoding:ebcdic,re2c:flags:ecb,re2c:flags:eโ same as the--ebcdicoption, but per-block.re2c:encoding:ucs2,re2c:flags:wide-chars,re2c:flags:wโ same as the--ucs2option, but per-block.re2c:encoding:utf8,re2c:flags:utf-8,re2c:flags:8โ same as the--utf8option, but per-block.re2c:encoding:utf16,re2c:flags:utf-16,re2c:flags:xโ same as the--utf16option, but per-block.re2c:encoding:utf32,re2c:flags:unicode,re2c:flags:uโ same as the--utf32option, but per-block.re2c:encoding-policy,re2c:flags:encoding-policyโ same as the--encoding-policyoption, but per-block.re2c:eofโ the sentinel symbol used with the end-of-input rule$. Default value is-1, which means the$rule just isn't used. Other possible values include all valid code units. Heads up: only decimal numbers are recognized here, so don't try anything cute. ๐ขre2c:header,re2c:flags:type-header,re2c:flags:tโ the name of the generated header file, relative to the directory of the output file. Same as the--headeroption except that the file path is relative. ๐๏ธre2c:indent:stringโ the string used for indentation. Default is a single tab character"\t". The indent string should contain whitespace characters only. Wanna disable indentation entirely? Set this to an empty string and slay. โจre2c:indent:topโ the minimum amount of indentation to use. Default value is0. The value should be a non-negative integer number.re2c:invert-capturesโ same as the--invert-capturesoption, but per-block.re2c:label:prefix,re2c:labelprefixโ the prefix used for DFA state labels. Default isyy.re2c:label:start,re2c:startlabelโ controls generation of the block start label. Default value is0, meaning the start label is generated only if it's used. An integer value greater than zero forces the start label to be generated even if the lexer never uses it. A string value also forces the start label to be generated and sets the label name to that string. Important detail: this configuration applies only to the current block โ it gets reset to default for the next block. ๐re2c:label:yyFillLabelโ the prefix ofYYFILLlabels used withre2c:eofand in storable state mode.re2c:label:yyloopโ the name of the label marking the start of the lexer loop with the--loop-switchoption. Default isyyloop.re2c:label:yyNextโ the name of the optional label that follows theYYGETSTATEswitch in storable state mode (enabled viare2c:state:nextlabel). Default isyyNext.re2c:lookahead,re2c:flags:lookaheadโ deprecated, bestie (see the deprecated--no-lookaheadoption). Don't come crying to me. ๐re2c:monadicโ if set to non-zero, the generated lexer uses monadic notation. This one's specific to Haskell. ๐งre2c:nested-ifs,re2c:flags:nested-ifs,re2c:flags:sโ same as the--nested-ifsoption, but per-block.re2c:posix-captures,re2c:flags:posix-captures,re2c:flags:Pโ same as the--posix-capturesoption, but per-block.re2c:posix-captvarsโ same as the--posix-captvarsoption, but per-block.re2c:tags,re2c:flags:tags,re2c:flags:Tโ same as the--tagsoption, but per-block. ๐ท๏ธre2c:tags:expressionโ this one sets the expression used for tag variables ๐ by defaultre2dspits out expressions shaped likeyyt<N>, which is lowkey annoying if your tag variables live as fields inside a struct. All occurrences of@@{tag}or@@get swapped for the actual tag name. Like,re2c:tags:expression = "s.@@";gives you expressions of the forms.yyt<N>in the generated code. Also peepre2c:api:sigilconfig โจre2c:tags:negativeโ specifies the constant expression used for a negative tag value ๐ (typically that's-1if tags are integer offsets into the input string, or a null pointer if they're pointers)re2c:tags:prefixโ sets the prefix for tag variable names. The default isyyt๐re2c:sentinelโ specifies the sentinel symbol used for end-of-input checks (the case when bounds checks are disabled withre2c:yyfill:enable = 0;andre2c:eofis not set). Heads up: this config does not affect code generation โ its whole job is to verify that the sentinel isn't allowed in the middle of a rule and to make sure the lexer won't read past the end of buffer ๐ The default value is-1(in that casere2dassumes that the sentinel is zero, which is the most common case). Only decimal numbers are recognized, no cap.re2c:state:abortโ set it to a positive integer and the default case in the generated state dispatch aborts program execution, plus an explicit-1case contains a transition to the start of the block ๐ฅre2c:state:nextlabelโ controls whether theYYGETSTATEswitch is followed by ayyNextlabel (default value is zero, which means no label). Alternatively you can usere2c:label:startto generate a specific start label, or an explicit getstate block to generate theYYGETSTATEswitch separately from the lexer block ๐ซre2c:unsafe,re2c:flags:unsafeโ same as the--no-unsafeoption, but configurable per-block ๐ฆ Set it to zero and it suppresses the generation of unsafe wrappers aroundYYPEEK. The default is non-zero (wrappers are generated). This configuration is specific to Rust, iykyk.re2c:YYBACKUP,re2c:define:YYBACKUPโ defines the generic API primitiveYYBACKUP.re2c:YYBACKUPCTX,re2c:define:YYBACKUPCTXโ defines the generic API primitiveYYBACKUPCTX.re2c:YYCONDTYPE,re2c:define:YYCONDTYPEโ defines the API primitiveYYCONDTYPE.re2c:YYCTYPE,re2c:define:YYCTYPEโ defines the API primitiveYYCTYPE.re2c:YYCTXMARKER,re2c:define:YYCTXMARKERโ defines the API primitiveYYCTXMARKER.re2c:YYCURSOR,re2c:define:YYCURSORโ defines the API primitiveYYCURSOR.re2c:YYDEBUG,re2c:define:YYDEBUGโ defines the API primitiveYYDEBUG.re2c:YYFILL,re2c:define:YYFILLโ defines the API primitiveYYFILL.re2c:YYFILL@len,re2c:define:YYFILL@lenโ specifies the sigil used for argument substitution in theYYFILLdefinition. Defaults to@@๐ and it overrides the more genericre2c:api:sigilconfiguration.re2c:YYFILL:naked,re2c:define:YYFILL:nakedโ overrides the more genericre2c:api:styleconfiguration forYYFILL. A zero value corresponds to free-form API style ๐ธre2c:YYFNโ defines the API primitiveYYFN.re2c:YYINPUTโ defines the API primitiveYYINPUT.re2c:YYGETCOND,re2c:define:YYGETCONDITIONโ defines the API primitiveYYGETCOND.re2c:YYGETCOND:naked,re2c:define:YYGETCONDITION:nakedโ overrides the more genericre2c:api:styleconfiguration forYYGETCOND. Zero value = free-form API style โจre2c:YYGETSTATE,re2c:define:YYGETSTATEโ defines the API primitiveYYGETSTATE.re2c:YYGETSTATE:naked,re2c:define:YYGETSTATE:nakedโ overrides the more genericre2c:api:styleconfiguration forYYGETSTATE. Zero value = free-form API style ๐re2c:YYGETACCEPT,re2c:define:YYGETACCEPTโ defines the API primitiveYYGETACCEPT.re2c:YYLESSTHAN,re2c:define:YYLESSTHANโ defines the generic API primitiveYYLESSTHAN.re2c:YYLIMIT,re2c:define:YYLIMITโ defines the API primitiveYYLIMIT.re2c:YYMARKER,re2c:define:YYMARKERโ defines the API primitiveYYMARKER.re2c:YYMTAGN,re2c:define:YYMTAGNโ defines the generic API primitiveYYMTAGN.re2c:YYMTAGP,re2c:define:YYMTAGPโ defines the generic API primitiveYYMTAGP.re2c:YYPEEK,re2c:define:YYPEEKโ defines the generic API primitiveYYPEEK.re2c:YYRESTORE,re2c:define:YYRESTOREโ defines the generic API primitiveYYRESTORE.re2c:YYRESTORECTX,re2c:define:YYRESTORECTXโ defines the generic API primitiveYYRESTORECTX.re2c:YYRESTORETAG,re2c:define:YYRESTORETAGโ defines the generic API primitiveYYRESTORETAG.re2c:YYSETCOND,re2c:define:YYSETCONDITIONโ defines the API primitiveYYSETCOND.re2c:YYSETCOND@cond,re2c:define:YYSETCONDITION@condโ specifies the sigil used for argument substitution in theYYSETCONDdefinition. Default value is@@๐ซถ and it overrides the more genericre2c:api:sigilconfiguration.re2c:YYSETCOND:naked,re2c:define:YYSETCONDITION:nakedโ overrides the more genericre2c:api:styleconfiguration forYYSETCOND. Zero value = free-form API style ๐re2c:YYSETSTATE,re2c:define:YYSETSTATEโ defines the API primitiveYYSETSTATE.re2c:YYSETSTATE@state,re2c:define:YYSETSTATE@stateโ specifies the sigil used for argument substitution in theYYSETSTATEdefinition. Default value is@@๐ and it overrides the more genericre2c:api:sigilconfiguration.re2c:YYSETSTATE:naked,re2c:define:YYSETSTATE:nakedโ overrides the more genericre2c:api:styleconfiguration forYYSETSTATE. Zero value = free-form API style โญre2c:YYSETACCEPT,re2c:define:YYSETACCEPTโ defines the API primitiveYYSETACCEPT.re2c:YYSKIP,re2c:define:YYSKIPโ defines the generic API primitiveYYSKIP.re2c:YYSHIFT,re2c:define:YYSHIFTโ defines the generic API primitiveYYSHIFT.re2c:YYCOPYMTAG,re2c:define:YYCOPYMTAGโ defines the generic API primitiveYYCOPYMTAG.re2c:YYCOPYSTAG,re2c:define:YYCOPYSTAGโ defines the generic API primitiveYYCOPYSTAG.re2c:YYSHIFTMTAG,re2c:define:YYSHIFTMTAGโ defines the generic API primitiveYYSHIFTMTAG.re2c:YYSHIFTSTAG,re2c:define:YYSHIFTSTAGโ defines the generic API primitiveYYSHIFTSTAG.re2c:YYSTAGN,re2c:define:YYSTAGNโ defines the generic API primitiveYYSTAGN.re2c:YYSTAGP,re2c:define:YYSTAGPโ defines the generic API primitiveYYSTAGP.re2c:yyaccept,re2c:variable:yyacceptโ defines the API primitiveyyaccept.re2c:yybm,re2c:variable:yybmโ defines the API primitiveyybm.re2c:yybm:hex,re2c:variable:yybm:hexโ set it to nonzero and the bitmaps for the--bit-vectorsoption get generated in hexadecimal format ๐ the default is zero (bitmaps are in decimal format).re2c:yych,re2c:variable:yychโ defines the API primitiveyych.re2c:yych:emit,re2c:variable:yych:emitโ set it to zero and theyychdefinition is not generated ๐ the default is non-zero.re2c:yych:conversion,re2c:variable:yych:conversionโ set it to non-zero andre2dautomatically generates a conversion toYYCTYPEevery single timeyychis read โจ the default is zero (no conversion).re2c:yych:literals,re2c:variable:yych:literalsโ specifies the form of literals thatyychis matched against. Possible values are:char(character literals in single quotes, non-printable ones use escape sequences that start with backslash),hex(hexadecimal integers) andchar_or_hex(a mixture of both โ character literals for printable characters and hexadecimal integers for others) ๐ฆre2c:yyctable,re2c:variable:yyctableโ defines the API primitiveyyctable.re2c:yynmatch,re2c:variable:yynmatchโ defines the API primitiveyynmatch.re2c:yypmatch,re2c:variable:yypmatchโ defines the API primitiveyypmatch.re2c:yytarget,re2c:variable:yytargetโ defines the API primitiveyytarget.re2c:yystable,re2c:variable:yystableโ deprecated, bestie ๐ that's it, that's the whole entry.re2c:yystate,re2c:variable:yystateโ defines the API primitiveyystate.re2c:yyfill,re2c:variable:yyfillโ defines the API primitiveyyfill.re2c:yyfill:checkโ set it to zero and it suppresses the generation of the pre-YYFILLcheck for the number of input characters (that's theYYLESSTHANdefinition in the generic API and theYYLIMIT-based comparison in the C pointer API) ๐ธ the default is non-zero (the check is generated).re2c:yyfill:enableโ set it to zero and it suppresses the generation ofYYFILL(together with the check). Use this when the whole input fits into one piece of memory (no buffering needed) and the end-of-input checks don't rely on theYYFILLchecks (e.g. if a sentinel character is used) ๐ Use the warnings (-Woption) and there2c:sentinelconfiguration to verify that the generated lexer cannot read past the end of input. The default is non-zero (YYFILLis enabled).re2c:yyfill:parameterโ set it to zero and it suppresses the generation of the parameter passed toYYFILL๐ that parameter is the minimum number of characters that must be supplied. Defaults to non-zero (the parameter is generated). This configuration can be overridden withre2c:YYFILL:nakedorre2c:api:style.re2c:yyfn:sepโ specifies the separator used inYYFNelements (defaults to semicolon) ๐re2c:yyfn:throwโ specifies the exceptions thrown by theYYFNfunction (defaults to empty, which means no exceptions) โจ
๐ Regular expressions ๐
re2d uses the following syntax for regular expressions, bestie โ memorise the vibe check:
"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 classesRandSR*โ zero or more occurrences ofRR+โ one or more occurrences ofRR?โ optionalRR{n}โ repetition ofRexactlyntimesR{n,}โ repetition ofRat leastntimesR{n,m}โ repetition ofRfromntomtimes(R)โ justR; parentheses are used to override precedence. If submatch extraction is enabled,(R)is a capturing or a non-capturing group depending on the--invert-capturesoption ๐ธ(!R)โ if submatch extraction is enabled,(!R)is a non-capturing or a capturing group depending on the--invert-capturesoption ๐ซR Sโ concatenation, bestie:Rand thenS, in that order ๐ซถR | Sโ alternative: literally justRorS, pick a lane ๐R / Sโ lookahead:Rfollowed byS, butSis not consumed. It's giving "I see you but I'm not keeping you" energy ๐nameโ a regular expression defined asname(or, in Flex compatibility mode, the literal string"name"){name}โ a regular expression defined asnamein Flex compatibility mode@stagโ an s-tag: saves the last input position where@stagmatches into a variable namedstagโจ#mtagโ an m-tag: saves all the input positions where#mtagmatches into a variable namedmtag๐ฅ$โ end of input, periodt ๐
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. No cap, that's the whole list, memorize it ๐ง
๐ธ Actions ๐ธ
okay so here's the list of predefined actions that re2d supports, and honestly they're so useful:
!entry codeโ the entry action binds a user-defined block of code to the start state of the current finite state machine. If start conditions are being used, you can set the entry action individually for each condition. This is the one you use for initialization โ like, say, saving the start location of a lexeme ๐!pre_rule codeโ the pre-rule action prepends a user-defined block of code to the semantic actions of all rules in the current block (or condition, if start conditions are used). Perfect for factoring out the common part of all your semantic actions โ e.g. saving the end location of a lexeme ๐!post_rule codeโ the post-rule action appends a user-defined block of code to the semantic actions of all rules in the current block (or condition, if start conditions are used). You'd use this to emit trap statements that guard against unintended control flow ๐ก๏ธ
๐ฆ Directives ๐ฆ
here's the full list of directives re2d supports, no gatekeeping:
!use:name ;โ an in-block use directive that merges a previously defined rules block with the specifiednameinto the current block. The named definitions, configurations and rules of the referenced block get added to the current ones. Conflicts between overlapping rules and configurations are resolved the usual way: the first rule takes priority, and the latest configuration overrides the preceding ones. One exception though โ the special rules*,$and<!>always go to the block-local definition, no matter what. A use directive can live anywhere inside of a block, and you can have multiple use directives, slay ๐!include file ;โ this directive is the same as an include block: it inserts the contents offileverbatim in place of the directive ๐
๐ Program interface ๐
The generated code interfaces with the outer program through primitives, collectively referred to as the API. Which primitives you need to define for a particular program depends on a bunch of factors โ the complexity of your regular expressions, the input representation, buffering, and whether you're using various features. All the necessary primitives have to be defined by you, in the form of macros, functions, variables, or literally any other suitable form that makes the generated code syntactically and semantically correct.
โ ๏ธ and here's the scary part: re2d does not (and cannot) check the definitions. So if anything is missing or defined incorrectly, your generated program may have compile-time or run-time errors ๐ญ This manual provides examples of API definitions in the most common cases, so like... read them bestie.
re2d has three API flavors that define the core set of primitives used by a program:
โจ Simple API
This is the default API for the D backend. It consists of the primitives YYCURSOR, YYMARKER, YYCTXMARKER and YYLIMIT, which should be defined as pointers of type YYCTYPE*.
โจ Record API
Record API is useful in cases when the lexer state must be stored in a struct. It's enabled with the --api record option or the re2c:api = record configuration. This API consists of a variable yyrecord (the name can be overridden with re2c:yyrecord) that should be defined as a struct with the fields yycursor, yymarker, yyctxmarker, yylimit โ and only the fields used by the generated code need to be defined, and their names can be configured ๐ซถ
โจ Generic API
This is the most flexible API, highkey iconic. It's enabled with the --api generic option or the re2c:api = generic configuration. It contains primitives for generic operations: YYPEEK, YYSKIP, YYBACKUP, YYBACKUPCTX, YYSTAGP, YYSTAGN, YYMTAGP, YYMTAGN, YYRESTORE, YYRESTORECTX, YYRESTORETAG, YYSHIFT, YYSHIFTSTAG, YYSHIFTMTAG, YYLESSTHAN, YYEND. That's the whole squad ๐
Here's the full list of API primitives that may be used by the generated code to interface with the outer program. Buckle up, it's long but it's so worth it:
YYCTYPEโ the type of the input characters (code units). For ASCII, EBCDIC and UTF-8 encodings it should be a 1-byte unsigned integer. For UTF-16 or UCS-2 it should be a 2-byte unsigned integer. For UTF-32 it should be a 4-byte unsigned integer. Size matters, bestie ๐YYCURSORโ an l-value that stores the current input position (a pointer, or an integer offset inYYINPUT). InitiallyYYCURSORshould point to the first input character, and later it gets advanced by the generated code. When a rule matches, theYYCURSORposition is the one after the last matched character ๐YYLIMITโ an r-value that stores the end of input position (a pointer, or an integer offset inYYINPUT). InitiallyYYLIMITshould point to the position after the last available input character. It is not changed by the generated code. The lexer comparesYYCURSORtoYYLIMITto figure out if there are enough input characters left ๐ธYYMARKERโ an l-value that stores the position of the latest matched rule (a pointer, or an integer offset inYYINPUT). It's used to restore theYYCURSORposition if the longer match fails and the lexer needs to rollback. No initialization needed ๐YYCTXMARKERโ an l-value that stores the position of the trailing context (a pointer, or an integer offset inYYINPUT). No initialization needed.YYCTXMARKERis needed only if the lookahead operator/is used โญYYFILLโ a generic API primitive with one variablelen.YYFILLshould provide at leastlenmore input characters or fail. Ifre2c:eofis used, thenlenis always1andYYFILLshould always return to the calling function; a zero return value indicates success. Ifre2c:eofis not used, then theYYFILLreturn value is ignored and it should not return on failure. The maximum value oflenisYYMAXFILL๐งYYFNโ a primitive that defines a function prototype in the--recursive-functionscode model. Its value should be an array of one or more strings, where each string contains two or three components separated by the string specified in there2c:fn:sepconfiguration (typically a semicolon). The first array element defines the function name and return type (empty for a void function). Subsequent elements define function arguments: first, the expression for the argument used in the function body (usually just a name); second, the argument type; third, an optional formal parameter (it defaults to the first component โ usually both the argument and the parameter are the same identifier) ๐งYYINPUTโ an r-value that stores the current input character sequence (string, buffer, etc.) ๐ฅYYMAXFILLโ an integral constant equal to the maximum value of the argument toYYFILL. It can be generated with amaxblock ๐งฎYYLESSTHANโ a generic API primitive with one variablelen. It should be defined as an r-value of boolean type that equalstrueif and only if there are less thanleninput characters left ๐YYENDโ a generic API primitive with no variables. It should be defined as an r-value of boolean type that equalstrueif and only if the logical end of input has been reached (excluding any padding or sentinel symbols).YYENDis used to implement the$symbol in regular expressions. It differs fromYYLESSTHAN, which is used to make sure the lexer won't read past the end of the buffer ๐YYPEEKโ a generic API primitive with no variables. It should be defined as an r-value of typeYYCTYPEthat is equal to the character at the current input position ๐YYSKIPโ a generic API primitive that should advance the current input position by one code unit ๐โโ๏ธYYBACKUPโ a generic API primitive that should save the current input position (so it can be restored withYYRESTORElater) ๐พYYRESTOREโ a generic API primitive that should restore the current input position to the value saved byYYBACKUPโชYYBACKUPCTXโ a generic API primitive that should save the current input position as the position of the trailing context (to be restored withYYRESTORECTXlater) ๐YYRESTORECTXโ a generic API primitive that should restore the trailing context position saved withYYBACKUPCTX๐YYRESTORETAGโ a generic API primitive with one variabletagthat should restore the trailing context position to the value oftag๐ท๏ธYYSTAGPโ a generic API primitive with one variabletag, wheretagcan be a pointer or an offset inYYINPUT(peep the submatch extraction section for details).YYSTAGPshould settagto the current input position โจYYSTAGNโ a generic API primitive with one variabletag, wheretagcan be a pointer or an offset inYYINPUT(again, submatch extraction section, iykyk).YYSTAGNshould settagto a value that represents a non-existent input position ๐YYMTAGPโ a generic API primitive with one variabletag.YYMTAGPshould append the current position to the submatch history oftag(see the submatch extraction section for details) ๐YYMTAGNโ a generic API primitive with one variabletag.YYMTAGNshould append a value that represents a non-existent input position to the submatch history oftag(see the submatch extraction section for details) ๐ซYYSHIFTโ a generic API primitive with one variableshiftthat should shift the current input position byshiftcharacters (and yes, the shift value may be negative) โ๏ธYYCOPYSTAGโ a generic API primitive with two variables,lhsandrhs, that should copy the right-hand-side s-tag variablerhsto the left-hand-side s-tag variablelhs. For most languages this primitive has a default definition that assignslhstorhs๐ซถYYCOPYMTAGโ a generic API primitive that takes two variables,lhsandrhs, and should copy the right-hand-side m-tag variablerhsonto the left-hand-side m-tag variablelhs๐ for most languages this one has a default definition that just assignslhstorhs.YYSHIFTSTAGโ a generic API primitive with two variables,tagandshift, that should shifttagbyshiftcode units (and yes, theshiftvalue is allowed to be negative ๐).YYSHIFTMTAGโ a generic API primitive with two variables,tagandshift, that should shift the latest value in the history oftagbyshiftcode units (negativeshiftis totally valid here too โจ).YYMAXNMATCHโ an integral constant equal to the maximal number of POSIX capturing groups in a rule, bestie ๐ it gets generated with amaxnmatchblock.YYCONDTYPEโ the type of the condition enum ๐ it can be generated either with aconditionsblock or with the--headeroption.YYGETACCEPTโ a primitive with one variablevarthat stores the numeric selector of the accepted rule ๐ for most languages it has a default definition that reads fromvar.YYSETACCEPTโ a primitive with two variables:var(an l-value that stores the numeric selector of the accepted rule) andval(the value of the selector) ๐ธ for most languages the default definition assignsvartoval.YYGETCONDโ an r-value of typeYYCONDTYPEthat equals the current condition identifier ๐ซถ.YYSETCONDโ a primitive with one variablecondthat should set the current condition identifier tocondโญ.YYGETSTATEโ an r-value of integer type equal to the current lexer state ๐ it should be initialized to-1.YYSETSTATEโ a primitive with one variablestatethat should set the current lexer state tostate๐ซ.YYDEBUGโ this primitive is generated only with the-d,--debug-outputoption ๐ its whole purpose is adding logging to the generated code (a typicalYYDEBUGdefinition is a print statement).YYDEBUGstatements are generated in every state and have two variables:state(either a DFA state index or-1) andsymbol(the current input symbol).yyacceptโ an l-value of unsigned integral type that stores the number of the latest matched rule ๐ user definition is necessary only with the--storable-stateoption.yybmโ a table containing compressed bitmaps for up to 8 transitions (used with the--bitmapsoption) โจ the table contains 256 elements and is indexed by 1-byte code units. Each 8-bit element combines boolean values for up to 8 transitions. k-Th bit of n-th element is true iff n-th code unit is in the range of k-th transition. The whole idea of this bitmap is to replace manyifbranches orswitchcases with one single bit check in the table โ it's giving efficiency, no cap ๐ .yychโ an l-value of typeYYCTYPEthat stores the current input character ๐ฆ user definition is necessary only with the-f,--storable-stateoption.yyctableโ jump table generated for the initial condition dispatch (enabled with the combination of--conditionsand--computed-gotosoptions) ๐.yyfillโ an l-value that stores the result of theYYFILLcall (this may be necessary for pure functional languages, whereYYFILLis a monadic function with a complex return value) ๐.yynmatchโ an l-value of unsigned integral type that stores the number of POSIX capturing groups in the matched rule ๐ธ used only with the-P,--posix-capturesoption.yypmatchโ an array of l-values that hold the tag values corresponding to the capturing parentheses in the matching rule ๐ซถ array length must be at leastyynmatch * 2(usuallyYYMAXNMATCH * 2is a good choice). Used only with the-P,--posix-capturesoption.yystableโ Deprecated. ๐ that's it, that's the whole note.yystateโ an l-value used with the--loop-switchoption to store the current DFA state โญ.yytargetโ jump table that contains jump targets (label addresses) for all transitions from a state ๐ this table is local to each state. Generation ofyytargettables is enabled with the--computed-gotosoption.
โจ Options โจ
okay so real talk: some of these 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, and internal options are useful for experimenting with the algorithms used in re2c ๐ง.
-?,--help,-hโ show the help message ๐.--api <simple | record | generic>โ specify the API that the generated code uses to interface with user-defined code. Optionsimpleis for simple cases when there's no need for buffer refilling and storing lexer state. Optionrecordis for when lexer state needs to be stored in a record (struct, class, etc.). Optiongenericis for complex cases when the other two APIs aren't flexible enough ๐ .--bit-vectors,-bโ optimize conditional jumps using bit masks โจ this option implies--nested-ifs.--captures,--leftmost-capturesโ enable submatch extraction with leftmost greedy capturing groups ๐ the result is collected into an arrayyybmatchof capacity2 * YYMAXNMATCH, andyynmatchis set to the number of groups for the matching rule.--captvars,--leftmost-captvarsโ enable submatch extraction with leftmost greedy capturing groups ๐ the result is collected into variablesyytl<k>,yytr<k>for k-th capturing group.--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 aswitchstatement into a range of the formlow ... highโญ this syntax is a C/C++ language extension supported by compilers like GCC, Clang and Tcc. The main advantage over using single cases is smaller generated code and faster generation time, although for some compilers like Tcc it also results in smaller binary size.--computed-gotos,-gโ optimize conditional jumps using the non-standard "computed goto" extension (which the compiler must support) ๐ฅre2dgenerates jump tables only in complex cases with a lot of conditional branches. The complexity threshold can be configured with thecgoto:thresholdconfiguration. Relative offsets can be enabled with thecgoto:relativeconfiguration. This option implies--bit-vectors.--computed-gotos-relativeโ similar to--computed-gotosbut generates relative offsets for jump tables instead (which the compiler must support) ๐ซ this option implies--computed-gotos.--conditions,--start-conditions,-cโ enable support of Flex-like "conditions": multiple interrelated lexers within one block ๐ this is the alternative to manually specifying differentre2dblocks connected withgotoor function calls.--depfile FILEโ write dependency information toFILEin the form of a Makefile rule:
<output-file> : <input-file> [include-file ...]
this lets you track build dependencies when include blocks/directives are in play, so that updating include files triggers regeneration of the output file ๐ this option depends on the --output option.
--ebcdic,--ecb,-eโ generate a lexer that reads input in EBCDIC encoding ๐re2dassumes that the character range is0--0xFFand character size is 1 byte.--empty-class <match-empty | match-none | error>โ define the wayre2dtreats empty character classes ๐ withmatch-empty(the default) an empty class matches empty input (which is illogical, but backwards-compatible). Withmatch-nonean empty class always fails to match. Witherroran empty class raises a compilation error ๐ญ.--encoding-policy <fail | substitute | ignore>โ define the wayre2dtreats Unicode surrogates ๐ธ withfailre2daborts with an error when a surrogate is encountered. Withsubstitutere2dsilently replaces surrogates with the error code point0xFFFD. Withignore(the default)re2dtreats surrogates as normal code points. The Unicode standard says standalone surrogates are invalid, but real-world libraries and programs behave in different ways ๐.--flex-syntax,-Fโ 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 with curly braces ๐ซถ names without curly braces are treated as double-quoted strings.--goto-labelโ use the "goto/label" code model: encode DFA in the form of labeled code blocks connected withgototransitions across blocks โญ this is only supported for languages that have agotostatement.--header,--type-header,-t HEADERโ generate aHEADERfile ๐ the contents of the file can be specified using special blocksheader:onandheader:off. If conditions are used, the generated header will have a condition enum automatically appended to it (unless there's an explicitconditionsblock).-I PATHโ addPATHto the list of locations used when searching for include files ๐ this option is useful in combination with an include block or directive.re2dlooks forFILEin the directory of the parent file and in the include locations specified with the-Ioption.--input <default | custom>โ deprecated alias for--api๐ optiondefaultcorresponds tosimple(it is indeed the default for most backends, but not for all). Optioncustomcorresponds togeneric.--input-encoding <ascii | utf8>โ specify the wayre2dparses regular expressions โจ withascii(the default)re2dhandles input as ASCII-encoded: any sequence of code units is a sequence of standalone 1-byte characters. Withutf8re2dhandles input as UTF8-encoded and recognizes multibyte characters ๐ฆ.--invert-capturesโ flips the whole capturing vibe ๐. Normally(...)captures and(! ...)is like "no thanks I'm just here for the group photo." With this turned on, it's the other way around:(! ...)starts capturing and(...)is suddenly camera-shy. Chaotic but valid ๐ .--lang <none | c | d | go | haskell | java | js | ocaml | python | rust | swift | v | zig>โ tells re2d what language you want your shiny lexer in โจ. The supported languages are C, D, Go, Haskell, Java, JS, OCaml, Python, Rust, Swift, V, and Zig (and yes bestie, more languages can be added via user-defined syntax files โ peep the--syntaxoption ๐). If you passnone, it disables the default syntax configs so the target language is literally undefined โ main character with no backstory, iykyk.--location-format <gnu | msvc>โ controls how locations show up in messages ๐. Withgnu, locations print as'filename:line:column: ...'. Withmsvc, they print as'filename(line,column) ...'. The default isgnu, no cap.--loop-switchโ uses the "loop/switch" code model, which encodes the DFA as a loop over a switch statement where each individual state is a switch case ๐. The state lives in a variable calledyystate. When you transition between states,yystategets updated to the case label of the destination state and execution continues to the head of the loop. It's giving very "we do a little looping" energy.--computed-continueโ this one requires the--loop-switchcode model, so no mixing and matching bestie ๐ซ. It uses computedcontinuestatements to pick the next switch case directly, which unlocks jump-table optimization similar to what--computed-gotosdoes in the goto/label code model. Fancy stuff โจ.--nested-ifs,-sโ uses nestedifstatements instead ofswitchstatements in conditional jumps. This usually results in more efficient code when you're working with non-optimizing compilers ๐ช. Lowkey a glow-up for your build.--no-debug-info,-iโ doesn't output line directives. This is super useful when the generated code lives in a version control system, because otherwise you get huge autogenerated diffs on even the tiniest change ๐ญ. Nobody wants that chaos in their git history.--no-generation-dateโ suppresses the date output in the generated file ๐ . Clean and minimal, we love to see it.--no-versionโ suppresses the version output in the generated file. Simple as that ๐ซถ.--no-unsafeโ doesn't generate the unsafe wrapper overYYPEEK(this one is Rust-specific btw ๐ฆ). For performance reasonsYYPEEKshould avoid bounds-checking, since the lexer already does end-of-input checks in a more efficient way. The user can choose to provide a safeYYPEEKdefinition, or one that's unsafe only in release builds โ in that case--no-unsafehelps avoid warnings about redundantunsafeblocks. Very thoughtful, very demure.--output,-o OUTPUTโ specifies theOUTPUTfile ๐. That's the one, that's the whole thing.--posix-captures,-Pโ enables submatch extraction with POSIX-style capturing groups. The result gets collected into an array calledyybmatchwith capacity2 * YYMAXNMATCH, andyynmatchis set to the number of groups for the matching rule ๐ฏ. Iconic behavior honestly.--posix-captvarsโ also enables submatch extraction with POSIX-style capturing groups, but this time the result is collected into variablesyytl<k>,yytr<k>for the k-th capturing group ๐. Different vibe, same goal.--recursive-functionsโ uses a code model based on co-recursive functions, where each DFA state is its own separate function that may call other state-functions or even itself ๐. It's giving recursive main character energy, fr fr.--reusable,-rโ deprecated since version 2.2 (reusable blocks are allowed by default now). So likeโฆ she's retired bestie ๐, but she's still in the manual for historical reasons.--skeleton,-Sโ ignores user-defined interface code and generates a self-contained "skeleton" program ๐ฆด. It also generates input files with strings derived from the regular grammar plus compressed match results, which are used to verify "skeleton" behavior on all inputs. This option is useful for finding bugs in optimizations and code generation. Important: this option is supported only for C โ ๏ธ.--storable-state,-fโ generates a lexer that can store its inner state ๐พ. This is useful in push-model lexers that get stopped by an outer program when there isn't enough input, then resumed when more input becomes available. In this mode, users should additionally defineYYGETSTATEandYYSETSTATEprimitives, and the variablesyych,yyaccept, andstateshould be part of the stored lexer state. Memory queen behavior ๐.--syntax FILEโ loads configurations from the specifiedFILEand applies them on top of the default syntax file ๐. Note thatFILEcan define just a few configurations (if it's used to amend the default syntax file), or it can define a whole new language backend โ and in that latter case it's recommended to use the--lang noneoption. Flexible and powerful, we stan.--tags,-Tโ enables submatch extraction with tags ๐ท๏ธ. Short flag, big energy.--ucs2,--wide-chars,-wโ generates a lexer that reads UCS2-encoded input. re2d assumes the character range is0โ0xFFFFand character size is 2 bytes. This option implies--nested-ifsโ ๏ธ. Wide chars, wide possibilities ๐ .--utf8,--utf-8,-8โ generates a lexer that reads input in UTF-8 encoding. re2d assumes the character range is0โ0x10FFFFand character size is 1 byte ๐. The classic, the icon, the default-adjacent choice.--utf16,--utf-16,-xโ generates a lexer that reads UTF16-encoded input. re2d assumes the character range is0โ0x10FFFFand character size is 2 bytes. This option implies--nested-ifsโ ๏ธ. Sixteen bits of pure vibes.--utf32,--unicode,-uโ generates a lexer that reads UTF32-encoded input. re2d assumes the character range is0โ0x10FFFFand character size is 4 bytes. This option implies--nested-ifsโ ๏ธ. Maximum character budget, slay ๐.--verboseโ outputs a short message in case of success โ . A little "you did it bestie" moment in the terminal.--vernum,-Vโ shows version information inMMmmppformat (major, minor, patch) ๐ข. Cute and numeric.--version,-vโ shows version information. That's it, that's the tweet ๐ .--single-pass,-1โ deprecated. Does nothing (single pass is the default now) ๐. She's literally just here for nostalgia.--debug-output,-dโ emitsYYDEBUGinvocations in the generated code. Super useful for tracing lexer execution ๐. Debug bestie mode activated.--dump-adfaโ debug option: outputs the DFA after tunneling (in.dotformat) ๐ฌ. For when you wanna see the tunnels, iykyk.--dump-cfgโ debug option: outputs the control flow graph of tag variables (in.dotformat) ๐ธ๏ธ. Flowchart realness.--dump-closure-statsโ debug option: outputs statistics on the number of states in closure ๐. Numbers bestie, numbers.--dump-dfa-detโ debug option: outputs the DFA immediately after determinization (in.dotformat) โก. Fresh-out-the-oven DFA, no cap.--dump-dfa-minโ debug option: outputs the DFA after minimization (in.dotformat) ๐. Smaller, cleaner, still iconic.--dump-dfa-tagoptโ debug option: outputs the DFA after tag optimizations (in.dotformat) ๐ท๏ธโจ. Tag-optimized and thriving.--dump-dfa-treeโ debug option: outputs the DFA under construction with states represented as tag history trees (in.dotformat) ๐ณ. Tree structure, tree drama, tree everything.--dump-dfa-rawโ debug option: outputs the DFA under construction with expanded state-sets (in.dotformat) ๐จ. Raw, unfiltered, expanded.--dump-interfโ debug option: outputs the interference table produced by liveness analysis of tag variables ๐. Table-core.--dump-nfaโ debug option: outputs the NFA (in.dotformat) ๐ธ. The NFA before the DFA glow-up, we love an origin story.--emit-dot,-Dโ instead of normal output, generates the lexer graph in.dotformat ๐บ๏ธ. The output can be converted to an image with the help of Graphviz โ something likedot -Tpng -odfa.png dfa.dot. Art direction, honestly ๐จ.--dfa-minimization <moore | table>โ internal option: the DFA minimization algorithm used by re2d ๐ง. Themooreoption is the Moore algorithm (and it's the default). Thetableoption is the "table filling" algorithm. Both algorithms should produce the same DFA up to states relabeling;tablefilling is simpler and much slower and serves as a reference implementation ๐ข. Slow but trustworthy, we respect her.--eager-skipโ internal option: makes the generated lexer advance the input position eagerly โ immediately after reading the input symbol โฉ. This changes the default behavior, where the input position is advanced lazily โ after transition to the next state. Eager vs lazy, the eternal mood war.--no-lookaheadโ internal option, deprecated ๐. It used to enable the TDFA(0) algorithm. Unlike TDFA(1), the TDFA(0) algorithm doesn't use one-symbol lookahead. It applies register operations to the incoming transitions rather than the outgoing ones. Benchmarks showed that TDFA(0) is less efficient than TDFA(1). So yeah, she's retired for a reason bestie.--no-optimize-tagsโ internal option: suppresses optimization of tag variables (useful for debugging) ๐. Sometimes you gotta turn off the optimization to see what's really going on.--posix-closure <gor1 | gtop>โ internal option: specifies the shortest-path algorithm used for constructing epsilon-closure with POSIX disambiguation semantics ๐.gor1(the default) stands for the Goldberg-Radzik algorithm, andgtopstands for "global topological order." Two algorithms, one goal. Pick your fighter.--posix-prectable <complex | naive>โ internal option: specifies the algorithm used to compute the POSIX precedence table ๐. Thecomplexalgorithm computes the precedence table in one traversal of the tag history tree and has quadratic complexity in the number of TNFA states โ and it's the default. Thenaivealgorithm has worst-case cubic complexity in the number of TNFA states, but it's much simpler thancomplexand may be slightly faster in non-pathological cases. Complex is default, naive is the underdog, both valid ๐.--stadfaโ internal option, deprecated ๐. It used to enable the staDFA algorithm, which differs from TDFA in that register operations are placed in states rather than on transitions. Benchmarks showed staDFA is less efficient than TDFA. Another retired queen, we remember her.--fixed-tags <none | toplevel | all>โ internal option: specifies 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 isallโจ. "Fixed" tags are the ones located within a fixed distance to some other tag (called "base"). In those cases, only the base tag needs to be tracked, and the value of the fixed tag can be computed as the base tag's value plus a static offset ๐ฏ. For tags under alternative or repetition, you also need to check if the base tag has a no-match value โ if so, the fixed tag should also be set to no-match, disregarding the offset. For tags in top-level concatenation the check isn't needed, because they always match. Big brain optimization, no cap ๐ง .
โ ๏ธ Warnings โ ๏ธ
Warnings can be individually enabled, disabled, and even turned into an error ๐ฑ. Choose your own adventure, bestie.
-Wโ turns on all the warnings ๐จ. Every single one. Maximum awareness mode.-Werrorโ turns warnings into errors ๐. Note: 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. So it's like a multiplier, not a summoner. Very important distinction, don't get it twisted.-W<warning>โ turns on that specific warning ๐ก. Targeted, precise, iconic.-Wno-<warning>โ turns off that specific warning ๐. Sometimes you just need peace and quiet, and that's valid.-Werror-<warning>โ turns that warning on and promotes it to a full-on error, bestie. This implies-W<warning>too, so you don't need both. ๐-Wno-error-<warning>โ okay so this one demotes a specific warning back down so it's not an error anymore. Careful though: it does not turn the warning itself off. It still yells at you, just less dramatically. ๐-Wcondition-orderโ screams if your generated program is out here making implicit assumptions about condition numbering. Rude. The fix: use the--headeroption or aconditionsblock to generate a mapping of condition names to numbers, then use the autogenerated condition names. Slay responsibly. โจ-Wempty-character-classโ warns you when a regular expression contains an empty character class. Like, trying to match an empty character class literally makes no sense โ it should always fail. But for backwards compatibility reasonsre2dpermits empty character classes and treats them as empty strings. Use the--empty-classoption to change the default behavior. ๐ซถ-Wmatch-empty-stringโ warns if a rule is nullable (i.e. it matches an empty string). Bestie, if the lexer runs in a loop and that empty match was not intentional, your lexer may unexpectedly hang in an infinite loop. Not the vibe. ๐-Wswapped-rangeโ warns if the lower bound of a range is greater than its upper bound. Default behavior? Silently swap the range bounds. Iconic chaos, honestly. ๐ฅ-Wundefined-control-flowโ warns if some input strings cause undefined control flow in the lexer (and it reports the faulty patterns). This is a dangerous and common mistake, ngl. It's easily fixed by adding the default rule*, which has the lowest priority, matches any code unit, and always consumes a single code unit. ๐-Wunreachable-rulesโ warns about rules that are shadowed by other rules and will never match. Living in someone else's shadow, tragic. ๐ญ-Wdeprecated-eof_ruleโ warns about standalone end of input rules$that will be broken by future changes and require fixing. At the moment these rules take precedence when conflicting with other rules, but after the introduction of the generalized end of input symbol$, precedence order will change and these rules will become shadowed by other rules. So like, fix them now fr fr.-Wuseless-escapeโ warns if a symbol is escaped when it shouldn't be. By defaultre2dsilently ignores such escapes, but this may as well indicate a typo or an error in the escape sequence. ๐-Wnondeterministic-tagsโ warns if a tag has n-th degree of nondeterminism, where n is greater than 1. That's a lot of degrees, bestie. ๐-Wsentinel-in-midruleโ warns if the sentinel symbol occurs in the middle of a rule โ which may cause reads past the end of buffer, crashes or memory corruption in the generated lexer. Yikes. This warning is only applicable if the sentinel method of checking for the end of input is used. It is set to an error ifre2c:sentinelconfiguration is used. ๐-Wundefined-syntax-configโ warns if the syntax file specified with--syntaxoption is missing definitions of some configurations. So helpful honestly โ it helps maintain user-defined syntax files: if a new release adds configurations, an old syntax file will raise a warning and the user gets notified. And if some configurations are unused and don't need a definition, they should be explicitly set to<undefined>. ๐ธ
โจ Syntax files โจ
So the support for different languages in re2c is based on the idea of syntax files. A syntax file is a configuration file that defines the syntax of the target language โ not the whole language, just a small part of it that's used by the generated code. Syntax files make re2c super flexible, but bestie, they should not be used as a replacement for re2c: configurations โ their purpose is to define syntax of the target language, not to customize one particular lexer. ๐ฆ
All supported languages have default syntax files that are part of the distribution (see include/syntax subdirectory); they're also embedded in the re2d binary. Users may provide a custom syntax file that overrides a few configurations for one of the supported languages, or they may choose to redefine all configurations (in that case the --lang none option should be used). Syntax files contain configurations of four different kinds: feature lists, language configurations, inplace configurations and code templates.
๐ Feature lists
A few list configurations define various features supported by a given backend, so that re2d may give a clear error if the user tries to enable an unsupported feature:
supported_apisโ a list of supported APIs with possible elementssimple,record,generic.supported_api_stylesโ a list of supported API styles with possible elementsfunctions,free-form.supported_code_modelsโ a list of supported code models with possible elementsgoto-label,loop-switch,recursive-functions.supported_targetsโ a list of supported codegen targets with possible elementscode,dot,skeleton.supported_featuresโ a list of supported features with possible elementsnested-ifs,bitmaps,computed-gotos,case-ranges,monadic,unsafe,tags,captures,captvars,computed-continue.
๐ Language configurations
A few boolean configurations describe features of the target language that affect the re2d parser and code generator:
semicolonsโ non-zero if the language uses semicolons after statements.backtick_quoted_stringsโ non-zero if the language has backtick-quoted strings.single_quoted_stringsโ non-zero if the language has single-quoted strings.indentation_sensitiveโ non-zero if the language is indentation sensitive.wrap_blocks_in_bracesโ non-zero if compound statements must be wrapped in curly braces.
๐ Inplace configurations
Syntax files define initial values of all re2c: configurations, as they may differ for different languages. See the configurations section for a full list of all inplace configurations and their meaning.
๐ Code templates
Code templates define the syntax of the target language. They're written in a simple domain-specific language with the following formal grammar:
code-template ::
name '=' code-exprs ';'
| CODE_TEMPLATE ';'
| '<undefined>' ';'
code-exprs ::
<EMPTY>
| code-exprs code-expr
code-expr ::
STRING
| VARIABLE
| optional
| list
optional ::
'(' CONDITIONAL '?' code-exprs ')'
| '(' CONDITIONAL '?' code-exprs ':' code-exprs ')'
list ::
'[' VARIABLE ':' code-exprs ']'
| '[' VARIABLE '{' NUMBER '}' ':' code-exprs ']'
| '[' VARIABLE '{' NUMBER ',' NUMBER '}' ':' code-exprs ']'
A code template is a sequence of string literals, variables, optional elements and lists, or a reference to another code template, or a special value <undefined>. Variables are placeholders that are substituted during the code generation phase. List variables are special: when expanding list templates, re2d repeats expressions on the right hand side of the column a few times, each time replacing occurrences of the list variable with a value specific to this repetition. Lists have optional bounds (negative values are counted from the end, e.g. -1 means the last element). Conditional names start with a dot. Both conditionals and variables may be either local (specific to the given code template) or global (allowed in all code templates). When re2d reads a syntax file, it checks that each code template uses only the variables and conditionals that are allowed in it. โจ
For example, the following code template defines an if-then-else construct for a C-like language:
code:if_then_else =
[branch{0}: topindent "if " cond " {" nl
indent [stmt: stmt] dedent]
[branch{1:-1}: topindent "} else" (.cond ? " if " cond) " {" nl
indent [stmt: stmt] dedent]
topindent "}" nl;
Here branch is a list variable: branch{0} expands to the first branch (which is special, as there is no else part), branch{1:-1} expands to all remaining branches (if any). stmt is also a list variable: [stmt: stmt] is a nested list that expands to a list of statements in the body of the current branch. topindent, indent, dedent and nl are global variables, and .cond is a local conditional (their meaning is described below). This code template could produce the following code:
if x {
// do something
} else if y {
// do something else
} else {
// don't do anything
}
Here's a list of all code templates supported by re2d with their local variables and conditionals. Note that a particular definition may, but does not have to, use local variables and conditionals. Any unused code templates should be set to <undefined>. ๐
code:var_localโ declaration or definition of a local variable. Supported variables:type(the type of the variable),name(its name) andinit(initial value, if any). Conditionals:.init(true if there is an initializer).code:var_globalโ same ascode:var_local, except that it's used in top-level.code:const_localโ definition of a local constant. Supported variables:type(the type of the constant),name(its name) andinit(initial value).code:const_globalโ same ascode:const_local, except that it's used in top-level.code:array_localโ definition of a local array (table). Supported variables:type(the type of array elements),name(array name),size(its size),row(a list variable that does not itself produce any code, but expands the list expression as many times as there are rows in the table) andelem(a list variable that expands to all table elements in the current row โ it's meant to be nested in therowlist). Supported conditional:.const(true if the array is immutable).code:array_globalโ same ascode:array_local, except that it's used in top-level.code:array_elemโ reference to an element of an array (table). Supported variables:array(the name of the array) andindex(index of the element).code:enumโ the definition of an enumeration, bestie โจ it can be defined using a special language construct for enumerations, or simply as a few standalone constants. Supported variables aretype(user-defined enumeration type or type of the constants),elem(list variable that expands to the name of each member) andinit(initializer for each member). Conditionals:.init(true if there is an initializer).code:enum_elemโ one enumeration element ๐ thatโs a member of a user-defined enumeration type or a name of a constant, depending on howcode:enumis defined. Supported variables arename(the name of the element) andtype(its type).code:assignโ assignment statement. Supported variables arelhs(left hand side) andrhs(right hand side).code:type_intโ signed integer type.code:type_uintโ unsigned integer type.code:type_yybmโ type of elements in theyybmtable.code:type_yytargetโ type of elements in theyytargettable.code:type_yyctableโ type of elements in theyyctabletable.code:cmp_eqโ operator"equals".code:cmp_neโ operator"not equals".code:cmp_ltโ operator"less than".code:cmp_gtโ operator"greater than".code:cmp_leโ operator"less or equal".code:cmp_geโ operator"greater or equal".code:if_then_elseโ if-then-else statement with one or more branches ๐ฆ supported variables:branch(a list variable that does not itself produce any code, but expands list expression as many times as there are branches),cond(condition of the current branch) andstmt(a list variable that expands to all statements in the current branch). Conditionals:.cond(true if the current branch has a condition),.many(true if thereโs more than one branch).code:if_then_else_onelineโ a specialization ofcode:if_then_elsefor the case when all branches have one-line statements. If this is<undefined>,code:if_then_elseis used instead.code:switchโ a switch statement with one or more cases. Supported variables:expr(the switched-on expression) andcase(a list variable that expands to all cases-groups with their code blocks).code:switch_casesโ a group of switch cases that maps to a single code block. Supported variables arecase(a list variable that expands to all cases in this group) andstmt(a list variable that expands to all statements in the code block).code:switch_cases_onelineโ a specialization ofcode:switch_casesfor the case when the code block consists of a single one-line statement. If this is<undefined>,code:switch_casesis used instead.code:switch_case_rangeโ a single switch case that covers a range of values (possibly consisting of a single value). Supported variable:val(a list variable that expands to all values in the range). Supported conditionals:.many(true if thereโs more than one value in the range) and.char_literals(true if this is a switch on character literals -- some languages provide special syntax for this case).code:switch_case_defaultโ default switch case.code:loopโ a loop that runs forever (unless interrupted from the loop body) ๐ supported variables:label(loop label),val(initial state),var(state variable),state(a list variable that expands to all state names) andstmt(a list variable that expands to all statements in the loop body or the current state).code:continueโ continue statement. Supported variables:label(label from which to continue execution),val(value passed to a labeled switch) andvar(state variable).code:gotoโ goto statement. Supported variables:label(label of the jump target).code:cgotoโ computed goto statement. Supported variables:array(the table containing computed goto information),index(index of the element in the table) andbase(base label, only used if.cgoto.relativeis true).code:cgoto:dataโ initializer expression for a single element in computed goto table. Supported variables:label(the label that is used to initialize the current element),type(underlying type of the elements in the table) andbase(base label - only used if.cgoto.relativeis true).code:fndeclโ function declaration. Supported variables:name(function name),type(return type),throw(exceptions thrown by this function, maps tore2c:yyfn:throwconfiguration),arg(a list variable that does not itself produce code, but expands list expression as many times as there are function arguments),argname(name of the current argument),argtype(type of the current argument). Conditional:.type(true if this is a non-void function).code:fndefโ likecode:fndecl, but used for function definitions, so it has one additional list variablestmtthat expands to all statements in the function body.code:fncallโ function call statement. Supported variables:name(function name),retval(l-value where the return value is stored, if any) andarg(a list variable that expands to all function arguments). Conditionals:.args(true if the function has arguments) and.retval(true if return value needs to be saved).code:tailcallโ tail call statement. Supported variables:name(function name), andarg(a list variable that expands to all function arguments). Conditionals:.args(true if the function has arguments) and.retval(true if this is a non-void function).code:recursive_functionsโ program body with--recursive-functionscode model. Supported variables:fn(a list variable that does not itself produce any code, but expands list expression as many times as there are functions),fndecl(declaration of the current function) andfndef(definition of the current function).code:fingerprintโ the fingerprint at the top of the generated output file ๐ supported variables:ver(re2dversion that was used to generate this) anddate(generation date).code:line_infoโ the format of line directives (if this is set to<undefined>, no directives are generated). Supported variables:line(line number) andfile(filename).code:abortโ a statement that aborts program execution.code:yydebugโYYDEBUGstatement, possibly specialized for different APIs. Supported variables:YYDEBUG,yyrecord,yych(map to the correspondingre2c:configurations),state(DFA state number).code:yypeekโYYPEEKstatement, possibly specialized for different APIs. Supported variables:YYPEEK,YYCTYPE,YYINPUT,YYCURSOR,yyrecord,yych(map to the correspondingre2c:configurations). Conditionals:.cast(true ifre2c:yych:conversionis set to non-zero).code:yyskipโYYSKIPstatement, possibly specialized for different APIs. Supported variables:YYSKIP,YYCURSOR,yyrecord(map to the correspondingre2c:configurations).code:yybackupโYYBACKUPstatement, possibly specialized for different APIs. Supported variables:YYBACKUP,YYCURSOR,YYMARKER,yyrecord(map to the correspondingre2c:configurations).code:yybackupctxโYYBACKUPCTXstatement, possibly specialized for different APIs. Supported variables:YYBACKUPCTX,YYCURSOR,YYCTXMARKER,yyrecord(map to the correspondingre2c:configurations).code:yyskip_yypeekโ combinedcode:yyskipandcode:yypeekstatement (defaults tocode:yyskipfollowed bycode:yypeek).code:yypeek_yyskipโ combinedcode:yypeekandcode:yyskipstatement (defaults tocode:yypeekfollowed bycode:yyskip).code:yyskip_yybackupโ combinedcode:yyskipandcode:yybackupstatement (defaults tocode:yyskipfollowed bycode:yybackup).code:yybackup_yyskipโ combinedcode:yybackupandcode:yyskipstatement (defaults tocode:yybackupfollowed bycode:yyskip).code:yybackup_yypeekโ combinedcode:yybackupandcode:yypeekstatement (defaults tocode:yybackupfollowed bycode:yypeek).code:yyskip_yybackup_yypeekโ combinedcode:yyskip,code:yybackupandcode:yypeekstatement (defaults tocode:yyskipfollowed bycode:yybackupfollowed bycode:yypeek).code:yybackup_yypeek_yyskipโ combinedcode:yybackup,code:yypeekandcode:yyskipstatement (defaults tocode:yybackupfollowed bycode:yypeekfollowed bycode:yyskip).code:yyrestoreโYYRESTOREstatement, possibly specialized for different APIs. Supported variables:YYRESTORE,YYCURSOR,YYMARKER,yyrecord(map to the correspondingre2c:configurations).code:yyrestorectxโYYRESTORECTXstatement, possibly specialized for different APIs. Supported variables:YYRESTORECTX,YYCURSOR,YYCTXMARKER,yyrecord(map to the correspondingre2c:configurations).code:yyrestoretagโYYRESTORETAGstatement, possibly specialized for different APIs. Supported variables:YYRESTORETAG,YYCURSOR,yyrecord(map to the correspondingre2c:configurations),tag(the name of tag variable used to restore position).code:yyshiftโYYSHIFTstatement, possibly specialized for different APIs. Supported variables:YYSHIFT,YYCURSOR,yyrecord(map to the correspondingre2c:configurations),offset(the number of code units to shift the current position).code:yyshiftstagโ theYYSHIFTSTAGstatement, and yes it can be specialized for different APIs. Supported variables:YYSHIFTSTAG,yyrecord,negative(map to the correspondingre2c:configurations),tag(the tag variable that needs to be shifted), andoffset(the number of code units to shift). Conditionals:.nested(true if this is a nested tag โ in this case its value may equal tore2c:tags:negative, which should not be shifted).code:yyshiftmtagโ theYYSHIFTMTAGstatement, possibly specialized for different APIs. Supported variables:YYSHIFTMTAG(maps to the correspondingre2c:configuration),tag(the tag variable that needs to be shifted), andoffset(the number of code units to shift).code:yystagpโ theYYSTAGPstatement, possibly specialized for different APIs. Supported variables:YYSTAGP,YYCURSOR,yyrecord(map to the correspondingre2c:configurations), andtag(the tag variable that should be updated).code:yymtagpโ theYYMTAGPstatement, possibly specialized for different APIs. Supported variables:YYMTAGP(maps to the correspondingre2c:configuration) andtag(the tag variable that should be updated).code:yystagnโ theYYSTAGNstatement, possibly specialized for different APIs. Supported variables:YYSTAGN,negative,yyrecord(map to the correspondingre2c:configurations), andtag(the tag variable that should be updated).code:yymtagnโ theYYMTAGNstatement, possibly specialized for different APIs. Supported variables:YYMTAGN(maps to the correspondingre2c:configuration) andtag(the tag variable that should be updated).code:yycopystagโ theYYCOPYSTAGstatement, possibly specialized for different APIs. Supported variables:YYCOPYSTAG,yyrecord(map to the correspondingre2c:configurations),lhs, andrhs(left and right hand side tag variables of the copy operation).code:yycopymtagโ theYYCOPYMTAGstatement, possibly specialized for different APIs. Supported variables:YYCOPYMTAG,yyrecord(map to the correspondingre2c:configurations),lhs, andrhs(left and right hand side tag variables of the copy operation).code:yygetacceptโ theYYGETACCEPTstatement, possibly specialized for different APIs. Supported variables:YYGETACCEPT,yyrecord(map to the correspondingre2c:configurations), andvar(maps to there2c:yyacceptconfiguration).code:yysetacceptโ theYYSETACCEPTstatement, possibly specialized for different APIs. Supported variables:YYSETACCEPT,yyrecord(map to the correspondingre2c:configurations),var(maps to there2c:yyacceptconfiguration), andval(numeric value of the accepted rule).code:yygetcondโ theYYGETCONDstatement, possibly specialized for different APIs. Supported variables:YYGETCOND,yyrecord(map to the correspondingre2c:configurations), andvar(maps to there2c:yycondconfiguration).code:yysetcondโ theYYSETCONDstatement, possibly specialized for different APIs. Supported variables:YYSETCOND,yyrecord(map to the correspondingre2c:configurations),var(maps to there2c:yycondconfiguration), andval(numeric condition identifier).code:yygetstateโ theYYGETSTATEstatement, possibly specialized for different APIs. Supported variables:YYGETSTATE,yyrecord(map to the correspondingre2c:configurations), andvar(maps to there2c:yystateconfiguration).code:yysetstateโ theYYSETSTATEstatement, possibly specialized for different APIs. Supported variables:YYSETSTATE,yyrecord(map to the correspondingre2c:configurations),var(maps to there2c:yystateconfiguration), andval(state number).code:yylessthanโ theYYLESSTHANstatement, possibly specialized for different APIs. Supported variables:YYLESSTHAN,YYCURSOR,YYLIMIT,yyrecord(map to the correspondingre2c:configurations), andneed(the number of code units to check against). Conditional:.many(true if theneedis more than one).code:yyendโ theYYENDexpression, possibly specialized for different APIs. Supported variables:YYEND,YYCURSOR, andYYLIMIT.code:yybm_filterโ the condition that is used to filter outyychvalues that are not covered by theyybmtable (used with--bitmapsoption). Supported variable:yych(maps to there2c:yychconfiguration).code:yybm_matchโ the format of theyybmtable check (generated with--bitmapsoption). Supported variables:yybm,yych(map to the correspondingre2c:configurations),offset(offset in theyybmtable that needs to be added toyych), andmask(bit mask that should be applied to the table entry to retrieve the boolean value that needs to be checked).code:yytarget_filterโ the condition that is used to filter outyychvalues that are not covered by theyytargettable (used with--computed-gotosoption). Supported variable:yych(maps to there2c:yychconfiguration).
Okay bestie, here's the full list of global variables that are allowed in syntax files:
nlโ a newline.indentโ a variable that does not produce any code, but has a side-effect of increasing indentation level.dedentโ a variable that does not produce any code, but has a side-effect of decreasing indentation level.topindentโ indentation string for the current statement. Indentation level is tracked and automatically updated by the code generator.
And here's the full list of global conditionals that are allowed in syntax files:
.api.simpleโ true if the simple API is used (--api simpleorre2c:api = simple)..api.genericโ true if the generic API is used (--api genericorre2c:api = generic)..api.recordโ true if the record API is used (--api recordorre2c:api = record)..api_style.functionsโ true if the function-like API style is used (re2c:api-style = functions)..api_style.freeformโ true if the free-form API style is used (re2c:api-style = free-form)..case_rangesโ true if the case ranges feature is enabled (--case-rangesorre2c:case-ranges = 1)..cgoto.relativeโ true if the relative form of computed goto is used (--computed-gotos-relativeorre2c:cgoto:relative = 1)..computed_continueโ true if the loop/switch model uses labeled-switch transitions (--computed-continue)..code_model.goto_labelโ true if the code model based on goto/label is used (--goto-label)..code_model.loop_switchโ true if the code model based on loop/switch is used (--loop-switch)..code_model.recursive_functionsโ true if the code model based on recursive functions is used (--recursive-function)..dateโ true if the generated fingerprint should contain the generation date..loop_labelโ true ifre2dgenerated loops must have a label (re2c:label:yyloopis set to a nonempty string)..monadicโ true if the generated code should be monadic (re2c:monadic = 1). This is only relevant for pure functional languages..start_conditionsโ true if start conditions are enabled (--start-conditions)..storable_stateโ true if storable state is enabled (--storable-state)..unsafeโ true ifre2dshould use "unsafe" blocks in order to generate faster code (--unsafe,re2c:unsafe = 1). This is only relevant for languages that have the "unsafe" feature..versionโ true if the generated fingerprint should contain there2dversion..yyfill.enableโ true ifYYFILLis enabled (re2c:yyfill:enable = 1)..yyfn.throwโ true if there2c:yyfn:throwconfiguration is defined to a nonempty string.
๐ HANDLING THE END OF INPUT ๐
One of the main problems for the lexer is knowing 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. re2d supports a few different methods for handling the end of input. Which one to use depends on the complexity of regular expressions, the need for buffering, performance considerations and other factors. Here is a list of methods:
- Sentinel. 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 should not be allowed by the regular expressions, except perhaps as the last character of a rule. The sentinel is appended at the end of input and serves as a stop signal: when the lexer reads this character, it is either a syntax error or the end of input. In both cases the lexer should stop. This method is used if
YYFILLis disabled withre2c:yyfill:enable = 0; andre2c:eofhas the default value-1. - Sentinel with bounds checks โ okay so this one is generic in the best way: it lets you handle any input with zero restrictions on your regexes ๐
The whole idea is to cut down on end-of-input checks by only doing them on certain characters. Same energy as the plain "sentinel" method โ you pick one character as the "sentinel" and slap it at the end of the input โ except there's no restriction on where the sentinel can show up (fr, literally any character can be your sentinel). When the lexer reads that character, it also does a bounds check. If the current position is still within bounds, the lexer just keeps matching and treats the sentinel like a normal character. If it's out of bounds, it invokes
YYFILL(unless that's disabled). If more input gets supplied, the lexer rematches that last character and carries on like the sentinel was never there. Otherwise it's the real end of input and the lexer stops. This method kicks in whenre2c:eofhas a non-negative value (set it to the numeric value of your sentinel).YYFILLis optional. โจ - Bounds checks with padding โ this one is generic too, and it can be faster than "sentinel with bounds checks", but it's also more complex (highkey a little extra ๐
). The idea: partition the DFA states into strongly connected components (SCCs) and generate a single check per SCC for enough characters to cover the longest non-looping path in that SCC. Fewer checks, slay โ but there's a catch with short lexemes at the end of input, because the check needs enough characters to cover the longest lexeme. Fix: pad the input with a few fake characters that don't form a valid lexeme suffix (so the lexer literally cannot match them). The padding length should be
YYMAXFILL, generated with a max block. If there isn't enough input, the lexer invokesYYFILL, which should supply at least the required number of characters or not return. This method is used ifYYFILLis enabled andre2c:eofis-1(that's the default config, btw ๐). - Custom checks โ the generic API lets you override basic operations like reading a character, which means you can fold the end-of-input checks right into them. Cute, but โ ๏ธ this approach is error-prone and should be used with caution. To use a custom method, enable the generic API with
--api customorre2c:api = custom;and disable the default bounds checks withre2c:yyfill:enable = 0;orre2c:yyfill:check = 0;.
The following subsections contain an example of each method. Let's gooo ๐ฆ
๐ธ Sentinel
This example uses a sentinel character to handle the end of input. The program counts space-separated words in a null-terminated string. The sentinel is null: it's the last character of each input string, and none of the rules allow it in the middle of a lexeme (in particular, it's not included in character ranges where it'd be easy to overlook ๐). If a null shows up in the middle of a string, that's a syntax error and the lexer will match the default rule *, but it won't read past the end of input or crash (use the -Wsentinel-in-midrule warning and the re2c:sentinel configuration to verify this). The configuration re2c:yyfill:enable = 0; suppresses the generation of bounds checks and YYFILL invocations. ๐ซถ
// re2d $INPUT -o $OUTPUT
module main;
// Expect a null-terminated string.
private int lex(const(char)* yycursor) {
uint count = 0;
for (;;) {
/*!re2c
re2c:YYCTYPE = char;
re2c:yyfill:enable = 0;
* { return -1; }
[\x00] { return count; }
[a-z]+ { ++count; continue; }
[ ]+ { continue; }
*/
}
assert(0); // unreachable
}
void main() {
assert(lex("") == 0);
assert(lex("one two three") == 3);
assert(lex("f0ur") == -1);
}
๐ Sentinel with bounds checks
This example uses sentinel with bounds checks to handle the end of input (this method was added in version 1.2, ok history icon ๐). The program counts space-separated single-quoted strings. The sentinel character is null, specified with the re2c:eof = 0; configuration. Just like in the sentinel method, null is the last character of each input string โ but here it's allowed in the middle of a rule (for example, 'aaa\0aa'\0 is valid input, but 'aaa\0 is a syntax error ๐ญ). Bounds checks are generated in each state that matches an input character, but they're scoped to the branch that handles null. Checks look like YYLIMIT <= YYCURSOR or YYLESSTHAN(1) with the generic API. If the check condition is true, the lexer has hit the end of input and should stop (YYFILL is disabled with re2c:yyfill:enable = 0; because the input fits into one buffer โ see the YYFILL with sentinel section for an example that actually uses YYFILL). Reaching the end of input opens three possibilities: if the lexer is in the initial state it'll match the end-of-input rule $, otherwise it may fallback to a previously matched rule (including default rule *) or go to a default state, which causes -Wundefined-control-flow. ๐
// re2d $INPUT -o $OUTPUT
module main;
// Expect a null-terminated string.
private int lex(immutable char[] s) {
const(char)* yycursor = s.ptr, yylimit = s.ptr + s.length, yymarker;
int count = 0;
for (;;) {
/*!re2c
re2c:YYCTYPE = char;
re2c:yyfill:enable = 0;
re2c:eof = 0;
str = ['] ([^'\\] | [\\][^])* ['];
* { return -1; }
$ { return count; }
str { ++count; continue; }
[ ]+ { continue; }
*/
}
assert(0); // unreachable
}
void main() {
assert(lex("") == 0);
assert(lex("'qu\0tes' 'are' 'fine: \\'' ") == 3);
assert(lex("'unterminated\\'") == -1);
}
๐ Bounds checks with padding
This example uses bounds checks with padding to handle the end of input (this method is enabled by default, bestie โ it's the one you get for free โจ). The program counts space-separated single-quoted strings. There's a padding of YYMAXFILL null characters appended at the end of input, where the YYMAXFILL value is autogenerated with a max block. You don't have to use null for padding โ any characters work as long as they don't form a valid lexeme suffix (in this example, padding should not contain single quotes, since they might get mistaken for a suffix of a single-quoted string ๐). There's a "stop" rule that matches the first padding character (null) and terminates the lexer (note that it checks whether null is at the beginning of the padding โ otherwise it's a syntax error ๐). Bounds checks are generated only in some states, determined by the strongly connected components of the underlying automaton. Checks have the form (YYLIMIT - YYCURSOR) < n or YYLESSTHAN(n) with the generic API, where n is the minimum number of characters needed for the lexer to proceed (which also means the next bounds check will happen in at most n characters). If the check condition is true, the lexer has reached the end of input and will invoke YYFILL(n), which should either supply at least n input characters or not return. In this example YYFILL always fails and terminates the lexer with an error (totally fine, since the input fits into one buffer). See the YYFILL with padding section for an example that actually refills the input buffer with YYFILL. ๐ฅ
// re2d $INPUT -o $OUTPUT
module main;
import core.stdc.stdlib;
import core.stdc.string;
/*!max:re2c*/
private int lex(immutable char[] s) {
// Make a copy of the string with YYMAXFILL zeroes at the end.
char *buf = cast(char*) malloc(s.length + YYMaxFill);
memcpy(buf, cast(const(void*)) s, s.length);
memset(buf + s.length, 0, YYMaxFill);
const(char)* yycursor = buf;
const(char)* yylimit = buf + s.length + YYMaxFill;
int count = 0;
loop:
/*!re2c
re2c:YYCTYPE = char;
re2c:YYFILL = "goto fail;";
str = ['] ([^'\\] | [\\][^])* ['];
[\x00] {
// Check that it is the sentinel, not some unexpected null.
if (yycursor - 1 == buf + s.length) goto exit; else goto fail;
}
str { ++count; goto loop; }
[ ]+ { goto loop; }
* { goto fail; }
*/
fail:
count = -1;
exit:
free(buf);
return count;
}
void main() {
assert(lex("") == 0);
assert(lex("'qu\0tes' 'are' 'fine: \\'' ") == 3);
assert(lex("'unterminated\\'") == -1);
assert(lex("'unexpected \0 null\\'") == -1);
}
๐ฆ Custom checks
This example uses a custom end-of-input handling method based on the generic API. The program counts space-separated single-quoted strings. It's the same as the sentinel example, except the input is not null-terminated. To cover for the missing sentinel character at the end of input, YYPEEK is redefined to do a bounds check before it reads the next input character. Ngl this is inefficient, because those checks happen very often ๐ญ. If the check condition fails, YYPEEK returns the real character; otherwise it returns a fake sentinel character. ๐ง
// re2d $INPUT -o $OUTPUT
module main;
import core.stdc.stdlib;
import core.stdc.string;
private int lex(immutable char[] s) {
// For the sake of example create a string without terminating null.
char *buf = cast(char*) malloc(s.length);
memcpy(buf, cast(const(void*)) s, s.length);
const(char) *cur = buf, lim = buf + s.length;
int count = 0;
for (;;) {
/*!re2c
re2c:api = generic;
re2c:yyfill:enable = 0;
re2c:YYCTYPE = char;
re2c:YYPEEK = "cur < lim ? *cur : 0"; // fake null
re2c:YYSKIP = "++cur;";
* { count = -1; break; }
[\x00] { break;{} }
[a-z]+ { ++count; continue;{} }
[ ]+ { continue; }
*/
}
free(buf);
return count;
}
void main() {
assert(lex("") == 0);
assert(lex("one two three ") == 3);
assert(lex("f0ur") == -1);
}
๐พ BUFFER REFILLING ๐พ
okay so bestie, buffering is the whole thing when the input can't just be mapped in memory all at once โ either it's too large, or it comes in a streaming fashion (like reading from a socket, iykyk). The usual technique in these 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 gets moved out and new data gets moved in. In practice it's somewhat more complex, because lexer state isn't just one single input position โ it's a whole little friend group of interrelated positions:
cursorโ the next input character to be read (YYCURSORin the C pointer API orYYSKIP/YYPEEKin the generic API).limitโ the position after the last available input character (YYLIMITin the C pointer API, implicitly handled byYYLESSTHANin the generic API).markerโ the position of the most recent match, if any (YYMARKERin the default API orYYBACKUP/YYRESTOREin the generic API).tokenโ the start of the current lexeme (implicit in the re2d API, since it's not needed for the normal lexer operation and can be defined and updated by the user).context markerโ the position of the trailing context (YYCTXMARKERin the C pointer API orYYBACKUPCTX/YYRESTORECTXin the generic API).tag variablesโ submatch positions (defined withstagsandmtagsblocks and the generic API primitivesYYSTAGP/YYSTAGN/YYMTAGP/YYMTAGN).
Not all of these are used in every case, but if they are used, they must be updated by YYFILL. All active positions are contained in the segment between token and cursor, so everything between buffer start and token can be discarded, the segment from token up to limit should be moved to the beginning of the buffer, and the free space at the end of the buffer should be filled with new data. In order to avoid frequent YYFILL calls it's 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 the EOF rule is somewhat simpler than the case of bounds-checking with padding. Also note that if the -f --storable-state option is used, YYFILL has slightly different semantics (described in the section about storable state).
โจ YYFILL with sentinel โจ
If the 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 the condition YYLIMIT <= YYCURSOR in the C pointer API and YYLESSTHAN() in the generic API. A non-zero return value means that YYFILL has failed. A successful YYFILL call must supply at least one character and adjust the input positions accordingly. limit must always be set to one after the last input position in the buffer, and the character at the limit position must be the sentinel symbol specified by the re2c:eof configuration. The pictures below show the relative locations of input positions in the buffer before and after the YYFILL call (the sentinel symbol is marked with #, and the second picture shows the case when there isn't 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's an example of a program that reads the input file input.txt in chunks of 4096 bytes and uses the EOF rule.
// re2d $INPUT -o $OUTPUT
module main;
import core.stdc.string;
import core.stdc.stdio;
enum BUFSIZE = 4095;
struct Input {
FILE* file;
char[BUFSIZE + 1] buffer;// +1 for sentinel
char* yylimit, yycursor, yymarker, token;
bool eof;
};
private int fill(ref Input it) {
if (it.eof) return 1;
const size_t shift = it.token - it.buffer.ptr;
const size_t used = it.yylimit - it.token;
// Error: lexeme too long. In real life could reallocate a larger buffer.
if (shift < 1) return 2;
// Shift buffer contents (discard everything up to the current token).
memmove(cast(void*)it.buffer.ptr, it.token, used);
it.yylimit -= shift;
it.yycursor -= shift;
it.yymarker -= shift;
it.token -= shift;
// Fill free space at the end of buffer with new data from file.
it.yylimit += fread(it.yylimit, 1, BUFSIZE - used, it.file);
it.yylimit[0] = 0;
it.eof = it.yylimit < (it.buffer.ptr + BUFSIZE);
return 0;
}
private int lex(ref Input yyrecord) {
int count = 0;
for (;;) {
yyrecord.token = yyrecord.yycursor;
/*!re2c
re2c:api = record;
re2c:YYCTYPE = "char";
re2c:YYFILL = "fill(yyrecord) == 0";
re2c:eof = 0;
str = ['] ([^'\\] | [\\][^])* ['`;`? Wait I need to be exact. Let me correct: the original line is `str = ['] ([^'\\] | [\\][^])* ['`;`? No, I must use the exact line. Let me paste it correctly:
*/
}
assert(0);
}
void main() {
const char[] fname = "input";
const char[] content = "'qu\0tes' 'are' 'fine: \\'' ";
// Prepare input file: a few times the size of the buffer, containing
// strings with zeroes and escaped quotes.
FILE* f = fopen(fname.ptr, "w");
for (int i = 0; i < BUFSIZE; ++i) {
fwrite(cast(const(void*)) content.ptr, 1, content.length - 1, f);
}
fclose(f);
int count = 3 * BUFSIZE; // number of quoted strings written to file
// Initialize lexer state: all pointers are at the end of buffer.
Input it;
it.file = fopen(fname.ptr, "r");
it.yycursor = it.yymarker = it.token = it.yylimit = it.buffer.ptr + BUFSIZE;
it.eof = 0;
// Sentinel (at YYLIMIT pointer) is set to zero, which triggers YYFILL.
it.yylimit[0] = 0;
// Run the lexer.
assert(lex(it) == count);
// Cleanup: remove input file.
fclose(it.file);
remove(fname.ptr);
}
๐ง YYFILL with padding ๐ง
In the default case (when the 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 the condition (YYLIMIT - YYCURSOR) < n in the C pointer API and YYLESSTHAN(n) in the 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's 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 the buffer, or to the end of the 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 the buffer before and after the 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's an example of a program that reads the input file input.txt in chunks of 4096 bytes and uses bounds-checking with padding.
// re2d $INPUT -o $OUTPUT
module main;
import core.stdc.string;
import core.stdc.stdio;
/*!max:re2c*/
enum BufSize = (4096 - YYMaxFill);
struct Input {
FILE* file;
char[BufSize + YYMaxFill] buffer;
char* yylimit, yycursor, token;
bool eof;
};
private int fill(ref Input it, size_t need) {
if (it.eof) return 1;
const size_t shift = it.token - it.buffer.ptr;
const size_t used = it.yylimit - it.token;
// Error: lexeme too long. In real life could reallocate a larger buffer.
if (shift < need) return 2;
// Shift buffer contents (discard everything up to the current token).
memmove(it.buffer.ptr, it.token, used);
it.yylimit -= shift;
it.yycursor -= shift;
it.token -= shift;
// Fill free space at the end of buffer with new data from file.
it.yylimit += fread(it.yylimit, 1, BufSize - used, it.file);
// If read less than expected, this is end of input => add zero padding
// so that the lexer can access characters at the end of buffer.
if (it.yylimit < it.buffer.ptr + BufSize) {
it.eof = true;
memset(it.yylimit, 0, YYMaxFill);
it.yylimit += YYMaxFill;
}
return 0;
}
private int lex(ref Input yyrecord) {
int count = 0;
for (;;) {
yyrecord.token = yyrecord.yycursor;
/*!re2c
re2c:api = record;
re2c:YYCTYPE = "char";
re2c:YYFILL = "if (fill(yyrecord, @@) != 0) return -1;";
str = ['] ([^'\\] | [\\][^])* ['`;`? Again, exact line should be here. Let me write it properly:
*/
}
assert(0);
}
void main() {
const char[] fname = "input";
const char[] content = "'qu\0tes' 'are' 'fine: \\'' ";
// Prepare input file: a few times the size of the buffer, containing
// strings with zeroes and escaped quotes.
FILE* f = fopen(fname.ptr, "w");
for (int i = 0; i < BufSize; ++i) {
fwrite(content.ptr, 1, content.length - 1, f);
}
fclose(f);
int count = 3 * BufSize; // number of quoted strings written to file
// Initialize lexer state: all pointers are at the end of buffer.
// This immediately triggers YYFILL, as the check `it.yycursor < it.yylimit` fails.
Input it;
it.file = fopen(fname.ptr, "r");
it.yycursor = it.token = it.yylimit = it.buffer.ptr + BufSize;
it.eof = 0;
// Run the lexer.
assert(lex(it) == count);
// Cleanup: remove input file.
fclose(it.file);
remove(fname.ptr);
}
๐ FEATURES ๐
๐ง Multiple blocks
okay so sometimes you literally need several lexers that all know about each other โ like when you've got a high-level state machine bouncing between lexer modes, bestie. that's a whole vibe. ๐ซ you can pull it off with multiple connected re2d blocks. another option? start conditions (more on those in a sec ๐).
how you wire the blocks together totally depends on your target language. no cap:
- in languages that have a
gotostatement (like C/C++ and Go ๐ซถ), you can just put all the blocks in one function, each one prefixed with its own label, and hop between them with a plaingoto. slay, easy. - in languages that don't have
goto(looking at you, Rust ๐), you gotta use a loop with a switch on a state variable โ same energy as theyystateloop/switch thatre2ditself generates โ or else wrap each block in its own function and use function calls.
the example below uses multiple blocks to parse binary, octal, decimal and hexadecimal numbers. every base gets its own block, the initial block figures out the base and dispatches to the others, and the common configs live in a separate block at the top of the program so the other blocks inherit them. iconic โจ
// re2d $INPUT -o $OUTPUT -i
module main;
enum ERROR = ulong.max;
private void add(ulong BASE)(ref ulong u, int d) {
u = u * BASE + d;
if (u > uint.max) { u = ERROR; }
}
private ulong parse_u32(const(char)* s) {
const(char)* yycursor = s, yymarker;
ulong u = 0;
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = char;
end = "\x00";
'0b' / [01] { goto bin; }
"0" { goto oct; }
"" / [1-9] { goto dec; }
'0x' / [0-9a-fA-F] { goto hex; }
* { return ERROR; }
*/
bin:
/*!re2c
end { return u; }
[01] { add!(2)(u, yycursor[-1] - '0'); goto bin; }
* { return ERROR; }
*/
oct:
/*!re2c
end { return u; }
[0-7] { add!(8)(u, yycursor[-1] - '0'); goto oct; }
* { return ERROR; }
*/
dec:
/*!re2c
end { return u; }
[0-9] { add!(10)(u, yycursor[-1] - '0'); goto dec; }
* { return ERROR; }
*/
hex:
/*!re2c
end { return u; }
[0-9] { add!(16)(u, yycursor[-1] - '0'); goto hex; }
[a-f] { add!(16)(u, yycursor[-1] - 'a' + 10); goto hex; }
[A-F] { add!(16)(u, yycursor[-1] - 'A' + 10); goto hex; }
* { return ERROR; }
*/
}
void main() {
assert(parse_u32("") == ERROR);
assert(parse_u32("1234567890") == 1234567890);
assert(parse_u32("0b1101") == 13);
assert(parse_u32("0x7Fe") == 2046);
assert(parse_u32("0644") == 420);
assert(parse_u32("9999999999") == ERROR);
}
๐ Start conditions
start conditions get switched on with the --start-conditions option, and honestly? they're the moment. ๐
they give you a way to encode multiple interrelated automata inside one single re2d block. one block, many moods.
each condition is basically its own little automaton. it has a unique name that you specify, plus a unique internal number that re2d makes up for you. those numbers are what you use to switch between conditions โ the generated code calls on the YYGETCOND and YYSETCOND primitives to read the current condition or set it to a given number. wanna generate numeric condition identifiers? use the conditions block, the --header option, or the re2c:header configuration. and the re2c:cond:enumprefix configuration sets the prefix on those generated identifiers. ๐ท๏ธ
when you're in condition mode, every single rule has to be prefixed with a list of comma-separated condition names wrapped in angle brackets โ or the wildcard <*> if you mean all conditions. the rule syntax gets extended like this:
< condition-list > regular-expression codeโ a rule that gets merged into every condition on the condition-list. it matches regular-expression and runs the associated code.< condition-list > regular-expression => condition codeโ a rule merged into every condition on the condition-list. it matches regular-expression, sets the current condition to condition, and runs the associated code.< condition-list > regular-expression :=> conditionโ a rule merged into every condition on the condition-list. it matches regular-expression and immediately transitions to condition (there's no semantic action, it just vibes on over).< condition-list > !action codeโ a rule that binds code to the place defined by action in every condition on the condition-list (peep the actions section for the various types of actions ๐).<! condition-list > codeโ a rule that prepends code to the semantic actions of all rules, for every condition on the condition-list. โ ๏ธ this syntax is deprecated โ use the!pre_ruleaction instead (does exactly the same thing, bestie).< > codeโ a rule that creates a special entry condition with number zero and name"0"which runs code before jumping to other conditions. โ ๏ธ this syntax is deprecated too โ use the!entryaction instead (it's way more fine-grained: you can specify the code per-condition, and you can jump straight to a condition's start without going through condition dispatch). glow-up fr.< > => condition codeโ same as the previous rule, except it sets the next condition.< > :=> conditionโ same as the previous rule, except it has no associated code and immediately jumps to condition.
the code re2d generates for conditions depends on whether it's using the goto/label approach or the loop/switch approach to encode the automata. two completely different fits, both cute. ๐
in languages with a goto statement (C/C++, Go โ hiii ๐ซถ), conditions naturally become blocks of code prefixed with labels of the form yyc_<cond>, where cond is a condition name. (you can change the label prefix with re2c:cond:prefix.) transitions between conditions are handled with goto and the condition labels. before all the conditions, re2d generates an initial switch on YYGETSTATE that jumps to the start state of the current condition. the shortcut rules :=> bypass that initial switch and jump directly to the specified condition โ and re2c:cond:goto can change that default behavior. the rules with semantic actions do not automatically jump to the next condition; you have to do that yourself in your user-defined action code. no cap, that part's on you.
in languages without goto (Rust, ilysm but ๐ญ), re2d reuses the yystate variable to store condition numbers instead. every condition gets a numeric identifier equal to the number of its start state, so switching between conditions is literally no different than switching between DFA states of a single condition. no separate initial condition switch needed. (and since that same approach is used to implement storable states, YYGETCOND/YYSETCOND are redundant if you're using both storable states and conditions. free real estate โจ)
the program below uses start conditions to parse binary, octal, decimal and hexadecimal numbers. it's a single block where each base has its own condition, and the initial condition is connected to all of them. the user-defined variable cond stores the current condition number, and it's initialized to the number of the initial condition generated with the conditions block. chef's kiss. ๐
// re2d $INPUT -o $OUTPUT -ci
module main;
enum ERROR = ulong.max;
/*!conditions:re2c*/
private void add(ulong BASE)(ref ulong u, int d) {
u = u * BASE + d;
if (u > uint.max) { u = ERROR; }
}
private ulong parse_u32(const(char)* s) {
const(char)* yycursor = s, yymarker;
YYCond yycond = YYCond.yycinit;
ulong u = 0;
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = char;
<*> * { return ERROR; }
<init> '0b' / [01] :=> bin
<init> "0" :=> oct
<init> "" / [1-9] :=> dec
<init> '0x' / [0-9a-fA-F] :=> hex
<bin, oct, dec, hex> "\x00" { return u; }
<bin> [01] { add!(2)(u, yycursor[-1] - '0'); goto yyc_bin; }
<oct> [0-7] { add!(8)(u, yycursor[-1] - '0'); goto yyc_oct; }
<dec> [0-9] { add!(10)(u, yycursor[-1] - '0'); goto yyc_dec; }
<hex> [0-9] { add!(16)(u, yycursor[-1] - '0'); goto yyc_hex; }
<hex> [a-f] { add!(16)(u, yycursor[-1] - 'a' + 10); goto yyc_hex; }
<hex> [A-F] { add!(16)(u, yycursor[-1] - 'A' + 10); goto yyc_hex; }
*/
}
void main() {
assert(parse_u32("") == ERROR);
assert(parse_u32("1234567890") == 1234567890);
assert(parse_u32("0b1101") == 13);
assert(parse_u32("0x7Fe") == 2046);
assert(parse_u32("0644") == 420);
assert(parse_u32("9999999999") == ERROR);
}
๐พ Storable state
Okay bestie, so with the --storable-state option, re2d generates a lexer that can store its current state, return to the caller, and later resume operations exactly where it left off. Iconic behavior, honestly. ๐
The default mode of operation in re2d is a "pull" model, where the lexer "pulls" more input whenever it needs it. That can be a problem 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 is intended exactly for those cases: it lets you generate lexers that work in a "push" model. When the lexer needs more input, it stores its state and returns to the caller. Later, when more input becomes available, the caller resumes the lexer exactly where it stopped. โจ
There are a few changes necessary compared to the "pull" model:
- Define
YYSETSTATE()andYYGETSTATE(state)primitives. - Define
yych,yyaccept(if used) and state variables as a part of persistent lexer state. The state variable should be initialized to-1. YYFILLshould return to the outer program instead of trying to supply more input. Return code should indicate that lexer needs more input.- The outer program should recognize situations when lexer needs more input and respond appropriately.
- Optionally use
getstateblock to generateYYGETSTATEswitch detached from the main lexer. This only works for languages that havegoto(not in--loop-switchmode). - Use
re2c:eofand the sentinel with bounds checks method to handle the end of input. Padding-based method may not work because it is unclear when to append padding: the current end of input may not be the ultimate end of input, and appending padding too early may cut off a partially read greedy lexeme. Furthermore, due to high-level program logic getting more input may depend on processing the lexeme at the end of buffer (which already is blocked due to the end-of-input condition).
Here is an example of a "push" model lexer that simulates reading packets from a socket. The lexer loops until it encounters the end of input and returns to the calling function. The calling function provides more input by "sending" the next packet and resumes lexing. This process stops when all the packets have been sent, or when there is an error. ๐ซถ
// re2d $INPUT -o $OUTPUT -f
module main;
import core.stdc.stdio;
import core.stdc.string;
// Use a small buffer to cover the case when a lexeme doesn't fit.
// In real world use a larger buffer.
enum BUFSIZE = 10;
struct State {
FILE* file;
char[BUFSIZE + 1] buffer;
char* yylimit, yycursor, yymarker, token;
int yystate;
};
enum Status {END, READY, WAITING, BAD_PACKET, BIG_PACKET};
private Status fill(ref State st) {
const size_t shift = st.token - cast(char*)st.buffer;
const size_t used = st.yylimit - st.token;
const size_t free = BUFSIZE - used;
// Error: no space. In real life can reallocate a larger buffer.
if (free < 1) return Status.BIG_PACKET;
// Shift buffer contents (discard already processed data).
memmove(cast(void*)st.buffer, st.token, used);
st.yylimit -= shift;
st.yycursor -= shift;
st.yymarker -= shift;
st.token -= shift;
// Fill free space at the end of buffer with new data.
const size_t read = fread(st.yylimit, 1, free, st.file);
st.yylimit += read;
st.yylimit[0] = 0; // append sentinel symbol
return Status.READY;
}
private Status lex(ref State yyrecord, uint* recv) {
char yych;
/*!getstate:re2c*/
for (;;) {
yyrecord.token = yyrecord.yycursor;
/*!re2c
re2c:api = record;
re2c:YYCTYPE = char;
re2c:YYFILL = "return Status.WAITING;";
re2c:eof = 0;
packet = [a-z]+[;];
* { return Status.BAD_PACKET; }
$ { return Status.END; }
packet { *recv = *recv + 1; continue; }
*/
}
assert(0); // unreachable
}
private void test(string[] packets, Status expect) {
// Create a pipe (open the same file for reading and writing).
const(char*) fname = "pipe";
FILE* fw = fopen(fname, "w");
FILE* fr = fopen(fname, "r");
setvbuf(fw, null, _IONBF, 0);
setvbuf(fr, null, _IONBF, 0);
// Initialize lexer state: `state` value is -1, all pointers are at the end
// of buffer.
State st;
st.file = fr;
st.yycursor = st.yymarker = st.token = st.yylimit = cast(char*)st.buffer + BUFSIZE;
// Sentinel (at YYLIMIT pointer) is set to zero, which triggers YYFILL.
st.yylimit[0] = 0;
st.yystate = -1;
// Main loop. The buffer contains incomplete data which appears packet by
// packet. When the lexer needs more input it saves its internal state and
// returns to the caller which should provide more input and resume lexing.
Status status;
uint send = 0, recv = 0;
for (;;) {
status = lex(st, &recv);
if (status == Status.END) {
debug{printf("done: got %u packets\n", recv);}
break;
} else if (status == Status.WAITING) {
debug{printf("waiting...\n");}
if (send < packets.length) {
debug{printf("sent packet %u\n", send);}
fprintf(fw, "%s", cast(char*)packets[send]);
++send;
}
status = fill(st);
debug{printf("queue: '%s'\n", cast(char*)st.buffer);}
if (status == Status.BIG_PACKET) {
debug{printf("error: packet too big\n");}
break;
}
assert(status == Status.READY);
} else {
assert(status == Status.BAD_PACKET);
debug{printf("error: ill-formed packet\n");}
break;
}
}
// Check results.
assert(status == expect);
if (status == Status.END) assert(recv == send);
// Cleanup: remove input file.
fclose(fw);
fclose(fr);
remove(fname);
}
void main() {
string[] packets1 = [];
string[] packets2 = ["zero;", "one;", "two;", "three;", "four;"];
string[] packets3 = ["zer0;"];
string[] packets4 = ["looooooooooong;"];
test(packets1, Status.END);
test(packets2, Status.END);
test(packets3, Status.BAD_PACKET);
test(packets4, Status.BIG_PACKET);
}
๐งฉ Reusable blocks
Reusable blocks of the form /*!rules:re2c[:<name>] ... */ or %{rules[:<name>] ... %} can be reused any number of times and combined with other re2d blocks. The <name> is optional. A rules block can be used in a use block or directive. The code for a rules block is generated at every point of use. ๐
Use blocks are defined with /*!use:re2c[:<name>] ... */ or %{use[:<name>] ... %}. The <name> is optional: if it's not specified, the associated rules block is the most recent one (whether named or unnamed). A use block can add named definitions, configurations and rules of its own. An important use case for use blocks is a lexer that supports multiple input encodings: the same rules block is reused multiple times with encoding-specific configurations (see the example below). ๐
In-block use directive !use:<name>; can be used from inside of a re2d 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 re2d blocks together in one block (see the example below). ๐
Named blocks and in-block use directive were added in re2d 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
// re2d $INPUT -o $OUTPUT
module main;
// 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.
enum What { COLOR, FISH, DUNNO };
/*!rules:re2c:colors
* { assert(false); }
"red" | "salmon" | "magenta" { return What.COLOR; }
*/
/*!rules:re2c:fish
* { assert(false); }
"haddock" | "salmon" | "eel" { return What.FISH; }
*/
private What lex(const(char)* s) {
const(char)* yycursor = s, yymarker;
/*!re2c
re2c:YYCTYPE = "char";
re2c:yyfill:enable = 0;
!use:fish;
!use:colors;
* { return What.DUNNO; } // overrides inherited '*' rules
*/
}
void main() {
assert(lex("salmon") == What.FISH);
assert(lex("what?") == What.DUNNO);
}
๐ธ Example of a /*!use:re2c ... */ block
// re2d $INPUT -o $OUTPUT --input-encoding utf8
module main;
import std.stdint;
// 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.
/*!rules:re2c
re2c:yyfill:enable = 0;
"โx โy" { return 0; }
* { return 1; }
*/
private int lex_utf8(const(uint8_t)* s) {
const(uint8_t)* yycursor = s, yymarker;
/*!use:re2c
re2c:YYCTYPE = uint8_t;
re2c:encoding:utf8 = 1;
*/
}
private int lex_utf32(const(uint32_t)* s) {
const(uint32_t)* yycursor = s, yymarker;
/*!use:re2c
re2c:YYCTYPE = uint32_t;
re2c:encoding:utf32 = 1;
*/
}
void main() {
immutable uint8_t[] s8 = // UTF-8
[ 0xe2, 0x88, 0x80, 0x78, 0x20, 0xe2, 0x88, 0x83, 0x79 ];
immutable uint32_t[] s32 = // UTF32
[ 0x00002200, 0x00000078, 0x00000020, 0x00002203, 0x00000079 ];
assert(lex_utf8(cast(const(uint8_t)*)s8) == 0);
assert(lex_utf32(cast(const(uint32_t)*)s32) == 0);
}
๐ Submatch extraction ๐
okay so this is the part everyone DMs me about โ how do you actually pull out the little pieces of what you matched? re2d has two options for submatch extraction, and they are not the same vibe. let's go ๐
โจ Tags โจ
The first option is to use standalone tags of the form @stag or #mtag, where stag and mtag are arbitrary used-defined names. Tags are enabled with -T --tags option or re2c:tags = 1 configuration. Semantically tags are position markers: they can be inserted anywhere in a regular expression, and they bind to the corresponding position (or multiple positions) in the input string.
S-tags bind to the last matching position, and m-tags bind to a list of positions (they may be used in repetition subexpressions, where a single position in a regular expression corresponds to multiple positions in the input string). All tags should be defined by the user, either manually or with the help of svars and mvars blocks. If there is more than one way tags can be matched against the input, ambiguity is resolved using leftmost greedy disambiguation strategy.
โจ Captures โจ
The second option is to use capturing groups. They are enabled with --captures option or re2c:captures = 1 configuration. There are two flavours for different disambiguation policies: --leftmost-captures (the default) is for leftmost greedy policy, and --posix-captures is for POSIX longest-match policy.
In this mode all parenthesized subexpressions are considered capturing groups, and a bang can be used to mark non-capturing groups: (! ... ). With --invert-captures option or re2c:invert-captures = 1 configuration the meaning of bang is inverted. ๐ซถ
The number of groups for the matching rule is stored in a variable yynmatch (the whole regular expression is group number zero), and submatch results are stored in yypmatch array. Both yynmatch and yypmatch should be defined by the user, and yypmatch size must be at least [yynmatch * 2]. Use maxnmatch block to define YYMAXNMATCH, a constant that equals to the maximum value of yynmatch among all rules.
โจ Captvars โจ
Another way to use capturing groups is the --captvars option or re2c:captvars = 1 configuration. The only difference with --captures is in the way the generated code stores submatch results: instead of yynmatch and yypmatch re2d generates variables yytl<k> and yytr<k> for k-th capturing group (the user should declare these using an svars block).
Captures with variables support two disambiguation policies: --leftmost-captvars or re2c:leftmost-captvars = 1 for leftmost greedy policy (the default one) and --posix-captvars or re2c:posix-captvars for POSIX longest-match policy.
Under the hood all these options translate into tags and Tagged Deterministic Finite Automata with Lookahead. The core idea of TDFA is to minimize the overhead on submatch extraction. In the extreme, if there're no tags or captures in a regular expression, TDFA is just an ordinary DFA. If the number of tags is moderate, the overhead is barely noticeable ๐
The generated TDFA uses a number of tag variables which do not map directly to tags: a single variable may be used for different tags, and a tag may require multiple variables to hold all its possible values. Eventually ambiguity is resolved, and only one final variable per tag survives. Tag variables should be defined using stags or mtags blocks. If lexer state is stored, tag variables should be part of it. They also need to be updated by YYFILL. ๐ญ
S-tags support the following operations:
- save input position to an s-tag:
t = YYCURSORwith C pointer API or a user-defined operationYYSTAGP(t)with generic API - save default value to an s-tag:
t = NULLwith C pointer API or a user-defined operationYYSTAGN(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 semantic versions consisting of three numeric components: major, minor, patch (the latter is optional). See below for a more complex example that uses YYFILL.
// re2d $INPUT -o $OUTPUT
module main;
struct SemVer {
int major;
int minor;
int patch;
};
private int s2n(const(char)* s, const(char)* e) { // pre-parsed string to number
int n = 0;
for (; s < e; ++s) n = n * 10 + (*s - '0');
return n;
}
private bool lex(const(char)* str, ref SemVer ver) {
const(char)* yycursor = str, yymarker;
// Final tag variables available in semantic action.
/*!svars:re2c format = 'const(char)* @@;\n'; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = 'const(char)* @@;\n'; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:tags = 1;
re2c:YYCTYPE = "char";
num = [0-9]+;
@t1 num @t2 "." @t3 num @t4 ("." @t5 num)? [\x00] {
ver.major = s2n(t1, t2);
ver.minor = s2n(t3, t4);
ver.patch = t5 != null ? s2n(t5, yycursor - 1) : 0;
return true;
}
* { return false; }
*/
}
void main() {
SemVer v;
assert(lex("23.34", v) && v.major == 23 && v.minor == 34 && v.patch == 0);
assert(lex("1.2.999", v) && v.major == 1 && v.minor == 2 && v.patch == 999);
assert(!lex("1.a", v));
}
Here is a more complex example of using s-tags with YYFILL to parse a file with newline-separated semantic versions. Tag variables are part of the lexer state, and they are adjusted in YYFILL like other input positions. Note that it is necessary for s-tags because their values are invalidated after shifting buffer contents. It may not be necessary in a custom implementation where tag variables store offsets relative to the start of the input string rather than the buffer, which may be the case with m-tags. ๐ฆ
// re2d $INPUT -o $OUTPUT --tags
module main;
import core.stdc.string;
import core.stdc.stdio;
import std.stdio;
enum BUFSIZE = 4095;
struct Input {
FILE* file;
char[BUFSIZE + 1] buffer;// +1 for sentinel
char* yylimit, yycursor, yymarker, token;
// Intermediate tag variables must be part of the lexer state passed to YYFILL.
// They don't correspond to tags and should be autogenerated by re2c.
/*!stags:re2c format = 'char* @@;'; */
bool eof;
};
struct SemVer {
int major;
int minor;
int patch;
};
private int s2n(const(char)* s, const(char)* e) { // pre-parsed string to number
int n = 0;
for (; s < e; ++s) n = n * 10 + (*s - '0');
return n;
}
private int fill(ref Input it) {
if (it.eof) return 1;
const size_t shift = it.token - it.buffer.ptr;
const size_t used = it.yylimit - it.token;
// Error: lexeme too long. In real life could reallocate a larger buffer.
if (shift < 1) return 2;
// Shift buffer contents (discard everything up to the current token).
memmove(cast(void*)it.buffer.ptr, it.token, used);
it.yylimit -= shift;
it.yycursor -= shift;
it.yymarker -= shift;
it.token -= shift;
// Tag variables need to be shifted like other input positions. The check
// for non-null is only needed if some tags are nested inside of alternative
// or repetition, so that they can have null value.
/*!stags:re2c format = "if (it.@@) it.@@ -= shift;\n"; */
// Fill free space at the end of buffer with new data from file.
it.yylimit += fread(it.yylimit, 1, BUFSIZE - used, it.file);
it.yylimit[0] = 0;
it.eof = it.yylimit < (it.buffer.ptr + BUFSIZE);
return 0;
}
private bool lex(ref Input yyrecord, ref SemVer[] vers) {
// Final variables available in semantic actions.
/*!svars:re2c format = 'char* @@;'; */
for (;;) {
yyrecord.token = yyrecord.yycursor;
/*!re2c
re2c:api = record;
re2c:YYCTYPE = "char";
re2c:YYFILL = "fill(yyrecord) == 0";
re2c:eof = 0;
num = [0-9]+;
num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] {
int major = s2n(yyrecord.token, t1);
int minor = s2n(t2, t3);
int patch = t4 != null ? s2n(t4, yyrecord.yycursor - 1) : 0;
SemVer ver = SemVer(major, minor, patch);
vers ~= ver;
continue;
}
$ { return true; }
* { return false; }
*/
}
assert(0);
}
void main() {
const char[] fname = "input";
const char[] content = "1.22.333\n' ";
SemVer[BUFSIZE] expect = SemVer(1, 22, 333);
SemVer[] actual;
okay so we're still mid-example โ the code keeps rolling like this:
// Prepare input file: a few times the size of the buffer, containing
// strings with zeroes and escaped quotes.
FILE* f = fopen(fname.ptr, "w");
for (int i = 0; i < BUFSIZE; ++i) {
fwrite(cast(const(void*)) content.ptr, 1, content.length - 2, f); // skip null-terminator
}
fclose(f);
// Initialize lexer state: all pointers are at the end of buffer.
Input it;
it.file = fopen(fname.ptr, "r");
it.yycursor = it.yymarker = it.token = it.yylimit = it.buffer.ptr + BUFSIZE;
it.eof = 0;
// Sentinel (at YYLIMIT pointer) is set to zero, which triggers YYFILL.
it.yylimit[0] = 0;
// Run the lexer.
assert(lex(it, actual) && actual == expect);
// Cleanup: remove input file.
fclose(it.file);
remove(fname.ptr);
}
Next up: capturing groups doing semantic version parsing, slay ๐
// re2d $INPUT -o $OUTPUT
module main;
struct SemVer { int major, minor, patch; };
private int s2n(const(char)* s, const(char)* e) { // pre-parsed string to number
int n = 0;
for (; s < e; ++s) n = n * 10 + (*s - '0');
return n;
}
private bool lex(const(char)* str, ref SemVer ver) {
const(char)* yycursor = str, yymarker;
// Final tag variables available in semantic action.
/*!svars:re2c format = 'const(char)* @@;\n'; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = 'const(char)* @@;\n'; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:captvars = 1;
re2c:YYCTYPE = "char";
num = [0-9]+;
(num) "." (num) ("." num)? [\x00] {
ver.major = s2n(yytl1, yytr1);
ver.minor = s2n(yytl2, yytr2);
ver.patch = yytl3 ? s2n(yytl3 + 1, yytr3) : 0;
return true;
}
* { return false; }
*/
}
void main() {
SemVer v;
assert(lex("23.34", v) && v.major == 23 && v.minor == 34 && v.patch == 0);
assert(lex("1.2.999", v) && v.major == 1 && v.minor == 2 && v.patch == 999);
assert(!lex("1.a", v));
}
And here's the m-tags flex: parsing a version with a variable number of components. Tag variables are stored in a trie ๐ง
// re2d $INPUT -o $OUTPUT
module main;
enum MtagRoot = -1;
// An m-tag tree is a way to store histories with an O(1) copy operation.
// Histories naturally form a tree, as they have common start and fork at some
// point. The tree is stored as an array of pairs (tag value, link to parent).
// An m-tag is represented with a single link in the tree (array index).
struct Mtag {
const(char)* elem; // tag value
int pred; // index of the predecessor node or root
};
alias MtagTrie = Mtag[];
alias Ver = int[];
private int s2n(const(char)* s, const(char)* e) { // pre-parsed string to number
int n = 0;
for (; s < e; ++s) n = n * 10 + (*s - '0');
return n;
}
// Append a single value to an m-tag history.
private void add_mtag(ref MtagTrie trie, ref int mtag, const(char)* value) {
Mtag m = {value, mtag};
mtag = cast(int)trie.length;
trie ~= [m];
}
// Recursively unwind tag histories and collect version components.
private void unfold(const ref MtagTrie trie, int x, int y, ref Ver ver) {
// Reached the root of the m-tag tree, stop recursion.
if (x == MtagRoot && y == MtagRoot) return;
// Unwind history further.
unfold(trie, trie[x].pred, trie[y].pred, ver);
// Get tag values. Tag histories must have equal length.
assert(x != MtagRoot && y != MtagRoot);
const(char)* ex = trie[x].elem, ey = trie[y].elem;
if (ex != null && ey != null) {
// Both tags are valid pointers, extract component.
ver ~= [s2n(ex, ey)];
} else {
// Both tags are null (this corresponds to zero repetitions).
assert(ex == null && ey == null);
}
}
private bool parse(const(char)* str, ref Ver ver) {
const(char)* yycursor = str, yymarker;
MtagTrie mt;
// Final tag variables available in semantic action.
/*!svars:re2c format = "const(char)* @@;"; */
/*!mvars:re2c format = "int @@;"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = "const(char)* @@ = null;"; */
/*!mtags:re2c format = "int @@ = MtagRoot;"; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:tags = 1;
re2c:YYCTYPE = "char";
re2c:YYMTAGP = "add_mtag(mt, @@, yycursor);";
re2c:YYMTAGN = "add_mtag(mt, @@, null);";
num = [0-9]+;
@t1 num @t2 ("." #t3 num #t4)* [\x00] {
ver = [];
ver ~= [s2n(t1, t2)];
unfold(mt, t3, t4, ver);
return true;
}
* { return false; }
*/
}
void main() {
Ver v;
assert(parse("1", v) && v == [1]);
assert(parse("1.2.3.4.5.6.7", v) && v == [1, 2, 3, 4, 5, 6, 7]);
assert(!parse("1.2.", v));
}
โจ Encoding support โจ
okay bestie, this is the part where we get into code points versus code units, and it actually matters fr fr. A code point is a numeric identifier of a symbol. A code unit is the smallest 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.
๐จ lowkey important: 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 is the default rule*).
The generated lexer works with a stream of code units: yych stores a code unit, and YYCTYPE is the code unit type. Regular expressions, on the other hand, are specified in terms of code points. When re2d compiles regular expressions to automata it translates code points to code units. This is generally not a simple mapping: in variable-length encodings a single code point range may get translated to a complex code unit graph.
The following encodings are supported:
- ASCII (enabled by default). It is a fixed-length encoding with code space
[0-255]and 1-byte code points and code units. - EBCDIC (enabled with
--ebcdicorre2c:encoding:ebcdic). It is a fixed-length encoding with code space[0-255]and 1-byte code points and code units. - UCS2 (enabled with
--ucs2orre2c:encoding:ucs2). It is a fixed-length encoding with code space[0-0xFFFF]and 2-byte code points and code units. - UTF8 (enabled with
--utf8orre2c:encoding:utf8). It is a variable-length Unicode encoding. Code unit size is 1 byte. Code points are represented with1 -- 4code units. - UTF16 (enabled with
--utf16orre2c:encoding:utf16). It is a variable-length Unicode encoding. Code unit size is 2 bytes. Code points are represented with1 -- 2code units. - UTF32 (enabled with
--utf32orre2c:encoding:utf32). It is a fixed-length Unicode encoding with code space[0-0x10FFFF]and 4-byte code points and code units.
Include files include/unicode_blocks.re, include/unicode_categories.re and include/unicode_properties.re provide re2d definitions for blocks, categories and properties described in the Unicode standard. ๐ฆ
Option --input-encoding specifies source file encoding, which can be used to enable Unicode literals in regular expressions. For example --input-encoding utf8 tells re2d that the source file is in UTF8 (it differs from --utf8 which sets input text encoding). Option --encoding-policy specifies the way re2d handles Unicode surrogates (code points in range [0xD800-0xDFFF]).
Below is an example of a lexer for UTF8 encoded Unicode identifiers ๐
// re2d $INPUT -o $OUTPUT -8 -i
module main;
/*!include:re2c "unicode_categories.re" */
private int lex(const(char)* s) {
const(char)* yycursor = s, yymarker;
/*!re2c
re2c:YYCTYPE = "char";
re2c:yyfill:enable = 0;
// Simplified "Unicode Identifier and Pattern Syntax"
// (see https://unicode.org/reports/tr31)
id_start = L | Nl | [$_];
id_continue = id_start | Mn | Mc | Nd | Pc | [\u200D\u05F3];
identifier = id_start id_continue*;
identifier { return 0; }
* { return 1; }
*/
}
void main() {
assert(lex("_ะซะดะตะฝัะธัะธะบะฐัะพั") == 0);
assert(lex("!!!")==1);
}
๐ Include files ๐
re2d allows one to include other files using a block of the form /*!include:re2c FILE */ or %{include FILE %}, or an in-block directive !include FILE ;, where FILE is a path to the file to be included. re2d looks for include files in the directory of the including file and in include locations, which can be specified with the -I option. Include blocks/directives in re2d work in the same way as C/C++ #include: FILE contents are copy-pasted verbatim in place of the block/directive. Include files may have further includes of their own. Use --depfile option to track build dependencies of the output file on include files. re2d provides some predefined include files that can be found in the include/ subdirectory of the project. These files contain definitions that may be useful to other projects (such as Unicode categories) and form something like a standard library for re2d. Below is an example of using include files.
๐๏ธ Include file 1 (definitions.d)
enum Result{ OK, FAIL };
/*!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 Result.OK; }
๐ธ Input file
// re2d $INPUT -o $OUTPUT -i
/*!include:re2c "definitions.d" */
private Result lex(const(char)* s) {
const(char)* yycursor = s, yymarker;
/*!re2c
re2c:YYCTYPE = "char";
re2c:yyfill:enable = 0;
* { return Result.FAIL; }
number { return Result.OK; }
!include "extra_rules.re.inc";
*/
}
void main() {
assert(lex("123") == Result.OK);
assert(lex("123.4567") == Result.OK);
}
๐ Header files ๐
Okay so re2d lets you generate a header file from the input .re file using the --header option or the re2c:header configuration โ plus block pairs of the form /*!header:re2c:on*/ and /*!header:re2c:off*/, or %{header:on%} and %{header:off%}. The first block marks the beginning of the header file, and the second block marks the end of it. Everything between these blocks is processed by re2d, and the generated code is written to the file specified with --header or re2c:header (or stdout if neither option nor configuration is used). Autogenerated header file may be needed in cases when re2d is used to generate definitions that must be visible from other translation units.
Hereโs an example of generating a header file that contains the definition of the lexer state with tag variables โ and yes, the number of variables depends on the regular grammar and is unknown to the programmer. ๐
Input file
// re2d $INPUT -o $OUTPUT -i --header lexer/state.d
module main;
import core.stdc.stddef;
import lexer.state; // the module is generated by re2c
/*!header:re2c:on*/
module lexer.state;
struct LexerState {
const(char)* str, yycursor;
/*!stags:re2c format = "const(char)* @@;"; */
};
/*!header:re2c:off*/
private long lex(ref LexerState yyrecord) {
const(char)* t;
/*!re2c
re2c:api = record;
re2c:YYCTYPE = "char";
re2c:tags = 1;
re2c:yyfill:enable = 0;
re2c:header = "lexer/state.d";
[a]* @t [b]* { return t - yyrecord.str; }
*/
}
void main() {
const(char)* s = "ab";
LexerState st = {s, s /*!stags:re2c format = ", null"; */};
assert(lex(st) == 1);
const(char)* s2 = "aaabbbbbbbb";
LexerState st2 = {s2, s2 /*!stags:re2c format = ", null"; */};
assert(lex(st2) == 3);
}
Header file
/* Generated by re2c */
module lexer.state;
struct LexerState {
const(char)* str, yycursor;
const(char)* yyt1;
};
โจ Skeleton programs โจ
With the -S, --skeleton option, re2d ignores all non-re2d 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), re2d 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
re2doptimizations (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). re2d 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) the skeleton is just an exact copy of the original DFA. For encodings with multibyte code units the skeleton is a copy of the DFA with certain transitions omitted: namely, re2d 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), re2d 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 (re2d writes data to file as soon as it is generated). ๐ญ
๐ฅ Visualization and debug ๐ฅ
With the -D, --emit-dot option, re2d 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 ๐
re2d was originally written by Peter Bumbulis (peter@csg.uwaterloo.ca) in 1993. Marcus Boerger and Dan Nuffer spent several years to turn the original idea into a production ready code generator. Since then it has been maintained and developed by multiple volunteers, most notably, Brian Young (bayoung@acm.org), Marcus Boerger, Dan Nuffer (nuffer@users.sourceforge.net), Ulya Trofimovich (skvadrik@gmail.com), Serghei Iakovlev, Sergei Trofimovich, Petr Skocik, ligfx raekye and PolarGoose. ๐
Later, bestie โ thatโs the whole RE2D(1) page, source/version/date footer and all. ๐โจ
๐ฆ where this page comes from
- arch rolling: re2c 4.6-1 ยท LicenseRef-re2c
- nixpkgs unstable: re2c 4.6
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms