RE2GO(1)
π RE2GO(1) β re2go: generate fast lexical analyzers for Go π
πΈ NAME πΈ
re2go β generate fast lexical analyzers for Go. Slay.
β¨ SYNOPSIS β¨
re2go [ OPTIONS ] [ WARNINGS ] INPUT
Input can be either a file or - for stdin. iykyk π
π¦ INTRODUCTION π¦
Okay so bestie, re2go works as a preprocessor. π It reads the input file (which is usually a program in Go, 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 re2go. It translates them to code in Go and outputs the generated code in place of the block. Literally main character energy. β¨
Here is an example of a small program that checks if a given string contains a decimal number:
//go:generate re2go $INPUT -o $OUTPUT -i --api simple
package main
func lex(yyinput string) {
var yycursor int
/*!re2c
re2c:YYCTYPE = byte;
re2c:yyfill:enable = 0;
[1-9][0-9]* { return }
* { panic("error!") }
*/
}
func main() {
lex("1234\x00")
}
In the output re2go replaced the block in the middle with the generated code:
// Code generated by re2go, DO NOT EDIT.
//go:generate re2go $INPUT -o $OUTPUT -i --api simple
package main
func lex(yyinput string) {
var yycursor int
{
var yych byte
yych = yyinput[yycursor]
switch (yych) {
case '1','2','3','4','5','6','7','8','9':
goto yy2
default:
goto yy1
}
yy1:
yycursor += 1
{ panic("error!") }
yy2:
yycursor += 1
yych = yyinput[yycursor]
switch (yych) {
case '0','1','2','3','4','5','6','7','8','9':
goto yy2
default:
goto yy3
}
yy3:
{ return }
}
}
func main() {
lex("1234\x00")
}
No cap, thatβs the whole preprocessor vibe. π«Ά
π BASICS π
A re2go 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 bindsnametoregular-expression. Names may contain alphanumeric characters and underscore. The regular expressions section gives an overview of re2go syntax for regular expressions. Once defined, the name can be used in other regular expressions and in rules. Recursion in named definitions is not allowed, and each name should be defined before it is used. A block inherits named definitions from the global scope. Redefining a name that exists in the current scope is an error. Rules are rules, bestie.configuration = value ;β A configuration allows one to change re2go behavior and customize the generated code. For a full list of configurations supported by re2go see the configurations section. Depending on a particular configuration, the value can be a keyword, a nonnegative integer number or a one-line string which should be enclosed in double or single quotes unless it consists of alphanumeric characters. A block inherits configurations from the global scope and may redefine them or add new ones. Configurations defined inside of a block affect the whole block, even if they appear at the end of it. Yes, even at the end β the whole block. Periodt. πregular-expression codeβ A rule bindsregular-expressionto 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. Longest match wins, then earliest wins β iconic behavior fr fr. π₯!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. Custom placement? Obsessed. β¨!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. re2go compiles regular expressions associated with each rule into a deterministic finite automaton, encodes it in the form of conditional jumps in the target language and replaces the block with the generated code. Names and configurations defined in a global block are added to the global scope and become visible to subsequent blocks. At the start of the program the global scope is initialized with command-line options. Global scope said βIβm the main character.β π/*!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). Local business stays local. π/*!rules:re2c[:<name>] ... */or%{rules[:<name>] ... %}β A rules block is like a local block, but it does not generate any code by itself, nor does it add any definitions to the global scope -- it is meant to be reused in other blocks. This is a way of sharing code (more details in the reusable blocks section). Prior to re2go version 2.2 rules blocks required-r --reusableoption. Reuse era. β»οΈ/*!use:re2c[:<name>] ... */or%{use[:<name>] ... %}β A use block that references a previously defined rules block. If the name is specified, re2go looks for a rules blocks with this name. Otherwise the most recent rules block is used (either a named or an unnamed one). A use block can add definitions, configurations and rules of its own, which are added to those of the referenced rules block. Prior to re2go version 2.2 use blocks required-r --reusableoption. π«Ά/*!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. Numbers but make it customizable. β¨/*!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 by re2go. 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. Tags getting their own little template moment. π/*!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 by re2go (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. Tags, templates, and separator code β the whole little ecosystem. π/*!getstate:re2c[:<name1>[:<name2>...]] ... */or%{getstate[:<name1>[:<name2>...]] ... %}β this block generates conditional dispatch on the lexer state, and it needs the--storable-stateoption. You can drop an optional list of block names to say which blocks get included in the state dispatch. The default transition goes to the start label of the first block on that 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. > heads up bestie: this block type is incompatible with the--loop-switchoption, because it requires cross-block transitions and those are unsupported withoutgotoor function calls. no cap./*!conditions:re2c[:<name1>[:<name2>...]] ... */,/*!types:re2c... */or%{conditions[:<name1>[:<name2>...]] ... %},%{types... %}β this one generates the condition enumeration and requires the--conditionsoption. An optional list of block names says which blocks get included when computing the set of conditions; if the list is empty, all blocks are included. By default the generated code is an enumerationYYCONDTYPE. You can customize it with the optional configurationsformatandseparator. Theformatconfig gives a template string where@@{cond}(or@@for short) gets replaced with the name of each condition, and@@{num}gets replaced with a numeric index of that condition. Theseparatorconfig gives a piece of code used to join the generated format pieces for different conditions. π/*!include:re2c <file> */or%{include <file> %}β this block lets you include<file>, which must be a double-quoted file path. The contents of the file are literally substituted in place of the block, the same way#includeworks in C/C++. You can use this block together with the--depfileoption to generate build system dependencies on the included files. π«Ά/*!header:re2c:on*/or%{header:on %}β marks the start of the header file. Everything after it and up to the followingheader:offblock is processed byre2goand written to the header file specified with the-t --type-headeroption. β¨/*!header:re2c:off*/or%{header:off %}β marks the end of the header file started with theheader:on*/block. π/*!ignore:re2c ... */or%{ignore ... %}β a block whose contents are ignored and removed from the output file. lowkey iconic for hiding stuff you don't want in the final result. π
π Configurations π
okay bestie, here's the full list of configurations supported by re2go β every single one, no skips, fr fr:
re2c:api,re2c:inputβ same as the--apioption.re2c:api:sigilβ specifies the marker ("sigil") used for argument placeholders in the API primitives. The default is@@. A placeholder starts with the sigil followed by the argument name in curly braces. For example, if the sigil is set to$, then placeholders have the form${name}. Single-argument APIs may use shorthand notation without the name in braces. This option can be overridden by options for individual API primitives, e.g.re2c:YYFILL@lenforYYFILL. πre2c:api:styleβ specifies API style. Possible values arefunctions(the default for C) andfree-form(the default for Go and Rust). Infunctionsstyle, API primitives are generated with an argument list in parentheses following the name of the primitive. The arguments are provided only for autogenerated parameters (such as the number of characters passed toYYFILL), but not for the general lexer context, so the primitives behave more like macros in C/C++ or closures in Go and Rust. Infree-formstyle, API primitives do not have a fixed form: they should be defined as strings containing free-form pieces of code with interpolated variables of the form@@{var}or@@(they correspond to arguments in function-like style). This configuration may be overridden for individual API primitives; see for example there2c:YYFILL:nakedconfiguration forYYFILL. β¨re2c:bit-vectors,re2c:flags:bit-vectors,re2c:flags:bβ same as the--bit-vectorsoption, but can be configured on a per-block basis.re2c:captures,re2c:leftmost-capturesβ same as the--leftmost-capturesoption, but can be configured on a per-block basis.re2c:captvars,re2c:leftmost-captvarsβ same as the--leftmost-captvarsoption, but can be configured on a per-block basis.re2c:case-insensitive,re2c:flags:case-insensitiveβ same as the--case-insensitiveoption, but can be configured on a per-block basis.re2c:case-inverted,re2c:flags:case-invertedβ same as the--case-invertedoption, but can be configured on a per-block basis.re2c:case-ranges,re2c:flags:case-rangesβ same as the--case-rangesoption, but can be configured on a per-block basis.re2c:computed-gotos,re2c:flags:computed-gotos,re2c:flags:gβ same as the--computed-gotosoption, but can be configured on a per-block basis.re2c:computed-gotos:relative,re2c:cgoto:relativeβ same as the--computed-gotos-relativeoption, but can be configured on a per-block basis. πre2c:computed-gotos:threshold,re2c:cgoto:thresholdβ if computed goto is used, this configuration specifies the complexity threshold that triggers generation of jump tables instead of nestedifstatements and bitmaps. The default value is9. π₯re2c:cond:abortβ if set to a positive integer value, the default case in the generated condition dispatch aborts program execution.re2c:cond:gotoβ specifies a piece of code used for the autogenerated shortcut rules:=>in conditions. The default isgoto @@;. The@@placeholder is substituted with the condition name (see configurationsre2c:api:sigilandre2c:cond:goto@cond). πre2c:cond:goto@condβ specifies the sigil used for argument substitution in there2c:cond:gotodefinition. The default value is@@. Overrides the more genericre2c:api:sigilconfiguration.re2c:cond:dividerβ defines the divider for condition blocks. The default value is/* *********************************** */. Placeholders are substituted with the condition name (seere2c:api;sigilandre2c:cond:divider@cond). πΈre2c:cond:divider@condβ specifies the sigil used for argument substitution in there2c:cond:dividerdefinition. The default is@@. Overrides the more genericre2c:api:sigilconfiguration.re2c:cond:prefix,re2c:condprefixβ specifies the prefix used for condition labels. The default isyyc_.re2c:cond:enumprefix,re2c:condenumprefixβ specifies the prefix used for condition identifiers. The default isyyc.re2c:debug-output,re2c:flags:debug-output,re2c:flags:dβ same as the--debug-outputoption, but can be configured on a per-block basis.re2c:empty-class,re2c:flags:empty-classβ same as the--empty-classoption, but can be configured on a per-block basis.re2c:encoding:ebcdic,re2c:flags:ecb,re2c:flags:eβ same as the--ebcdicoption, but can be configured on a per-block basis.re2c:encoding:ucs2,re2c:flags:wide-chars,re2c:flags:wβ same as the--ucs2option, but can be configured on a per-block basis.re2c:encoding:utf8,re2c:flags:utf-8,re2c:flags:8β same as the--utf8option, but can be configured on a per-block basis.re2c:encoding:utf16,re2c:flags:utf-16,re2c:flags:xβ same as the--utf16option, but can be configured on a per-block basis.re2c:encoding:utf32,re2c:flags:unicode,re2c:flags:uβ same as the--utf32option, but can be configured on a per-block basis.re2c:encoding-policy,re2c:flags:encoding-policyβ same as the--encoding-policyoption, but can be configured on a per-block basis.re2c:eofβ specifies the sentinel symbol used with the end-of-input rule$. The default value is-1(the$rule is not used). Other possible values include all valid code units. Only decimal numbers are recognized. π¦re2c:header,re2c:flags:type-header,re2c:flags:tβ specifies the name of the generated header file relative to the directory of the output file. Same as the--headeroption except that the file path is relative.re2c:indent:stringβ specifies the string used for indentation. The default is a single tab character"\t". The indent string should contain whitespace characters only. To disable indentation entirely, set this configuration to an empty string.re2c:indent:topβ specifies the minimum amount of indentation to use. The default value is zero. The value should be a non-negative integer number.re2c:invert-capturesβ same as the--invert-capturesoption, but can be configured on a per-block basis.re2c:label:prefix,re2c:labelprefixβ specifies the prefix used for DFA state labels. The default isyy.re2c:label:start,re2c:startlabelβ controls the generation of a block start label. The default value is zero, which means the start label is generated only if it is used. An integer value greater than zero forces generation of the start label even if it is unused by the lexer. A string value also forces start label generation and sets the label name to the specified string. This configuration applies only to the current block (it is reset to default for the next block). πre2c:label:yyFillLabelβ specifies the prefix ofYYFILLlabels used withre2c:eofand in storable state mode.re2c:label:yyloopβ specifies the name of the label marking the start of the lexer loop with the--loop-switchoption. The default isyyloop.re2c:label:yyNextβ specifies the name of the optional label that follows theYYGETSTATEswitch in storable state mode (enabled withre2c:state:nextlabel). The default isyyNext. βre2c:lookahead,re2c:flags:lookaheadβ deprecated (see the deprecated--no-lookaheadoption).re2c:monadicβ if set to non-zero, the generated lexer will use monadic notation (this configuration is specific to Haskell). π§re2c:nested-ifs,re2c:flags:nested-ifs,re2c:flags:sβ same as the--nested-ifsoption, but can be configured on a per-block basis.re2c:posix-captures,re2c:flags:posix-captures,re2c:flags:Pβ literally the same energy as the--posix-capturesoption, except you can set it per-block πre2c:posix-captvarsβ again, exactly what--posix-captvarsdoes, but scoped per-block πre2c:tags,re2c:flags:tags,re2c:flags:Tβ the--tagsoption, but per-block. bestie it's the same deal every time β¨re2c:tags:expressionβ sets the expression used for tag variables π·οΈ by default re2go spits out expressions of the formyyt<N>. That can be super inconvenient, like if your tag variables are fields in a struct. Every occurrence of@@{tag}or@@gets swapped for the actual tag name. So:
re2c:tags:expression = "s.@@";
gives you expressions of the form s.yyt<N> in the generated code. see also the re2c:api:sigil configuration π
re2c:tags:negativeβ the constant expression used for a negative tag value (typically this would be-1if tags are integer offsets in the input string, or a null pointer if they're pointers). no cap π«Άre2c:tags:prefixβ the prefix for tag variable names. default isyytβre2c:sentinelβ the sentinel symbol used for the end-of-input checks (this kicks in when bounds checks are disabled withre2c:yyfill:enable = 0;andre2c:eofis not set). Heads up: this configuration 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 the buffer. The default value is-1(in that case re2go assumes that the sentinel is zero, which is the most common case). Only decimal numbers are recognized π’re2c:state:abortβ if you set it to a positive integer value, the default case in the generated state dispatch aborts program execution, and an explicit-1case contains the transition to the start of the block πre2c:state:nextlabelβ controls whether theYYGETSTATEswitch is followed by ayyNextlabel (the default value is zero, which corresponds to 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. If set to zero it suppresses the generation of unsafe wrappers aroundYYPEEK. The default is non-zero (wrappers are generated). This configuration is specific to Rust π¦
okay so now the whole YY* section β yes it's long, yes it's iconic, we're doing all of it, no skipping π
re2c:YYBACKUP,re2c:define:YYBACKUPβ defines the generic API primitiveYYBACKUPre2c:YYBACKUPCTX,re2c:define:YYBACKUPCTXβ defines the generic API primitiveYYBACKUPCTXre2c:YYCONDTYPE,re2c:define:YYCONDTYPEβ defines the API primitiveYYCONDTYPEre2c:YYCTYPE,re2c:define:YYCTYPEβ defines the API primitiveYYCTYPEre2c:YYCTXMARKER,re2c:define:YYCTXMARKERβ defines the API primitiveYYCTXMARKERre2c:YYCURSOR,re2c:define:YYCURSORβ defines the API primitiveYYCURSORre2c:YYDEBUG,re2c:define:YYDEBUGβ defines the API primitiveYYDEBUGre2c:YYFILL,re2c:define:YYFILLβ defines the API primitiveYYFILLre2c:YYFILL@len,re2c:define:YYFILL@lenβ the sigil used for argument substitution in theYYFILLdefinition. defaults to@@. 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 primitiveYYFNre2c:YYINPUTβ defines the API primitiveYYINPUTre2c:YYGETCOND,re2c:define:YYGETCONDITIONβ defines the API primitiveYYGETCONDre2c:YYGETCOND:naked,re2c:define:YYGETCONDITION:nakedβ overrides the more genericre2c:api:styleconfiguration forYYGETCOND. a zero value corresponds to free-form API style πΈre2c:YYGETSTATE,re2c:define:YYGETSTATEβ defines the API primitiveYYGETSTATEre2c:YYGETSTATE:naked,re2c:define:YYGETSTATE:nakedβ overrides the more genericre2c:api:styleconfiguration forYYGETSTATE. a zero value corresponds to free-form API style πre2c:YYGETACCEPT,re2c:define:YYGETACCEPTβ defines the API primitiveYYGETACCEPTre2c:YYLESSTHAN,re2c:define:YYLESSTHANβ defines the generic API primitiveYYLESSTHANre2c:YYLIMIT,re2c:define:YYLIMITβ defines the API primitiveYYLIMITre2c:YYMARKER,re2c:define:YYMARKERβ defines the API primitiveYYMARKERre2c:YYMTAGN,re2c:define:YYMTAGNβ defines the generic API primitiveYYMTAGNre2c:YYMTAGP,re2c:define:YYMTAGPβ defines the generic API primitiveYYMTAGPre2c:YYPEEK,re2c:define:YYPEEKβ defines the generic API primitiveYYPEEKre2c:YYRESTORE,re2c:define:YYRESTOREβ defines the generic API primitiveYYRESTOREre2c:YYRESTORECTX,re2c:define:YYRESTORECTXβ defines the generic API primitiveYYRESTORECTXre2c:YYRESTORETAG,re2c:define:YYRESTORETAGβ defines the generic API primitiveYYRESTORETAGre2c:YYSETCOND,re2c:define:YYSETCONDITIONβ defines the API primitiveYYSETCONDre2c:YYSETCOND@cond,re2c:define:YYSETCONDITION@condβ the sigil used for argument substitution in theYYSETCONDdefinition. the default value is@@. overrides the more genericre2c:api:sigilconfiguration πre2c:YYSETCOND:naked,re2c:define:YYSETCONDITION:nakedβ overrides the more genericre2c:api:styleconfiguration forYYSETCOND. a zero value corresponds to free-form API style πre2c:YYSETSTATE,re2c:define:YYSETSTATEβ defines the API primitiveYYSETSTATEre2c:YYSETSTATE@state,re2c:define:YYSETSTATE@stateβ the sigil used for argument substitution in theYYSETSTATEdefinition. the default value is@@. overrides the more genericre2c:api:sigilconfiguration βre2c:YYSETSTATE:naked,re2c:define:YYSETSTATE:nakedβ overrides the more genericre2c:api:styleconfiguration forYYSETSTATE. a zero value corresponds to free-form API style πre2c:YYSETACCEPT,re2c:define:YYSETACCEPTβ defines the API primitiveYYSETACCEPTre2c:YYSKIP,re2c:define:YYSKIPβ defines the generic API primitiveYYSKIPre2c:YYSHIFT,re2c:define:YYSHIFTβ defines the generic API primitiveYYSHIFTre2c:YYCOPYMTAG,re2c:define:YYCOPYMTAGβ defines the generic API primitiveYYCOPYMTAGre2c:YYCOPYSTAG,re2c:define:YYCOPYSTAGβ defines the generic API primitiveYYCOPYSTAGre2c:YYSHIFTMTAG,re2c:define:YYSHIFTMTAGβ defines the generic API primitiveYYSHIFTMTAGre2c:YYSHIFTSTAG,re2c:define:YYSHIFTSTAGβ defines the generic API primitiveYYSHIFTSTAGre2c:YYSTAGN,re2c:define:YYSTAGNβ defines the generic API primitiveYYSTAGNre2c:YYSTAGP,re2c:define:YYSTAGPβ defines the generic API primitiveYYSTAGP
bestie we're not done, the lowercase ones are next π«Ά
re2c:yyaccept,re2c:variable:yyacceptβ defines the API primitiveyyacceptre2c:yybm,re2c:variable:yybmβ defines the API primitiveyybmre2c:yybm:hex,re2c:variable:yybm:hexβ if set to nonzero, bitmaps for the--bit-vectorsoption are generated in hexadecimal format. the default is zero (bitmaps are in decimal format) π’re2c:yych,re2c:variable:yychβ defines the API primitiveyychre2c:yych:emit,re2c:variable:yych:emitβ if set to zero, theyychdefinition is not generated. the default is non-zero πre2c:yych:conversion,re2c:variable:yych:conversionβ if set to non-zero, re2go automatically generates a conversion toYYCTYPEevery single timeyychis read. the default is zero (no conversion) β¨re2c:yych:literals,re2c:variable:yych:literalsβ 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 the others) πre2c:yyctable,re2c:variable:yyctableβ defines the API primitiveyyctablere2c:yynmatch,re2c:variable:yynmatchβ defines the API primitiveyynmatchre2c:yypmatch,re2c:variable:yypmatchβ defines the API primitiveyypmatchre2c:yytarget,re2c:variable:yytargetβ defines the API primitiveyytargetre2c:yystable,re2c:variable:yystableβ deprecated π© like, don't, bestiere2c:yystate,re2c:variable:yystateβ defines the API primitiveyystatere2c:yyfill,re2c:variable:yyfillβ defines the API primitiveyyfillre2c:yyfill:checkβ if set to zero, suppresses the generation of the pre-YYFILLcheck for the number of input characters (that's theYYLESSTHANdefinition in generic API and theYYLIMIT-based comparison in C pointer API). the default is non-zero (generate the check) π¦re2c:yyfill:enableβ if set to zero, suppresses the generation ofYYFILL(together with the check). You should use this when the whole input fits into one piece of memory (there's no need for buffering) and the end-of-input checks don't rely on theYYFILLchecks (e.g. if a sentinel character is used). Use warnings (the-Woption) and there2c:sentinelconfiguration to verify that the generated lexer cannot read past the end of input. the default is non-zero (YYFILLis enabled) β οΈ
fr fr please verify that sentinel situation, reading past the end of input is giving undefined behaviour and we don't stan that
re2c:yyfill:parameterβ if set to zero, 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β the separator used inYYFNelements (defaults to semicolon) β¨re2c:yyfn:throwβ the exceptions thrown by theYYFNfunction (defaults to empty, which means no exceptions) π
β¨ Regular expressions β¨
okay so re2go uses the following syntax for regular expressions, and honestly? it ate π₯
"foo"β case-sensitive string literal'foo'β case-insensitive string literal πΈ[a-xyz],[^a-xyz]β character class (possibly negated).β any character except newlineR \ Sβ difference of character classesRandSR*β zero or more occurrences ofRR+β one or more occurrences ofRR?β optionalRπR{n}β repetition ofRexactlyntimesR{n,}β bestie, this is just R on repeat, at leastntimes. Slay, but make it minimum.R{n,m}β R fromntomtimes. A little range, a little flexibility, we love to see it. π(R)β literally just R, but the parentheses are there to override precedence because sometimes you gotta be louder than the default order of operations. And here's the tea: if submatch extraction is enabled,(R)becomes a capturing or a non-capturing group β which one depends on the--invert-capturesoption. π«Ά(!R)β same energy but reversed: if submatch extraction is enabled,(!R)is a non-capturing or a capturing group, again depending on--invert-captures. Sneaky little flip, iconic. β¨R Sβ concatenation, aka "R followed by S". Simple. Elegant. Main character energy.R | Sβ alternative: R or S. Pick a lane, we support both. πR / Sβ lookahead: R followed by S, but S is not consumed. It's giving "look but don't touch", and honestly? Respect. πnameβ a regular expression defined as name (or, in Flex compatibility mode, the literal string"name"). Same name, different timeline. π«{name}β regular expression defined as name in Flex compatibility mode. The braces are the whole vibe here.@stagβ an s-tag. It saves the last input position at which@stagmatches, into a variable named stag. One position, one moment, no cap. π#mtagβ an m-tag. It saves all input positions at which#mtagmatches, into a variable named mtag. Why pick one when you can collect them all? π$β end of input. The finale. The curtain call. The "okay this is literally the last character" moment. π¬
Also, heads up bestie: 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. Memorize them, they come up constantly. π§
π¬ Actions
Okay so re2go comes with a list of predefined actions, and they're honestly so useful it's giving cheat codes. Here's the whole lineup:
!entry codeβ the entry action. It binds a user-defined block of code to the start state of the current finite state machine. If start conditions are used, you can set the entry action individually for each condition. This is your initialization era β for example, saving the start location of a lexeme. πΈ!pre_rule codeβ the pre-rule action. It 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). Use it to factor out the common part of all your semantic actions β like saving the end location of a lexeme. Because copy-pasting the same three lines into 40 rules is not the vibe. π!post_rule codeβ the post-rule action. It 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). Perfect for emitting trap statements that guard against unintended control flow. Safety first, besties. π
π Directives
And here's the full list of directives re2go supports. Yes, full. We don't skip. π«Ά
!use:name ;β an in-block use directive that merges a previously defined rules block with the specified name into 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 in the usual way: the first rule takes priority, and the latest configuration overrides the preceding ones. One exception though π β the special rules*,$and<!>, for which a block-local definition always takes priority. A use directive can be placed anywhere inside a block, and multiple use directives are allowed. Go off. π!include file ;β this directive is the same as the include block: it inserts the file contents verbatim in place of the directive. No edits, no vibes-based interpretation, just paste. π
π Program interface
So here's how the generated code actually talks to your outer program: through primitives, collectively referred to as the API. Which primitives you need to define for a particular program depends on multiple factors β the complexity of your regular expressions, the input representation, buffering, and the use of various features. All the necessary primitives should be defined by you, in the form of macros, functions, variables, or any other suitable form that makes the generated code syntactically and semantically correct.
β οΈ Real talk: re2go does not (and cannot) check the definitions. So if anything is missing or defined incorrectly, the generated program may have compile-time or run-time errors. This manual provides examples of API definitions in the most common cases β use them, bestie. π
re2go has three API flavors that define the core set of primitives used by a program:
π¬ Simple API
(added in version 4.0) This is a basic API that can be enabled with the --api simple option or the re2c:api = simple configuration. It consists of the following primitives: YYINPUT (which should be defined as a sequence of code units, e.g. a string) and YYCURSOR, YYMARKER, YYCTXMARKER, YYLIMIT (which should be defined as indices in YYINPUT). Low effort, high reward. β¨
π Record API
(added in version 4.0) Record API is useful in cases when 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 fields yyinput, yycursor, yymarker, yyctxmarker, yylimit β and listen, only the fields used by the generated code need to be defined, and their names can be configured. We love a customizable struct. π
𧬠Generic API
This is the most flexible API and the default API for the Go backend. It contains primitives for generic operations: YYPEEK, YYSKIP, YYBACKUP, YYBACKUPCTX, YYSTAGP, YYSTAGN, YYMTAGP, YYMTAGN, YYRESTORE, YYRESTORECTX, YYRESTORETAG, YYSHIFT, YYSHIFTSTAG, YYSHIFTMTAG, YYLESSTHAN, YYEND. Generic API supports two styles that determine the form in which the primitives should be defined:
Free-form β Free-form style is the default one. It can also be enabled with configuration re2c:api:style = free-form. In this style, interface primitives should be defined as free-form pieces of code with interpolated variables of the form @@{var} or optionally just @@ if there is a single variable. The set of variables is specific to each primitive. Here's how free-form generic API can be defined in terms of integer variables cursor, limit, marker, ctxmarker and a string (or a byte slice) data:
/*!re2c
re2c:YYPEEK = "data[cursor]";
re2c:YYSKIP = "cursor++";
re2c:YYBACKUP = "marker = cursor";
re2c:YYRESTORE = "cursor = marker";
re2c:YYBACKUPCTX = "ctxmarker = cursor";
re2c:YYRESTORECTX = "cursor = ctxmarker";
re2c:YYRESTORETAG = "cursor = ${tag}";
re2c:YYLESSTHAN = "limit - cursor < @@{len}";
re2c:YYEND = "limit == cursor";
re2c:YYSTAGP = "@@{tag} = cursor";
re2c:YYSTAGN = "@@{tag} = -1";
re2c:YYSHIFT = "cursor += @@{shift}";
re2c:YYSHIFTSTAG = "@@{tag} += @@{shift}";
*/
Function-like β Function-like style is enabled with configuration re2c:api:style = functions. In this style, primitives should be defined as closures accepting the necessary arguments. Here's how function-like generic API can be defined in terms of integer variables cursor, limit, marker, ctxmarker and a string (or a byte slice) data:
YYPEEK := func() byte { return data[cursor] }
YYSKIP := func() { cursor++ }
YYBACKUP := func() { marker = cursor }
YYRESTORE := func() { cursor = marker }
YYBACKUPCTX := func() { ctxmarker = cursor }
YYRESTORECTX := func() { cursor = ctxmarker }
YYLESSTHAN := func(n int) bool { return limit-cursor < n }
YYEND := func(n int) bool { return limit == cursor }
YYSHIFT := func(n int) { cursor += n }
And now, the full list of API primitives that may be used by the generated code in order to interface with the outer program. Buckle up, bestie, this is the whole roster. π
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, pick correctly. π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. It's always a little ahead of the drama. π¦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 comparesYYCURSORtoYYLIMITin order to determine if there are enough input characters left. The boundary-setter, the limit-definer. β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. Initialization is not needed. It's your undo button, basically. πYYCTXMARKERβ an l-value that stores the position of the trailing context (a pointer or an integer offset inYYINPUT). No initialization is needed.YYCTXMARKERis needed only if the lookahead operator/is used. Conditional queen. πYYFILLβ a generic API primitive with one variablelen.YYFILLshould provide at leastlenmore input characters or fail. Ifre2c:eofis used, thenlenis always 1 andYYFILLshould 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. Big responsibility, tiny parameter. πYYFNβ a primitive that defines the 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 function name and return type (empty for a void function). Subsequent elements define function arguments: first, the expression for the argument used in function body (usually just a name); second, argument type; third, an optional formal parameter (it defaults to the first component β usually both the argument and the parameter are the same identifier). So many components, so little time. π§YYINPUTβ an r-value that stores the current input character sequence (string, buffer, etc.). The whole buffet. πΈYYMAXFILLβ an integral constant that equals the maximum value of the argument you can pass toYYFILL. It can be generated with amaxblock. πYYLESSTHANβ a generic API primitive that takes one variable,len. Define it as an r-value of boolean type that'strueif and only if there are less thanleninput characters left. Basically a "do we have enough left, bestie?" check. β¨YYENDβ a generic API primitive with no variables, defined as an r-value of boolean type that'strueif and only if we've hit the logical end of input (that's excluding any padding or sentinel symbols, okay?).YYENDis what implements the$symbol in regular expressions. It's different fromYYLESSTHANβ that one's the one making sure the lexer won't read past the end of buffer. Two different jobs, both iconic. πYYPEEKβ a generic API primitive with no variables. Define it as an r-value of typeYYCTYPEequal to the character sitting at the current input position. Peekaboo. π¦YYSKIPβ a generic API primitive that should advance the current input position by one code unit. Move it along, nothing to see here. πYYBACKUPβ a generic API primitive that should save the current input position (so you can restore it later withYYRESTORE). β¨YYRESTOREβ a generic API primitive that should restore the current input position to whatever valueYYBACKUPsaved. The comeback is real. πΈYYBACKUPCTXβ a generic API primitive that should save the current input position as the position of the trailing context, to be restored later withYYRESTORECTX. π«ΆYYRESTORECTXβ a generic API primitive that should restore the trailing context position that was saved withYYBACKUPCTX. πYYRESTORETAGβ a generic API primitive with one variable,tag, that should restore the trailing context position to the value oftag. π₯YYSTAGPβ a generic API primitive with one variable,tag, wheretagcan be a pointer or an offset inYYINPUT(peep the submatch extraction section for the details).YYSTAGPshould settagto the current input position. πYYSTAGNβ a generic API primitive with one variable,tag, wheretagcan be a pointer or an offset inYYINPUT(again, submatch extraction section, go look).YYSTAGNshould settagto a value that represents a non-existent input position. πYYMTAGPβ a generic API primitive with one variable,tag.YYMTAGPshould append the current position to the submatch history oftag(see the submatch extraction section for details). βYYMTAGNβ a generic API primitive with one variable,tag.YYMTAGNshould append a value that represents a non-existent input position position to the submatch history oftag(see the submatch extraction section for details). Yes, it says "position position" and yes, we're keeping it. πYYSHIFTβ a generic API primitive with one variable,shift, that should shift the current input position byshiftcharacters. And plot twist: 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 with two variables,lhsandrhs, that should copy the right-hand-side m-tag variablerhsto the left-hand-side m-tag variablelhs. For most languages this primitive has a default definition that assignslhstorhs. Same vibe, m-tag edition. π§YYSHIFTSTAGβ a generic API primitive with two variables,tagandshift, that should shifttagbyshiftcode units (and yep, the shift value may be negative). πYYSHIFTMTAGβ a generic API primitive with two variables,tagandshift, that should shift the latest value in the history oftagbyshiftcode units (negative shift values are allowed here too, bestie). πYYMAXNMATCHβ an integral constant equal to the maximal number of POSIX capturing groups in a rule. It's 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 variable,var, that stores the numeric selector of the accepted rule. For most languages this primitive 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 this primitive has a default definition that assignsvartoval. πYYGETCONDβ an r-value of typeYYCONDTYPEthat's equal to the current condition identifier. πΈYYSETCONDβ a primitive with one variable,cond, that should set the current condition identifier tocond. π«ΆYYGETSTATEβ an r-value of integer type that's equal to the current lexer state. It should be initialized to-1. πYYSETSTATEβ a primitive with one variable,state, that 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 get 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. A 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. The k-Th bit of the n-th element is true iff the n-th code unit is in the range of the k-th transition. The whole idea of this bitmap is replacing a ton ofifbranches orswitchcases with one single bit check in the table. Kind of a slay, honestly. βyychβ an l-value of typeYYCTYPEthat stores the current input character. A user definition is necessary only with the-f--storable-stateoption. πyyctableβ a 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 used to hold the tag values corresponding to the capturing parentheses in the matching rule. The 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 entry. She's retired. πyystateβ an l-value used with the--loop-switchoption to store the current DFA state. πyytargetβ a 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 π
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 the internal options? Those are for experimenting with the algorithms used in re2c. Little lab experiments, we love to see it. π
-?,--help,-hβ show the help message. The "hello, what is this" button. π¦--api <simple | record | generic>β specify the API the generated code uses to interface with user-defined code.simpleβ use it in simple cases when there's no need for buffer refilling and storing lexer state.recordβ use it when lexer state needs to be stored in a record (struct, class, etc.).genericβ use it in complex cases when the other two APIs are just not 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 the 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. Flip it and reverse it. π--case-rangesβ collapse consecutive cases in a switch statement 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. Small code, fast code, iconic. π--computed-gotos,-gβ optimize conditional jumps using the non-standard "computed goto" extension (which has to be supported by the compiler). re2go generates 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 it generates relative offsets for jump tables instead (which, again, must be supported by the compiler). This option implies--computed-gotos. π--conditions,--start-conditions,-cβ enable support of Flex-like "conditions": multiple interrelated lexers within one block. This is an alternative to manually specifying different re2go blocks connected withgotoor function calls. π--depfileFILE β writes dependency info into FILE as a Makefile rule, shaped exactly like<output-file> : <input-file> [include-file ...]. Why do you care? Because it lets you track build deps when include blocks/directives are in play, so touching an include file actually triggers a regen of the output file instead of you sitting there confused why nothing rebuilt π Heads up tho: this option depends on the--outputoption. No output, no depfile, no slay.--ebcdic,--ecb,-eβ makes a lexer that reads input in EBCDIC encoding. re2go assumes the character range is0--0xFFand character size is1byte. Mainframe bestie behavior fr π--empty-class<match-empty | match-none | error> β decides how re2go treats empty character classes. Pick your fighter:match-emptyβ empty class matches empty input. This is the default. Is it illogical? Yes bestie. Is it backwards-compatible? Also yes. Both things can be true π«Άmatch-noneβ empty class always fails to match.errorβ empty class raises a compilation error. Fair honestly.
--encoding-policy<fail | substitute | ignore> β how re2go handles Unicode surrogates:failβ re2go aborts with an error the second it meets a surrogate.substituteβ silently swaps surrogates for the error code point0xFFFD.ignoreβ treats surrogates as normal code points. This is the default. The Unicode standard says standalone surrogates are invalid, but real-world libraries and programs behave in wildly different ways, so likeβ¦ pick based on your chaos tolerance π
--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 you use them they have to be wrapped in curly braces. Names without curly braces get treated as double-quoted strings. Muscle-memory Flex girlies, this one's for you π--goto-labelβ uses the "goto/label" code model: the DFA gets encoded as labeled code blocks connected withgototransitions across blocks. Only works for languages that actually have agotostatement, so don't come crying to me if your language said no ππββοΈ--header,--type-header,-tHEADER β generates a HEADER file. What goes in it? You decide, via the special blocksheader:onandheader:off. And if conditions are used, the generated header gets a condition enum auto-appended to it β unless you wrote an explicitconditionsblock, in which case it respects your art β¨-IPATH β adds PATH to the list of locations searched when looking for include files. This is lowkey iconic in combination with an include block or directive. re2go looks for the FILE in the directory of the parent file and in the include locations you specified with the-Ioption.--input<default | custom> β deprecated alias for--api. Optiondefaultcorresponds tosimple(and it really is the default for most backends β but not for all, so don't @ me). Optioncustomcorresponds togeneric.--input-encoding<ascii | utf8> β how re2go parses your regexes:asciiβ the default. re2go handles input as ASCII-encoded, meaning any sequence of code units is a sequence of standalone 1-byte characters.utf8β re2go handles input as UTF8-encoded and recognizes multibyte characters. Multibyte girlies rise π¦
--invert-capturesβ flips the meaning of capturing vs non-capturing groups. By default(...)is capturing and(! ...)is non-capturing. With this option,(! ...)is capturing and(...)is non-capturing. Full uno-reverse card moment π--lang<none | c | d | go | haskell | java | js | ocaml | python | rust | swift | v | zig> β picks your target language. The supported ones are C, D, Go, Haskell, Java, JS, OCaml, Python, Rust, Swift, V, and Zig (and more can be added via user-defined syntax files β see the--syntaxoption). Optionnonedisables the default syntax configs, which leaves the target language undefined. Spooky but valid π--location-format<gnu | msvc> β how locations show up in messages:gnuβ printed as'filename:line:column: ...'. This one's the default.msvcβ printed as'filename(line,column) ...'.
--loop-switchβ the "loop/switch" code model: DFA encoded as a loop over aswitchstatement, where individual states are the switch cases. State lives in a variable calledyystate. Transitions between states updateyystateto the case label of the destination state and then continue execution back at the head of the loop. Round and round we go π--computed-continueβ requires the--loop-switchcode model (so, prerequisite, no skipping). 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. Efficiency serve π₯--nested-ifs,-sβ uses nestedifstatements instead ofswitchstatements in conditional jumps. Usually that means more efficient code with non-optimizing compilers. Respect the compiler's whole deal π--no-debug-info,-iβ do not output line directives. Genuinely useful when the generated code lives in version control, because otherwise you get huge autogenerated diffs on the tiniest changes and your reviewer will simply pass away π--no-generation-dateβ suppresses date output in the generated file.--no-versionβ suppresses version output in the generated file.--no-unsafeβ don't generate the unsafe wrapper overYYPEEK. This one is Rust-specific, okay? For performance reasonsYYPEEKshould avoid bounds-checking, since the lexer already does end-of-input checks in a way that's more efficient. You can provide a safeYYPEEKdefinition, or one that's unsafe only in release builds β and in that case,--no-unsafehelps you dodge warnings about redundantunsafeblocks. Very thoughtful, very demure π--output,-oOUTPUT β specifies the OUTPUT file. That's it. That's the whole thing.--posix-captures,-Pβ enables submatch extraction with POSIX-style capturing groups. The result gets collected into an arrayyybmatchof capacity2 * YYMAXNMATCH, andyynmatchis set to the number of groups for the matching rule. Arrays of destiny β¨--posix-captvarsβ also enables submatch extraction with POSIX-style capturing groups, but this time the result lands in variablesyytl<k>andyytr<k>for the k-th capturing group. Same energy, different storage container π--recursive-functionsβ code model based on co-recursive functions, where every single DFA state is its own separate function that may call other state-functions or itself. Function inception, but make it lexing π§--reusable,-rβ deprecated since version 2.2. Reusable blocks are allowed by default now, so this flag is just vibing here for historical reasons.--skeleton,-Sβ ignores your 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 get used to verify "skeleton" behavior on all inputs. Extremely useful for finding bugs in optimizations and code generation β like a little stress-test bestie π«Ά But note: supported only for C. C girlies only, sorry to the rest of you π--storable-state,-fβ generates a lexer that can store its inner state. Perfect for push-model lexers, the ones that get stopped by an outer program when there isn't enough input and then resumed once more input shows up. In this mode you also need to define theYYGETSTATEandYYSETSTATEprimitives, and the variablesyych,yyaccept, andstateshould be part of the stored lexer state. Pack it up, save it, come back later πΎ--syntaxFILE β loads configurations from FILE and applies them on top of the default syntax file. Note that FILE can define just a few configurations (great if you're amending the default syntax file), or it can define a whole new language backend β and for that second one it's recommended to use the--lang noneoption. Build your own backend, main character energy π--tags,-Tβ enables submatch extraction with tags.--ucs2,--wide-chars,-wβ lexer that reads UCS2-encoded input. re2go assumes the character range is0--0xFFFFand character size is2bytes. This option implies--nested-ifs.--utf8,--utf-8,-8β lexer that reads input in UTF-8 encoding. re2go assumes the character range is0--0x10FFFFand character size is1byte. The classic, the icon, the default of my heart πΈ--utf16,--utf-16,-xβ lexer that reads UTF16-encoded input. re2go assumes the character range is0--0x10FFFFand character size is2bytes. This option implies--nested-ifs.--utf32,--unicode,-uβ lexer that reads UTF32-encoded input. re2go assumes the character range is0--0x10FFFFand character size is4bytes. This option implies--nested-ifs.--verboseβ outputs a short message in case of success. Just a lil "you did it" π₯Ή--vernum,-Vβ shows version information inMMmmppformat (major, minor, patch). Numbers bestie.--version,-vβ shows version information. Full sentences bestie.--single-pass,-1β deprecated, does nothing. Single pass is the default now. It's giving retired.--debug-output,-dβ emitsYYDEBUGinvocations in the generated code. Super useful for tracing lexer execution, like a little spy cam for your DFA π--dump-adfaβ debug option: outputs the DFA after tunneling, in.dotformat.--dump-cfgβ debug option: outputs the control flow graph of tag variables, in.dotformat.--dump-closure-statsβ debug option: outputs statistics on the number of states in closure.--dump-dfa-detβ debug option: outputs the DFA immediately after determinization, in.dotformat.--dump-dfa-minβ debug option: outputs the DFA after minimization, in.dotformat.--dump-dfa-tagoptβ debug option: outputs the DFA after tag optimizations, in.dotformat.--dump-dfa-treeβ debug option: outputs the DFA under construction with states represented as tag history trees, in.dotformat.--dump-dfa-rawβ debug option: outputs the DFA under construction with expanded state-sets, in.dotformat.--dump-interfβ debug option: outputs the interference table produced by liveness analysis of tag variables.--dump-nfaβ debug option: outputs the NFA, in.dotformat. NFA girlies, this is your moment π¦--emit-dot,-Dβ instead of the normal output, generates the lexer graph in.dotformat. Then you can turn it into an image with a little help from Graphviz, like:
dot -Tpng -odfa.png dfa.dot
Pretty picture of your automaton? We love to see it π
--dfa-minimization<moore | table> β internal option: which DFA minimization algorithm re2go uses.mooreβ the Moore algorithm, and it's the default.tableβ the "table filling" algorithm. Both should produce the same DFA up to states relabeling. Table filling is simpler and much slower, and it serves as a reference implementation. Slow but honest, we respect her π
okay so these next option girlies are all marked internal, meaning they're for the re2go girlies hacking on the tool itself β but bestie, every single detail is still right here, no cap π
--eager-skipβ internal option: make the generated lexer advance the input position eagerly β immediately after reading the input symbol. This changes the default behavior where the input position is advanced lazily β after transition to the next state. β¨--no-lookaheadβ internal option, deprecated. It used to enable the TDFA(0) algorithm. Unlike TDFA(1), the TDFA(0) algorithm does not use one-symbol lookahead. It applies register operations to the incoming transitions rather than the outgoing ones. Benchmarks showed that the TDFA(0) algorithm is less efficient than TDFA(1). π--no-optimize-tagsβ internal option: suppress optimization of tag variables (useful for debugging). π«Ά--posix-closure <gor1 | gtop>β internal option: specify the shortest-path algorithm used for the construction of epsilon-closure with POSIX disambiguation semantics:gor1(the default) stands for the Goldberg-Radzik algorithm, andgtopstands for the βglobal topological orderβ algorithm. πΈ--posix-prectable <complex | naive>β internal option: specify 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; it is the default. Thenaivealgorithm has worst-case cubic complexity in the number of TNFA states, but it is much simpler thancomplexand may be slightly faster in non-pathological cases. π¦--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 that the staDFA algorithm is less efficient than TDFA. π--fixed-tags <none | toplevel | all>β internal option: specify whether the fixed-tag optimization should be applied to all tags (all), none of them (none), or only those in toplevel concatenation (toplevel). The default isall. βFixedβ tags are those that are located within a fixed distance to some other tag (called βbaseβ). In such cases only the base tag needs to be tracked, and the value of the fixed tag can be computed as the value of the base tag plus a static offset. For tags that are under alternative or repetition it is also necessary to check if the base tag has a no-match value (in that case the fixed tag should also be set to no-match, disregarding the offset). For tags in top-level concatenation the check is not needed, because they always match. π₯
β οΈ Warnings β οΈ
Warnings can be individually enabled, disabled and turned into an error, bestie. π
-Wβ turn on all warnings. π-Werrorβ turn warnings into errors. Note that this option alone doesn't turn on any warnings; it only affects those warnings that have been turned on so far or will be turned on later. π-W<warning>β turn on warning. β¨-Wno-<warning>β turn off warning. π-Werror-<warning>β turn on warning and treat it as an error (this implies-W<warning>). π₯-Wno-error-<warning>β don't treat this particular warning as an error. This doesn't turn off the warning itself. π-Wcondition-orderβ warn if the generated program makes implicit assumptions about condition numbering. One should use either the--headeroption or conditions block to generate a mapping of condition names to numbers and then use the autogenerated condition names. π-Wempty-character-classβ warn if a regular expression contains an empty character class. Trying to match an empty character class makes no sense: it should always fail. However, for backwards compatibility reasons re2go permits empty character classes and treats them as empty strings. Use the--empty-classoption to change the default behavior. π-Wmatch-empty-stringβ warn if a rule is nullable (matches an empty string). If the lexer runs in a loop and the empty match is unintentional, the lexer may unexpectedly hang in an infinite loop. π-Wswapped-rangeβ warn if the lower bound of a range is greater than its upper bound. The default behavior is to silently swap the range bounds. π¦-Wundefined-control-flowβ warn if some input strings cause undefined control flow in the lexer (the faulty patterns are reported). This is a dangerous and common mistake. It can be 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β warn about rules that are shadowed by other rules and will never match. πΈ-Wdeprecated-eof_ruleβ warn 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. π«Ά-Wuseless-escapeβ warn if a symbol is escaped when it shouldn't be. By default, re2go silently ignores such escapes, but this may as well indicate a typo or an error in the escape sequence. β¨-Wnondeterministic-tagsβ warn if a tag has n-th degree of nondeterminism, where n is greater than 1. π-Wsentinel-in-midruleβ warn if the sentinel symbol occurs in the middle of a rule β this may cause reads past the end of buffer, crashes or memory corruption in the generated lexer. This warning is only applicable if the sentinel method of checking for the end of input is used. It is set to an error ifre2c:sentinelconfiguration is used. β οΈ-Wundefined-syntax-configβ warn if the syntax file specified with--syntaxoption is missing definitions of some configurations. This helps to maintain user-defined syntax files: if a new release adds configurations, the old syntax file will raise a warning, and the user will be notified. If some configurations are unused and do not need a definition, they should be explicitly set to<undefined>. π§
π§ Syntax files π§
Support for different languages in re2c is based on the idea of syntax files. A syntax file is a configuration file that defines the syntax of the target language β not the whole language, but a small part of it that is used by the generated code. Syntax files make re2c very flexible, but they should not be used as a replacement for re2c: configurations: their purpose is to define the 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 are also embedded in the re2go 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 re2go 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 re2go 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 are 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 like a little recipe made of string literals, variables, optional elements and lists β or a pointer to another code template β or the special value <undefined>. Variables are placeholders that get swapped in during the code generation phase (think: mad-libs but make it compiler). List variables are the β¨specialβ¨ ones: when re2go expands list templates, it repeats the expressions on the right hand side of the colon a few times, each time replacing occurrences of the list variable with a value specific to that repetition. Lists have optional bounds β negative values count from the end, so -1 means the last element, bestie π. Conditional names start with a dot. Both conditionals and variables can be either local (specific to that one code template) or global (allowed in all code templates). When re2go reads the syntax file, it checks that each code template only uses the variables and conditionals that are allowed in it. Rude? No. Helpful π
.
For example, this code template defines an if-then-else construct for a C-like language:
code:if_then_else =
[branch{0}: topindent "if " cond " {" nl
indent [stmt: stmt] dedent]
[branch{1:-1}: topindent "} else" (.cond ? " if " cond) " {" nl
indent [stmt: stmt] dedent]
topindent "}" nl;
So branch here is a list variable: branch{0} expands to the first branch (which is special, because there's no else part), and branch{1:-1} expands to all the remaining branches (if any exist). 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 the full list of all code templates supported by re2go, 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 at 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 at 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 at 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β Definition of an enumeration (it may 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β Enumeration element (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 the 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 the computed goto table. Supported variables:label(the label that is used to initialize the current element),type(underlying type of the elements in the table) 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 the list expression as many times as there are function arguments),argname(name of the current argument),argtype(type of the current argument). Conditional:.type(true if this is a non-void function).code:fndefβ 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 the 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 the 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(re2go version that was used to generate this) anddate(generation date).
okay continuing the syntax-file tour, bestie β these are the code: knobs that tell re2c exactly what code to spit out for each DFA move β¨
code:line_infoβ the format of line directives (and if this is set to<undefined>, literally no directives get generated, periodt). Supported variables:line(the line number) andfile(the filename).code:abortβ a statement that aborts program execution. dramatic but valid πcode:yydebugβ theYYDEBUGstatement, possibly specialized for different APIs. Supported variables:YYDEBUG,yyrecord,yych(these map to the correspondingre2c:configurations), andstate(the DFA state number).code:yypeekβ theYYPEEKstatement, possibly specialized for different APIs. Supported variables:YYPEEK,YYCTYPE,YYINPUT,YYCURSOR,yyrecord,yych(all mapping to the correspondingre2c:configurations). Conditionals:.cast(true ifre2c:yych:conversionis set to non-zero).code:yyskipβ theYYSKIPstatement, possibly specialized for different APIs. Supported variables:YYSKIP,YYCURSOR,yyrecord(mapping to the correspondingre2c:configurations).code:yybackupβ theYYBACKUPstatement, possibly specialized for different APIs. Supported variables:YYBACKUP,YYCURSOR,YYMARKER,yyrecord(mapping to the correspondingre2c:configurations).code:yybackupctxβ theYYBACKUPCTXstatement, possibly specialized for different APIs. Supported variables:YYBACKUPCTX,YYCURSOR,YYCTXMARKER,yyrecord(mapping to the correspondingre2c:configurations).code:yyskip_yypeekβ the combinedcode:yyskipandcode:yypeekstatement (defaults tocode:yyskipfollowed bycode:yypeek).code:yypeek_yyskipβ the combinedcode:yypeekandcode:yyskipstatement (defaults tocode:yypeekfollowed bycode:yyskip).code:yyskip_yybackupβ the combinedcode:yyskipandcode:yybackupstatement (defaults tocode:yyskipfollowed bycode:yybackup).code:yybackup_yyskipβ the combinedcode:yybackupandcode:yyskipstatement (defaults tocode:yybackupfollowed bycode:yyskip).code:yybackup_yypeekβ the combinedcode:yybackupandcode:yypeekstatement (defaults tocode:yybackupfollowed bycode:yypeek).code:yyskip_yybackup_yypeekβ the combinedcode:yyskip,code:yybackupandcode:yypeekstatement (defaults tocode:yyskipfollowed bycode:yybackupfollowed bycode:yypeek).code:yybackup_yypeek_yyskipβ the combinedcode:yybackup,code:yypeekandcode:yyskipstatement (defaults tocode:yybackupfollowed bycode:yypeekfollowed bycode:yyskip).code:yyrestoreβ theYYRESTOREstatement, possibly specialized for different APIs. Supported variables:YYRESTORE,YYCURSOR,YYMARKER,yyrecord(mapping to the correspondingre2c:configurations).code:yyrestorectxβ theYYRESTORECTXstatement, possibly specialized for different APIs. Supported variables:YYRESTORECTX,YYCURSOR,YYCTXMARKER,yyrecord(mapping to the correspondingre2c:configurations).code:yyrestoretagβ theYYRESTORETAGstatement, possibly specialized for different APIs. Supported variables:YYRESTORETAG,YYCURSOR,yyrecord(mapping to the correspondingre2c:configurations), andtag(the name of the tag variable used to restore the position).code:yyshiftβ theYYSHIFTstatement, possibly specialized for different APIs. Supported variables:YYSHIFT,YYCURSOR,yyrecord(mapping to the correspondingre2c:configurations), andoffset(the number of code units to shift the current position).code:yyshiftstagβ theYYSHIFTSTAGstatement, possibly specialized for different APIs. Supported variables:YYSHIFTSTAG,yyrecord,negative(mapping 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(mapping 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(mapping to the correspondingre2c:configurations), andtag(the tag variable that should be updated).code:yymtagpβ theYYMTAGPstatement, possibly specialized for different APIs. Supported variables:YYMTAGP(mapping 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(mapping to the correspondingre2c:configurations), andtag(the tag variable that should be updated).code:yymtagnβ theYYMTAGNstatement, possibly specialized for different APIs. Supported variables:YYMTAGN(mapping to the correspondingre2c:configuration) andtag(the tag variable that should be updated).code:yycopystagβ theYYCOPYSTAGstatement, possibly specialized for different APIs. Supported variables:YYCOPYSTAG,yyrecord(mapping to the correspondingre2c:configurations),lhs, andrhs(the left and right hand side tag variables of the copy operation).code:yycopymtagβ theYYCOPYMTAGstatement, possibly specialized for different APIs. Supported variables:YYCOPYMTAG,yyrecord(mapping to the correspondingre2c:configurations),lhs, andrhs(the left and right hand side tag variables of the copy operation).code:yygetacceptβ theYYGETACCEPTstatement, possibly specialized for different APIs. Supported variables:YYGETACCEPT,yyrecord(mapping to the correspondingre2c:configurations), andvar(mapping to there2c:yyacceptconfiguration).code:yysetacceptβ theYYSETACCEPTstatement, possibly specialized for different APIs. Supported variables:YYSETACCEPT,yyrecord(mapping to the correspondingre2c:configurations),var(mapping to there2c:yyacceptconfiguration), andval(the numeric value of the accepted rule).code:yygetcondβ theYYGETCONDstatement, possibly specialized for different APIs. Supported variables:YYGETCOND,yyrecord(mapping to the correspondingre2c:configurations), andvar(mapping to there2c:yycondconfiguration).code:yysetcondβ theYYSETCONDstatement, possibly specialized for different APIs. Supported variables:YYSETCOND,yyrecord(mapping to the correspondingre2c:configurations),var(mapping to there2c:yycondconfiguration), andval(the numeric condition identifier).code:yygetstateβ theYYGETSTATEstatement, possibly specialized for different APIs. Supported variables:YYGETSTATE,yyrecord(mapping to the correspondingre2c:configurations), andvar(mapping to there2c:yystateconfiguration).code:yysetstateβ theYYSETSTATEstatement, possibly specialized for different APIs. Supported variables:YYSETSTATE,yyrecord(mapping to the correspondingre2c:configurations),var(mapping to there2c:yystateconfiguration), andval(the state number).code:yylessthanβ theYYLESSTHANstatement, possibly specialized for different APIs. Supported variables:YYLESSTHAN,YYCURSOR,YYLIMIT,yyrecord(mapping 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,YYLIMIT.code:yybm_filterβ the condition used to filter outyychvalues that are not covered by theyybmtable (used with the--bitmapsoption). Supported variable:yych(mapping to there2c:yychconfiguration).code:yybm_matchβ the format of theyybmtable check (generated with the--bitmapsoption). Supported variables:yybm,yych(mapping to the correspondingre2c:configurations),offset(the offset in theyybmtable that needs to be added toyych), andmask(the 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 used to filter outyychvalues that are not covered by theyytargettable (used with the--computed-gotosoption). Supported variable:yych(mapping to there2c:yychconfiguration).
and here's the full guest list of global variables you're allowed to use in syntax files π
nlβ a newline.indentβ a variable that doesn't produce any code, but has the side-effect of increasing the indentation level.dedentβ a variable that doesn't produce any code, but has the side-effect of decreasing the indentation level.topindentβ the indentation string for the current statement. The indentation level is tracked and automatically updated by the code generator.
and the global conditionals β the vibe-check booleans that let a syntax file ask "which API are we even in?" π¦
.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βTrueif the code model is based on goto/label (the--goto-labellife)..code_model.loop_switchβTrueif the code model is based on loop/switch (--loop-switch)..code_model.recursive_functionsβTrueif the code model is based on recursive functions (--recursive-function)..dateβTrueif the generated fingerprint should contain the generation date..loop_labelβTrueif re2go-generated loops must have a label (re2c:label:yyloopis set to a nonempty string)..monadicβTrueif the generated code should be monadic (re2c:monadic = 1). This is only relevant for pure functional languages, bestie..start_conditionsβTrueif start conditions are enabled (--start-conditions)..storable_stateβTrueif storable state is enabled (--storable-state)..unsafeβTrueif re2go should 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βTrueif the generated fingerprint should contain the re2go version..yyfill.enableβTrueifYYFILLis enabled (re2c:yyfill:enable = 1)..yyfn.throwβTrueifre2c:yyfn:throwconfiguration is defined to a nonempty string.
π HANDLING THE END OF INPUT π
Okay so one of the main character problems for the lexer is knowing when to stop. There are a few terminating conditions, fr fr:
- 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. re2go 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. This method is generic: it allows one to handle any input without restrictions on the regular expressions. The idea is to reduce the number of end-of-input checks by performing them only on certain characters. Similar to the "sentinel" method, one of the characters is chosen as a "sentinel" and appended at the end of input. However, there is no restriction on where the sentinel may occur (in fact, any character can be chosen for a sentinel). When the lexer reads this character, it additionally performs a bounds check. If the current position is within bounds, the lexer resumes matching and handles the sentinel as a regular character. Otherwise it invokes
YYFILL(unless it is disabled). If more input is supplied, the lexer will rematch the last character and continue as if the sentinel wasn't there. Otherwise it must be the real end of input, and the lexer stops. This method is used whenre2c:eofhas non-negative value (it should be set to the numeric value of the sentinel).YYFILLis optional. - Bounds checks with padding. This method is generic, and it may be faster than the "sentinel with bounds checks" method, but it is also more complex. The idea is to partition DFA states into strongly connected components (SCCs) and generate a single check per SCC for enough characters to cover the longest non-looping path in this SCC. This reduces the number of checks, but there is a problem with short lexemes at the end of input, as the check requires enough characters to cover the longest lexeme. This can be fixed by padding the input with a few fake characters that do not form a valid lexeme suffix (so that the lexer cannot match them). The length of padding should be
YYMAXFILL, generated with a max block. If there is not enough input, the lexer invokesYYFILLwhich should supply at least the required number of characters or not return. This method is used ifYYFILLis enabled andre2c:eofis-1(this is the default configuration). - Custom checks. Generic API allows one to override basic operations like reading a character, which makes it possible to include the end-of-input checks as part of them. This approach is error-prone and should be used with caution. To use a custom method, enable generic API with
--api customorre2c:api = custom;and disable default bounds checks withre2c:yyfill:enable = 0;orre2c:yyfill:check = 0;.
The following subsections contain an example of each method. π«Ά
π Sentinel
This example uses a sentinel character to handle the end of input. The program counts space-separated words in a null-terminated string. The sentinel is null: it is the last character of each input string, and it is not allowed in the middle of a lexeme by any of the rules (in particular, it is not included in character ranges where it is easy to overlook). If a null occurs in the middle of a string, it is a syntax error and the lexer will match default rule *, but it won't read past the end of input or crash (use -Wsentinel-in-midrule warning and re2c:sentinel configuration to verify this). Configuration re2c:yyfill:enable = 0; suppresses the generation of bounds checks and YYFILL invocations.
//go:generate re2go $INPUT -o $OUTPUT --api simple
package main
// Expect a null-terminated string.
func lex(yyinput string) int {
yycursor := 0
count := 0
for { /*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
* { return -1 }
[\x00] { return count }
[a-z]+ { count += 1; continue }
[ ]+ { continue }
*/
}
}
func main() {
assert_eq := func(x, y int) { if x != y { panic("error") } }
assert_eq(lex("\000"), 0)
assert_eq(lex("one two three\000"), 3)
assert_eq(lex("f0ur\000"), -1)
}
π Sentinel with bounds checks
This example uses sentinel with bounds checks to handle the end of input (this method was added in version 1.2). The program counts space-separated single-quoted strings. The sentinel character is null, which is specified with re2c:eof = 0; configuration. As in the sentinel method, null is the last character of each input string, but it is allowed in the middle of a rule (for example, 'aaa\0aa'\0 is valid input, but 'aaa\0 is a syntax error). Bounds checks are generated in each state that matches an input character, but they are scoped to the branch that handles null. Bounds checks are of the form YYLIMIT <= YYCURSOR or YYLESSTHAN(1) with generic API. If the check condition is true, lexer has reached the end of input and should stop (YYFILL is disabled with re2c:yyfill:enable = 0; as the input fits into one buffer, see the YYFILL with sentinel section for an example that uses YYFILL). Reaching the end of input opens three possibilities: if the lexer is in the initial state it will match the end-of-input rule $, otherwise it may fallback to a previously matched rule (including default rule *) or go to a default state, causing -Wundefined-control-flow.
//go:generate re2go $INPUT -o $OUTPUT --api simple
package main
// Expects a null-terminated string.
func lex(yyinput string) int {
var yycursor, yymarker int
yylimit := len(yyinput) - 1 // lim points at the terminating null
count := 0
for { /*!re2c
re2c:YYCTYPE = byte;
re2c:yyfill:enable = 0;
re2c:eof = 0;
str = ['] ([^'\\] | [\\][^])* ['];
* { return -1 }
$ { return count }
str { count += 1; continue }
[ ]+ { continue }
*/
}
}
func main() {
assert_eq := func(x, y int) { if x != y { panic("error") } }
assert_eq(lex("\000"), 0)
assert_eq(lex("'qu\000tes' 'are' 'fine: \\'' \000"), 3)
assert_eq(lex("'unterminated\\'\000"), -1)
}
π Bounds checks with padding
This example uses bounds checks with padding to handle the end of input (this method is enabled by default). The program counts space-separated single-quoted strings. There is a padding of YYMAXFILL null characters appended at the end of input, where YYMAXFILL value is autogenerated with a max block. It is not necessary to use null for padding --- any characters can be used as long as they do not form a valid lexeme suffix (in this example padding should not contain single quotes, as they may be mistaken for a suffix of a single-quoted string). There is a "stop" rule that matches the first padding character (null) and terminates the lexer (note that it checks if null is at the beginning of padding, otherwise it is a syntax error). Bounds checks are generated only in some states that are determined by the strongly connected components of the underlying automaton. Checks have the form (YYLIMIT - YYCURSOR) < n or YYLESSTHAN(n) with generic API, where n is the minimum number of characters that are needed for the lexer to proceed (it also means that the next bounds check will occur in at most n characters). If the check condition is true, the lexer has reached the end of input and will invoke YYFILL(n) that should either supply at least n input characters or not return. In this example YYFILL always fails and terminates the lexer with an error (which is fine because the input fits into one buffer). See the YYFILL with padding section for an example that refills the input buffer with YYFILL. π«Ά
//go:generate re2go $INPUT -o $OUTPUT --api simple
package main
import "strings"
/*!max:re2c*/
// Expects YYMAXFILL-padded string.
func lex(str string) int {
// Pad string with YYMAXFILL zeroes at the end.
yyinput := str + strings.Repeat("\000", int(YYMAXFILL))
yycursor := 0
yylimit := len(yyinput)
count := 0
for { /*!re2c
re2c:YYCTYPE = byte;
re2c:YYFILL = "return -1";
str = ['] ([^'\\] | [\\][^])* ['];
[\x00] {
// Check that it is the sentinel, not some unexpected null.
if yycursor - 1 == len(str) { return count } else { return -1 }
}
str { count += 1; continue }
[ ]+ { continue }
* { return -1 }
*/
}
}
func main() {
assert_eq := func(x, y int) { if x != y { panic("error") } }
assert_eq(lex(""), 0)
assert_eq(lex("'qu\000tes' 'are' 'fine: \\'' "), 3)
assert_eq(lex("'unterminated\\'"), -1)
assert_eq(lex("'unexpected \000 null\\'"), -1)
}
π«Ά Custom checks π«Ά
Okay so this one is a whole different vibe β it uses a custom end-of-input handling method, built on top of the generic API. π The program counts space-separated single-quoted strings, bestie, and it's literally the same as the sentinel example except β plot twist β the input is not null-terminated.
So how do we cover up for the absence of that little sentinel character at the end of input? We redefine YYPEEK so it does a bounds check before it reads the next input character. π
And yes, this is inefficient because the checks happen very often β ngl, it's giving "works but at what cost". If the check condition fails, YYPEEK returns the real character; otherwise it returns a fake sentinel character. π§
//go:generate re2go $INPUT -o $OUTPUT
package main
// Returns "fake" terminating null if cursor has reached limit.
func peek(str string, cur int) byte {
if cur >= len(str) {
return 0 // fake null
} else {
return str[cur]
}
}
// Expects a string without terminating null.
func lex(str string) int {
var cur int
count := 0
for { /*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
re2c:YYPEEK = "peek(str, cur)";
re2c:YYSKIP = "cur += 1";
* { return -1 }
[\x00] { return count }
[a-z]+ { count += 1; continue }
[ ]+ { continue }
*/
}
}
func main() {
assert_eq := func(x, y int) { if x != y { panic("error") } }
assert_eq(lex(""), 0)
assert_eq(lex("one two three"), 3)
assert_eq(lex("f0ur"), -1)
}
π BUFFER REFILLING π
So the need for buffering arises when the input cannot be mapped in memory all at once β either it's too large, or it comes in a streaming fashion (like reading from a socket π¦). The usual technique in such cases is to allocate a fixed-sized memory buffer and process input in chunks that fit into the buffer. When the current chunk is processed, it's moved out and new data is moved in. β¨
In practice it's somewhat more complex, because β and this is the part that gets people β lexer state is not just a single input position, it's a whole set of interrelated positions. It's giving group project where everyone has to stay in sync π:
- cursor: the next input character to be read (
YYCURSORin C pointer API orYYSKIP/YYPEEKin generic API) - limit: the position after the last available input character (
YYLIMITin C pointer API, implicitly handled byYYLESSTHANin generic API) - marker: the position of the most recent match, if any (
YYMARKERin default API orYYBACKUP/YYRESTOREin generic API) - token: the start of the current lexeme (implicit in re2go API, as 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 C pointer API orYYBACKUPCTX/YYRESTORECTXin generic API) - tag variables: submatch positions (defined with
stagsandmtagsblocks and 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, therefore everything between buffer start and token can be discarded, the segment from token and up to limit should be moved to the beginning of buffer, and the free space at the end of buffer should be filled with new data. π In order to avoid frequent YYFILL calls it's best to fill in as many input characters as possible (even though fewer characters might suffice to resume the lexer β yes, we're being extra, and that's the point π).
The details of YYFILL implementation are slightly different depending on which EOF handling method is used: the case of EOF rule is somewhat simpler than the case of bounds-checking with padding. Also note that if -f --storable-state option is used, YYFILL has slightly different semantics (described in the section about storable state β go read that one, bestie π«Ά).
β YYFILL with sentinel β
If EOF rule is used, YYFILL is a function-like primitive that accepts no arguments and returns a value which is checked against zero. YYFILL invocation is triggered by condition YYLIMIT <= YYCURSOR in C pointer API and YYLESSTHAN() in generic API. A non-zero return value means that YYFILL has failed. π
A successful YYFILL call must supply at least one character and adjust input positions accordingly. limit must always be set to one after the last input position in buffer, and the character at the limit position must be the sentinel symbol specified by re2c:eof configuration. π
The pictures below show the relative locations of input positions in buffer before and after YYFILL call (sentinel symbol is marked with #, and the second picture shows the case when there isn't enough input to fill the whole buffer β no cap, that happens fr fr).
<-- 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 input file input.txt in chunks of 4096 bytes and uses EOF rule. Obsessed with this one honestly π
//go:generate re2go $INPUT -o $OUTPUT
package main
import (
"os"
"strings"
)
const BUFSIZE uint = 4096
type Input struct {
file *os.File
yyinput []byte
yycursor uint
yymarker uint
yylimit uint
token uint
eof bool
}
func fill(in *Input) int {
if in.eof { return -1 } // unexpected EOF
// Error: lexeme too long. In real life can reallocate a larger buffer.
if in.token < 1 { return -2 }
// Shift buffer contents (discard everything up to the current token).
copy(in.yyinput[0:], in.yyinput[in.token:in.yylimit])
in.yycursor -= in.token
in.yymarker -= in.token
in.yylimit -= in.token
in.token = 0
// Fill free space at the end of buffer with new data from file.
n, _ := in.file.Read(in.yyinput[in.yylimit:BUFSIZE])
in.yylimit += uint(n)
in.yyinput[in.yylimit] = 0
// If read less than expected, this is the end of input.
in.eof = in.yylimit < BUFSIZE
return 0
}
func lex(yyrecord *Input) int {
count := 0
for {
yyrecord.token = yyrecord.yycursor
/*!re2c
re2c:api = record;
re2c:eof = 0;
re2c:YYCTYPE = byte;
re2c:YYFILL = "fill(yyrecord) == 0";
str = ['] ([^'\\] | [\\][^])* ['];
* { return -1 }
$ { return count }
str { count += 1; continue }
[ ]+ { continue }
*/
}
}
func main() () {
fname := "input"
content := "'qu\000tes' 'are' 'fine: \\'' ";
// Prepare input file: a few times the size of the buffer, containing
// strings with zeroes and escaped quotes.
f, _ := os.Create(fname)
f.WriteString(strings.Repeat(content, int(BUFSIZE)))
f.Seek(0, 0)
count := 3 * int(BUFSIZE) // number of quoted strings written to file
// Prepare lexer state: all offsets are at the end of buffer.
in := &Input{
file: f,
// Sentinel at `yylimit` offset is set to zero, which triggers YYFILL.
yyinput: make([]byte, BUFSIZE+1),
yycursor: BUFSIZE,
yymarker: BUFSIZE,
yylimit: BUFSIZE,
token: BUFSIZE,
eof: false,
}
// Run the lexer.
if lex(in) != count { panic("error"); }
// Cleanup: remove input file.
f.Close();
os.Remove(fname);
}
πΈ YYFILL with padding πΈ
In the default case (when EOF rule isn't used) YYFILL is a function-like primitive that accepts a single argument and does not return any value. π
YYFILL invocation is triggered by condition (YYLIMIT - YYCURSOR) < n in C pointer API and YYLESSTHAN(n) in generic API. The argument passed to YYFILL is the minimal number of characters that must be supplied. π
If it fails to do so, YYFILL must not return to the lexer β for that reason it's best implemented as a macro that returns from the calling function on failure. Like, don't come back, it's not safe π.
In case of a successful YYFILL invocation the limit position must be set either to one after the last input position in buffer, or to the end of YYMAXFILL padding (in case YYFILL has successfully read at least n characters, but not enough to fill the entire buffer). β¨
The pictures below show the relative locations of input positions in buffer before and after YYFILL invocation (YYMAXFILL padding on the second picture is marked with # symbols).
<-- shift --> <-- need -->
>-A------------B---------C-----D-------E---F--------G->
buffer token marker cursor limit
>-A------------B---------C-----D-------E---F--------G->
buffer, marker cursor limit
token
okay so the buffer visual is giving this:
<-- 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 input file input.txt in chunks of 4096 bytes and uses bounds-checking with padding.
//go:generate re2go $INPUT -o $OUTPUT
package main
import (
"os"
"strings"
)
/*!max:re2c*/
const BUFSIZE uint = 4096
type Input struct {
file *os.File
yyinput []byte
yycursor uint
yylimit uint
token uint
eof bool
}
func fill(in *Input, need uint) int {
if in.eof { return -1 } // unexpected EOF
// Error: lexeme too long. In real life can reallocate a larger buffer.
if in.token < need { return -2 }
// Shift buffer contents (discard everything up to the current token).
copy(in.yyinput[0:], in.yyinput[in.token:in.yylimit])
in.yycursor -= in.token
in.yylimit -= in.token
in.token = 0
// Fill free space at the end of buffer with new data from file.
n, _ := in.file.Read(in.yyinput[in.yylimit:BUFSIZE])
in.yylimit += uint(n)
// 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 in.yylimit < BUFSIZE {
in.eof = true
for i := uint(0); i < YYMAXFILL; i += 1 { in.yyinput[in.yylimit+i] = 0 }
in.yylimit += YYMAXFILL
}
return 0
}
func lex(yyrecord *Input) int {
count := 0
for {
yyrecord.token = yyrecord.yycursor
/*!re2c
re2c:api = record;
re2c:YYCTYPE = byte;
re2c:YYFILL = "if r := fill(yyrecord, @@); r != 0 { return r }";
str = ['] ([^'\\] | [\\][^])* ['];
[\x00] {
// Check that it is the sentinel, not some unexpected null.
if yyrecord.token == yyrecord.yylimit - YYMAXFILL { return count } else { return -1 }
}
str { count += 1; continue }
[ ]+ { continue }
* { return -1 }
*/
}
}
func main() () {
fname := "input"
content := "'qu\000tes' 'are' 'fine: \\'' ";
// Prepare input file: a few times the size of the buffer, containing
// strings with zeroes and escaped quotes.
f, _ := os.Create(fname)
f.WriteString(strings.Repeat(content, int(BUFSIZE)))
f.Seek(0, 0)
count := 3 * int(BUFSIZE) // number of quoted strings written to file
// Prepare lexer state: all offsets are at the end of buffer.
// This immediately triggers YYFILL, as the YYLESSTHAN condition is true.
in := &Input{
file: f,
yyinput: make([]byte, BUFSIZE+YYMAXFILL),
yycursor: BUFSIZE,
yylimit: BUFSIZE,
token: BUFSIZE,
eof: false,
}
// Run the lexer.
if lex(in) != count { panic("error"); }
// Cleanup: remove input file.
f.Close();
os.Remove(fname);
}
π FEATURES π
π¦ Multiple blocks π¦
Sometimes you literally need multiple interrelated lexers, bestie β like when there's a high-level state machine bopping between lexer modes. You can do this with multiple connected re2go blocks. Another option is start conditions.
How the connections between blocks actually work depends on the target language. In languages that have a goto statement (such as C/C++ and Go), you can have all blocks in one function, each one prefixed with a label, and transitioning from one block to another is just a simple goto. In languages that don't have goto (such as Rust), you need to use a loop with a switch on a state variable β similar to the yystate loop/switch that re2go generates β or else wrap each block in a function and use function calls.
The example below uses multiple blocks to parse binary, octal, decimal and hexadecimal numbers. Each base has its own block. The initial block determines the base and dispatches to the other blocks. Common configurations are defined in a separate block at the beginning of the program; they are inherited by the other blocks.
//go:generate re2go $INPUT -o $OUTPUT -i --api simple
package main
import "errors"
const u32Limit uint64 = 1<<32
var (
eSyntax = errors.New("syntax error")
eOverflow = errors.New("overflow error")
)
func parse_u32(yyinput string) (uint32, error) {
var yycursor, yymarker int
result := uint64(0)
add := func(base uint64, offset byte) {
result = result * base + uint64(yyinput[yycursor-1] - offset)
if result >= u32Limit {
result = u32Limit
}
}
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
end = "\x00";
'0b' / [01] { goto bin }
"0" { goto oct }
"" / [1-9] { goto dec }
'0x' / [0-9a-fA-F] { goto hex }
* { goto err }
*/
bin:
/*!re2c
end { goto end }
[01] { add(2, '0'); goto bin }
* { goto err }
*/
oct:
/*!re2c
end { goto end }
[0-7] { add(8, '0'); goto oct }
* { goto err }
*/
dec:
/*!re2c
end { goto end }
[0-9] { add(10, '0'); goto dec }
* { goto err }
*/
hex:
/*!re2c
end { goto end }
[0-9] { add(16, '0'); goto hex }
[a-f] { add(16, 'a'-10); goto hex }
[A-F] { add(16, 'A'-10); goto hex }
* { goto err }
*/
end:
if result < u32Limit {
return uint32(result), nil
} else {
return 0, eOverflow
}
err:
return 0, eSyntax
}
func main() {
test := func(num uint32, str string, err error) {
if n, e := parse_u32(str); !(n == num && e == err) {
panic("error")
}
}
test(1234567890, "1234567890\000", nil)
test(13, "0b1101\000", nil)
test(0x7fe, "0x007Fe\000", nil)
test(0644, "0644\000", nil)
test(0, "9999999999\000", eOverflow)
test(0, "123??\000", eSyntax)
}
πΈ Start conditions πΈ
Start conditions are enabled with the --start-conditions option. They give you a way to encode multiple interrelated automata inside the same re2go block. π
Each condition corresponds to a single automaton and has a unique name specified by the user and a unique internal number defined by re2go. Those numbers are used to switch between conditions: the generated code uses YYGETCOND and YYSETCOND primitives to get the current condition or set it to the given number. Use conditions block, the --header option or the re2c:header configuration to generate numeric condition identifiers. Configuration re2c:cond:enumprefix specifies the generated identifier prefix.
In condition mode every rule must be prefixed with a list of comma-separated condition names in angle brackets, or a wildcard <*> to denote all conditions. The rule syntax is extended as follows:
< condition-list > regular-expression codeβ a rule that is merged to every condition on thecondition-list. It matchesregular-expressionand executes the associatedcode.< condition-list > regular-expression => condition codeβ a rule that is merged to every condition on thecondition-list. It matchesregular-expression, sets the current condition toconditionand executes the associatedcode.< condition-list > regular-expression :=> conditionβ a rule that is merged to every condition on thecondition-list. It matchesregular-expressionand immediately transitions tocondition(there is no semantic action).< condition-list > !action codeβ a rule that bindscodeto the place defined byactionin every condition on thecondition-list(see the actions section for various types of actions).<! condition-list > codeβ a rule that prependscodeto semantic actions of all rules for every condition on thecondition-list. This syntax is deprecated and the!pre_ruleaction should be used instead (it does exactly the same).< > codeβ a rule that creates a special entry condition with number zero and name"0"that executescodebefore jumping to other conditions. This syntax is deprecated, and the!entryaction should be used instead (it provides a more fine-grained control, as the code can be specified on a per-condition basis, and one can jump directly to condition start without going through condition dispatch).< > => condition codeβ same as the previous rule, except that it sets the next condition.< > :=> conditionβ same as the previous rule, except that it has no associated code and immediately jumps tocondition.
The code re2go generates for conditions depends on whether re2go uses the goto/label approach or the loop/switch approach to encode the automata.
So, in languages that have a goto statement (such as C/C++ and Go π), conditions are naturally implemented as blocks of code prefixed with labels of the form yyc_<cond>, where cond is a condition name β and yes, that label prefix can be changed with re2c:cond:prefix. Transitions between conditions are implemented using goto and condition labels. Before all conditions, re2go 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 be used to change the default behavior). Rules with semantic actions do not automatically jump to the next condition β that should be done by your user-defined action code, bestie. π
In languages that do not have goto (such as Rust), re2go reuses the yystate variable to store condition numbers. Each condition gets a numeric identifier equal to the number of its start state, and a switch between conditions is no different than a switch between DFA states of a single condition. There is no need for a separate initial condition switch. (Since the same approach is used to implement storable states, YYGETCOND/YYSETCOND are redundant if both storable states and conditions are used.)
The program below uses start conditions to parse binary, octal, decimal and hexadecimal numbers. There is a single block where each base has its own condition, and the initial condition is connected to all of them. User-defined variable cond stores the current condition number; it is initialized to the number of the initial condition generated with the conditions block. π
//go:generate re2go -c $INPUT -o $OUTPUT -i --api simple
package main
import "errors"
var (
eSyntax = errors.New("syntax error")
eOverflow = errors.New("overflow error")
)
/*!conditions:re2c*/
const u32Limit uint64 = 1<<32
func parse_u32(yyinput string) (uint32, error) {
var yycursor, yymarker int
result := uint64(0)
yycond := yycinit
add := func(base uint64, offset byte) {
result = result * base + uint64(yyinput[yycursor-1] - offset)
if result >= u32Limit {
result = u32Limit
}
}
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
re2c:YYGETCOND = "cond";
re2c:YYSETCOND = "cond = @@";
<*> * { return 0, eSyntax }
<init> '0b' / [01] :=> bin
<init> "0" :=> oct
<init> "" / [1-9] :=> dec
<init> '0x' / [0-9a-fA-F] :=> hex
<bin, oct, dec, hex> "\x00" {
if result < u32Limit {
return uint32(result), nil
} else {
return 0, eOverflow
}
}
<bin> [01] { add(2, '0'); goto yyc_bin }
<oct> [0-7] { add(8, '0'); goto yyc_oct }
<dec> [0-9] { add(10, '0'); goto yyc_dec }
<hex> [0-9] { add(16, '0'); goto yyc_hex }
<hex> [a-f] { add(16, 'a'-10); goto yyc_hex }
<hex> [A-F] { add(16, 'A'-10); goto yyc_hex }
*/
}
func main() {
test := func(num uint32, str string, err error) {
if n, e := parse_u32(str); !(n == num && e == err) {
panic("error")
}
}
test(1234567890, "1234567890\000", nil)
test(13, "0b1101\000", nil)
test(0x7fe, "0x007Fe\000", nil)
test(0644, "0644\000", nil)
test(0, "9999999999\000", eOverflow)
test(0, "123??\000", eSyntax)
}
πΎ Storable state
With the --storable-state option, re2go generates a lexer that can store its current state, return to the caller, and later resume operations exactly where it left off. The default mode of operation in re2go is a βpullβ model, in which the lexer βpullsβ more input whenever it needs it. This may be unacceptable in cases when the input becomes available piece by piece β for example, if the lexer is invoked by the parser, or if the lexer program communicates via a socket protocol with some other program that must wait for a reply from the lexer before it transmits the next message. Storable state is intended exactly for such cases: it lets you generate lexers that work in a βpushβ model. When the lexer needs more input, it stores its state and returns to the caller. Later, when more input becomes available, the caller resumes the lexer exactly where it stopped. 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. π¦
//go:generate re2go -f $INPUT -o $OUTPUT
package main
import (
"fmt"
"os"
)
// Use a small buffer to cover the case when a lexeme doesn't fit.
// In real world use a larger buffer.
const BUFSIZE int = 10
type State struct {
file *os.File
yyinput []byte
yycursor int
yymarker int
yylimit int
token int
yystate int
}
const (
lexEnd = iota
lexReady
lexWaitingForInput
lexPacketBroken
lexPacketTooBig
)
func fill(st *State) int {
shift := st.token
used := st.yylimit - st.token
free := BUFSIZE - used
// Error: no space. In real life can reallocate a larger buffer.
if free < 1 { return lexPacketTooBig }
// Shift buffer contents (discard already processed data).
copy(st.yyinput[0:], st.yyinput[shift:shift+used])
st.yycursor -= shift
st.yymarker -= shift
st.yylimit -= shift
st.token -= shift
// Fill free space at the end of buffer with new data.
n, _ := st.file.Read(st.yyinput[st.yylimit:BUFSIZE])
st.yylimit += n
st.yyinput[st.yylimit] = 0 // append sentinel symbol
return lexReady
}
func lex(yyrecord *State, recv *int) int {
var yych byte
/*!getstate:re2c*/
loop:
yyrecord.token = yyrecord.yycursor
/*!re2c
re2c:api = record;
re2c:eof = 0;
re2c:YYFILL = "return lexWaitingForInput";
packet = [a-z]+[;];
* { return lexPacketBroken }
$ { return lexEnd }
packet { *recv = *recv + 1; goto loop }
*/
}
func test(expect int, packets []string) {
// Create a pipe (open the same file for reading and writing).
fname := "pipe"
fw, _ := os.Create(fname)
fr, _ := os.Open(fname)
// Initialize lexer state: `state` value is -1, all offsets are at the end
// of buffer.
st := &State{
file: fr,
// Sentinel at `yylimit` offset is set to zero, which triggers YYFILL.
yyinput: make([]byte, BUFSIZE+1),
yycursor: BUFSIZE,
yymarker: BUFSIZE,
yylimit: BUFSIZE,
token: BUFSIZE,
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.
var status int
send := 0
recv := 0
for {
status = lex(st, &recv)
if status == lexEnd {
break
} else if status == lexWaitingForInput {
if send < len(packets) {
fw.WriteString(packets[send])
send += 1
}
status = fill(st)
if status != lexReady {
break
}
} else if status == lexPacketBroken {
break
}
}
// Check results.
if status != expect || (status == lexEnd && recv != send) {
panic(fmt.Sprintf("got %d, want %d", status, expect))
}
// Cleanup: remove input file.
fr.Close()
fw.Close()
os.Remove(fname)
}
func main() {
test(lexEnd, []string{})
test(lexEnd, []string{"zero;", "one;", "two;", "three;", "four;"})
test(lexPacketBroken, []string{"??;"})
test(lexPacketTooBig, []string{"looooooooooooong;"})
}
π§© Reusable blocks
Reusable blocks of the form /*!rules:re2c[:<name>] ... */ or %{rules[:<name>] ... %} can be reused any number of times and combined with other re2go 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. β¨
Okay so a use block gets written like /*!use:re2c[:<name>] ... */ or %{use[:<name>] ... %}. The <name> is optional β if you don't give one, the associated rules block is just the most recent one (named or unnamed, don't care). A use block can add named definitions, configurations and rules of its own. π
The big iconic use case for use blocks? A lexer that supports multiple input encodings β you reuse the same rules block multiple times with encoding-specific configurations (peep the example below, it's literally that).
The in-block use directive !use:<name>; can be used from inside a re2go block, and 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 get resolved the usual way: the earliest rule takes priority, and the latest configuration overrides preceding ones. One exception tho β the special rules *, $ and (in condition mode) <!> are different: a block-local definition overrides any inherited ones. So basically the use directive lets you combine different re2go blocks together into one block (again, example below π).
Named blocks and the in-block use directive were added in re2go version 2.2. Since that version, reusable blocks are allowed by default (no special option needed, slay). Before 2.2 you had to enable reuse mode with the-r,--reusableoption. And before version 1.2, reusable blocks couldn't be mixed with normal blocks at all. π«Ά
Example of a !use directive
//go:generate re2go $INPUT -o $OUTPUT --api simple
package 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.
const (
Color = iota
Fish
Dunno
)
/*!rules:re2c:colors
* { panic("eh!") }
"red" | "salmon" | "magenta" { return Color }
*/
/*!rules:re2c:fish
* { panic("oh!") }
"haddock" | "salmon" | "eel" { return Fish }
*/
func lex(yyinput string) int {
var yycursor, yymarker int
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
!use:fish;
!use:colors;
* { return Dunno } // overrides inherited '*' rules
*/
}
func main() {
assert_eq := func(x, y int) { if x != y { panic("error") } }
assert_eq(lex("salmon"), Fish);
assert_eq(lex("what?"), Dunno);
}
Example of a /*!use:re2c ... */ block
//go:generate re2go $INPUT -o $OUTPUT --input-encoding utf8 --api simple
package main
// 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; }
*/
func lexUTF8(yyinput []uint8) int {
var yycursor, yymarker int
/*!use:re2c
re2c:encoding:utf8 = 1;
re2c:YYCTYPE = uint8;
*/
}
func lexUTF32(yyinput []uint32) int {
var yycursor, yymarker int
/*!use:re2c
re2c:encoding:utf32 = 1;
re2c:YYCTYPE = uint32;
*/
}
func main() {
assert_eq := func(x, y int) { if x != y { panic("error") } }
assert_eq(lexUTF8([]uint8{0xe2, 0x88, 0x80, 0x78, 0x20, 0xe2, 0x88, 0x83, 0x79}), 0)
assert_eq(lexUTF32([]uint32{0x2200, 0x78, 0x20, 0x2203, 0x79}), 0)
}
π Submatch extraction π
re2go has two options for submatch extraction. Two whole flavours, pick your fighter.
Tags
The first option is to use standalone tags of the form @stag or #mtag, where stag and mtag are arbitrary user-defined names. Tags are enabled with the -T, --tags option or the re2c:tags = 1 configuration. Semantically, tags are position markers: you can insert them 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 β yes, that's the whole point π«). All tags should be defined by the user, either manually or with the help of svars and mvars blocks. If there's more than one way tags can be matched against the input, ambiguity is resolved using the leftmost greedy disambiguation strategy.
Captures
The second option is to use capturing groups. They're enabled with the --captures option or the re2c:captures = 1 configuration. There are two flavours for different disambiguation policies: --leftmost-captures (the default, bestie) 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 the --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 the yypmatch array. Both yynmatch and yypmatch should be defined by the user, and yypmatch size must be at least [yynmatch * 2]. Use a maxnmatch block to define YYMAXNMATCH, a constant that equals the maximum value of yynmatch among all rules. π
Captvars
Another way to use capturing groups is the --captvars option or the re2c:captvars = 1 configuration. The only difference with --captures is in the way the generated code stores submatch results: instead of yynmatch and yypmatch, re2go generates variables yytl<k> and yytr<k> for the k-th capturing group (the user should declare these using an svars block). Captures with variables support two disambiguation policies: --leftmost-captvars or re2c:leftmost-captvars = 1 for 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 the C pointer API, or a user-defined operationYYSTAGP(t)with the generic API - save default value to an s-tag:
t = NULLwith the C pointer API, or a user-defined operationYYSTAGN(t)with the generic API - copy one s-tag to another:
t1 = t2
M-tags support the following operations:
- append input position to an m-tag: a user-defined operation
YYMTAGP(t)with both 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 an array of nodes (v, p), where v is the tag value and p is a pointer to the parent node. πΈ
Here's 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. π
//go:generate re2go $INPUT -o $OUTPUT --api simple
package main
import "reflect"
type SemVer struct { major, minor, patch int }
func s2n(s string) int { // convert pre-parsed string to a number
n := 0
for _, c := range s { n = n*10 + int(c-'0') }
return n
}
func parse(yyinput string) *SemVer {
var yycursor, yymarker int
// Final tag variables available in semantic action.
/*!svars:re2c format = 'var @@ int;'; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = 'var @@ int;'; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
re2c:tags = 1;
num = [0-9]+;
@t1 num @t2 "." @t3 num @t4 ("." @t5 num)? [\x00] {
major := s2n(yyinput[t1:t2])
minor := s2n(yyinput[t3:t4])
patch := 0
if t5 != -1 { patch = s2n(yyinput[t5:yycursor-1]) }
return &SemVer{major, minor, patch}
}
* { return nil }
*/
}
func main() {
assert_eq := func(x, y *SemVer) {
if !reflect.DeepEqual(x, y) { panic("error") }
}
assert_eq(parse("23.34\000"), &SemVer{23, 34, 0})
assert_eq(parse("1.2.9999\000"), &SemVer{1, 2, 9999})
assert_eq(parse("1.a\000"), nil)
}
Here's 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. π¦
//go:generate re2go $INPUT -o $OUTPUT --tags
package main
import (
"os"
"reflect"
"strings"
)
const BUFSIZE int = 4095
type Input struct {
file *os.File
yyinput []byte
yycursor int
yymarker int
yylimit int
token int
// 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 = "\t@@ int\n"; */
eof bool
}
type SemVer struct { major, minor, patch int }
func s2n(s []byte) int { // convert pre-parsed string to a number
n := 0
for _, c := range s { n = n*10 + int(c-'0') }
return n
}
func fill(in *Input) int {
if in.eof { return -1 } // unexpected EOF
// Error: lexeme too long. In real life can reallocate a larger buffer.
if in.token < 1 { return -2 }
// Shift buffer contents (discard everything up to the current token).
copy(in.yyinput[0:], in.yyinput[in.token:in.yylimit])
in.yycursor -= in.token
in.yymarker -= in.token
in.yylimit -= in.token
// Tag variables need to be shifted like other input positions. The check
// for -1 is only needed if some tags are nested inside of alternative or
// repetition, so that they can have -1 value.
/*!stags:re2c format = "\tif in.@@ != -1 { in.@@ -= in.token }\n"; */
in.token = 0
// Fill free space at the end of buffer with new data from file.
n, _ := in.file.Read(in.yyinput[in.yylimit:BUFSIZE])
in.yylimit += n
in.yyinput[in.yylimit] = 0
// If read less than expected, this is the end of input.
in.eof = in.yylimit < BUFSIZE
return 0
}
func parse(in *Input) []SemVer {
// Final tag variables available in semantic action.
/*!svars:re2c format = "var @@ int;"; */
vers := make([]SemVer, 0)
for {
in.token = in.yycursor
/*!re2c
re2c:api = record;
re2c:eof = 0;
re2c:yyrecord = in;
re2c:YYCTYPE = byte;
re2c:YYFILL = "fill(in) == 0";
num = [0-9]+;
num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] {
major := s2n(in.yyinput[in.token:t1])
minor := s2n(in.yyinput[t2:t3])
patch := 0
if t4 != -1 { patch = s2n(in.yyinput[t4:in.yycursor-1]) }
vers = append(vers, SemVer{major, minor, patch})
continue
}
$ { return vers }
* { return nil }
*/
}
}
func main() () {
fname := "input"
content := "1.22.333\n";
expect := make([]SemVer, 0, BUFSIZE)
for i := 0; i < BUFSIZE; i += 1 { expect = append(expect, SemVer{1, 22, 333}) }
// Prepare input file (make sure it exceeds buffer size).
f, _ := os.Create(fname)
f.WriteString(strings.Repeat(content, BUFSIZE))
f.Seek(0, 0)
// Initialize lexer state: all offsets are at the end of buffer.
in := &Input{
file: f,
// Sentinel at `yylimit` offset is set to zero, which triggers YYFILL.
yyinput: make([]byte, BUFSIZE+1),
yycursor: BUFSIZE,
yymarker: BUFSIZE,
yylimit: BUFSIZE,
token: BUFSIZE,
eof: false,
}
// Run the lexer and check results.
if !reflect.DeepEqual(parse(in), expect) { panic("error"); }
// Cleanup: remove input file.
f.Close();
os.Remove(fname);
}
Okay bestie, now the tags era begins π
Here's a lil example of using capturing groups to parse semantic versions β yes, the (num) "." (num) type of situation, it's giving very demure, very mindful π
//go:generate re2go $INPUT -o $OUTPUT --api simple
package main
import "reflect"
type SemVer struct { major, minor, patch int }
func s2n(s string) int { // convert pre-parsed string to a number
n := 0
for _, c := range s { n = n*10 + int(c-'0') }
return n
}
func parse(yyinput string) *SemVer {
var yycursor, yymarker int
// Final tag variables used in semantic action.
/*!svars:re2c format = 'var @@ int;'; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = 'var @@ int;'; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
re2c:captvars = 1;
num = [0-9]+;
(num) "." (num) ("." num)? [\x00] {
_ = yytl0; _ = yytr0; // some variables are unused
major := s2n(yyinput[yytl1:yytr1])
minor := s2n(yyinput[yytl2:yytr2])
patch := 0
if yytl3 != -1 { patch := s2n(yyinput[yytl3+1:yytr3]) }
return &SemVer{major, minor, patch}
}
* { return nil }
*/
}
Hmm wait, I gotta give you the real one, no typos from me β here it is exactly, patch := 0 and if yytl3 != -1 { patch = ... } π«Ά
//go:generate re2go $INPUT -o $OUTPUT --api simple
package main
import "reflect"
type SemVer struct { major, minor, patch int }
func s2n(s string) int { // convert pre-parsed string to a number
n := 0
for _, c := range s { n = n*10 + int(c-'0') }
return n
}
func parse(yyinput string) *SemVer {
var yycursor, yymarker int
// Final tag variables used in semantic action.
/*!svars:re2c format = 'var @@ int;'; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = 'var @@ int;'; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
re2c:captvars = 1;
num = [0-9]+;
(num) "." (num) ("." num)? [\x00] {
_ = yytl0; _ = yytr0; // some variables are unused
major := s2n(yyinput[yytl1:yytr1])
minor := s2n(yyinput[yytl2:yytr2])
patch := 0
if yytl3 != -1 { patch = s2n(yyinput[yytl3+1:yytr3]) }
return &SemVer{major, minor, patch}
}
* { return nil }
*/
}
func main() {
assert_eq := func(x, y *SemVer) {
if !reflect.DeepEqual(x, y) { panic("error") }
}
assert_eq(parse("23.34\000"), &SemVer{23, 34, 0})
assert_eq(parse("1.2.9999\000"), &SemVer{1, 2, 9999})
assert_eq(parse("1.a\000"), nil)
}
π And now my personal fave: m-tags to parse a version with a variable number of components. Tag variables get stored in a trie, which is lowkey iconic. Brace yourself, it's a big one π
//go:generate re2go $INPUT -o $OUTPUT --api simple
package main
import "reflect"
const (
mtagRoot int = -1
tagNone int = -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).
type mtagElem struct {
elem int
pred int
}
type mtagTrie = []mtagElem
type Ver = []int // unbounded number of version components
func s2n(s string) int { // convert pre-parsed string to a number
n := 0
for _, c := range s { n = n*10 + int(c-'0') }
return n
}
// Append a single value to an m-tag history.
func add_mtag(trie *mtagTrie, mtag int, value int) int {
*trie = append(*trie, mtagElem{value, mtag})
return len(*trie) - 1
}
// Recursively unwind tag histories and collect version components.
func unwind(trie mtagTrie, x int, y int, str string) Ver {
// Reached the root of the m-tag tree, stop recursion.
if x == mtagRoot && y == mtagRoot {
return []int{}
}
// Unwind history further.
ver := unwind(trie, trie[x].pred, trie[y].pred, str)
// Get tag values. Tag histories must have equal length.
if x == mtagRoot || y == mtagRoot {
panic("tag histories have different length")
}
ex := trie[x].elem
ey := trie[y].elem
if ex != tagNone && ey != tagNone {
// Both tags are valid string indices, extract component.
ver = append(ver, s2n(str[ex:ey]))
} else if !(ex == tagNone && ey == tagNone) {
panic("both tags should be tagNone")
}
return ver
}
func parse(yyinput string) []int {
var yycursor, yymarker int
trie := make([]mtagElem, 0)
// Final tag variables available in semantic action.
/*!svars:re2c format = 'var @@ int;'; */
/*!mvars:re2c format = "var @@ int;"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = 'var @@ int'; separator = "\n\t"; */
/*!mtags:re2c format = "\t@@ := mtagRoot\n"; */
/*!re2c
re2c:tags = 1;
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
re2c:YYMTAGP = "@@ = add_mtag(&trie, @@, yycursor)";
re2c:YYMTAGN = "@@ = add_mtag(&trie, @@, tagNone)";
num = [0-9]+;
@t1 num @t2 ("." #t3 num #t4)* [\x00] {
ver := make([]int, 0)
ver = append(ver, s2n(yyinput[t1:t2]))
ver = append(ver, unwind(trie, t3, t4, yyinput)...)
return ver
}
* { return nil }
*/
}
func main() {
assert_eq := func(x, y []int) {
if !reflect.DeepEqual(x, y) { panic("error") }
}
assert_eq(parse("1\000"), []int{1})
assert_eq(parse("1.2.3.4.5.6.7\000"), []int{1, 2, 3, 4, 5, 6, 7})
assert_eq(parse("1.\000"), nil)
}
π Encoding support π
Okay so before we go any further you gotta understand the difference between code points and code units, bestie, because this is the whole vibe check of the section π¦
- A code point is the numeric identifier of a symbol.
- A code unit is the smallest unit of storage in the encoded text.
A single code point can be represented with one or more code units. In a fixed-length encoding, all code points get the same number of code units. In a variable-length encoding, code points may be represented with a different number of code units π
Note note note: 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*. Put that in your notes app fr fr π
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 re2go compiles regular expressions to automata it translates code points to code units. And ngl 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, she's the main character π It's a fixed-length encoding with code space
[0-255]and 1-byte code points and code units. - EBCDIC β enabled with
--ebcdicorre2c:encoding:ebcdic. It's a fixed-length encoding with code space[0-255]and 1-byte code points and code units. - UCS2 β enabled with
--ucs2orre2c:encoding:ucs2. It's a fixed-length encoding with code space[0-0xFFFF]and 2-byte code points and code units. - UTF8 β enabled with
--utf8orre2c:encoding:utf8. It's 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's a variable-length Unicode encoding, bestie. Code unit size is2bytes. Code points are represented with1 -- 2code units. πUTF32(enabled with--utf32orre2c:encoding:utf32) β fixed-length Unicode encoding with code space[0-0x10FFFF]and 4-byte code points and code units. iconic, no cap. β¨
The include files include/unicode_blocks.re, include/unicode_categories.re and include/unicode_properties.re provide re2go 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 re2go that the source file is in UTF8 (it differs from --utf8 which sets input text encoding). Option --encoding-policy specifies the way re2go handles Unicode surrogates (code points in range [0xD800-0xDFFF]). π
Below is an example of a lexer for UTF8 encoded Unicode identifiers.
//go:generate re2go $INPUT -o $OUTPUT -8si --api simple
package main
/*!include:re2c "unicode_categories.re" */
func lex(yyinput string) int {
var yycursor, yymarker int
/*!re2c
re2c:yyfill:enable = 0;
re2c:YYCTYPE = byte;
// 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 }
*/
}
func main() {
if lex("_Π«Π΄Π΅Π½ΡΠΈΡΠΈΠΊΠ°ΡΠΎΡ\000") != 0 {
panic("error")
}
}
π Include files π
re2go 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. re2go 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 re2go 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. re2go 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 re2go. Below is an example of using include files. π
π Include file 1 (definitions.go) π
const (
ResultOk = iota
ResultFail
)
/*!re2c
number = [1-9][0-9]*;
*/
π Include file 2 (extra_rules.re.inc) π
// floating-point numbers
frac = [0-9]* "." [0-9]+ | [0-9]+ ".";
exp = 'e' [+-]? [0-9]+;
float = frac exp? | [0-9]+ exp;
float { return ResultOk }
π Input file π
//go:generate re2go $INPUT -o $OUTPUT -i --api simple
package main
/*!include:re2c "definitions.go" */
func lex(yyinput string) int {
var yycursor, yymarker int
/*!re2c
re2c:YYCTYPE = byte;
re2c:yyfill:enable = 0;
* { return ResultFail }
number { return ResultOk }
!include "extra_rules.re.inc";
*/
}
func main() {
assert_eq := func(x, y int) { if x != y { panic("error") } }
assert_eq(lex("123\000"), ResultOk)
assert_eq(lex("123.4567\000"), ResultOk)
}
π Header files π
re2go allows one to generate header file from the input .re file using --header option or re2c:header configuration and block pairs of the form /*!header:re2c:on*/ and /*!header:re2c:off*/, or %{header:on%} and %{header:off%}. The first block marks the beginning of header file, and the second block marks the end of it. Everything between these blocks is processed by re2go, and the generated code is written to the file specified with --header option or re2c:header configuration (or stdout if neither option nor configuration is used). Autogenerated header file may be needed in cases when re2go is used to generate definitions that must be visible from other translation units. π
Here is an example of generating a header file that contains definition of the lexer state with tag variables (the number variables depends on the regular grammar and is unknown to the programmer).
π¦ Input file π¦
//go:generate re2go $INPUT -o $OUTPUT -i --header lexer/state.go
package main
import "./lexer" // the package is generated by re2c
/*!header:re2c:on*/
package lexer
type State struct {
Data string
Cur /*!stags:re2c format=", @@"; */ int
}
/*!header:re2c:off*/
func lex(yyrecord *lexer.State) int {
var t int
/*!re2c
re2c:header = "lexer/state.go";
re2c:api = record;
re2c:YYCTYPE = byte;
re2c:YYINPUT = "yyrecord.Data";
re2c:YYCURSOR = "yyrecord.Cur";
re2c:yyfill:enable = 0;
re2c:tags = 1;
re2c:tags:prefix = "Tag";
[a]* @t [b]* { return t }
*/
}
func main() {
st := &lexer.State{Data:"ab\x00",}
if lex(st) != 1 {
panic("error")
}
}
π¦ Header file π¦
// Code generated by re2c, DO NOT EDIT.
package lexer
type State struct {
Data string
Cur, Mar, Tag1 int
}
π₯ Skeleton programs π₯
With the -S, --skeleton option, re2go ignores all non-re2go 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) re2go 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 re2go optimizations (the data is generated early in the process, before any DFA transformations have taken place).
- Generating a set of input data with good coverage may be useful for both testing and benchmarking.
- Generating self-contained executable programs allows one to get minimized test cases (the original code may be large or have a lot of dependencies).
The difficulty with generating input data is that for all but the most trivial cases the number of possible input strings is too large (even if the string length is limited). re2go solves this difficulty by generating sufficiently many strings to cover almost all DFA transitions. It uses the following algorithm. First, it constructs a skeleton of the DFA. For encodings with 1-byte code unit size (such as ASCII, UTF-8 and EBCDIC) skeleton is just an exact copy of the original DFA. For encodings with multibyte code units skeleton is a copy of DFA with certain transitions omitted: namely, re2go 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) re2go 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 (re2go writes data to file as soon as it is generated). π
π¦ Visualization and debug π¦
With the -D, --emit-dot option, re2go 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 π
re2go was originally written by Peter Bumbulis (peter@csg.uwaterloo.ca) in 1993. Marcus Boerger and Dan Nuffer spent several years to turn the original idea into a production ready code generator. Since then it has been maintained and developed by multiple volunteers, most notably, Brian Young (bayoung@acm.org), Marcus Boerger, Dan Nuffer (nuffer@users.sourceforge.net), Ulya Trofimovich (skvadrik@gmail.com), Serghei Iakovlev, Sergei Trofimovich, Petr Skocik, ligfx raekye and PolarGoose. β¨
okay bestie, that's the whole RE2GO(1) manual page β signed off with the RE2GO(1) footer tag and all the sparkles it deserves. date stamp? not in this snippet, just vibes. stay slay, keep those DFA transitions covered, and see you in the group chat ππ
π
π¦ 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