RE2JS(1)
RE2JS(1) 💅
NAME 🎀
okay bestie, re2js — generate fast lexical analyzers for JavaScript. slay, that's the whole vibe.
SYNOPSIS ✨
re2js [ OPTIONS ] [ WARNINGS ] INPUT
INPUT can be either a file or - for stdin. yes, a literal dash for stdin, no cap.
INTRODUCTION 🦋
re2js works as a preprocessor. It reads the input file (which is usually a program in JavaScript, 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 re2js. It translates them to code in JavaScript and outputs the generated code in place of the block.
Here is an example of a small program that checks if a given string contains a decimal number:
// re2js $INPUT -o $OUTPUT
function lex(yyinput) {
let yycursor = 0;
/*!re2c
re2c:yyfill:enable = 0;
[1-9][0-9]* { return true; }
* { return false; }
*/
}
if (!lex("1234\0")) {
throw "error!"
}
In the output re2js replaced the block in the middle with the generated code:
// Generated by re2js
// re2js $INPUT -o $OUTPUT
function lex(yyinput) {
let yycursor = 0;
{
let yych = 0
let yystate = 0
yyl: while (true) {
switch (yystate) {
case 0:
yych = yyinput.charCodeAt(yycursor)
yycursor += 1;
switch (yych) {
case 0x31:
case 0x32:
case 0x33:
case 0x34:
case 0x35:
case 0x36:
case 0x37:
case 0x38:
case 0x39:
yystate = 2
continue yyl
default:
yystate = 1
continue yyl
}
case 1:
{ return false; }
case 2:
yych = yyinput.charCodeAt(yycursor)
switch (yych) {
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
case 0x35:
case 0x36:
case 0x37:
case 0x38:
case 0x39:
yycursor += 1;
yystate = 2
continue yyl
default:
yystate = 3
continue yyl
}
case 3:
{ return true; }
default:
throw "internal lexer error"
}
}
}
}
if (!lex("1234\0")) {
throw "error!"
}
BASICS 🌈
A re2js 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 ofre2jssyntax 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. no recursion, bestie, that's a hard no.configuration = value ;— A configuration allows one to changere2jsbehavior and customize the generated code. For a full list of configurations supported byre2jssee 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 feels it.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 theregular-expressionmatches, the associated code is executed. If multiple rules match, the longest match takes precedence. If multiple rules match the same string, the earliest one takes precedence. There are two special rules: the default rule*and the end of input rule$. Default rule should always be defined, it has the lowest priority regardless of its place in the block, and it matches any code unit (not necessarily a valid character, see the encoding support section). The end of input rule should be defined if the corresponding method for handling the end of input is used. With start conditions rules have more complex syntax.!action code— An action binds a user-defined block of code to a particular place in the generated finite state machine (in the same way as semantic actions bind code to the final states). See the actions section for a full list of predefined actions. it's giving backstage pass to the FSM.!directive ;— A directive is one of the special predefined statements. Each directive has a unique purpose. See the directives section for details. iykyk.
🧚 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.re2jscompiles 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. main character block energy./*!local:re2c[:<name>] ... */or%{local[:<name>] ... %}— A local block is like a global block, but the names and configurations in it have local scope (they do not affect other blocks)./*!rules: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 tore2jsversion 2.2 rules blocks required-r --reusableoption. reuse era fr fr./*!use:re2c[:<name>] ... */or%{use[:<name>] ... %}— A use block that references a previously defined rules block. If the name is specified,re2jslooks for a rules block 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 tore2jsversion 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 configuration format that specifies a template string where@@{max}(or@@for short) is replaced with the numeric value ofYYMAXFILL. max fill said customize me please./*!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 configuration format that 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 byre2js. 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. tag variables getting their own little template moment ✨/*!svars:re2c[:<name1>[:<name2>...]] ... */,/*!mvars:re2c[:<name1>[:<name2>...]] ... */,%{svars[:<name1>[:<name2>...]] ... %},%{mvars[:<name1>[:<name2>...]] ... %{— these are the blocks that hold a little template snippet of code, and that snippet gets expanded once for each s-tag / m-tag. Which tags? Either the ones your rules explicitly mention (that's with the--tagsoption), or the ones re2js quietly makes on its own (that's with--captvarsor--posix-captvars). You can optionally hand it a list of block names to say "only count these blocks when you're figuring out the set of tags" — and if the list is empty, literally all blocks get counted, no cap. There are two optional configs here:formatandseparator. Theformatconfig is a template string where@@{tag}(or just@@for short) gets swapped out for the name of each tag. Theseparatorconfig is the piece of code used to glue together the generated format pieces for the different tags. 🧩/*!getstate:re2c[:<name1>[:<name2>...]] ... */,%{getstate[:<name1>[:<name2>...]] ... %}— this block generates conditional dispatch on the lexer state, and heads up, it requires the--storable-stateoption. Optional list of block names = which blocks get included in the state dispatch. The default transition goes to the start label of the first block on the list. If the list is empty, all blocks are included, and the default transition goes to the first block in the file that has a start label. 💅 This block type is incompatible with--loop-switch, because it needs cross-block transitions and those are unsupported withoutgotoor function calls. So yeah, pick one, bestie./*!conditions:re2c[:<name1>[:<name2>...]] ... */,/*!types:re2c... */,%{conditions[:<name1>[:<name2>...]] ... %},%{types... %}— this one generates the condition enumeration (and yes, it requires--conditions). Optional list of block names = which blocks get included when computing the set of conditions; empty list means all blocks. By default the generated code is an enumeration calledYYCONDTYPE, but you can customize it with the optionalformatandseparatorconfigs.formatis a template string where@@{cond}(or@@shorthand) becomes the name of each condition, and@@{num}becomes that condition's numeric index.separatoris the piece of code that joins the generated format pieces for different conditions together. ✨/*!include:re2c <file> */,%{include <file> %}— this block lets you include<file>, which must be a double-quoted file path. The file's contents get literally substituted right where the block was, same energy as#includein C/C++. 🫶 Bonus: you can use this block with the--depfileoption to generate build system dependencies on the included files./*!header:re2c:on*/,%{header:on %}— this block marks the start of the header file. Everything after it, up until the followingheader:offblock, gets processed by re2js and written out to the header file you specified with the-t/--type-headeroption. 🎀/*!header:re2c:off*/,%{header:off %}— and this one marks the end of the header file that theheader:onblock started. Bookend vibes. 🦋/*!ignore:re2c ... */,%{ignore ... %}— a block whose contents are straight-up ignored and removed from the output file. Poof, gone, not in the build. 💀
✨ Configurations ✨
Okay so here's the full list of every configuration re2js supports. Yes, all of them. Buckle up, bestie. 🌈
re2c:api,re2c:input— same as the--apioption.re2c:api:sigil— sets 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 — so if you set the sigil to$, your placeholders look like${name}. Single-argument APIs may use shorthand without the name in braces. This option can be overridden by options for individual API primitives, e.g.re2c:YYFILL@lenforYYFILL. 🎯re2c:api:style— sets the 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 right after the primitive's name. The arguments are provided only for autogenerated parameters (like the number of characters passed toYYFILL), not for the general lexer context — so the primitives behave more like macros in C/C++ or closures in Go and Rust. Infree-formstyle, API primitives don't have a fixed form at all: you define them as strings containing free-form pieces of code with interpolated variables of the form@@{var}or@@(these correspond to the arguments in the function-like style). This config 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 you can configure it 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 sets 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. 😳 Dramatic, but like, on purpose.re2c:cond:goto— the piece of code used for the autogenerated shortcut rules:=>in conditions. The default isgoto @@;. The@@placeholder gets substituted with the condition name (see there2c:api:sigilandre2c:cond:goto@condconfigurations).re2c:cond:goto@cond— 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 get substituted with the condition name (seere2c:api;sigilandre2c:cond:divider@cond). 🎀re2c:cond:divider@cond— the sigil used for argument substitution in there2c:cond:dividerdefinition. The default is@@. Overrides the more genericre2c:api:sigilconfiguration.re2c:cond:prefix,re2c:condprefix— the prefix used for condition labels. The default isyyc_.re2c:cond:enumprefix,re2c:condenumprefix— 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— the sentinel symbol used with the end-of-input rule$. The default value is-1(meaning the$rule is not used). Other possible values include all valid code units. Only decimal numbers are recognized, so don't get cute with hex. 🔢re2c:header,re2c:flags:type-header,re2c:flags:t— the name of the generated header file, relative to the directory of the output file. Same as the--headeroption, except that the file path is relative. 📁re2c:indent:string— the string used for indentation. 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— 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— the prefix used for DFA state labels. The default isyy. 🏷️re2c:label:start,re2c:startlabel— controls generation of a block start label. The default value is zero, which means the start label is generated only if it's used. An integer value greater than zero forces generation of the start label even if the lexer never uses it. A string value also forces start label generation and sets the label name to that specified string. Heads up: this configuration applies only to the current block — it gets reset to default for the next block. 👑re2c:label:yyFillLabel— sets the prefix for all theYYFILLlabels 💅 you get these when you're running withre2c:eofand also over in storable state mode.re2c:label:yyloop— the name of the label that marks the start of the lexer loop when you're using the--loop-switchoption. Default?yyloop. cute, iconic, predictable ✨re2c:label:yyNext— names that optional label hanging out right after theYYGETSTATEswitch in storable state mode (you turn that on withre2c:state:nextlabel). Default isyyNext. she's optional and she knows it 💖re2c:lookahead,re2c:flags:lookahead— deprecated bestie, don't get attached 😭 (peep the deprecated--no-lookaheadoption if you're curious).re2c:monadic— set it to non-zero and the generated lexer busts out monadic notation. this one is Haskell-specific, so if that's your world, slay 🦋re2c:nested-ifs,re2c:flags:nested-ifs,re2c:flags:s— literally the same as the--nested-ifsoption, except you can configure it per-block. flexible queen 👑re2c:posix-captures,re2c:flags:posix-captures,re2c:flags:P— same as the--posix-capturesoption, but configurable per-block. yes, per-block. we love options 💅re2c:posix-captvars— same as the--posix-captvarsoption, and yeah — per-block configurable too 🎀re2c:tags,re2c:flags:tags,re2c:flags:T— same as the--tagsoption, per-block configurable. that's the whole vibe ✨re2c:tags:expression— this one specifies the expression used for tag variables. by default re2js generates expressions of the formyyt<N>, which ngl can be lowkey inconvenient — say your tag variables are defined as fields in a struct? 😬 every occurrence of@@{tag}or@@gets replaced with the actual tag name, so for example:
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 your tags are integer offsets into the input string, or a null pointer if they're pointers 💫re2c:tags:prefix— the prefix for tag variable names. default isyyt, obviously 💅re2c:sentinel— specifies 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 config doesn't affect code generation at all — 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 🛑 default value is-1(and in that case re2js assumes the sentinel is zero, which is the most common case). only decimal numbers are recognized — no hex shenanigans, sorry 😭re2c:state:abort— set it to a positive integer and the default case in the generated state dispatch aborts program execution, and an explicit-1case contains the transition back to the start of the block 💀 dramatic but validre2c:state:nextlabel— controls whether theYYGETSTATEswitch is followed by ayyNextlabel. default value is zero, which means no label 🙈 alternatively you can usere2c:label:startto generate a specific start label, or an explicitgetstateblock to generate theYYGETSTATEswitch separately from the lexer block 🎀re2c:unsafe,re2c:flags:unsafe— same as the--no-unsafeoption, but configurable per-block. if you set it to zero, it suppresses the generation of unsafe wrappers aroundYYPEEK👀 the default is non-zero (so wrappers are generated). this configuration is specific to Rust 🦀
the generic API primitives, aka the whole alphabet soup 💖
re2c:YYBACKUP,re2c:define:YYBACKUP— defines the generic API primitiveYYBACKUP.re2c:YYBACKUPCTX,re2c:define:YYBACKUPCTX— defines the generic API primitiveYYBACKUPCTX.re2c:YYCONDTYPE,re2c:define:YYCONDTYPE— defines the API primitiveYYCONDTYPE.re2c:YYCTYPE,re2c:define:YYCTYPE— defines the API primitiveYYCTYPE.re2c:YYCTXMARKER,re2c:define:YYCTXMARKER— defines the API primitiveYYCTXMARKER.re2c:YYCURSOR,re2c:define:YYCURSOR— defines the API primitiveYYCURSOR.re2c:YYDEBUG,re2c:define:YYDEBUG— defines the API primitiveYYDEBUG.re2c:YYFILL,re2c:define:YYFILL— defines the API primitiveYYFILL.re2c:YYFILL@len,re2c:define:YYFILL@len— the sigil used for argument substitution in theYYFILLdefinition. defaults to@@, and it overrides the more genericre2c:api:sigilconfiguration 💫re2c:YYFILL:naked,re2c:define:YYFILL:naked— overrides the more genericre2c:api:styleconfiguration just forYYFILL. a zero value corresponds to free-form API style 🎀re2c:YYFN— defines the API primitiveYYFN.re2c:YYINPUT— defines the API primitiveYYINPUT.re2c:YYGETCOND,re2c:define:YYGETCONDITION— defines the API primitiveYYGETCOND.re2c:YYGETCOND:naked,re2c:define:YYGETCONDITION:naked— overrides the more genericre2c:api:styleconfiguration forYYGETCOND. zero value = free-form API style ✨re2c:YYGETSTATE,re2c:define:YYGETSTATE— defines the API primitiveYYGETSTATE.re2c:YYGETSTATE:naked,re2c:define:YYGETSTATE:naked— overrides the more genericre2c:api:styleconfiguration forYYGETSTATE. zero value = free-form API style, same deal 💅re2c:YYGETACCEPT,re2c:define:YYGETACCEPT— defines the API primitiveYYGETACCEPT.re2c:YYLESSTHAN,re2c:define:YYLESSTHAN— defines the generic API primitiveYYLESSTHAN.re2c:YYLIMIT,re2c:define:YYLIMIT— defines the API primitiveYYLIMIT.re2c:YYMARKER,re2c:define:YYMARKER— defines the API primitiveYYMARKER.re2c:YYMTAGN,re2c:define:YYMTAGN— defines the generic API primitiveYYMTAGN.re2c:YYMTAGP,re2c:define:YYMTAGP— defines the generic API primitiveYYMTAGP.re2c:YYPEEK,re2c:define:YYPEEK— defines the generic API primitiveYYPEEK.re2c:YYRESTORE,re2c:define:YYRESTORE— defines the generic API primitiveYYRESTORE.re2c:YYRESTORECTX,re2c:define:YYRESTORECTX— defines the generic API primitiveYYRESTORECTX.re2c:YYRESTORETAG,re2c:define:YYRESTORETAG— defines the generic API primitiveYYRESTORETAG.re2c:YYSETCOND,re2c:define:YYSETCONDITION— defines the API primitiveYYSETCOND.re2c:YYSETCOND@cond,re2c:define:YYSETCONDITION@cond— the sigil used for argument substitution in theYYSETCONDdefinition. default value is@@, and it overrides the more genericre2c:api:sigilconfiguration 🌸re2c:YYSETCOND:naked,re2c:define:YYSETCONDITION:naked— overrides the more genericre2c:api:styleconfiguration forYYSETCOND. zero value = free-form API style 🫶re2c:YYSETSTATE,re2c:define:YYSETSTATE— defines the API primitiveYYSETSTATE.re2c:YYSETSTATE@state,re2c:define:YYSETSTATE@state— the sigil used for argument substitution in theYYSETSTATEdefinition. default value is@@, and yep, it overrides the more genericre2c:api:sigilconfiguration 💜re2c:YYSETSTATE:naked,re2c:define:YYSETSTATE:naked— overrides the more genericre2c:api:styleconfiguration forYYSETSTATE. zero value = free-form API style, always 😌re2c:YYSETACCEPT,re2c:define:YYSETACCEPT— defines the API primitiveYYSETACCEPT.re2c:YYSKIP,re2c:define:YYSKIP— defines the generic API primitiveYYSKIP.re2c:YYSHIFT,re2c:define:YYSHIFT— defines the generic API primitiveYYSHIFT.re2c:YYCOPYMTAG,re2c:define:YYCOPYMTAG— defines the generic API primitiveYYCOPYMTAG.re2c:YYCOPYSTAG,re2c:define:YYCOPYSTAG— defines the generic API primitiveYYCOPYSTAG.re2c:YYSHIFTMTAG,re2c:define:YYSHIFTMTAG— defines the generic API primitiveYYSHIFTMTAG.re2c:YYSHIFTSTAG,re2c:define:YYSHIFTSTAG— defines the generic API primitiveYYSHIFTSTAG.re2c:YYSTAGN,re2c:define:YYSTAGN— defines the generic API primitiveYYSTAGN.re2c:YYSTAGP,re2c:define:YYSTAGP— defines the generic API primitiveYYSTAGP.
the variables, aka the lowercase girlies 💅
re2c:yyaccept,re2c:variable:yyaccept— defines the API primitiveyyaccept.re2c:yybm,re2c:variable:yybm— defines the API primitiveyybm.re2c:yybm:hex,re2c:variable:yybm:hex— if you set it to nonzero, the bitmaps for the--bit-vectorsoption get generated in hexadecimal format. default is zero, meaning bitmaps come out in decimal 🎀re2c:yych,re2c:variable:yych— defines the API primitiveyych.re2c:yych:emit,re2c:variable:yych:emit— set it to zero and theyychdefinition simply isn't generated. default is non-zero (she's emitted, obviously) ✨re2c:yych:conversion,re2c:variable:yych:conversion— set it to non-zero and re2js automatically generates a conversion toYYCTYPEevery single timeyychis read 👀 default is zero, aka no conversion 💫re2c:yych:literals,re2c:variable:yych:literals— specifies the form of the literals thatyychis matched against. the possible values are:char— character literals in single quotes, and non-printable ones use escape sequences that start with a backslashhex— hexadecimal integerschar_or_hex— a mixture of both: character literals for printable characters, hexadecimal integers for the others 🌈
re2c:yyctable,re2c:variable:yyctable— defines the API primitiveyyctable.re2c:yynmatch,re2c:variable:yynmatch— defines the API primitiveyynmatch.re2c:yypmatch,re2c:variable:yypmatch— defines the API primitiveyypmatch.re2c:yytarget,re2c:variable:yytarget— defines the API primitiveyytarget.re2c:yystable,re2c:variable:yystable— deprecated. that's it, that's the entry 😭re2c:yystate,re2c:variable:yystate— defines the API primitiveyystate.re2c:yyfill,re2c:variable:yyfill— defines the API primitiveyyfill.re2c:yyfill:check— if set to zero, it suppresses the generation of the pre-YYFILLcheck for the number of input characters (that's theYYLESSTHANdefinition in generic API, and theYYLIMIT-based comparison in the C pointer API). default is non-zero, so the check is generated 🫶re2c:yyfill:enable— if set to zero, it suppresses the generation ofYYFILL(together with the check). use this when the whole input fits into one piece of memory — no buffering needed — and the end-of-input checks don't rely on theYYFILLchecks (like when a sentinel character is used, for instance) 🦋
⚠️ bestie listen to me: use the warnings (-Woption) and there2c:sentinelconfiguration to verify that your generated lexer literally cannot read past the end of input. that's not optional behaviour, that's the safety net. the default is non-zero, meaningYYFILLis enabled 💖
re2c:yyfill:parameter— okay bestie, if you set this to zero, it suppresses the generation of the parameter passed toYYFILL💅. That parameter is literally the minimum number of characters that must be supplied. Defaults to non-zero (yes, the parameter is generated). This configuration can be overridden withre2c:YYFILL:nakedorre2c:api:style. ✨re2c:yyfn:sep— specifies the separator used inYYFNelements (defaults to semicolon). 🎀re2c:yyfn:throw— specifies exceptions thrown by theYYFNfunction (defaults to empty, which means no exceptions). 🦋
✨ Regular expressions ✨
re2js uses the following syntax for regular expressions, and no cap it's lowkey iconic: 🧚
"foo"— case-sensitive string literal. 💖'foo'— case-insensitive string literal. 🎀[a-xyz],[^a-xyz]— character class (possibly negated). 🌸.— any character except newline. 🦋R \ S— difference of character classesRandS. 💅R*— zero or more occurrences ofR. ⭐R+— one or more occurrences ofR. 🔥R?— optionalR. 🫶R{n}— repetition ofRexactlyntimes. 👑R{n,}— repetition ofRat leastntimes. 🌈R{n,m}— repetition ofRfromntomtimes. ✨(R)— justR; parentheses are used to override precedence. If submatch extraction is enabled,(R)is a capturing or a non-capturing group depending on--invert-capturesoption. 💖(!R)— if submatch extraction is enabled,(!R)is a non-capturing or a capturing group depending on--invert-capturesoption. 🦋R S— concatenation:Rfollowed byS. 🎀R | S— alternative:RorS. 🌸R / S— lookahead:Rfollowed byS, butSis not consumed. 💅- name — regular expression defined as name (or literal string
"name"in Flex compatibility mode). 🧚 {name}— regular expression defined as name in Flex compatibility mode. ⭐@stag— an s-tag: saves the last input position at which@stagmatches in a variable namedstag. 🔥#mtag— an m-tag: saves all input positions at which#mtagmatches in a variable namedmtag. 👑$— end of input. 💖
Character classes and string literals may contain the following escape sequences: \a, \b, \f, \n, \r, \t, \v, \\, octal escapes \ooo and hexadecimal escapes \xhh, \uhhhh and \Uhhhhhhhh. 🌸
🎬 Actions 🎬
Here is a list of predefined actions supported by re2js — these are the little backstage helpers, iykyk: 💅
!entry code— Entry action binds a user-defined block of code to the start state of the current finite state machine. If start conditions are used, the entry action can be set individually for each condition. This action may be used to perform initialization, e.g. to save start location of a lexeme. 🫶!pre_rule code— Pre-rule action prepends a user-defined block of code to semantic actions of all rules in the current block (or condition, if start conditions are used). This action may be used to factor out the common part of all semantic actions (e.g. saving the end location of a lexeme). 🎀!post_rule code— Post-rule action appends a user-defined block of code to semantic actions of all rules in the current block (or condition, if start conditions are used). This action may be used to emit trap statements that guard against unintended control flow. 🦋
📜 Directives 📜
Here is a full list of directives supported by re2js, bestie — copy these exactly: 💖
!use:name ;— An in-block use directive that merges a previously defined rules block with the specified name into the current block. Named definitions, configurations and rules of the referenced block are added to the current ones. Conflicts between overlapping rules and configurations are resolved in the usual way: the first rule takes priority, and the latest configuration overrides the preceding ones. One exception is the special rules*,$and<!>for which a block-local definition always takes priority. A use directive can be placed anywhere inside of a block, and multiple use directives are allowed. 💅!include file ;— This directive is the same as include block: it inserts file contents verbatim in place of the directive. 🌸
🧠 Program interface 🧠
The generated code interfaces with the outer program with the help of primitives, collectively referred to as the API. 💖 Which primitives should be defined for a particular program depends on multiple factors, including the complexity of regular expressions, input representation, buffering and the use of various features. All the necessary primitives should be defined by the user in the form of macros, functions, variables or any other suitable form that makes the generated code syntactically and semantically correct. re2js 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. 🫶
re2js has three API flavors that define the core set of primitives used by a program: 🌈
- Simple API — This is the default API for the JavaScript backend. It consists of the following primitives:
YYINPUT(which should be defined as a sequence of code units, e.g. a string) andYYCURSOR,YYMARKER,YYCTXMARKER,YYLIMIT(which should be defined as indices inYYINPUT). ✨ - Record API — Record API is useful in cases when lexer state must be stored in an object. It is enabled with
--api recordoption orre2c:api = recordconfiguration. This API consists of a variableyyrecord(the name can be overridden withre2c:yyrecord) that should be defined as an object with propertiesyyinput,yycursor,yymarker,yyctxmarker,yylimit(only the fields used by the generated code need to be defined, and their names can be configured). 🎀 - Generic API — This is the most flexible API. It is enabled with
--api genericoption orre2c:api = genericconfiguration. It contains primitives for generic operations:YYPEEK,YYSKIP,YYBACKUP,YYBACKUPCTX,YYSTAGP,YYSTAGN,YYMTAGP,YYMTAGN,YYRESTORE,YYRESTORECTX,YYRESTORETAG,YYSHIFT,YYSHIFTSTAG,YYSHIFTMTAG,YYLESSTHAN,YYEND. 💅
Here is a full list of API primitives that may be used by the generated code in order to interface with the outer program. 👑
YYCTYPE— the type of the input characters (code units). For ASCII, EBCDIC and UTF-8 encodings it should be 1-byte unsigned integer. For UTF-16 or UCS-2 it should be 2-byte unsigned integer. For UTF-32 it should be 4-byte unsigned integer. 🌸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 is advanced by the generated code. When a rule matches,YYCURSORposition is the one after the last matched character. 🦋YYLIMIT— an r-value that stores the end of input position (a pointer or an integer offset inYYINPUT). InitiallyYYLIMITshould point to the position after the last available input character. It is not changed by the generated code. The lexer comparesYYCURSORtoYYLIMITin order to determine if there are enough input characters left. 💖YYMARKER— an l-value that stores the position of the latest matched rule (a pointer or an integer offset inYYINPUT). It is used to restore theYYCURSORposition if the longer match fails and the lexer needs to rollback. Initialization is not needed. ✨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. 🎀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; zero return value indicates success. Ifre2c:eofis not used, thenYYFILLreturn value is ignored and it should not return on failure. The maximum value oflenisYYMAXFILL. 🔥YYFN— A primitive that defines function prototype in--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 inre2c: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). 👑YYINPUT— an r-value that stores the current input character sequence (string, buffer, etc.). 🌈YYMAXFILL— an integral constant equal to the maximum value of the argument toYYFILL. It can be generated with a max block. ⭐YYLESSTHAN— A generic API primitive with one variablelen. It should be defined as an r-value of boolean type that equals true if and only if there are less thanleninput characters left. 💅YYEND— A generic API primitive with no variables. It should be defined as an r-value of boolean type that equals true if and only if the logical end of input has been reached (excluding any padding or sentinel symbols).YYENDis used to implement$symbol in regular expressions. It differs fromYYLESSTHAN, which is used to ensure that the lexer won't read past the end of buffer. 🫶YYPEEK— A generic API primitive with no variables. It should be defined as an r-value of typeYYCTYPEthat is equal to the character at the current input position. 🌸YYSKIP— A generic API primitive that should advance the current input position by one code unit. 🦋YYBACKUP— A generic API primitive that should save the current input position (to be restored withYYRESTORElater). 🎀YYRESTORE— A generic API primitive that should restore the current input position to the value saved byYYBACKUP. ✨YYBACKUPCTX— A generic API primitive that should save the current input position as the position of the trailing context (to be restored withYYRESTORECTXlater). 💖YYRESTORECTX— A generic API primitive that should restore the trailing context position saved withYYBACKUPCTX. 💅YYRESTORETAG— a generic API primitive rockin' one variable,tag, that should restore the trailing context position back to whatever valuetagis holding. Rewind era 💅YYSTAGP— generic API primitive, one variable,tag— and bestie,tagcan be a pointer or an offset inYYINPUT(peep the submatch extraction section for the deets).YYSTAGPshould settagto the current input position. Slay, we're here, we're present 📍YYSTAGN— same one-variabletagsituation (pointer or offset inYYINPUT, go read the submatch extraction section).YYSTAGNshould settagto a value that represents a non-existent input position. Ghosted, but on purpose 👻YYMTAGP— generic API primitive with one variabletag.YYMTAGPshould append the current position onto the submatch history oftag(submatch extraction section, you know the drill). Adding to the story ✨YYMTAGN— generic API primitive, one variabletag.YYMTAGNshould append a value representing a non-existent input position onto the submatch history oftag(again: submatch extraction section). A little "and then nothing happened" for the timeline 🫥YYSHIFT— generic API primitive with one variable,shift, that should shift the current input position byshiftcharacters (and yeah,shiftcan be negative — we go backwards sometimes, it's fine) 🦋YYCOPYSTAG— generic API primitive with two variables,lhsandrhs, that should copy the right-hand-side s-tag variablerhsinto the left-hand-side s-tag variablelhs. For most languages this primitive has a default definition that assignslhstorhs. Copy-paste but make it compiler 🎀YYCOPYMTAG— generic API primitive with two variables,lhsandrhs, that should copy the right-hand-side m-tag variablerhsinto the left-hand-side m-tag variablelhs. For most languages this primitive has a default definition that assignslhstorhs. Same energy, different tag type 💫YYSHIFTSTAG— generic API primitive with two variables,tagandshift, that should shifttagbyshiftcode units (negative values allowed, we don't judge) 🧚YYSHIFTMTAG— generic API primitive with two variables,tagandshift, that should shift the latest value in the history oftagbyshiftcode units (again,shiftmay be negative) ⭐YYMAXNMATCH— an integral constant equal to the max number of POSIX capturing groups in a rule. It gets generated with amaxnmatchblock. It's giving "the ceiling, literally" 👑YYCONDTYPE— the type of the condition enum. Generated either with aconditionsblock or with the--headeroption. Pick your origin story 🌸YYGETACCEPT— a primitive with one variablevarthat stores the numeric selector of the accepted rule. For most languages this primitive has a default definition that reads fromvar. Reading the room 📖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. Setting the record straight 💅YYGETCOND— an r-value of typeYYCONDTYPEthat's equal to the current condition identifier. Which timeline are we in rn 🌀YYSETCOND— a primitive with one variablecondthat should set the current condition identifier tocond. Switching lanes, no cap 🚗YYGETSTATE— an r-value of integer type equal to the current lexer state. It should be initialized to-1. Starting fresh, before anything happens 🙈YYSETSTATE— a primitive with one variablestatethat should set the current lexer state tostate. Save point activated 💾YYDEBUG— this primitive is generated only with the-d, --debug-outputoption. Its whole purpose is to add 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). Narrating your own life, iconic 🔥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. Not me keeping receipts of the last match 💀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 to replace a ton ofifbranches orswitchcases with one single bit check in the table. Efficiency is the vibe 🌈yych— an l-value of typeYYCTYPEthat stores the current input character. A user definition is necessary only with the-f --storable-stateoption. Hold my current character 🍓yyctable— a jump table generated for the initial condition dispatch (enabled when you combine--conditionsand--computed-gotosoptions). The table of "where do we even begin" 🧭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). Functional besties, this one's for you 🫶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. Counting the group chat members 💜yypmatch— an array of l-values used to hold the tag values corresponding to the capturing parentheses in the matching rule. Array length must be at leastyynmatch * 2(usuallyYYMAXNMATCH * 2is a good choice). Used only with the-P --posix-capturesoption. Size it properly, bestie, no vibes-based memory 💅yystable— deprecated. We don't talk about her 🙈yystate— an l-value used with the--loop-switchoption to store the current DFA state. Where are we? Loop city 🌀yytarget— a jump table containing 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. Every jump needs a destination, periodt 🎯
🌸 Options 🌸
Okay so the ✨lore✨ on options: some of them have a corresponding configuration, and others are global — meaning they literally cannot be changed once re2c starts reading the input file. Fix it before, not after, bestie. Debug options generally require building re2c in debug configuration. And internal options? Those are for experimenting with the algorithms used in re2c. Mad scientist hours 🧪
-? --help -h— show the help message. That's it, that's the option. You're already doing great 🫶--api <simple | record | generic>— specify which API the generated code uses to interface with user-defined code. Picksimplefor simple cases where you don't need buffer refilling and storing lexer state. Pickrecordwhen the lexer state needs to be stored in a record (a struct, a class, whatever). Pickgenericfor the complex cases when the other two APIs just aren't flexible enough. Choose your fighter 🎀--bit-vectors -b— optimize conditional jumps using bit masks. Heads up: this option implies--nested-ifs. Bits doing bits things ✨--captures, --leftmost-captures— enable submatch extraction with leftmost greedy capturing groups. The result gets collected into an arrayyybmatchof capacity2 * YYMAXNMATCH, andyynmatchis set to the number of groups for the matching rule. Catching everything 👑--captvars, --leftmost-captvars— enable submatch extraction with leftmost greedy capturing groups. This time the result gets collected into variablesyytl<k>,yytr<k>for the k-th capturing group. Same tea, different container 🍵--case-insensitive— treat single-quoted and double-quoted strings as case-insensitive. Case? Never heard of her 💅--case-inverted— invert the meaning of single-quoted and double-quoted strings: single-quoted strings become case-sensitive and double-quoted strings become case-insensitive. Plot twist 🌀--case-ranges— collapse consecutive cases inswitchstatements 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. Glow up at every level 🌈--computed-gotos -g— optimize conditional jumps using the non-standard "computed goto" extension (which the compiler must support, so check that first, bestie).re2jsonly generates jump tables 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. Fancy footwork 🔥--computed-gotos-relative— similar to--computed-gotos, except it generates relative offsets for jump tables instead (and again, the compiler must support that). This option implies--computed-gotos. Everything's relative, iykyk 🦋--conditions --start-conditions -c— enable support of Flex-like "conditions": multiple interrelated lexers within one block. This is the alternative to manually specifying differentre2jsblocks connected withgotoor function calls. Choose your multiverse 🌌--depfile FILE— write dependency information toFILEin the form of a Makefile rule<output-file> : <input-file> [include-file ...]. This lets you track build dependencies when include blocks/directives are in play, so that updating include files triggers regeneration of the output file. Note: this option depends on the--outputoption. Receipts for your build system 🧾--ebcdic --ecb -e— generate a lexer that reads input in EBCDIC encoding.re2jsassumes the character range is0--0xFFand the character size is 1 byte. Vintage encoding era 🕰️--empty-class <match-empty | match-none | error>— define howre2jstreats empty character classes. Withmatch-empty(the default) an empty class matches empty input — which is illogical, but backwards-compatible, we love a legacy decision 😭. Withmatch-nonean empty class always fails to match. Witherroran empty class raises a compilation error. Pick your chaos 🌸--encoding-policy <fail | substitute | ignore>— define howre2jstreats Unicode surrogates. Withfail,re2jsaborts with an error when a surrogate is encountered. Withsubstitute,re2jssilently replaces surrogates with the error code point0xFFFD. Withignore(the default)re2jstreats surrogates as normal code points. The Unicode standard says standalone surrogates are invalid, but real-world libraries and programs behave in all kinds of different ways. Real world is messy, bestie 💀--flex-syntax -F— partial support for Flex syntax: in this mode named definitions don't need the equal sign and the terminating semicolon, and when used they must be surrounded with curly braces. Names without curly braces are treated as double-quoted strings. Braces are the whole personality here 🎀
--goto-label— okay so this one is the "goto/label" code model era 💫 it encodes the DFA as labeled code blocks that are all connected with goto transitions hopping across blocks. Tiny catch: it's only supported for languages that actually have a goto statement, so check your fave before you commit 🫶--header,--type-header,-t HEADER— generates a HEADER file 📄 the stuff that goes in it gets specified with the special blocksheader:onandheader:off. And if conditions are used, the generated header will have a condition enum automatically appended to it — unless there's an explicit conditions block, in which case it minds its business ✨-I PATH— adds PATH to the list of locations re2js searches when it's looking for include files 🔍 this one is a whole vibe in combination with an include block or directive. re2js looks for FILE in the directory of the parent file and in the include locations you specified with-I, so it's giving "check both spots bestie" 💅--input <default | custom>— deprecated alias for--api🫠 optiondefaultcorresponds tosimple(which is indeed the default for most backends, but like, not for all of them, don't come for me), and optioncustomcorresponds togeneric.--input-encoding <ascii | utf8>— specifies the way re2js parses regular expressions 👀 withascii(the default!) re2js handles input as ASCII-encoded: any sequence of code units is a sequence of standalone 1-byte characters. withutf8re2js handles input as UTF8-encoded and recognizes multibyte characters 🌈--invert-captures— flips the whole meaning of capturing vs non-capturing groups 🙃 by default(...)is capturing and(! ...)is non-capturing. with this option(! ...)is capturing and(...)is non-capturing. literally a swap, no cap.--lang <none | c | d | go | haskell | java | js | ocaml | python | rust | swift | v | zig>— specifies the target language 💖 supported languages are C, D, Go, Haskell, Java, JS, OCaml, Python, Rust, Swift, V, and Zig (and more languages can be added via user-defined syntax files, see the--syntaxoption 👑). optionnonedisables default syntax configs, so the target language is undefined.--location-format <gnu | msvc>— specifies the location format in messages 📍 withgnulocations print as'filename:line:column: ...', withmsvcthey print as'filename(line,column) ...'. the default isgnu. slay.--loop-switch— here's the "loop/switch" code model 🔁 it encodes the DFA as a loop over a switch statement, where individual states are the switch cases. state lives in a variableyystate. transitions between states updateyystateto the case label of the destination state and continue execution to the head of the loop. it's giving hamster wheel but make it iconic 🐹--computed-continue— heads up, this option requires the--loop-switchcode model ⚠️ it uses computed continue statements to select the next switch case directly, which enables jump-table optimization similar to--computed-gotosin the goto/label code model 🔥--nested-ifs,-s— uses nested if statements instead of switch statements in conditional jumps. this usually results in more efficient code with non-optimizing compilers 💪--no-debug-info,-i— do not output line directives 🚫 this is lowkey useful when the generated code is stored in a version control system (so you avoid huge autogenerated diffs on small changes). honestly, respect.--no-generation-date— suppresses date output in the generated file 🗓️--no-version— suppresses version output in the generated file 🏷️--no-unsafe— do not generate unsafe wrapper overYYPEEK(heads up, this option is specific to Rust 🦀). for performance reasonsYYPEEKshould avoid bounds-checking, since the lexer already performs end-of-input checks in a more efficient way. the user may choose to provide a safeYYPEEKdefinition, or a definition that's unsafe only in release builds — in which case the--no-unsafeoption helps avoid warnings about redundant unsafe blocks ✨--output,-o OUTPUT— specifies the OUTPUT file 📁--posix-captures,-P— enables submatch extraction with POSIX-style capturing groups 💅 the result is collected into an arrayyybmatchof capacity2 * YYMAXNMATCH, andyynmatchis set to the number of groups for the matching rule.--posix-captvars— also enables submatch extraction with POSIX-style capturing groups, but this time the result is collected into variablesyytl<k>,yytr<k>for the k-th capturing group 🎀--recursive-functions— uses a code model based on co-recursive functions, where each DFA state is its own separate function that may call other state-functions or itself 🌀 main character energy, honestly.--reusable,-r— deprecated since version2.2(reusable blocks are allowed by default now, so like… you don't gotta ask anymore) 🙈--skeleton,-S— ignores user-defined interface code and generates a self-contained "skeleton" program 💀 additionally, it generates input files with strings derived from the regular grammar and compressed match results, which are used to verify "skeleton" behavior on all inputs. this option is useful for finding bugs in optimizations and code generation 🐛 and it's supported only for C. periodt.--storable-state,-f— generates a lexer which can store its inner state 🧠 this is useful in push-model lexers, which get stopped by an outer program when there isn't enough input and then resumed when more input becomes available. in this mode users should additionally define theYYGETSTATEandYYSETSTATEprimitives, and the variablesyych,yyacceptandstateshould be part of the stored lexer state 🫡--syntax FILE— loads configurations from the specified FILE and applies them on top of the default syntax file 🌸 note that FILE can define only a few configurations (if it's used to amend the default syntax file), or it can define a whole new language backend — and in the latter case it's recommended to use the--lang noneoption 💡--tags,-T— enables submatch extraction with tags 🏷️✨--ucs2,--wide-chars,-w— generates a lexer that reads UCS2-encoded input. re2js assumes the character range is0--0xFFFFand character size is2bytes. this option implies--nested-ifs💜--utf8,--utf-8,-8— generates a lexer that reads input in UTF-8 encoding. re2js assumes the character range is0--0x10FFFFand character size is1byte 🦋--utf16,--utf-16,-x— generates a lexer that reads UTF16-encoded input. re2js assumes the character range is0--0x10FFFFand character size is2bytes. this option implies--nested-ifs💜--utf32,--unicode,-u— generates a lexer that reads UTF32-encoded input. re2js assumes the character range is0--0x10FFFFand character size is4bytes. this option implies--nested-ifs💜--verbose— outputs a short message in case of success 🎉 tiny lil yay.--vernum,-V— shows version information inMMmmppformat (major, minor, patch) 🔢--version,-v— shows version information ⭐--single-pass,-1— deprecated. does literally nothing (single pass is the default now) 💀 iconic retirement.--debug-output,-d— emitsYYDEBUGinvocations in the generated code. this is useful to trace lexer execution 🔎--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 🕸️--emit-dot,-D— instead of normal output, generates the lexer graph in.dotformat 🎨 the output can be converted to an image with the help of Graphviz, e.g. something like:
dot -Tpng -odfa.png dfa.dot
--dfa-minimization <moore | table>— internal option: the DFA minimization algorithm used by re2js ⚙️ themooreoption is the Moore algorithm (it's the default). thetableoption is the "table filling" algorithm. both algorithms should produce the same DFA up to states relabeling — table filling is simpler and much slower, and serves as a reference implementation 🐢--eager-skip— internal option: makes the generated lexer advance the input position eagerly, like, 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) 📉 so yeah, it's resting now.--no-optimize-tags— internal option: suppresses optimization of tag variables (useful for debugging) 🐞--posix-closure <gor1 | gtop>— internal option: specifies the shortest-path algorithm used for the construction of epsilon-closure with POSIX disambiguation semantics 🧵gor1(the default) stands for the Goldberg-Radzik algorithm, andgtopstands for the "global topological order" algorithm.--posix-prectable <complex | naive>— internal option: specifies the algorithm used to compute the POSIX precedence table 🧮 thecomplexalgorithm computes the precedence table in one traversal of the tag history tree and has quadratic complexity in the number of TNFA states — it's the default. thenaivealgorithm has worst-case cubic complexity in the number of TNFA states, but it's much simpler thancomplexand may be slightly faster in non-pathological cases ✨--stadfa— Internal option, deprecated. It used to enable thestaDFAalgorithm, which differs fromTDFAin that register operations are placed in states rather than on transitions. Benchmarks showed that thestaDFAalgorithm is less efficient thanTDFA. So yeah, it’s giving retired-legend vibes.--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 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. Math girlie optimization moment ✨
⚠️ Warnings ⚠️
Okay so warnings can be individually enabled, disabled and turned into an error. Here’s the whole menu:
-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--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 re2js 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. Infinite loop jump scare 😭-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 the future changes and require fixing. At the moment these rules take precedence when conflicting with other rules, but after the introduction of 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, re2js 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, wherenis 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. Do not ignore this one, bestie 💀-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, 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 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 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 re2js binary. Users may provide a custom syntax file that overrides a few configurations for one of supported languages, or they may choose to redefine all configurations (in that case --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 re2js 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 re2js 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 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 a sequence of string literals, variables, optional elements and lists, or a reference to another code template, or a special value <undefined>. Variables are placeholders that are substituted during code generation phase. List variables are special: when expanding list templates, re2js repeats expressions the right hand side of the column a few times, each time replacing occurrences of the list variable with a value specific to this repetition. Lists have optional bounds (negative values are counted from the end, e.g. -1 means the last element). Conditional names start with a dot. Both conditionals and variables may be either local (specific to the given code template) or global (allowed in all code templates). When re2js reads syntax file, it checks that each code template uses only the variables and conditionals that are allowed in it.
For example, the following code template defines if-then-else construct for a C-like language:
code:if_then_else =
[branch{0}: topindent "if " cond " {" nl
indent [stmt: stmt] dedent]
[branch{1:-1}: topindent "} else" (.cond ? " if " cond) " {" nl
indent [stmt: stmt] dedent]
topindent "}" nl;
Here branch is a list variable: branch{0} expands to the first branch (which is special, as there is no else part), branch{1:-1} expands to all remaining branches (if any). stmt is also a list variable: [stmt: stmt] is a nested list that expands to a list of statements in the body of the current branch. topindent, indent, dedent and nl are global variables, and .cond is a local conditional (their meaning is described below). This code template could produce the following code:
if x {
// do something
} else if y {
// do something else
} else {
// don't do anything
}
Here’s a list of all code templates supported by re2js 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— the declaration/definition of a local variable, bestie. What you get to play with:type(the type of the variable),name(its name) andinit(initial value, if any). Conditional in the house:.init— true if there actually is an initializer 💅code:var_global— literallycode:var_localbut it lives at top-level, main character energy only ✨code:const_local— defining a local constant. Variables:type(the type of the constant),name(its name) andinit(initial value). No.initconditional here, it's always got one, periodt 💖code:const_global— same ascode:const_local, except it's used in top-level. Your global-iconic constants 🎀code:array_local— defining a local array (a table, if we're being fancy). Variables:type(the type of array elements),name(array name),size(its size),row(a list variable that doesn't 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 inside therowlist, iykyk). Conditional:.const— true if the array is immutable 🦋code:array_global— same ascode:array_local, just top-level. Slay 🫶code:array_elem— a reference to one element of an array (table). Variables:array(the name of the array) andindex(index of the element). Cute and indexed 💅code:enum— defining an enumeration. And ngl it can be defined either with a special language construct for enumerations, or just as a few standalone constants — both valid. Variables:type(user-defined enumeration type or type of the constants),elem(a list variable that expands to the name of each member) andinit(initializer for each member). Conditional:.init— true if there's an initializer 🌸code:enum_elem— one enumeration element (a member of a user-defined enumeration type, or the name of a constant, depending on howcode:enumis defined). Variables:name(the name of the element) andtype(its type) ⭐code:assign— an assignment statement. Variables:lhs(left hand side) andrhs(right hand side). The classic ✨code:type_int— signed integer type.intsaid hi 🔥code:type_uint— unsigned integer type. No negatives allowed, we stay positive 💖code:type_yybm— the type of elements in theyybmtable. Yes it's a real name, don't @ me 🌈code:type_yytarget— the type of elements in theyytargettable 🎀code:type_yyctable— the type of elements in theyyctabletable. Three yy-tables, three types, no cap 👑code:cmp_eq— the"equals"operator ⭐code:cmp_ne— the"not equals"operator 💀code:cmp_lt— the"less than"operator 🦋code:cmp_gt— the"greater than"operator 🔥code:cmp_le— the"less or equal"operator 🌸code:cmp_ge— the"greater or equal"operator 💜code:if_then_else— if-then-else, but make it multi-branch. Variables:branch(a list variable that doesn't 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 — and.many— true if there's more than one branch 🧚code:if_then_else_oneline— a specialization ofcode:if_then_elsefor when all the branches have one-line statements. And listen: if this one is<undefined>, thencode:if_then_elseis used instead. Fallback queen 👑code:switch— a switch statement with one or more cases. 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 all map to a single code block. Variables:case(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 when the code block is a single one-line statement. If it's<undefined>,code:switch_casesgets used instead. Same fallback deal, iconic ✨code:switch_case_range— one switch case covering a range of values (and yeah, a range can totally be a single value, no stress). Variable:val(a list variable that expands to all values in the range). 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, because some languages give you special syntax for exactly that case 🦋code:switch_case_default— the default switch case. The catch-all bestie 🫶code:loop— a loop that runs forever, unless something in the loop body interrupts it 😭 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 in the current state) 💀code:continue— a continue statement. Variables:label(label from which to continue execution),val(value passed to a labeled switch) andvar(state variable). Keep it moving 💫code:goto— a goto statement. Variable:label(label of the jump target). We jumping 🦘code:cgoto— a computed goto statement, extra. 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— the initializer expression for a single element in the computed goto table. Variables:label(the label used to initialize the current element),type(underlying type of the elements in the table) andbase(base label — only used if.cgoto.relativeis true). Note the:in the name, that's real, keep it 🌈code:fndecl— a function declaration. Variables:name(function name),type(return type),throw(exceptions thrown by this function — maps tore2c:yyfn:throwconfiguration),arg(a list variable that doesn't itself produce code, but expands the list expression as many times as there are function arguments),argname(name of the current argument) andargtype(type of the current argument). Conditional:.type— true if this is a non-void function 🎀code:fndef— likecode:fndecl, but for function definitions, so it gets one extra list variable:stmt, which expands to all statements in the function body. Same energy, more body 💅code:fncall— a function call statement. 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 a return value needs to be saved ⭐code:tailcall— a tail call statement. 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— the program body with the--recursive-functionscode model. Variables:fn(a list variable that doesn't itself produce 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). Recursion but make it organized 👑code:fingerprint— the fingerprint at the top of the generated output file. Variables:ver(there2jsversion that was used to generate this) anddate(generation date). Leave your signature, icon 💖code:line_info— the format of line directives. And btw: if this is set to<undefined>, then no directives get generated at all. Variables:line(line number) andfile(filename) 🌸code:abort— a statement that aborts program execution. Dramatic exit, but make it intentional 💀code:yydebug— theYYDEBUGstatement, possibly specialized for different APIs. Variables:YYDEBUG,yyrecord,yych(these map to the correspondingre2c:configurations) andstate(DFA state number) 🔍code:yypeek— theYYPEEKstatement, possibly specialized for different APIs. Variables:YYPEEK,YYCTYPE,YYINPUT,YYCURSOR,yyrecord,yych(mapping to the correspondingre2c:configurations). Conditional:.cast— true ifre2c:yych:conversionis set to non-zero 👀code:yyskip— theYYSKIPstatement, possibly specialized for different APIs. Variables:YYSKIP,YYCURSOR,yyrecord(mapping to the correspondingre2c:configurations) 🦋code:yybackup— theYYBACKUPstatement, possibly specialized for different APIs. Variables:YYBACKUP,YYCURSOR,YYMARKER,yyrecord(mapping to the correspondingre2c:configurations) 🎀code:yybackupctx— theYYBACKUPCTXstatement, possibly specialized for different APIs. Variables:YYBACKUPCTX,YYCURSOR,YYCTXMARKER,yyrecord(mapping to the correspondingre2c:configurations). The CTX one, don't skip it 💅code:yyskip_yypeek— a combinedcode:yyskipandcode:yypeekstatement, and it defaults tocode:yyskipfollowed bycode:yypeek. Combo meal ✨code:yypeek_yyskip— a combinedcode:yypeekandcode:yyskipstatement, defaulting tocode:yypeekfollowed bycode:yyskip. Same items, opposite order, pay attention 🔥code:yyskip_yybackup— a combinedcode:yyskipandcode:yybackupstatement, defaulting tocode:yyskipfollowed bycode:yybackup🌈code:yybackup_yyskip— a combinedcode:yybackupandcode:yyskipstatement, defaulting tocode:yybackupfollowed bycode:yyskip💜code:yybackup_yypeek— a combinedcode:yybackupandcode:yypeekstatement, defaulting tocode:yybackupfollowed bycode:yypeek🫶yyskip_yybackup_yypeek— the combo-pack statement:yyskip,yybackupandyypeekall in one (defaults toyyskipfollowed byyybackupfollowed byyypeek) 💫yybackup_yypeek_yyskip— same combo energy but reshuffled order:yybackup, thenyypeek, thenyyskip(that's literally what it defaults to).yyrestore— theYYRESTOREstatement, possibly specialized for different APIs. Supported variables:YYRESTORE,YYCURSOR,YYMARKER,yyrecord(these map to the correspondingre2c:configurations).yyrestorectx— theYYRESTORECTXstatement, possibly specialized for different APIs. Supported variables:YYRESTORECTX,YYCURSOR,YYCTXMARKER,yyrecord(mapping to the correspondingre2c:configurations).yyrestoretag— theYYRESTORETAGstatement, possibly specialized for different APIs. Supported variables:YYRESTORETAG,YYCURSOR,yyrecord(map to the correspondingre2c:configurations), andtag(the name of the tag variable used to restore position).yyshift— theYYSHIFTstatement, possibly specialized for different APIs. Supported variables:YYSHIFT,YYCURSOR,yyrecord(map to the correspondingre2c:configurations), andoffset(the number of code units to shift the current position).yyshiftstag— theYYSHIFTSTAGstatement, possibly specialized for different APIs. Supported variables:YYSHIFTSTAG,yyrecord,negative(map to the correspondingre2c:configurations),tag(the tag variable that needs to be shifted), andoffset(the number of code units to shift). Conditionals:.nested— true if this is a nested tag, in which case its value may equalre2c:tags:negative, which should not be shifted 👀yyshiftmtag— theYYSHIFTMTAGstatement, possibly specialized for different APIs. Supported variables:YYSHIFTMTAG(maps to the correspondingre2c:configuration),tag(the tag variable that needs to be shifted), andoffset(the number of code units to shift).yystagp— theYYSTAGPstatement, possibly specialized for different APIs. Supported variables:YYSTAGP,YYCURSOR,yyrecord(map to the correspondingre2c:configurations), andtag(the tag variable that should be updated).yymtagp— theYYMTAGPstatement, possibly specialized for different APIs. Supported variables:YYMTAGP(maps to the correspondingre2c:configuration) andtag(the tag variable that should be updated).yystagn— theYYSTAGNstatement, possibly specialized for different APIs. Supported variables:YYSTAGN,negative,yyrecord(map to the correspondingre2c:configurations), andtag(the tag variable that should be updated).yymtagn— theYYMTAGNstatement, possibly specialized for different APIs. Supported variables:YYMTAGN(maps to the correspondingre2c:configuration) andtag(the tag variable that should be updated).yycopystag— theYYCOPYSTAGstatement, possibly specialized for different APIs. Supported variables:YYCOPYSTAG,yyrecord(map to the correspondingre2c:configurations),lhs,rhs(the left and right hand side tag variables of the copy operation).yycopymtag— theYYCOPYMTAGstatement, possibly specialized for different APIs. Supported variables:YYCOPYMTAG,yyrecord(map to the correspondingre2c:configurations),lhs,rhs(the left and right hand side tag variables of the copy operation).yygetaccept— theYYGETACCEPTstatement, possibly specialized for different APIs. Supported variables:YYGETACCEPT,yyrecord(map to the correspondingre2c:configurations), andvar(maps to there2c:yyacceptconfiguration).yysetaccept— theYYSETACCEPTstatement, possibly specialized for different APIs. Supported variables:YYSETACCEPT,yyrecord(map to the correspondingre2c:configurations),var(maps to there2c:yyacceptconfiguration), andval(the numeric value of the accepted rule).yygetcond— theYYGETCONDstatement, possibly specialized for different APIs. Supported variables:YYGETCOND,yyrecord(map to the correspondingre2c:configurations), andvar(maps to there2c:yycondconfiguration).yysetcond— theYYSETCONDstatement, possibly specialized for different APIs. Supported variables:YYSETCOND,yyrecord(map to the correspondingre2c:configurations),var(maps to there2c:yycondconfiguration), andval(the numeric condition identifier).yygetstate— theYYGETSTATEstatement, possibly specialized for different APIs. Supported variables:YYGETSTATE,yyrecord(map to the correspondingre2c:configurations), andvar(maps to there2c:yystateconfiguration).yysetstate— theYYSETSTATEstatement, possibly specialized for different APIs. Supported variables:YYSETSTATE,yyrecord(map to the correspondingre2c:configurations),var(maps to there2c:yystateconfiguration), andval(the state number).yylessthan— theYYLESSTHANstatement, possibly specialized for different APIs. Supported variables:YYLESSTHAN,YYCURSOR,YYLIMIT,yyrecord(map to the correspondingre2c:configurations), andneed(the number of code units to check against). Conditional:.many— true if theneedis more than one.yyend— theYYENDexpression, possibly specialized for different APIs. Supported variables:YYEND,YYCURSOR,YYLIMIT.yybm_filter— the condition used to filter outyychvalues that are not covered by theyybmtable (used together with the--bitmapsoption). Supported variable:yych(maps to there2c:yychconfiguration).yybm_match— the format of theyybmtable check (generated with the--bitmapsoption). Supported variables:yybm,yych(map 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).yytarget_filter— the condition used to filter outyychvalues that are not covered by theyytargettable (used together with the--computed-gotosoption). Supported variable:yych(maps to there2c:yychconfiguration).
okay and now, the whole roster 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. Indentation level is tracked and automatically updated by the code generator. ✨
And here's every global conditional that's allowed in syntax files, bestie — no gatekeeping:
.api.simple— true if the simple API is used (--api simpleorre2c:api = simple)..api.generic— true if the generic API is used (--api genericorre2c:api = generic)..api.record— true if the record API is used (--api recordorre2c:api = record)..api_style.functions— true if the function-like API style is used (re2c:api-style = functions)..api_style.freeform— true if the free-form API style is used (re2c:api-style = free-form)..case_ranges— true if the case ranges feature is enabled (--case-rangesorre2c:case-ranges = 1)..cgoto.relative— true if the relative form of computed goto is used (--computed-gotos-relativeorre2c:cgoto:relative = 1)..computed_continue— true if the loop/switch model uses labeled-switch transitions (--computed-continue)..code_model.goto_label— true if the code model based on goto/label is used (--goto-label)..code_model.loop_switch— true if the code model based on loop/switch is used (--loop-switch)..code_model.recursive_functions— true if the code model based on recursive functions is used (--recursive-function)..date— true if the generated fingerprint should contain the generation date..loop_label— true ifre2jsgenerated loops must have a label (re2c:label:yyloopis set to a nonempty string)..monadic— true if the generated code should be monadic (re2c:monadic = 1). This is only relevant for pure functional languages. 🧚.start_conditions— true if start conditions are enabled (--start-conditions)..storable_state— true if storable state is enabled (--storable-state)..unsafe— true ifre2jsshould use "unsafe" blocks in order to generate faster code (--unsafe,re2c:unsafe = 1). This is only relevant for languages that have the "unsafe" feature. 🔥.version— true if the generated fingerprint should contain there2jsversion..yyfill.enable— true ifYYFILLis enabled (re2c:yyfill:enable = 1)..yyfn.throw— true if there2c:yyfn:throwconfiguration is defined to a nonempty string.
🌸 HANDLING THE END OF INPUT 🌸
Okay so literally one of the main problems for a lexer is knowing when to stop 😭 Like, when is it over? There are a few terminating conditions, and here they are:
- the lexer may match some rule (including the default rule
*) and come to a final state 💅 - the lexer may fail to match any rule and come to a default state
- the lexer may reach the end of input 🙈
And here's the thing about that third condition 👀 — the first two terminate the lexer in a nice "natural" way: it reaches a state with no outgoing transitions and the matching just stops by itself. But end of input? It can happen in any state, so the lexer has to actually be ready to handle it.
Checking for the end of input interrupts the normal lexer workflow and adds conditional branches to the generated program, so you lowkey need to minimize the number of those checks. re2js supports a few different methods for handling the end of input, and which one you should use depends on how complex your regular expressions are, whether you need buffering, performance considerations, and other factors. Here's the lineup 💅:
- Sentinel — this method eliminates the need for end of input checks altogether. Simple and efficient, but it's limited to the case where there's a natural "sentinel" character that can never occur in valid input. That character may still occur in invalid input, but your regular expressions shouldn't allow it — except maybe as the last character of a rule. The sentinel gets appended at the end of input and serves as a stop signal 🛑: when the lexer reads this character, it's either a syntax error or the end of input, and in both cases the lexer should stop. This method is used if YYFILL is disabled with
re2c:yyfill:enable = 0;andre2c:eofhas the default value-1. - Sentinel with bounds checks — this one's generic: it lets you handle any input with no restrictions on the regular expressions. The idea is to reduce the number of end of input checks by only performing them on certain characters. Just like the "sentinel" method, one of the characters is chosen as a "sentinel" and appended at the end of input. But there's no restriction on where the sentinel may occur (fr, any character can be chosen as 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's disabled). If more input is supplied, the lexer will rematch the last character and continue as if the sentinel wasn't there. Otherwise it must be the real end of input, and the lexer stops. This method is used when
re2c:eofhas a non-negative value (it should be set to the numeric value of the sentinel). YYFILL is optional. - Bounds checks with padding — generic too, and it may be faster than the "sentinel with bounds checks" method, but it's 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's a problem with short lexemes at the end of input, since the check requires enough characters to cover the longest lexeme. This can be fixed by padding the input with a few fake characters that don't form a valid lexeme suffix (so that the lexer can't match them). The length of padding should be
YYMAXFILL, generated with a max block. If there isn't enough input, the lexer invokes YYFILL, which should supply at least the required number of characters or not return. This method is used if YYFILL is enabled andre2c:eofis-1(this is the default configuration). - Custom checks — the generic API lets you 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 — one little demo per vibe, let's go 🎀
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 here is null: it's the last character of each input string, and none of the rules allow it in the middle of a lexeme (in particular, it's not included in character ranges, where it'd be super easy to overlook 👀). If a null shows up in the middle of a string, that's a syntax error and the lexer will match the default rule *, but it won't read past the end of input or crash (use -Wsentinel-in-midrule warning and re2c:sentinel configuration to verify this). The re2c:yyfill:enable = 0; configuration suppresses the generation of bounds checks and YYFILL invocations.
// re2js $INPUT -o $OUTPUT
// expects a null-terminated string
function lex(yyinput) {
let yycursor = 0;
let count = 0
loop: while (true) {
/*!re2c
re2c:yyfill:enable = 0;
* { return -1 }
[\x00] { return count }
[ ]+ { continue loop }
[a-z]+ { count += 1; continue loop }
*/
}
}
function test(s, n) { if (lex(s) != n) throw "error!"; }
test("\0", 0)
test("one two three\0", 3)
test("f0ur\0", -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, for the record 📝). The program counts space-separated single-quoted strings. The sentinel character is null, specified with the re2c:eof = 0; configuration. Same as in the sentinel method, null is the last character of every input string, but here it's allowed in the middle of a rule — for example 'aaa\0aa'\0 is valid input, but 'aaa\0 is a syntax error. Bounds checks are generated in each state that matches an input character, but they're scoped to the branch that handles null. These bounds checks look like YYLIMIT <= YYCURSOR or YYLESSTHAN(1) with generic API. If the check condition is true, the lexer has reached the end of input and should stop (YYFILL is disabled with re2c:yyfill:enable = 0; since the input fits into one buffer — see the YYFILL with sentinel section for an example that actually uses YYFILL). Reaching the end of input opens three possibilities: if the lexer is in the initial state it'll match the end-of-input rule $, otherwise it may fallback to a previously matched rule (including default rule *) or go to a default state, causing -Wundefined-control-flow.
// re2js $INPUT -o $OUTPUT
// expects a null-terminated string
function lex(yyinput) {
let yycursor = 0;
let yylimit = yyinput.length - 1 // terminating null not included
let count = 0
loop: while (true) {
/*!re2c
re2c:yyfill:enable = 0;
re2c:eof = 0;
str = ['] ([^'\\] | [\\][^])* ['];
* { return -1 }
$ { return count }
[ ]+ { continue loop }
str { count += 1; continue loop }
*/
}
}
function test(s, n) { if (lex(s) != n) throw "error!"; }
test("\0", 0)
test("'qu\0tes' 'are' 'fine: \\'' \0", 3)
test("'unterminated\\'\0", -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's a padding of YYMAXFILL null characters appended at the end of input, where the YYMAXFILL value is autogenerated with a max block. You don't have to use null for the padding — any characters work, as long as they don't form a valid lexeme suffix (in this example the padding shouldn't contain single quotes, since they might get mistaken for a suffix of a single-quoted string). There's a "stop" rule that matches the first padding character (null) and terminates the lexer (note that it checks whether null is at the beginning of the padding, otherwise it's a syntax error). Bounds checks are generated only in some states, determined by the strongly connected components of the underlying automaton. The checks have the form (YYLIMIT - YYCURSOR) < n or YYLESSTHAN(n) with generic API, where n is the minimum number of characters the lexer needs to proceed (which also means the next bounds check will happen in at most n characters). If the check condition is true, the lexer has reached the end of input and will invoke YYFILL(n), which should either supply at least n input characters or not return. In this example YYFILL always fails and terminates the lexer with an error (totally fine, because the input fits into one buffer). See the YYFILL with padding section for an example that refills the input buffer with YYFILL.
// re2js $INPUT -o $OUTPUT
/*!max:re2c*/
function lex(yyinput) {
let yycursor = 0;
let yylimit = yyinput.length
let count = 0
loop: while (true) {
/*!re2c
re2c:YYFILL = "return -1";
str = ['] ([^'\\] | [\\][^])* ['];
[\x00] {
// check that it is the sentinel, not some unexpected null
return (yycursor == yylimit - YYMAXFILL + 1) ? count : -1
}
str { count += 1; continue loop }
[ ]+ { continue loop }
* { return -1 }
*/
}
}
function test(s, n) {
let padded_s = s + "\0".repeat(YYMAXFILL)
if (lex(padded_s) != n) throw "error!"
}
test("", 0)
test("'unterminated\\'", -1)
test("'qu\0tes' 'are' 'fine: \\'' ", 3)
test("'unexpected \0 null", -1)
Custom checks
This example uses a custom end-of-input handling method based on the generic API. The program counts space-separated single-quoted strings. It's the same as the sentinel example, except that the input is not null-terminated. To cover up for the missing sentinel character at the end of input, YYPEEK is redefined to perform a bounds check before it reads the next input character. This is inefficient because the checks are done very often 🥲. If the check condition fails, YYPEEK returns the real character; otherwise it returns a fake sentinel character.
// re2js $INPUT -o $OUTPUT
// expects a string without terminating null
function lex(str) {
let cur = 0;
let lim = str.length
let count = 0
loop: while (true) {
/*!re2c
re2c:api = generic;
re2c:YYPEEK = "cur < lim ? str.charCodeAt(cur) : 0";
re2c:YYSKIP = "cur += 1";
re2c:yyfill:enable = 0;
* { return -1 }
[\x00] { return count }
[ ]+ { continue loop }
[a-z]+ { count += 1; continue loop }
*/
}
}
function test(s, n) { if (lex(s) != n) throw "error!"; }
test("", 0)
test("one two three", 3)
test("f0ur", -1)
okay so picking right back up in the alternative list, the last four rules are honestly such a slay 💅 let me read them out loud:
*→{ return -1 }— the catch-all, the "literally anything else" rule, and it does not pass go, it does not collect$200, it just returns-1. it's giving "nope, not valid, goodbye" 💀[\x00]→{ return count }— the null byte is the end-of-input signal here, so this is the "we're done, hand back whatevercountgot to" moment. main character exit ✨[ ]+→{ continue loop }— a whole run of spaces? skipped. not counted, not returned, just vibes and acontinue loop🎀[a-z]+→{ count += 1; continue loop }— every run of lowercase letters bumpscountby one and then goes right back around the loop 🦋
then */ closes that big comment block (we made it out alive 😭), and the two } close out lex — one for the function, and... yeah, that's the shape of it. } } and we're free 🫶
and then, the part that actually keeps us honest: the test harness 💖
function test(s, n) { if (lex(s) != n) throw "error!"; }
that's it. that's the whole thing. it takes a string s and an expected number n, runs lex(s), and if the result is not n it throws plain old "error!". no fancy assertion library, no little diff output, just an immediate, loud, public "error!" — and honestly? iconic. lowkey the most honest error message in the game 🔥
then the three calls, which are basically the vibe check for the whole lexer:
test("", 0)— empty string in,0expected out 👑test("one two three", 3)— three lowercase runs, socountlands on3, and the spaces just get skipped on the way through 🌸test("f0ur", -1)— and here's the lil gotcha 🫶 that0is not[a-z], so it falls all the way through to the*rule, hits{ return -1 }, and the expected answer is-1— not1, not0,-1🙈
no cap, that last one is the test that earns its keep: it's the one proving your catch-all actually catches 💜
bestie note: the moment you change any rule up there, these three lines are the ones that'll start yelling "error!" at you — and if it throws, it's not being mean, it's doing its job 💅
🌊 BUFFER REFILLING 🌊
okay so buffering? it's giving “we can’t map the whole input into memory at once” energy, bestie. maybe the input is too large, or maybe it’s streaming in (like reading from a socket). the usual technique in such cases is to allocate a fixed-sized memory buffer and process input in chunks that fit into the buffer. when the current chunk is processed, it is moved out and new data is moved in. in practice it is somewhat more complex, because lexer state consists not of a single input position, but a set of interrelated positions:
- cursor: the next input character to be read (
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 re2js API, as it is not needed for the normal lexer operation and can be defined and updated by the user)
- context marker: the position of the trailing context (
YYCTXMARKERin C pointer API orYYBACKUPCTX/YYRESTORECTXin generic API) - tag variables: submatch positions (defined with
stagsandmtagsblocks and generic API primitivesYYSTAGP/YYSTAGN/YYMTAGP/YYMTAGN)
not all these are used in every case, but if used, they must be updated by YYFILL. all active positions are contained in the segment between token and cursor, therefore everything between buffer start and token can be discarded, the segment from token and up to limit should be moved to the beginning of buffer, and the free space at the end of buffer should be filled with new data. in order to avoid frequent YYFILL calls it is best to fill in as many input characters as possible (even though fewer characters might suffice to resume the lexer). the details of YYFILL implementation are slightly different depending on which EOF handling method is used: the case of EOF rule is somewhat simpler than the case of bounds-checking with padding. also note that if -f --storable-state option is used, YYFILL has slightly different semantics (described in the section about storable state).
🧚 YYFILL with sentinel 🧚
if EOF rule is used, YYFILL is a function-like primitive that accepts no arguments and returns a value which is checked against zero. YYFILL invocation is triggered by condition YYLIMIT <= YYCURSOR in C pointer API and YYLESSTHAN() in generic API. a non-zero return value means that YYFILL has failed. a successful YYFILL call must supply at least one character and adjust input positions accordingly. limit must always be set to one after the last input position in buffer, and the character at the limit position must be the sentinel symbol specified by re2c:eof configuration. the pictures below show the relative locations of input positions in buffer before and after YYFILL call (sentinel symbol is marked with #, and the second picture shows the case when there is not enough input to fill the whole buffer).
<-- shift -->
>-A------------B---------C-------------D#-----------E->
buffer token marker limit,
cursor
>-A------------B---------C-------------D------------E#->
buffer, marker cursor limit
token
<-- shift -->
>-A------------B---------C-------------D#--E (EOF)
buffer token marker limit,
cursor
>-A------------B---------C-------------D---E#........
buffer, marker cursor limit
token
here is an example of a program that reads input file input.txt in chunks of 4096 bytes and uses EOF rule.
// re2js $INPUT -o $OUTPUT
const fs = require('fs')
const BUFSIZE = 4096
const OK = 0
const EOF = 1
const LONG_LEXEME = 2
function fill(st) {
if (st.eof) return EOF
// Error: lexeme too long. In real life could reallocate a larger buffer.
if (st.token < 1) return LONG_LEXEME
// Shift buffer contents (discard everything up to the current token).
st.yyinput.copy(st.yyinput, 0, st.token, st.yylimit)
st.yycursor -= st.token;
st.yymarker -= st.token;
st.yylimit -= st.token;
st.token = 0;
// Read a new chunk of data from file and append it to `yyinput`.
let want = BUFSIZE - st.yylimit - 1 // -1 for sentinel
let nread = fs.readSync(st.file, st.yyinput, st.yylimit, want)
st.eof = nread < want // end of file?
st.yylimit += nread
st.yyinput.writeUInt8(0, st.yylimit) // sentinel
return OK
}
function lex(yyrecord, count) {
loop: while (true) {
yyrecord.token = yyrecord.yycursor
/*!re2c
re2c:api = record;
re2c:YYPEEK = "readUInt8";
re2c:YYFILL = "fill(yyrecord) == OK";
re2c:eof = 0;
str = ['] ([^'\\] | [\\][^])* ['];
* { return -1 }
$ { return count }
[ ]+ { continue loop }
str { count += 1; continue loop }
*/
}
}
function main() {
let fname = "input"
// Create input file.
let content = "'qu\0tes' 'are' 'fine: \\'' ".repeat(BUFSIZE)
fs.writeFileSync(fname, content, function(err) { if (err) throw err; })
// Init lexer state.
let limit = BUFSIZE - 1 // exclude terminating null
let st = {
file: fs.openSync(fname, 'r'),
yyinput: Buffer.alloc(BUFSIZE),
yylimit: limit,
yycursor: limit,
yymarker: limit,
token: limit,
eof: false
}
// Run lexer on the prepared file.
if (lex(st, 0) != 3 * BUFSIZE) { throw "error :[" }
// Cleanup.
fs.unlink(fname, function(err){ if (err) throw err; })
}
main()
🧸 YYFILL with padding 🧸
in the default case (when EOF rule is not used) YYFILL is a function-like primitive that accepts a single argument and does not return any value. YYFILL invocation is triggered by condition (YYLIMIT - YYCURSOR) < n in C pointer API and YYLESSTHAN(n) in generic API. the argument passed to YYFILL is the minimal number of characters that must be supplied. if it fails to do so, YYFILL must not return to the lexer (for that reason it is best implemented as a macro that returns from the calling function on failure). in case of a successful YYFILL invocation the limit position must be set either to one after the last input position in buffer, or to the end of YYMAXFILL padding (in case YYFILL has successfully read at least n characters, but not enough to fill the entire buffer). the pictures below show the relative locations of input positions in buffer before and after YYFILL invocation (YYMAXFILL padding on the second picture is marked with # symbols).
<-- shift --> <-- need -->
>-A------------B---------C-----D-------E---F--------G->
buffer token marker cursor limit
>-A------------B---------C-----D-------E---F--------G->
buffer, marker cursor limit
token
<-- shift --> <-- need -->
>-A------------B---------C-----D-------E-F (EOF)
buffer token marker cursor limit
>-A------------B---------C-----D-------E-F###############
buffer, marker cursor limit
token <- YYMAXFILL ->
here is an example of a program that reads input file input.txt in chunks of 4096 bytes and uses bounds-checking with padding.
// re2js $INPUT -o $OUTPUT
const fs = require('fs')
const BUFSIZE = 4096
const OK = 0
const EOF = 1
const LONG_LEXEME = 2
/*!max:re2c*/
function fill(st, need) {
if (st.eof) return EOF
// Error: lexeme too long. In real life could reallocate a larger buffer.
if (st.token < need) return LONG_LEXEME
// Shift buffer contents (discard everything up to the current token).
st.yyinput.copy(st.yyinput, 0, st.token, st.yylimit)
st.yycursor -= st.token;
st.yylimit -= st.token;
st.token = 0;
// Read a new chunk of data from file and append it to `yyinput`.
let want = BUFSIZE - st.yylimit - 1 // -1 for sentinel
let nread = fs.readSync(st.file, st.yyinput, st.yylimit, want)
st.yylimit += nread
if (nread < want) {
st.eof = true // end of file
st.yyinput.write("\0".repeat(YYMAXFILL), st.yylimit)
st.yylimit += YYMAXFILL
}
return OK
}
function lex(yyrecord, count) {
loop: while (true) {
yyrecord.token = yyrecord.yycursor
/*!re2c
re2c:api = record;
re2c:YYPEEK = "readUInt8";
re2c:YYFILL = "if (fill(yyrecord, @@) != OK) return -1;";
str = ['] ([^'\\] | [\\][^])* ['];
[\x00] {
// Check that it is the sentinel, not some unexpected null.
return yyrecord.token == yyrecord.yylimit - YYMAXFILL ? count : -1
}
str { count += 1; continue loop }
[ ]+ { continue loop }
* { return -1 }
*/
}
}
function main() {
let fname = "input"
// Create input file.
let content = "'qu\0tes' 'are' 'fine: \\'' ".repeat(BUFSIZE)
fs.writeFileSync(fname, content, function(err) { if (err) throw err; })
// Init lexer state.
let limit = BUFSIZE - 1 // exclude terminating null
let st = {
file: fs.openSync(fname, 'r'),
yyinput: Buffer.alloc(BUFSIZE),
yylimit: limit,
yycursor: limit,
token: limit,
eof: false
}
// Run lexer on the prepared file.
if (lex(st, 0) != 3 * BUFSIZE) { throw "error :[" }
// Cleanup.
fs.unlink(fname, function(err){ if (err) throw err; })
}
main()
✨ FEATURES ✨
🧩 Multiple blocks 🧩
okay so sometimes you literally need multiple interrelated lexers — like when there's a high-level state machine transitioning between lexer modes. You can do that with multiple connected re2js blocks. Another option is start conditions. 💅
How the connections between blocks work depends on the target language. In languages that have a goto statement (such as C/C++ and Go) one can have all blocks in one function, each of them prefixed with a label. Transition from one block to another is a simple goto. In languages that do not have goto (such as Rust) it is necessary to use a loop with a switch on a state variable, similar to the yystate loop/switch generated by re2js, 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 base and dispatches to other blocks. Common configurations are defined in a separate block at the beginning of the program; they are inherited by the other blocks. 🫶
// re2js $INPUT -o $OUTPUT
/*!re2c // Common re2c definitions shared between all functions.
re2c:api = record;
re2c:yyrecord = st;
re2c:yyfill:enable = 0;
*/
function parse_u32(str) {
let st = {
yyinput: str,
yycursor: 0,
yymarker: 0
}
/*!re2c
'0b' / [01] { return parse_bin(st) }
"0" { return parse_oct(st) }
"" / [1-9] { return parse_dec(st) }
'0x' / [0-9a-fA-F] { return parse_hex(st) }
* { return null }
*/
}
function parse_bin(st) {
n = 0
loop: while (true) {
/*!re2c
[01] { n = n * 2 + (st.yyinput.charCodeAt(st.yycursor - 1) - 48); continue loop }
* { return n }
*/
}
}
function parse_oct(st) {
n = 0
loop: while (true) {
/*!re2c
[0-7] { n = n * 8 + (st.yyinput.charCodeAt(st.yycursor - 1) - 48); continue loop }
* { return n }
*/
}
}
function parse_dec(st) {
n = 0
loop: while (true) {
/*!re2c
[0-9] { n = n * 10 + (st.yyinput.charCodeAt(st.yycursor - 1) - 48); continue loop }
* { return n }
*/
}
}
function parse_hex(st) {
n = 0
loop: while (true) {
/*!re2c
[0-9] { n = n * 16 + (st.yyinput.charCodeAt(st.yycursor - 1) - 48); continue loop }
[a-f] { n = n * 16 + (st.yyinput.charCodeAt(st.yycursor - 1) - 87); continue loop }
[A-F] { n = n * 16 + (st.yyinput.charCodeAt(st.yycursor - 1) - 55); continue loop }
* { return n }
*/
}
}
function test(s, n) {
if (parse_u32(s) != n) throw "error!"
}
test("\0", null)
test("1234567890\0", 1234567890)
test("0b1101\0", 13)
test("0x7Fe\0", 2046)
test("0644\0", 420)
test("9999999999\0", 9999999999)
🎀 Start conditions 🎀
Start conditions are enabled with --start-conditions option. They give you a way to encode multiple interrelated automata within the same re2js block. ✨
Each condition corresponds to a single automaton and has a unique name specified by the user and a unique internal number defined by re2js. The numbers are used to switch between conditions: the generated code uses YYGETCOND and YYSETCOND primitives to get the current condition or set it to the given number. Use conditions block, --header option or re2c:header configuration to generate numeric condition identifiers. Configuration re2c:cond:enumprefix specifies the generated identifier prefix.
In condition mode every rule must be prefixed with a list of comma-separated condition names in angle brackets, or a wildcard <*> to denote all conditions. The rule syntax is extended as follows:
< condition-list > regular-expression code— a rule that is merged to every condition on the condition-list. It matches regular-expression and executes the associated code.< condition-list > regular-expression => condition code— a rule that is merged to every condition on the condition-list. It matches regular-expression, sets the current condition to condition and executes the associated code.< condition-list > regular-expression :=> condition— a rule that is merged to every condition on the condition-list. It matches regular-expression and immediately transitions to condition (there is no semantic action).< condition-list > !action code— a rule that binds code to the place defined by action in every condition on the condition-list (see the actions section for various types of actions).<! condition-list > code— a rule that prepends code to semantic actions of all rules for every condition on the condition-list. This syntax is deprecated and the!pre_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 executes code before 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 to condition.
The code re2js generates for conditions depends on whether re2js uses goto/label approach or loop/switch approach to encode the automata.
In languages that have goto statement (such as C/C++ and Go) conditions are naturally implemented as blocks of code prefixed with labels of the form yyc_<cond>, where cond is a condition name (label prefix can be changed with re2c:cond:prefix). Transitions between conditions are implemented using goto and condition labels. Before all conditions re2js generates an initial switch on YYGETSTATE that jumps to the start state of the current condition. The shortcut rules :=> bypass the initial switch and jump directly to the specified condition (re2c:cond:goto can be used to change the default behavior). The rules with semantic actions do not automatically jump to the next condition; this should be done by the user-defined action code.
In languages that do not have goto (such as Rust) re2js 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 conditions block. 🦋
// re2js $INPUT -o $OUTPUT -c
/*!conditions:re2c*/
function parse_u32(yyinput) {
let yycursor = 0
let yycond = YYC_INIT
let n = 0
loop: while (true) {
/*!re2c
re2c:yyfill:enable = 0;
re2c:indent:top = 2;
<INIT> '0b' / [01] :=> BIN
<INIT> "0" :=> OCT
<INIT> "" / [1-9] :=> DEC
<INIT> '0x' / [0-9a-fA-F] :=> HEX
<INIT> * { return null }
<BIN> [01] { n = n * 2 + (yyinput.charCodeAt(yycursor - 1) - 48); continue loop }
<OCT> [0-7] { n = n * 8 + (yyinput.charCodeAt(yycursor - 1) - 48); continue loop }
<DEC> [0-9] { n = n * 10 + (yyinput.charCodeAt(yycursor - 1) - 48); continue loop }
<HEX> [0-9] { n = n * 16 + (yyinput.charCodeAt(yycursor - 1) - 48); continue loop }
<HEX> [a-f] { n = n * 16 + (yyinput.charCodeAt(yycursor - 1) - 87); continue loop }
<HEX> [A-F] { n = n * 16 + (yyinput.charCodeAt(yycursor - 1) - 55); continue loop }
<BIN, OCT, DEC, HEX> * { return n }
*/
}
}
function test(s, n) {
if (parse_u32(s) != n) throw "error!"
}
test("\0", null)
test("1234567890\0", 1234567890)
test("0b1101\0", 13)
test("0x7Fe\0", 2046)
test("0644\0", 420)
test("9999999999\0", 9999999999)
💾 Storable state 💾
With --storable-state option re2js 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 re2js is a "pull" model, in which the lexer "pulls" more input whenever it needs it. This may be unacceptable in cases when the input becomes available piece by piece (for example, if the lexer is invoked by the parser, or if the lexer program communicates via a socket protocol with some other program that must wait for a reply from the lexer before it transmits the next message). Storable state feature is intended exactly for such cases: it allows one to generate lexers that work in a "push" model. When the lexer needs more input, it stores its state and returns to the caller. Later, when more input becomes available, the caller resumes the lexer exactly where it stopped. There are a few changes necessary compared to the "pull" model: 👑
- Define
YYSETSTATE()andYYGETSTATE(state)primitives. - Define
yych,yyaccept(if used) andstatevariables as a part of persistent lexer state. Thestatevariable 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.
- Lowkey you can optionally use a
getstateblock to spin up theYYGETSTATEswitch, detached from the main lexer. Caveat though: this only works for languages that actually havegoto— so not in--loop-switchmode, bestie. - Use
re2c:eofplus the sentinel-with-bounds-checks method to handle end of input. The padding-based method might just not work here, and here's why, fr fr: it's 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. On top of that, because of high-level program logic, getting more input may depend on processing the lexeme at the end of buffer (which is already blocked thanks to the end-of-input condition). It's giving circular dependency 💀.
Here's an example of a "push" model lexer that simulates reading packets from a socket. The lexer loops until it hits the end of input and then returns to the calling function. The calling function provides more input by "sending" the next packet and resumes lexing. This whole process stops when all packets have been sent, or when there's an error. ✨
// re2js $INPUT -o $OUTPUT -f
const fs = require('fs')
// Use a small buffer to cover the case when a lexeme doesn't fit.
// In real world use a larger buffer.
const BUFSIZE = 10
const DEBUG = false
const END = 0
const READY = 1
const WAITING = 2
const BIG_PACKET = 3
const BAD_PACKET = 4
function log() {
if (DEBUG) console.log.apply(console, arguments)
}
function fill(st) {
// Error: lexeme too long. In real life could reallocate a larger buffer.
if (st.token < 1) return BIG_PACKET
// Shift buffer contents (discard everything up to the current token).
st.yyinput.copy(st.yyinput, 0, st.token, st.yylimit)
st.yycursor -= st.token;
st.yymarker -= st.token;
st.yylimit -= st.token;
st.token = 0;
// Read a new chunk of data from file and append it to `yyinput`.
let want = BUFSIZE - st.yylimit - 1 // -1 for sentinel
let nread = fs.readSync(st.file, st.yyinput, st.yylimit, want)
st.yylimit += nread
st.yyinput.writeUInt8(0, st.yylimit) // sentinel
return READY
}
function lex(yyrecord) {
loop: while (true) {
yyrecord.token = yyrecord.yycursor
/*!re2c
re2c:api = record;
re2c:YYPEEK = "readUInt8";
re2c:YYFILL = "return WAITING";
re2c:eof = 0;
packet = [a-z]+[;];
* { return BAD_PACKET }
$ { return END }
packet { yyrecord.received += 1; continue loop }
*/
}
}
function test(packets, expect) {
// Emulate a "pipe" by opening the same file for reading and writing.
let fname = "input"
let fw = fs.openSync(fname, 'w');
let fr = fs.openSync(fname, 'r');
// Init lexer state.
let limit = BUFSIZE - 1 // exclude terminating null
let st = {
file: fr,
yyinput: Buffer.alloc(BUFSIZE),
yylimit: limit,
yycursor: limit,
yymarker: limit,
token: limit,
yystate: -1,
received: 0
}
// Main loop. The buffer contains incomplete data which appears packet by
// packet. When the lexer needs more input it saves its internal state and
// returns to the caller which should provide more input and resume lexing.
let send = 0
let status
loop: while (true) {
status = lex(st)
if (status == END) {
log("done: got", st.received, "packets")
break loop
} else if (status == WAITING) {
log("waiting...");
if (send < packets.length) {
log("sent packet", send, packets[send])
fs.writeFileSync(fw, packets[send])
send += 1
}
status = fill(st)
log("queue:", st.yyinput.toString())
if (status == BIG_PACKET) {
log("error: packet too big")
break loop
}
if (status != READY) throw "expected READY"
} else {
if (status != BAD_PACKET) throw "expected BAD_PACKET"
log("error: ill-formed packet")
break loop
}
}
// Check results.
if (status != expect) throw "unexpected status"
if (status == END && st.received != send) "unexpected packet count"
// Cleanup.
fs.unlinkSync(fname, function(err){ if (err) throw err; })
}
function main() {
test([], END)
test(["zero;", "one;", "two;", "three;", "four;"], END)
test(["zer0;"], BAD_PACKET)
test(["goooooooooogle;"], BIG_PACKET)
}
main()
🎀 Reusable blocks 🎀
Reusable blocks of the form /*!rules:re2c[:<name>] ... */ or %{rules[:<name>] ... %} can be reused any number of times and combined with other re2js blocks. The <name> is optional. A rules block can be used in a use block or directive. And the code for a rules block is generated at every single point of use — yes, every one, no cap. 💅
Use blocks are defined with /*!use:re2c[:<name>] ... */ or %{use[:<name>] ... %}. The <name> is optional: if it's not specified, the associated rules block is the most recent one (whether named or unnamed — she doesn't discriminate 🫶). A use block can add named definitions, configurations and rules of its own. An important use case for use blocks is a lexer that supports multiple input encodings: the same rules block is reused multiple times with encoding-specific configurations (peep the example below ⬇️).
In-block use directive !use:<name>; can be used from inside of a re2js block. It merges the referenced block <name> into the current one. If some of the merged rules and configurations overlap with the previously defined ones, conflicts get resolved the usual way: the earliest rule takes priority, and the latest configuration overrides preceding ones. One exception are the special rules *, $ and (in condition mode) <!>, for which a block-local definition overrides any inherited ones. The use directive lets you combine different re2js blocks together in one block (again, example below 👇).
Named blocks and the in-block use directive were added in re2js version 2.2. Since that version, reusable blocks are allowed by default (no special option needed, we love a low-effort king 👑). Before version 2.2, reuse mode was enabled with -r, --reusable option. And before version 1.2, reusable blocks could not be mixed with normal blocks. History lesson over, bestie.
🌈 Example of a !use directive
// re2js $INPUT -o $OUTPUT
// This example shows how to combine reusable re2c blocks: two blocks
// ('colors' and 'fish') are merged into one. The 'salmon' rule occurs
// in both blocks; the 'fish' block takes priority because it is used
// earlier. Default rule * occurs in all three blocks; the local (not
// inherited) definition takes priority.
const COLOR = 1
const FISH = 2
const DUNNO = 3
/*!rules:re2c:colors
* { throw "ah" }
"red" | "salmon" | "magenta" { return COLOR }
*/
/*!rules:re2c:fish
* { throw "oh" }
"haddock" | "salmon" | "eel" { return FISH }
*/
function lex(yyinput) {
let yycursor = 0
/*!re2c
re2c:yyfill:enable = 0;
!use:fish;
!use:colors;
* { return DUNNO } // overrides inherited '*' rules
*/
}
function test(s, n) { if (lex(s) != n) throw "error!"; }
test("salmon", FISH)
test("what?", DUNNO)
🦋 Example of a /*!use:re2c ... */ block
// re2js $INPUT -o $OUTPUT --input-encoding utf8
// This example supports multiple input encodings: UTF-8 and UTF-32.
// Both lexers are generated from the same rules block, and the use
// blocks add only encoding-specific configurations.
/*!rules:re2c
re2c:yyfill:enable = 0;
re2c:YYPEEK = "at";
"∀x ∃y" { return yycursor }
* { return null }
*/
function lex_utf8(yyinput) {
let yycursor = 0
/*!use:re2c
re2c:encoding:utf8 = 1;
*/
}
function lex_utf32(yyinput) {
let yycursor = 0
/*!use:re2c
re2c:encoding:utf32 = 1;
*/
}
function test(f, s) {
if (f(s) != s.length) throw "error!"
}
test(lex_utf8, [0xe2, 0x88, 0x80, 0x78, 0x20, 0xe2, 0x88, 0x83, 0x79])
test(lex_utf32, [0x2200, 0x78, 0x20, 0x2203, 0x79])
💖 Submatch extraction 💖
re2js has two options for submatch extraction, and honestly? Both ate. 🍓
⭐ Tags
The first option is to use standalone tags of the form @stag or #mtag, where stag and mtag are arbitrary user-defined names. Tags are enabled with the -T, --tags option or the re2c:tags = 1 configuration. Semantically, tags are position markers: they can be inserted anywhere in a regular expression, and they bind to the corresponding position (or multiple positions) in the input string. S-tags bind to the last matching position, and m-tags bind to a list of positions (they may be used in repetition subexpressions, where a single position in a regular expression corresponds to multiple positions in the input string — iconic behavior, tbh ✨). All tags should be defined by the user, either manually or with the help of svars and mvars blocks. And if there's more than one way tags can be matched against the input, ambiguity is resolved using the leftmost greedy disambiguation strategy. Periodt. 💅
Captures ✨
Option number two, bestie: capturing groups 💖. You turn these on with the --captures option or the re2c:captures = 1 configuration. There are two flavours, and the flavour is literally just about how we disambiguate stuff: --leftmost-captures (the default, queen of the leftmost greedy policy 👑) and --posix-captures, which is the POSIX longest-match policy vibe.
In this mode, every single parenthesized subexpression counts as a capturing group, and you can slap a bang on one to mark it as non-capturing: (! ... ). And if you pass --invert-captures (or set re2c:invert-captures = 1), the meaning of that bang gets flipped upside down 🙈.
The number of groups for the matching rule lives in a variable called yynmatch — and yes, the whole regular expression is group number zero, no cap — and the actual submatch results go into the yypmatch array. Both yynmatch and yypmatch are your job to define, okay? And the size of yypmatch has to be at least [yynmatch * 2]. Use the maxnmatch block to define YYMAXNMATCH, a constant that equals the maximum value of yynmatch among all rules 💅.
Captvars 🎀
Another way to do capturing groups: the --captvars option or re2c:captvars = 1 configuration. The only difference from --captures is how the generated code stores submatch results — instead of yynmatch and yypmatch, re2js generates variables yytl<k> and yytr<k> for the k-th capturing group (and you, yes you, should declare these using an svars block 🫶).
Captures-with-variables supports two disambiguation policies:
--leftmost-captvarsorre2c:leftmost-captvars = 1— leftmost greedy policy, which is the default one 💖--posix-captvarsorre2c:posix-captvars— POSIX longest-match policy
Under the hood, all of 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 case, if there're no tags or captures in a regular expression, TDFA is just an ordinary DFA. And if the number of tags is moderate, the overhead is barely noticeable ✨.
The generated TDFA uses a bunch of tag variables that do not map directly to tags: a single variable may be used for different tags, and a tag may require multiple variables to hold all its possible values. Eventually ambiguity is resolved, and only one final variable per tag survives 👑. Tag variables should be defined using stags or mtags blocks. If lexer state is stored, tag variables should be part of it. They also need to be updated by YYFILL.
S-tags support the following operations:
- save input position to an s-tag:
t = YYCURSORwith C pointer API, or a user-defined operationYYSTAGP(t)with generic API - save default value to an s-tag:
t = NULLwith C pointer API, or a user-defined operationYYSTAGN(t)with generic API - copy one s-tag to another:
t1 = t2
M-tags support the following operations:
- append input position to an m-tag: a user-defined operation
YYMTAGP(t)with both default and generic API - append default value to an m-tag: a user-defined operation
YYMTAGN(t)with both default and generic API - copy one m-tag to another:
t1 = t2
S-tags can be implemented as scalar values (pointers or offsets). M-tags need a more complex representation, because 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 tag value and p is a pointer to 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 👀.
// re2js $INPUT -o $OUTPUT
const assert = require('assert');
function parse(yyinput) {
let yycursor = 0
// Final tag variables available in semantic action.
/*!svars:re2c format = "let @@\n"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = "let @@\n"; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:tags = 1;
num = [0-9]+;
@t1 num @t2 "." @t3 num @t4 ("." @t5 num)? [\x00] {
return {
major: Number(yyinput.substring(t1, t2)),
minor: Number(yyinput.substring(t3, t4)),
patch: t5 == -1 ? 0 : Number(yyinput.substring(t5, yycursor - 1))
}
}
* { return null }
*/
}
assert.deepEqual(parse("23.34\0"), {major: 23, minor: 34, patch: 0})
assert.deepEqual(parse("1.2.99999\0"), {major: 1, minor: 2, patch: 99999})
assert.deepEqual(parse("1.a\0"), null)
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 get adjusted in YYFILL just like other input positions. Note that this 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 👑.
// re2js $INPUT -o $OUTPUT
const assert = require('assert');
const fs = require('fs')
const BUFSIZE = 4096
const OK = 0
const EOF = 1
const LONG_LEXEME = 2
function fill(st) {
if (st.eof) return EOF
// Error: lexeme too long. In real life could reallocate a larger buffer.
if (st.token < 1) return LONG_LEXEME
// Shift buffer contents (discard everything up to the current token).
st.yyinput.copy(st.yyinput, 0, st.token, st.yylimit)
st.yycursor -= st.token;
st.yymarker -= st.token;
st.yylimit -= st.token;
/*!stags:re2c format = "if (st.@@ != -1) st.@@ -= st.token\n"; */
st.token = 0;
// Read a new chunk of data from file and append it to `yyinput`.
let want = BUFSIZE - st.yylimit - 1 // -1 for sentinel
let nread = fs.readSync(st.file, st.yyinput, st.yylimit, want)
st.eof = nread < want // end of file?
st.yylimit += nread
st.yyinput.writeUInt8(0, st.yylimit) // sentinel
return OK
}
function lex(st) {
let vers = []
loop: while (true) {
st.token = st.yycursor
// Final tag variables available in semantic action.
/*!svars:re2c format = "let @@\n"; */
/*!re2c
re2c:api = record;
re2c:yyrecord = st;
re2c:YYPEEK = "readUInt8";
re2c:YYFILL = "fill(st) == OK";
re2c:eof = 0;
re2c:tags = 1;
num = [0-9]+;
num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] {
vers.push({
major: Number(st.yyinput.subarray(st.token, t1)),
minor: Number(st.yyinput.subarray(t2, t3)),
patch: t4 == -1 ? 0 : Number(st.yyinput.subarray(t4, st.yycursor - 1))
})
continue loop
}
$ { return vers }
* { return null }
*/
}
}
function main() {
let fname = "input"
// Create input file.
let content = "1.22.333\n".repeat(BUFSIZE)
fs.writeFileSync(fname, content, function(err) { if (err) throw err; })
// Init lexer state.
let limit = BUFSIZE - 1 // exclude terminating null
let st = {
file: fs.openSync(fname, 'r'),
yyinput: Buffer.alloc(BUFSIZE),
yylimit: limit,
yycursor: limit,
yymarker: limit,
token: limit,
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = "@@: -1,\n"; */
eof: false
}
// Run lexer on the prepared file.
assert.deepEqual(lex(st), Array(BUFSIZE).fill({major: 1, minor: 22, patch: 333}))
// Cleanup.
fs.unlink(fname, function(err){ if (err) throw err; })
}
main()
Here's an example of using capturing groups to parse semantic versions 💅.
// re2js $INPUT -o $OUTPUT
const assert = require('assert');
function parse(yyinput) {
let yycursor = 0
// Final tag variables available in semantic action.
/*!svars:re2c format = "let @@\n"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = "let @@\n"; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:captvars = 1;
num = [0-9]+;
(num) "." (num) ("." num)? [\x00] {
return {
major: Number(yyinput.substring(yytl1, yytr1)),
minor: Number(yyinput.substring(yytl2, yytr2)),
patch: yytl3 == -1 ? 0 : Number(yyinput.substring(yytl3 + 1, yytr3))
}
}
* { return null }
*/
}
assert.deepEqual(parse("23.34\0"), {major: 23, minor: 34, patch: 0})
assert.deepEqual(parse("1.2.99999\0"), {major: 1, minor: 2, patch: 99999})
assert.deepEqual(parse("1.a\0"), null)
And here's an example of using m-tags to parse a version with a variable number of components — tag variables are stored in a trie 🧚.
// re2js $INPUT -o $OUTPUT
const assert = require('assert')
function parse(yyinput) {
let yycursor = 0
// Final tag variables available in semantic action.
/*!svars:re2c format = "let @@\n"; */
/*!mvars:re2c format = "let @@\n"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = "let @@\n"; */
/*!mtags:re2c format = "let @@ = []\n"; */
/*!re2c
re2c:YYMTAGP = "@@.push(yycursor)";
re2c:YYMTAGN = ""; // do nothing
re2c:yyfill:enable = 0;
re2c:tags = 1;
num = [0-9]+;
@t1 num @t2 ("." #t3 num #t4)* [\x00] {
let vers = [Number(yyinput.substring(t1, t2))]
for (let i = 0; i < t3.length; ++i) {
vers.push(Number(yyinput.substring(t3[i], t4[i])))
}
return vers
}
* { return null }
*/
}
assert.deepEqual(parse("1\0"), [1])
assert.deepEqual(parse("1.2.3.4.5.6.7\0"), [1, 2, 3, 4, 5, 6, 7])
assert.deepEqual(parse("1.2.\0"), null)
💜 Encoding support 💜
okay so before we go any further, bestie, you GOTTA understand the difference between code points and code units. A code point is a numeric identifier of a symbol. A code unit is the smallest unit of storage in the encoded text. A single code point may be represented with one or more code units. In a fixed-length encoding all code points are represented with the same number of code units. In a variable-length encoding code points may be represented with a different number of code units.
note that the “any” rule[^]matches any code point, but not necessarily any code unit (the only way to match any code unit regardless of the encoding is the default rule*).
The generated lexer works with a stream of code units: yych stores a code unit, and YYCTYPE is the code unit type. Regular expressions, on the other hand, are specified in terms of code points. When re2js compiles regular expressions to automata it translates code points to code units. This is generally not a simple mapping: in variable-length encodings a single code point range may get translated to a complex code unit graph. The following encodings are supported:
- ASCII — enabled by default. It is a fixed-length encoding with code space
[0-255]and 1-byte code points and code units. - EBCDIC — enabled with
--ebcdicorre2c:encoding:ebcdic. It is a fixed-length encoding with code space[0-255]and 1-byte code points and code units. - UCS2 — enabled with
--ucs2orre2c:encoding:ucs2. It is a fixed-length encoding with code space[0-0xFFFF]and 2-byte code points and code units. - UTF8 — enabled with
--utf8orre2c:encoding:utf8. It is a variable-length Unicode encoding. Code unit size is 1 byte. Code points are represented with 1 -- 4 code units. - UTF16 — enabled with
--utf16orre2c:encoding:utf16. It is a variable-length Unicode encoding. Code unit size is 2 bytes. Code points are represented with 1 -- 2 code units. - UTF32 — enabled with
--utf32orre2c:encoding:utf32. It is a fixed-length Unicode encoding with code space[0-0x10FFFF]and 4-byte code points and code units.
Include files include/unicode_blocks.re, include/unicode_categories.re and include/unicode_properties.re provide re2js 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 re2js that the source file is in UTF8 (it differs from --utf8 which sets input text encoding). Option --encoding-policy specifies the way re2js handles Unicode surrogates (code points in range [0xD800-0xDFFF]).
Below is an example of a lexer for UTF8 encoded Unicode identifiers. iconic behavior honestly ✨
// re2js $INPUT -o $OUTPUT --utf8 -s
/*!include:re2c "unicode_categories.re" */
function lex(yyinput) {
let yycursor = 0
/*!re2c
re2c:yyfill:enable = 0;
// Simplified "Unicode Identifier and Pattern Syntax"
// (see https://unicode.org/reports/tr31)
id_start = L | Nl | [$_];
id_continue = id_start | Mn | Mc | Nd | Pc | [\u200D\u05F3];
identifier = id_start id_continue*;
identifier { return true }
* { return false }
*/
}
if (!lex("_Ыдентификатор\0")) throw "error!"
🦋 Include files 🦋
re2js 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. re2js 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 re2js 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. re2js 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 re2js. Below is an example of using include files. 💅
🌸 Include file 1 (definitions.js) 🌸
const INT = 1
const FLOAT = 2
const NAN = 3
/*!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 FLOAT }
🌸 Input file 🌸
// re2js $INPUT -o $OUTPUT
/*!include:re2c "definitions.js" */
function lex(yyinput) {
let yycursor = 0
/*!re2c
re2c:yyfill:enable = 0;
* { return NAN }
number { return INT }
!include "extra_rules.re.inc";
*/
}
function test(s, n) {
if (lex(s) != n) throw "error!"
}
test("123\0", INT)
test("123.4567\0", FLOAT)
🎀 Header files 🎀
re2js 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 re2js, 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 re2js 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). wild, right? 😭
✨ Input file ✨
// re2js $INPUT -o $OUTPUT --header lexer/state.js
let state = require('./lexer/state.js');
/*!header:re2c:on*/
exports.mk_state = function(str) {
return {
yyinput: str,
/*!stags:re2c format = "@@: 0,\n"; */
yycursor: 0
}
}
/*!header:re2c:off*/
function lex(yyrecord) {
let t
/*!re2c
re2c:api = record;
re2c:tags = 1;
re2c:yyfill:enable = 0;
re2c:header = "lexer/state.js";
[a]* @t [b]* { return t }
*/
}
if (lex(state.mk_state("ab\0")) != 1) {
throw "error!"
}
✨ Header file ✨
// Generated by re2c
exports.mk_state = function(str) {
return {
yyinput: str,
yyt1: 0,
yycursor: 0
}
}
🔥 Skeleton programs 🔥
With the -S, --skeleton option, re2js ignores all non-re2js 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) re2js 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 re2js 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). re2js 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, re2js 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) re2js 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 (re2js writes data to file as soon as it is generated).
🌈 Visualization and debug 🌈
With the -D, --emit-dot option, re2js 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). lowkey obsessed with a good debug dump tbh 🫶
🌟 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). go off, bestie 💅
💖 AUTHORS 💖
okay so bestie, gather round, because this page has lore 🫶
re2jswas originally written by Peter Bumbulis (peter@csg.uwaterloo.ca) in 1993 — yes, 1993, the year of big hair and even bigger regex dreams ✨- Marcus Boerger and Dan Nuffer spent several years turning the original idea into a production ready code generator 💅 the way that's a whole commitment, no cap
- Since then it's 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
- PolarGoose
- Brian Young (
shoutout to every single one of these people fr fr 😭 they carried this thing across decades and that's iconic behavior 👑 those emails are copied exactly as they appear on the page, weird little dash and all, because we do not edit the legends 💀
and that's a wrap on the whole page, bestie 🎀 it's RE2JS(1), and the date stamp lives down at the bottom of the terminal where it always does — go check it there, i'm not retyping it 🙈
slay, read the whole manpage, you're officially a regex girlie now 🌈
📦 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