RE2SWIFT(1)
✨ NAME ✨
Okay bestie, this is the manual for re2swift — that’s RE2SWIFT(1) if we’re being formal 💅. It generates fast lexical analyzers for Swift. Periodt.
🎀 SYNOPSIS 🎀
re2swift [ OPTIONS ] [ WARNINGS ] INPUT
Input can be either a file or - for stdin. Yep, stdin is iconic like that 🫶.
🦋 INTRODUCTION 🦋
Okay so re2swift is literally a preprocessor. It reads the input file — which is usually a program in Swift, 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 re2swift. It translates them to code in Swift and outputs the generated code in place of the block. Slay.
Here’s an example of a small program that checks if a given string contains a decimal number:
// re2swift $INPUT -o $OUTPUT -i
func lex(_ yyinput: UnsafePointer<UInt8>) -> Bool {
var yycursor = 0
/*!re2c
re2c:yyfill:enable = 0;
[1-9][0-9]* { return true }
* { return false }
*/
}
assert(lex("1234"))
In the output, re2swift replaced the block in the middle with the generated code:
/* Generated by re2swift */
// re2swift $INPUT -o $OUTPUT -i
func lex(_ yyinput: UnsafePointer<UInt8>) -> Bool {
var yycursor = 0
var yych: UInt8 = 0
var yystate: UInt = 0
yyl: while true {
switch yystate {
case 0:
yych = yyinput[yycursor]
yycursor += 1
switch yych {
case 0x31...0x39:
yystate = 2
continue yyl
default:
yystate = 1
continue yyl
}
case 1: return false
case 2:
yych = yyinput[yycursor]
switch yych {
case 0x30...0x39:
yycursor += 1
yystate = 2
continue yyl
default:
yystate = 3
continue yyl
}
case 3: return true
default: fatalError("internal lexer error")
}
}
}
assert(lex("1234"))
🌈 BASICS 🌈
A re2swift 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 ofre2swiftsyntax for regular expressions. Once defined, the name can be used in other regular expressions and in rules.
Recursion in named definitions is not allowed, and each name should be defined before it is used. A block inherits named definitions from the global scope. Redefining a name that exists in the current scope is an error 🚨.
configuration = value ;— a configuration allows one to changere2swiftbehavior and customize the generated code. For a full list of configurations supported byre2swift, see the configurations section. Depending on a particular configuration, the value can be a keyword, a nonnegative integer number, or a one-line string which should be enclosed in double or single quotes unless it consists of alphanumeric characters. A block inherits configurations from the global scope and may redefine them or add new ones. Configurations defined inside of a block affect the whole block, even if they appear at the end of it. No cap.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 $.
The default rule should always be defined. It has the lowest priority regardless of its place in the block, and it matches any code unit (not necessarily a valid character — see the encoding support section). The end of input rule should be defined if the corresponding method for handling the end of input is used.
With start conditions, rules have more complex syntax.
!action code— an action binds a user-defined block of code to a particular place in the generated finite state machine (in the same way as semantic actions bind code to the final states). See the actions section for a full list of predefined actions ✨.!directive ;— a directive is one of the special predefined statements. Each directive has a unique purpose. See the directives section for details.
🧚 Blocks 🧚
Block start and end markers are either /*!re2c and */, or %{ and %} (both styles are supported). Starting from version 2.2, blocks may have optional names that allow them to be referenced in other blocks. There are different kinds of blocks:
/*!re2c[:<name>] ... */or%{[:<name>] ... %}— a global block contains definitions, configurations, rules and directives.re2swiftcompiles regular expressions associated with each rule into a deterministic finite automaton, encodes it in the form of conditional jumps in the target language, and replaces the block with the generated code. Names and configurations defined in a global block are added to the global scope and become visible to subsequent blocks. At the start of the program, the global scope is initialized with command-line options./*!local:re2c[:<name>] ... */or%{local[:<name>] ... %}— a local block is like a global block, but the names and configurations in it have local scope (they do not affect other blocks)./*!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 tore2swiftversion 2.2, rules blocks required the-r --reusableoption./*!use:re2c[:<name>] ... */or%{use[:<name>] ... %}— a use block that references a previously defined rules block. If the name is specified,re2swiftlooks 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 tore2swiftversion 2.2, use blocks required the-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 computing theYYMAXFILLvalue (if the list is empty, all blocks are included). By default the generated code is a macro-definition for C (#define YYMAXFILL <n>), or a global variable for Go (var YYMAXFILL int = <n>). It can be customized with an optional configurationformatthat specifies a template string where@@{max}(or@@for short) is replaced with the numeric value ofYYMAXFILL./*!maxnmatch:re2c[:<name1>[:<name2>...]] ... */or%{maxnmatch[:<name1>[:<name2>...]] ... %}— a block that generatesYYMAXNMATCHdefinition (it requires the-P --posix-capturesoption). An optional list of block names specifies which blocks should be included when computing theYYMAXNMATCHvalue (if the list is empty, all blocks are included). By default the generated code is a macro-definition for C (#define YYMAXNMATCH <n>), or a global variable for Go (var YYMAXNMATCH int = <n>). It can be customized with an optional configurationformatthat specifies a template string where@@{max}(or@@for short) is replaced with the numeric value ofYYMAXNMATCH./*!stags:re2c[:<name1>[:<name2>...]] ... */,/*!mtags:re2c[:<name1>[:<name2>...]] ... */or%{stags[:<name1>[:<name2>...]] ... %},%{mtags[:<name1>[:<name2>...]] ... %{— blocks that specify a template piece of code that is expanded for each s-tag/m-tag variable generated byre2swift. An optional list of block names specifies which blocks should be included when computing the set of tag variables (if the list is empty, all blocks are included). There are two optional configurations:formatandseparator. Configurationformatspecifies a template string where@@{tag}(or@@for short) is replaced with the name of each tag variable. Configurationseparatorspecifies a piece of code used to join the generated format pieces for different tag variables./*!svars:re2c[:<name1>[:<name2>...]] ... */,/*!mvars:re2c[:<name1>[:<name2>...]] ... */or%{svars[:<name1>[:<name2>...]] ... %},%{mvars[:<name1>[:<name2>...]] ... %{— blocks that specify a template piece of code that is expanded for each s-tag/m-tag that is either explicitly mentioned by the rules (with the--tagsoption) or implicitly generated byre2swift(with the--captvarsor--posix-captvarsoptions). An optional list of block names specifies which blocks should be included when computing the set of tags (if the list is empty, all blocks are included). There are two optional configurations:formatandseparator. Configurationformatspecifies a template string where@@{tag}(or@@for short) is replaced with the name of each tag. Configurationseparatorspecifies a piece of code used to join the generated format pieces for different tags./*!getstate:re2c[:<name1>[:<name2>...]] ... */or%{getstate[:<name1>[:<name2>...]] ... %}— okay so this one generates a conditional dispatch on the lexer state, and it needs--storable-stateto work at all (like, it will not function without it, no cap). You can drop an optional list of block names to say which blocks get included in the state dispatch. The default transition goes to the start label of the first block on that list. If the list is empty, every block gets 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 not supported withoutgotoor function calls. So yeah, pick one, bestie./*!conditions:re2c[:<name1>[:<name2>...]] ... */,/*!types:re2c... */or%{conditions[:<name1>[:<name2>...]] ... %},%{types... %}— this block generates a condition enumeration (and yup, it requires--conditions). An optional list of block names says which blocks get included when computing the set of conditions — empty list means all blocks are included. By default the generated code is an enumeration calledYYCONDTYPE. You can customize it with the optional configurationsformatandseparator. 🎀 Theformatconfig specifies a template string where@@{cond}(or just@@for short) gets replaced with the name of each condition, and@@{num}gets replaced with that condition's numeric index. Theseparatorconfig specifies a piece of code used to join up the generated format pieces for different conditions. Cute, right?/*!include:re2c <file> */or%{include <file> %}— this lets you include<file>, which must be a double-quoted file path. The contents of the file are literally substituted in place of the block, exactly the way#includeworks in C/C++. You can use this block together with the--depfileoption to generate build system dependencies on the included files. 🫶/*!header:re2c:on*/or%{header:on %}— marks the start of the header file. Everything after it, up until the followingheader:offblock, gets processed byre2swiftand written to the header file specified with the-t --type-headeroption./*!header:re2c:off*/or%{header:off %}— marks the end of the header file started with theheader:on*/block. Matching pair, iconic./*!ignore:re2c ... */or%{ignore ... %}— a block whose contents are ignored and removed from the output file. Poof, gone, we don't talk about it. 💅
✨ Configurations ✨
Here's the full list of configurations re2swift supports, bestie — buckle up:
re2c:api,re2c:input— same as the--apioption.re2c:api:sigil— specifies the marker ("sigil") used for argument placeholders in the API primitives. Default is@@. A placeholder starts with the sigil followed by the argument name in curly braces. For example, if the sigil is set to$, then placeholders take the form${name}. Single-argument APIs may use shorthand notation without the name in braces. This option can be overridden by options for individual API primitives — e.g.re2c:YYFILL@lenforYYFILL.re2c:api:style— specifies 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 following the name of the primitive. The arguments are provided only for autogenerated parameters (such as 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: they should be defined as strings containing free-form pieces of code with interpolated variables of the form@@{var}or@@(these correspond to arguments in function-like style). This configuration may be overridden for individual API primitives — see, for example, there2c:YYFILL:nakedconfiguration forYYFILL.re2c:bit-vectors,re2c:flags:bit-vectors,re2c:flags:b— same as the--bit-vectorsoption, but it can be configured on a per-block basis.re2c:captures,re2c:leftmost-captures— same as the--leftmost-capturesoption, but it can be configured on a per-block basis.re2c:captvars,re2c:leftmost-captvars— same as the--leftmost-captvarsoption, but it can be configured on a per-block basis.re2c:case-insensitive,re2c:flags:case-insensitive— same as the--case-insensitiveoption, but it can be configured on a per-block basis.re2c:case-inverted,re2c:flags:case-inverted— same as the--case-invertedoption, but it can be configured on a per-block basis.re2c:case-ranges,re2c:flags:case-ranges— same as the--case-rangesoption, but it can be configured on a per-block basis.re2c:computed-gotos,re2c:flags:computed-gotos,re2c:flags:g— same as the--computed-gotosoption, but it can be configured on a per-block basis.re2c:computed-gotos:relative,re2c:cgoto:relative— same as the--computed-gotos-relativeoption, but it can be configured on a per-block basis.re2c:computed-gotos:threshold,re2c:cgoto:threshold— if computed goto is used, this specifies the complexity threshold that triggers the generation of jump tables instead of nested if statements 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 valid.re2c:cond:goto— specifies a piece of code used for the autogenerated shortcut rules:=>in conditions. The default isgoto @@;. The@@placeholder is substituted with the condition name (see configurationsre2c:api:sigilandre2c:cond:goto@cond).re2c:cond:goto@cond— specifies the sigil used for argument substitution in there2c:cond:gotodefinition. The default value is@@. This overrides the more genericre2c:api:sigilconfiguration.re2c:cond:divider— defines the divider for condition blocks. The default value is/* *********************************** */. Placeholders are substituted with the condition name (seere2c:api;sigilandre2c:cond:divider@cond).re2c:cond:divider@cond— specifies the sigil used for argument substitution in there2c:cond:dividerdefinition. The default is@@. This overrides the more genericre2c:api:sigilconfiguration.re2c:cond:prefix,re2c:condprefix— specifies the prefix used for condition labels. The default isyyc_.re2c:cond:enumprefix,re2c:condenumprefix— specifies the prefix used for condition identifiers. The default isyyc.re2c:debug-output,re2c:flags:debug-output,re2c:flags:d— same as the--debug-outputoption, but it can be configured on a per-block basis.re2c:empty-class,re2c:flags:empty-class— same as the--empty-classoption, but it can be configured on a per-block basis.re2c:encoding:ebcdic,re2c:flags:ecb,re2c:flags:e— same as the--ebcdicoption, but it can be configured on a per-block basis.re2c:encoding:ucs2,re2c:flags:wide-chars,re2c:flags:w— same as the--ucs2option, but it can be configured on a per-block basis.re2c:encoding:utf8,re2c:flags:utf-8,re2c:flags:8— same as the--utf8option, but it can be configured on a per-block basis.re2c:encoding:utf16,re2c:flags:utf-16,re2c:flags:x— same as the--utf16option, but it can be configured on a per-block basis.re2c:encoding:utf32,re2c:flags:unicode,re2c:flags:u— same as the--utf32option, but it can be configured on a per-block basis.re2c:encoding-policy,re2c:flags:encoding-policy— same as the--encoding-policyoption, but it can be configured on a per-block basis.re2c:eof— specifies the sentinel symbol used with the end-of-input rule$. The default value is-1(meaning the$rule is not used). Other possible values include all valid code units. Only decimal numbers are recognized — no hex shenanigans, bestie.re2c:header,re2c:flags:type-header,re2c:flags:t— specifies the name of the generated header file relative to the directory of the output file. Same as the--headeroption, except that the file path is relative. 👑re2c:indent:string— specifies the string used for indentation. The default is a single tab character"\t". The indent string should contain whitespace characters only. To disable indentation entirely, set this configuration to an empty string.re2c:indent:top— specifies the minimum amount of indentation to use. The default value is zero. The value should be a non-negative integer number.re2c:invert-captures— same as the--invert-capturesoption, but it can be configured on a per-block basis.re2c:label:prefix,re2c:labelprefix— specifies the prefix used for DFA state labels. The default isyy.re2c:label:start,re2c:startlabel— controls the generation of a block start label. The default value is zero, which means the start label is generated only if it's used. An integer value greater than zero forces the generation of the start label even if the lexer doesn't use it. A string value also forces start label generation and sets the label name to the specified string. Heads up: this configuration applies only to the current block — it gets reset to default for the next block. 🌀re2c:label:yyFillLabel— specifies the prefix ofYYFILLlabels used withre2c:eofand in storable state mode.re2c:label:yyloop— specifies the name of the label marking the start of the lexer loop with the--loop-switchoption. The default isyyloop.re2c:label:yyNext— specifies the name of the optional label that follows theYYGETSTATEswitch in storable state mode (enabled withre2c:state:nextlabel). The default isyyNext.re2c:lookahead,re2c:flags:lookahead— deprecated (see the deprecated--no-lookaheadoption). Old news, we've moved on, but she's still here.re2c:monadic— if set to non-zero, the generated lexer will use monadic notation (this configuration is specific to Haskell). 🌸re2c:nested-ifs,re2c:flags:nested-ifs,re2c:flags:s— same as the--nested-ifsoption, but it can be configured on a per-block basis.re2c:posix-captures,re2c:flags:posix-captures,re2c:flags:P— bestie this is literally the same thing as the--posix-capturesoption, except you can set it per-block instead of globally. so you get to be picky about it ✨re2c:posix-captvars— same deal as--posix-captvars, just configurable per-block. that's it, that's the whole vibe 🎀re2c:tags,re2c:flags:tags,re2c:flags:T— identical to the--tagsoption, but you can set it on a per-block basis. per-block girlies rise 🙌re2c:tags:expression— this one sets the expression used for tag variables. default? re2swift spits out expressions shaped likeyyt<N>. which is fine until it's not — like if your tag variables are fields inside a struct, then it's just annoying. every occurrence of@@{tag}or@@gets swapped for the actual tag name. so for example:
re2c:tags:expression = "s.@@";
…gives you expressions of the form s.yyt<N> in the generated code. also peep the re2c:api:sigil configuration while you're at it 💜
re2c:tags:negative— the constant expression used for a negative tag value. typically you'd want-1if tags are integer offsets into the input string, or a null pointer if they're pointers. pick your fighter 🥊re2c:tags:prefix— the prefix for tag variable names. default isyyt. that's the whole thing, no notes ✨re2c:sentinel— sets the sentinel symbol used for end-of-input checks (that's when bounds checks are off viare2c:yyfill:enable = 0;andre2c:eofisn't set). important: this config does not 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 your lexer won't read past the end of the buffer. default value is-1(and in that case re2swift assumes the sentinel is zero, which is the most common case). only decimal numbers are recognized, so don't get cute with it 🚫re2c:state:abort— if you set this to a positive integer value, the default case in the generated state dispatch aborts program execution, and an explicit-1case holds the transition to the start of the block. like, it will straight up end things 💀re2c:state:nextlabel— controls whether theYYGETSTATEswitch is followed by ayyNextlabel. default value is zero, which means no label. alternatively you can usere2c:label:startto generate a specific start label, or an explicitgetstateblock to generate theYYGETSTATEswitch separately from the lexer block. options on options, we love to see it 👑re2c:unsafe,re2c:flags:unsafe— same as the--no-unsafeoption but configurable per-block. set it to zero and it suppresses the generation of unsafe wrappers aroundYYPEEK. default is non-zero, meaning wrappers are generated. heads up: this configuration is specific to Rust 🦀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— sets the sigil used for argument substitution in theYYFILLdefinition. default is@@. this overrides the more genericre2c:api:sigilconfiguration 🎯re2c:YYFILL:naked,re2c:define:YYFILL:naked— overrides the more genericre2c:api:styleconfiguration, specifically forYYFILL. a zero value corresponds to free-form API style.re2c:YYFN— defines the API primitiveYYFN.re2c:YYINPUT— defines the API primitiveYYINPUT.re2c:YYGETCOND,re2c:define:YYGETCONDITION— defines the API primitiveYYGETCOND.re2c:YYGETCOND:naked,re2c:define:YYGETCONDITION:naked— overrides the more genericre2c:api:styleconfiguration forYYGETCOND. zero value = free-form API style.re2c:YYGETSTATE,re2c:define:YYGETSTATE— defines the API primitiveYYGETSTATE.re2c:YYGETSTATE:naked,re2c:define:YYGETSTATE:naked— overrides the more genericre2c:api:styleconfiguration forYYGETSTATE. zero value = free-form API style.re2c:YYGETACCEPT,re2c:define:YYGETACCEPT— defines the API primitiveYYGETACCEPT.re2c:YYLESSTHAN,re2c:define:YYLESSTHAN— defines the generic API primitiveYYLESSTHAN.re2c:YYLIMIT,re2c:define:YYLIMIT— defines the API primitiveYYLIMIT.re2c:YYMARKER,re2c:define:YYMARKER— defines the API primitiveYYMARKER.re2c:YYMTAGN,re2c:define:YYMTAGN— defines the generic API primitiveYYMTAGN.re2c:YYMTAGP,re2c:define:YYMTAGP— defines the generic API primitiveYYMTAGP.re2c:YYPEEK,re2c:define:YYPEEK— defines the generic API primitiveYYPEEK.re2c:YYRESTORE,re2c:define:YYRESTORE— defines the generic API primitiveYYRESTORE.re2c:YYRESTORECTX,re2c:define:YYRESTORECTX— defines the generic API primitiveYYRESTORECTX.re2c:YYRESTORETAG,re2c:define:YYRESTORETAG— defines the generic API primitiveYYRESTORETAG.re2c:YYSETCOND,re2c:define:YYSETCONDITION— defines the API primitiveYYSETCOND.re2c:YYSETCOND@cond,re2c:define:YYSETCONDITION@cond— the sigil used for argument substitution in theYYSETCONDdefinition. default value is@@. 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@@. overrides the more genericre2c:api:sigilconfiguration.re2c:YYSETSTATE:naked,re2c:define:YYSETSTATE:naked— overrides the more genericre2c:api:styleconfiguration forYYSETSTATE. zero value = free-form API style.re2c:YYSETACCEPT,re2c:define:YYSETACCEPT— defines the API primitiveYYSETACCEPT.re2c:YYSKIP,re2c:define:YYSKIP— defines the generic API primitiveYYSKIP.re2c:YYSHIFT,re2c:define:YYSHIFT— defines the generic API primitiveYYSHIFT.re2c:YYCOPYMTAG,re2c:define:YYCOPYMTAG— defines the generic API primitiveYYCOPYMTAG.re2c:YYCOPYSTAG,re2c:define:YYCOPYSTAG— defines the generic API primitiveYYCOPYSTAG.re2c:YYSHIFTMTAG,re2c:define:YYSHIFTMTAG— defines the generic API primitiveYYSHIFTMTAG.re2c:YYSHIFTSTAG,re2c:define:YYSHIFTSTAG— defines the generic API primitiveYYSHIFTSTAG.re2c:YYSTAGN,re2c:define:YYSTAGN— defines the generic API primitiveYYSTAGN.re2c:YYSTAGP,re2c:define:YYSTAGP— defines the generic API primitiveYYSTAGP.re2c:yyaccept,re2c:variable:yyaccept— defines the API primitiveyyaccept.re2c:yybm,re2c:variable:yybm— defines the API primitiveyybm.re2c:yybm:hex,re2c:variable:yybm:hex— set this to nonzero and the bitmaps for the--bit-vectorsoption get generated in hexadecimal format. default is zero, which means bitmaps come out in decimal format. choose your aesthetic 🌈re2c:yych,re2c:variable:yych— defines the API primitiveyych.re2c:yych:emit,re2c:variable:yych:emit— set it to zero and theyychdefinition is simply not generated. default is non-zero.re2c:yych:conversion,re2c:variable:yych:conversion— if you set this to non-zero, re2swift automatically generates a conversion toYYCTYPEevery single timeyychis read. default is zero, meaning no conversion. no cap 🫶re2c:yych:literals,re2c:variable:yych:literals— sets the form of literals thatyychis matched against. the possible values are:char— character literals in single quotes, where non-printable ones use escape sequences starting with a backslashhex— hexadecimal integerschar_or_hex— a mixture of both: character literals for printable characters, hexadecimal integers for the others
pick your poison, all three are valid 💅
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. don't use it, she's retired.re2c:yystate,re2c:variable:yystate— defines the API primitiveyystate.re2c:yyfill,re2c:variable:yyfill— defines the API primitiveyyfill.re2c:yyfill:check— set it to zero and it suppresses the generation of the pre-YYFILLcheck for the number of input characters (that's theYYLESSTHANdefinition in generic API, and theYYLIMIT-based comparison in C pointer API). default is non-zero, i.e. the check is generated. don't turn this off unless you know what you're doing bestie 😭re2c:yyfill:enable— set it to zero and it suppresses the generation ofYYFILL(along with the check). you'd use this when the whole input fits into one piece of memory (no buffering needed) and the end-of-input checks don't rely onYYFILLchecks — like when a sentinel character is in play. use the warnings (-Woption) and there2c:sentinelconfiguration to verify that your generated lexer can't read past the end of input. default is non-zero, meaningYYFILLis enabled. this is a "read the fine print" moment, fr fr ⚠️re2c:yyfill:parameter— set it to zero and it suppresses the generation of the parameter passed toYYFILL. that parameter is the minimum number of characters that must be supplied. defaults to non-zero, so the parameter gets generated. this configuration can be overridden withre2c:YYFILL:nakedorre2c:api:style. stacking configs like makeup layers 💄re2c:yyfn:sep— the separator used inYYFNelements. defaults to semicolon.re2c:yyfn:throw— the exceptions thrown by theYYFNfunction. defaults to empty, which means no exceptions. peaceful ✨
🌸 Regular expressions 🌸
okay so re2swift uses the following syntax for regular expressions — memorize this, it's giving cheat sheet energy:
"foo"— case-sensitive string literal.'foo'— case-insensitive string literal. yes, the quotes matter, don't mix them up 🙈[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 ofRexactly n times.R{n,}— R repeated at leastntimes. like, minimumn, sky's the limit 💫R{n,m}— R repeated fromntomtimes. the classic "between" era 🎀(R)— literally just R bestie, the parentheses are only there to override precedence (grouping flex, iykyk). ⚠️ important: if submatch extraction is enabled,(R)is a capturing or a non-capturing group depending on the--invert-capturesoption. so it's giving "depends on your settings" energy.(!R)— if submatch extraction is enabled,(!R)is a non-capturing or a capturing group depending on the--invert-capturesoption. yes it's the flipped one, that's the whole point 💅R S— concatenation: R followed by S. the "and then" of regex, periodt.R | S— alternative: R or S. pick a lane, either is valid ✨R / S— lookahead: R followed by S, but S is not consumed. it peeks, it doesn't eat. main character energy fr 🫶name— a regular expression defined as name (or the literal string"name"in Flex compatibility mode). lowkey flex-compatible, highkey iconic.{name}— a regular expression defined as name in Flex compatibility mode. braces = flex mode deluxe 🦋@stag— an s-tag: saves the last input position at which@stagmatches in a variable namedstag. one position, final answer 📍#mtag— an m-tag: saves all input positions at which#mtagmatches in a variable namedmtag. collecting them all like pokémon 💀$— end of input. the final boss, the last page, the closing credits 🌈
okay so character classes and string literals can contain these escape sequences, and yes you need all of them:
\a, \b, \f, \n, \r, \t, \v, \\, octal escapes \ooo, and hexadecimal escapes \xhh, \uhhhh and \Uhhhhhhhh.
ngl the \Uhhhhhhhh one is so many h's, but that's literally how it's written so we keep it exactly 💖
🎬 ACTIONS 🎬
here's the full list of predefined actions that re2swift supports. these are the little pre-game rituals for your state machine ✨
!entry code— the entry action binds a user-defined block of code to the start state of the current finite state machine. if start conditions are used, the entry action can be set individually for each condition. this is your get-ready-with-me moment: use it to perform initialization, e.g. to save the start location of a lexeme. 💅!pre_rule code— the 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). it's for factoring out the common part of all semantic actions — e.g. saving the end location of a lexeme. no more copy-paste bestie 🫶!post_rule code— the 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). use it to emit trap statements that guard against unintended control flow. safety girlie behavior, we stan 🛡️
📋 DIRECTIVES 📋
here's the full list of directives re2swift supports — short list but make it count 💫
!use:name ;— an in-block use directive that merges a previously defined rules block with the specifiednameinto 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: the special rules*,$and<!>— for those a block-local definition always takes priority. a use directive can be placed anywhere inside of a block, and multiple use directives are allowed. like, mix and match, it's giving customizable 💐!include file ;— this directive is the same as include block: it insertsfilecontents verbatim in place of the directive. copy-paste but make it official ✨
🔌 PROGRAM INTERFACE 🔌
okay bestie this is the big one, stay with me.
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. re2swift 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.
fr fr this is the "you're on your own but we love you" part — the compiler will not hold your hand here 💀
re2swift has three API flavors that define the core set of primitives used by a program:
🌸 Simple API 🌸
this is the default for the Swift backend. it consists of the following primitives: YYINPUT (which should be defined as a sequence of code units, e.g. a string) and YYCURSOR, YYMARKER, YYCTXMARKER, YYLIMIT (which should be defined as indices into YYINPUT). simple, clean, default slay 💅
🎀 Record API 🎀
the Record API is useful in cases when lexer state must be stored in an object. it is enabled with the --api record option or re2c:api = record configuration. this API consists of a variable yyrecord (the name can be overridden with re2c:YYRECORD) that should be defined as a struct or class with fields yyinput, yycursor, yymarker, yyctxmarker, yylimit — only the fields used by the generated code need to be defined, and their names can be configured. objectified lexer state, we love a struct moment 🦋
🧚 Generic API 🧚
this is the most flexible API. it is enabled with the --api generic option or re2c:api = generic configuration. this API contains the following primitives for generic operations: YYPEEK, YYSKIP, YYBACKUP, YYBACKUPCTX, YYSTAGP, YYSTAGN, YYMTAGP, YYMTAGN, YYRESTORE, YYRESTORECTX, YYRESTORETAG, YYSHIFT, YYSHIFTSTAG, YYSHIFTMTAG, YYLESSTHAN, YYEND. maximum flexibility, maximum work, but honestly iconic 😌
for example, if the input is a zero-terminated array of bytes buffer: [UInt8], variables cursor, limit, marker and ctxmarker of type Int represent input positions, and -1 represents invalid positions, then a generic API can be defined as follows:
/*!re2c
re2c:YYPEEK = "buffer[cursor]";
re2c:YYSKIP = "cursor++";
re2c:YYBACKUP = "marker = cursor";
re2c:YYRESTORE = "cursor = marker";
re2c:YYBACKUPCTX = "ctxmarker = cursor";
re2c:YYRESTORECTX = "cursor = ctxmarker";
re2c:YYRESTORETAG = "cursor = ${tag}";
re2c:YYLESSTHAN = "limit - cursor < @@{len}";
re2c:YYEND = "limit == cursor";
re2c:YYSTAGP = "@@{tag} = cursor";
re2c:YYSTAGN = "@@{tag} = -1";
re2c:YYSHIFT = "cursor += @@{shift}";
re2c:YYSHIFTSTAG = "@@{tag} += @@{shift}";
*/
here's the full list of API primitives that may be used by the generated code in order to interface with the outer program. buckle up 💖
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. match the width to the encoding, that's the whole vibe 🌈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. it's always one step ahead, main character energy 👑YYLIMIT— an r-value that stores the end of input position (a pointer or an integer offset inYYINPUT). initiallyYYLIMITshould point to the position after the last available input character. it is not changed by the generated code. the lexer comparesYYCURSORtoYYLIMITin order to determine if there are enough input characters left. the responsible one in the group chat 🫶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. the "undo" button basically ↩️YYCTXMARKER— an l-value that stores the position of the trailing context (a pointer or an integer offset inYYINPUT). no initialization is needed.YYCTXMARKERis needed only if the lookahead operator/is used. context queen 📍YYFILL— a generic API primitive with one variablelen.YYFILLshould provide at leastlenmore input characters or fail. ifre2c:eofis used, thenlenis always1andYYFILLshould always return to the calling function; zero return value indicates success. ifre2c:eofis not used, thenYYFILLreturn value is ignored and it should not return on failure. the maximum value oflenisYYMAXFILL. 🚨 two different failure regimes, don't mix them up!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). multifunctional fr 💫YYINPUT— an r-value that stores the current input character sequence (string, buffer, etc.). the actual content, the material, the moment 📚YYMAXFILL— an integral constant equal to the maximum value of the argument toYYFILL. it can be generated with amaxblock. the ceiling, literally.YYLESSTHAN— a generic API primitive with one variablelen. it should be defined as an r-value of boolean type that equalstrueif and only if there are less thanleninput characters left. the "are we running out" check 🕵️YYEND— a generic API primitive with no variables. it should be defined as an r-value of boolean type that equalstrueif and only if the logical end of input has been reached (excluding any padding or sentinel symbols).YYENDis used to implement the$symbol in regular expressions. it differs fromYYLESSTHAN, which is used to ensure that the lexer won't read past the end of buffer. ⚠️ these two are not the same thing, bestie, don't swap them!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. a little peek, harmless, iconic 👀YYSKIP— a generic API primitive that should advance the current input position by one code unit. baby steps, one at a time ✨YYBACKUP— a generic API primitive that should save the current input position (to be restored withYYRESTORElater). bookmark behavior 🔖YYRESTORE— a generic API primitive that should restore the current input position to the value saved byYYBACKUP. the bookmark gets used, we love a callback 💅YYBACKUPCTX— a generic API primitive that should save the current input position as the position of the trailing context (to be restored withYYRESTORECTXlater). context bookmark, different bookmark 📌YYRESTORECTX— a generic API primitive that should restore the trailing context position saved withYYBACKUPCTX. and the context bookmark gets used too 🎀YYRESTORETAG— a generic API primitive with one variable,tag, and its whole job is to restore the trailing context position to whatevertagsays. ✨YYSTAGP— generic API primitive, one variabletag, andtagcan be a pointer or an offset inYYINPUT(peep the submatch extraction section for the tea 🍵).YYSTAGPshould settagto the current input position.YYSTAGN— generic API primitive, one variabletag, pointer or offset inYYINPUTagain (same submatch extraction section, iykyk).YYSTAGNshould settagto a value that represents a non-existent input position.YYMTAGP— generic API primitive with one variabletag.YYMTAGPshould append the current position to the submatch history oftag(yes, the submatch extraction section again 🫶).YYMTAGN— generic API primitive with one variabletag.YYMTAGNshould append a value that represents a non-existent input position to the submatch history oftag(see the submatch extraction section for details).YYSHIFT— generic API primitive with one variableshiftthat should shift the current input position byshiftcharacters. And ngl, the shift value may be negative (yes bestie, backwards is allowed 💅).YYCOPYSTAG— generic API primitive with two variables,lhsandrhs, that should copy the right-hand-side s-tag variablerhsto the left-hand-side s-tag variablelhs. For most languages this primitive has a default definition that assignslhstorhs.YYCOPYMTAG— generic API primitive with two variables,lhsandrhs, that should copy the right-hand-side m-tag variablerhsto the left-hand-side m-tag variablelhs. For most languages this primitive has a default definition that assignslhstorhs.YYSHIFTSTAG— generic API primitive with two variables,tagandshift, that should shifttagbyshiftcode units (and yup, the shift value may be negative).YYSHIFTMTAG— generic API primitive with two variables,tagandshift, that should shift the latest value in the history oftagbyshiftcode units (negative shift value? still valid, bestie).YYMAXNMATCH— an integral constant equal to the maximal number of POSIX capturing groups in a rule. It's generated with amaxnmatchblock. 🎀YYCONDTYPE— the type of the condition enum. It can be generated either with aconditionsblock or the--headeroption.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.YYSETACCEPT— a primitive with two variables:var(an l-value that stores the numeric selector of the accepted rule) andval(the value of the selector). For most languages this primitive has a default definition that assignsvartoval.YYGETCOND— an r-value of typeYYCONDTYPEthat equals the current condition identifier.YYSETCOND— a primitive with one variablecondthat should set the current condition identifier tocond.YYGETSTATE— an r-value of integer type that equals the current lexer state. It should be initialized to-1. 🙈YYSETSTATE— a primitive with one variablestatethat should set the current lexer state tostate.YYDEBUG— this one is generated only with the-d,--debug-outputoption. Its whole purpose is adding logging to the generated code (a typicalYYDEBUGdefinition is a print statement, iconic).YYDEBUGstatements get generated in every state and carry two variables:state(either a DFA state index or-1) andsymbol(the current input symbol).yyaccept— an l-value of unsigned integral type that stores the number of the latest matched rule. You only need to define it yourself with the--storable-stateoption.yybm— a table containing compressed bitmaps for up to 8 transitions (used with the--bitmapsoption). The table has256elements 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? Replace a millionifbranches orswitchcases with one single bit check in the table. Efficiency ate. 🔥yych— an l-value of typeYYCTYPEthat stores the current input character. You only need to define it yourself with-f--storable-state.yyctable— a jump table generated for the initial condition dispatch (enabled with the combo of--conditionsand--computed-gotosoptions). Slay.yyfill— an l-value that stores the result of theYYFILLcall (this may be necessary for pure functional languages, whereYYFILLis a monadic function with a complex return value).yynmatch— an l-value of unsigned integral type that stores the number of POSIX capturing groups in the matched rule. Used only with the-P--posix-capturesoption.yypmatch— an array of l-values used to hold the tag values corresponding to the capturing parentheses in the matching rule. Array length must be at leastyynmatch * 2(usuallyYYMAXNMATCH * 2is a solid choice 💜). Used only with the-P--posix-capturesoption.yystable— deprecated. That's it. That's the whole entry. 💀yystate— an l-value used with the--loop-switchoption to store the current DFA state.yytarget— a jump table containing jump targets (label addresses) for all transitions from a state. This table is local to each state. Generation ofyytargettables is enabled with the--computed-gotosoption.
✨ Options ✨
Okay so heads up before we dive in: some of these options have corresponding configurations, others are global and straight up cannot be changed after re2c starts reading the input file. Debug options generally require building re2c in debug configuration. And the internal options? Those are for experimenting with the algorithms used in re2c — very much lab-coat main character energy. 🧚
-?,--help,-h— show the help message. Your classic "bestie I'm lost" button. 🫶--api <simple | record | generic>— specify the API that the generated code uses to interface with used-defined code. Usesimplein simple cases when there's no need for buffer refilling and storing lexer state. Userecordwhen the lexer state needs to be stored in a record (struct, class, etc.). Usegenericin complex cases when the other two APIs just aren't flexible enough. 🌈--bit-vectors,-b— optimize conditional jumps using bit masks. This option implies--nested-ifs.--captures,--leftmost-captures— enable submatch extraction with leftmost greedy capturing groups. The result is collected into an arrayyybmatchof capacity2 * YYMAXNMATCH, andyynmatchis set to the number of groups for the matching rule. 🎀--captvars,--leftmost-captvars— enable submatch extraction with leftmost greedy capturing groups. The result is collected into variablesyytl<k>,yytr<k>for the k-th capturing group.--case-insensitive— treat single-quoted and double-quoted strings as case-insensitive.--case-inverted— invert the meaning of single-quoted and double-quoted strings: treat single-quoted strings as case-sensitive and double-quoted strings as case-insensitive. Yes, it's the flip. 🔄--case-ranges— collapse consecutive cases in switch statements 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. Smaller and faster? Obsessed. 💅--computed-gotos,-g— optimize conditional jumps using the non-standard "computed goto" extension (which must be supported by the compiler).re2swiftgenerates jump tables only in complex cases with a lot of conditional branches. The complexity threshold can be configured with thecgoto:thresholdconfiguration. Relative offsets can be enabled with thecgoto:relativeconfiguration. This option implies--bit-vectors.--computed-gotos-relative— similar to--computed-gotosbut generate relative offsets for jump tables instead (which, again, must be supported by the compiler). This option implies--computed-gotos.--conditions,--start-conditions,-c— enable support of Flex-like "conditions": multiple interrelated lexers within one block. This is the alternative to manually specifying differentre2swiftblocks connected withgotoor function calls. 🦋--depfile FILE— write dependency information toFILEin the form of a Makefile rule<output-file> : <input-file> [include-file ...]. This lets you track build dependencies in the presence of include blocks/directives, so that updating include files triggers regeneration of the output file. This option depends on the--outputoption.--ebcdic,--ecb,-e— generate a lexer that reads input in EBCDIC encoding.re2swiftassumes that the character range is0--0xFFand the character size is 1 byte.--empty-class <match-empty | match-none | error>— define the wayre2swifttreats empty character classes. Withmatch-empty(the default) an empty class matches empty input (which is illogical, but backwards-compatible — yes, we know 😭). Withmatch-nonean empty class always fails to match. Witherroran empty class raises a compilation error.--encoding-policy <fail | substitute | ignore>— define the wayre2swifttreats Unicode surrogates. Withfail,re2swiftaborts with an error when a surrogate is encountered. Withsubstitute,re2swiftsilently replaces surrogates with the error code point0xFFFD. Withignore(the default),re2swifttreats surrogates as normal code points. The Unicode standard says standalone surrogates are invalid, but real-world libraries and programs behave in different ways. 🤷♀️--flex-syntax,-F— partial support for Flex syntax: in this mode named definitions don't need the equal sign and the terminating semicolon, and when used they must be surrounded with curly braces. Names without curly braces are treated as double-quoted strings. 🌸--goto-label— bestie this one uses the "goto/label" code model: the DFA gets encoded as labeled code blocks all holding hands viagototransitions across blocks 🫶. Lowkey only works for languages that actually have agotostatement, so don't come crying to me if your fave lang ghosts you.--header,--type-header,-t HEADER— generate aHEADERfile ✨. You get to pick what goes inside with the special blocksheader:onandheader:off. And if conditions are in play, the generated header just… automatically gets a condition enum slapped on the end (unless you were like "no bestie I got this" and wrote an explicit conditions block). It's giving prepared.-I PATH— addsPATHto the list of locations re2swift searches when it's hunting for include files 🔍. Chef's kiss when you pair it with theincludeblock or directive. re2swift looks forFILEin the directory of the parent file and in the include locations you specified with-I. Periodt.--input <default | custom>— ok so this is a deprecated alias for--api, noted 💀.defaultmaps tosimple(and yeah it really is the default for most backends — but not all of them, so don't @ me).custommaps togeneric.--input-encoding <ascii | utf8>— tells re2swift how to parse your regular expressions 🎀. Withascii(the default, and yes that's fr the default) re2swift handles input as ASCII-encoded: any sequence of code units is a sequence of standalone 1-byte characters. Withutf8it handles input as UTF8-encoded and recognizes multibyte characters 🦋.--invert-captures— flips the whole meaning of capturing vs non-capturing groups, chaos mode 🙈. By default(...)is capturing and(! ...)is non-capturing. With this option it's the other way around:(! ...)is capturing and(...)is non-capturing.--lang <none | c | d | go | haskell | java | js | ocaml | python | rust | swift | v | zig>— picks your target language 👑. The supported ones are C, D, Go, Haskell, Java, JS, OCaml, Python, Rust, Swift, V, Zig (and more languages can be added via user-defined syntax files — see the--syntaxoption, iykyk). Optionnonedisables default syntax configs, so the target language is just… undefined, main character of nothing 🌈.--location-format <gnu | msvc>— how messages print their locations 📍. Withgnulocations show up as'filename:line:column: ...'. Withmsvcthey show up as'filename(line,column) ...'. The default isgnu.--loop-switch— the "loop/switch" code model bestie! Encodes the DFA as a loop over aswitchstatement where individual states areswitchcases 🔁. State lives in a variable calledyystate. Transitions between states updateyystateto the case label of the destination state and then continue execution to the head of the loop. It's giving merry-go-round.--computed-continue— heads up, this one requires the--loop-switchcode model, no exceptions 🙅. It uses computedcontinuestatements to pick the nextswitchcase directly, which enables jump-table optimization similar to--computed-gotosin thegoto/labelcode model. Speed 💅.--nested-ifs,-s— uses nestedifstatements instead ofswitchstatements in conditional jumps 🎀. Usually gives you more efficient code when your compiler is out here not optimizing. (We love a compiler that minds its own business.)--no-debug-info,-i— do not output line directives 🚫. Genuinely useful when the generated code lives in a version control system, because otherwise you get huge autogenerated diffs on the tiniest little change and it's a whole thing 😭.--no-generation-date— suppresses date output in the generated file 📅. No timestamps, no drama.--no-version— suppresses version output in the generated file 🏷️.--no-unsafe— don't generate the unsafe wrapper overYYPEEK(Rust only, bestie, this one's specific) 🦀. For performance reasonsYYPEEKshould avoid bounds-checking since the lexer already does end-of-input checks in a much more efficient way. You can choose to provide a safeYYPEEKdefinition, or one that's unsafe only in release builds — and in that case,--no-unsafehelps you dodge warnings about redundantunsafeblocks. So considerate 💜.--output,-o OUTPUT— specifies theOUTPUTfile 📁. That's it. That's the whole vibe.--posix-captures,-P— enables submatch extraction with POSIX-style capturing groups ✨. The result gets collected into an arrayyybmatchof capacity2 * YYMAXNMATCH, andyynmatchis set to the number of groups for the matching rule. Numbers are exact, don't come for me.--posix-captvars— also enables submatch extraction with POSIX-style capturing groups, but this time the result goes into variablesyytl<k>,yytr<k>for the k-th capturing group 🎀. Same energy, different storage.--recursive-functions— code model based on co-recursive functions 🌀, where each DFA state is its own separate function that may call other state-functions… or itself. Very "I contain multitudes" of it.--reusable,-r— deprecated since version 2.2 💀 (reusable blocks are allowed by default now, so this one's just vibing in the past).--skeleton,-S— ignores user-defined interface code and generates a self-contained"skeleton"program 🦴. It also generates input files with strings derived from the regular grammar plus compressed match results, and those get used to verify"skeleton"behavior on all inputs. This is the bug-hunting option — great for finding bugs in optimizations and code generation. Only supported for C though, sorry to the rest of y'all. This option is supported only for C.--storable-state,-f— generates a lexer that can store its inner state 🧠. Useful for push-model lexers that an outer program stops when there's not enough input, and then resumes when more input shows up. In this mode you should additionally define theYYGETSTATEandYYSETSTATEprimitives, and the variablesyych,yyacceptandstateshould be part of the stored lexer state. Don't forget, bestie, I'm serious 🫶.--syntax FILE— loads configurations from the specifiedFILEand applies them on top of the default syntax file 🌸. Note thatFILEcan define only a few configurations (if it's being used to amend the default syntax file), or it can define a whole entire new language backend — and in that latter case it's recommended to use the--lang noneoption. Big-brain move.--tags,-T— enables submatch extraction with tags 🏷️✨.--ucs2,--wide-chars,-w— generates a lexer that reads UCS2-encoded input 🎀. re2swift assumes the character range is0--0xFFFFand character size is2bytes. Heads up: this option implies--nested-ifs.--utf8,--utf-8,-8— generates a lexer that reads input in UTF-8 encoding 🦋. re2swift assumes the character range is0--0x10FFFFand character size is1byte.--utf16,--utf-16,-x— generates a lexer that reads UTF16-encoded input 💜. re2swift assumes the character range is0--0x10FFFFand character size is2bytes. And yup, this option implies--nested-ifstoo.--utf32,--unicode,-u— generates a lexer that reads UTF32-encoded input 🌈. re2swift assumes the character range is0--0x10FFFFand character size is4bytes. Also implies--nested-ifs. We stan a consistent family of options.--verbose— outputs a short message in case of success 🎉. Tiny little "you did it" energy.--vernum,-V— shows version information inMMmmppformat (major, minor, patch) 🔢. Numbers, not vibes.--version,-v— shows version information 💅.--single-pass,-1— deprecated. Does nothing (single pass is the default now). Literally a decorative flag at this point 🙈.--debug-output,-d— emitsYYDEBUGinvocations in the generated code 🔍. Great for tracing lexer execution, aka watching your baby run.--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 🎨. You can convert the output to an image with the help of Graphviz — e.g. something likedot -Tpng -odfa.png dfa.dot. Aesthetic.--dfa-minimization <moore | table>— internal option: the DFA minimization algorithm re2swift uses 🧮. 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 —tablefilling is simpler and much slower, and it serves as a reference implementation. Slow but honest 💀.--eager-skip— internal option: makes the generated lexer advance the input position eagerly — immediately after reading the input symbol 🏃♀️. This changes the default behavior, where the input position is advanced lazily — after transition to the next state.--no-lookahead— internal option, deprecated 🙈. It used to enable the TDFA(0) algorithm. Unlike TDFA(1), the TDFA(0) algorithm doesn't use one-symbol lookahead — it applies register operations to the incoming transitions rather than the outgoing ones. Benchmarks showed TDFA(0) is less efficient than TDFA(1), so yeah, it's retired.--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 constructing the 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. Lowkey a whole personality difference between them 😭.--stadfa— bestie this one is an internal option and it's deprecated, so don't get attached 💀. It used to turn on the staDFA algorithm, which is different from TDFA in that register operations are placed in states rather than on transitions. Benchmarks showed staDFA is less efficient than TDFA, so yeah, it's giving "retired icon" energy.--fixed-tags <none | toplevel | all>— another internal option: tells re2swift whether the fixed-tag optimization should be applied to all tags (all), none of them (none), or only the ones in toplevel concatenation (toplevel). Default isall. So what's a "fixed" tag? It's a tag located within a fixed distance of some other tag (that other one's called the "base"). In those cases only the base tag needs to be tracked, and the fixed tag's value can be computed as the value of the base tag plus a static offset. For tags under alternative or repetition you also have to check whether the base tag has a no-match value — and in that case the fixed tag should also be set to no-match, disregarding the offset. For tags in top-level concatenation the check isn't needed, because they always match. Slay, math 💅
Warnings
Warnings can be individually enabled, disabled, and turned into an error. Literally a whole lil control panel for them 🎛️✨
-W— turn on all warnings. Go off king.-Werror— turn warnings into errors. But careful bestie: this option alone doesn't turn on any warnings. It only affects the warnings that have been turned on so far or will be turned on later. It's giving "strict teacher who only grades what you actually submitted" 🍎-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, it just stops being dramatic about it.-Wcondition-order— warns you if the generated program makes implicit assumptions about condition numbering. The fix? Use either the--headeroption or aconditionsblock to generate a mapping of condition names to numbers, and then use the autogenerated condition names. Periodt 💅-Wempty-character-class— warns if a regular expression contains an empty character class. Trying to match an empty character class makes no sense: it should always fail. But for backwards compatibility reasons, re2swift permits empty character classes and treats them as empty strings. Use the--empty-classoption to change the default behavior 🫶-Wmatch-empty-string— warns if a rule is nullable (matches an empty string). If the lexer runs in a loop and that empty match was unintentional, the lexer may unexpectedly hang in an infinite loop. Not the cute kind of loop 😭-Wswapped-range— warns if the lower bound of a range is greater than its upper bound. Default behavior is to silently swap the range bounds. So it's like "we fixed it but we're judging you a little."-Wundefined-control-flow— warns if some input strings cause undefined control flow in the lexer (and yep, the faulty patterns are reported). This is a dangerous and common mistake. Easy fix though: add the default rule*which has the lowest priority, matches any code unit, and always consumes a single code unit. 🔥-Wunreachable-rules— warns about rules that are shadowed by other rules and will never match. They're literally being ignored, ngl 💀-Wdeprecated-eof_rule— warns about standalone end of input rules$that will be broken by future changes and require fixing. At the moment these rules take precedence when conflicting with other rules, but after the introduction of the generalized end of input symbol$, the precedence order will change and these rules will become shadowed by other rules. Future-you will thank present-you 🙏-Wuseless-escape— warns if a symbol is escaped when it shouldn't be. By default re2swift silently ignores such escapes, but it may as well indicate a typo or an error in the escape sequence. Trust your gut on this one 🦋-Wnondeterministic-tags— warns if a tag has n-th degree of nondeterminism, where n is greater than1.-Wsentinel-in-midrule— warns if the sentinel symbol occurs in the middle of a rule. This may cause reads past the end of buffer, crashes or memory corruption in the generated lexer 😭😭 This warning is only applicable if the sentinel method of checking for the end of input is used. It is set to an error ifre2c:sentinelconfiguration is used.-Wundefined-syntax-config— warns if the syntax file specified with--syntaxoption is missing definitions of some configurations. This helps to maintain user-defined syntax files: if a new release adds configurations, the old syntax file will raise a warning and the user gets notified. If some configurations are unused and don't need a definition, they should be explicitly set to<undefined>. Communication queen 👑
Syntax files
Support for different languages in re2c is based on the idea of syntax files ✨ A syntax file is a configuration file that defines syntax of the target language — not the whole language, just the small part of it that's used by the generated code. Syntax files make re2c super flexible, but bestie, listen: 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 the include/syntax subdirectory), and they're also embedded in the re2swift binary. Users may provide a custom syntax file that overrides a few configurations for one of the supported languages, or they may choose to redefine all configurations — in which case the --lang none option should be used. 🎀
Syntax files contain configurations of four different kinds: 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 re2swift can give you a clear error if you try to enable an unsupported feature:
supported_apis— a list of supported APIs with possible elementssimple,record,generic.supported_api_styles— a list of supported API styles with possible elementsfunctions,free-form.supported_code_models— a list of supported code models with possible elementsgoto-label,loop-switch,recursive-functions.supported_targets— a list of supported codegen targets with possible elementscode,dot,skeleton.supported_features— a list of supported features with possible elementsnested-ifs,bitmaps,computed-gotos,case-ranges,monadic,unsafe,tags,captures,captvars,computed-continue.
Language configurations
A few boolean configurations describe features of the target language that affect the re2swift 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. (Python besties, this one's for you 🐍)wrap_blocks_in_braces— non-zero if compound statements must be wrapped in curly braces.
Inplace configurations
Syntax files define initial values of all re2c: configurations, as they may differ for different languages. See the configurations section for a full list of all inplace configurations and their meaning. 👑
Code templates
Code templates define syntax of the target language. They're written in a simple domain-specific language 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 the special value <undefined>. 💅
Variables are placeholders that get substituted during the code generation phase. List variables are special: when expanding list templates, re2swift repeats expressions on the right hand side of the column a few times, each time replacing occurrences of the list variable with a value specific to this repetition. Lists have optional bounds (negative values are counted from the end, e.g. -1 means the last element). Conditional names start with a dot. Both conditionals and variables may be either local (specific to the given code template) or global (allowed in all code templates). When re2swift reads a syntax file, it checks that each code template uses only the variables and conditionals that are allowed in it. Fr fr, it's checking your work 🧐✨
For example, the following code template defines an if-then-else construct for a C-like language:
code:if_then_else =
[branch{0}: topindent "if " cond " {" nl
indent [stmt: stmt] dedent]
[branch{1:-1}: topindent "} else" (.cond ? " if " cond) " {" nl
indent [stmt: stmt] dedent]
topindent "}" nl;
Here branch is a list variable: branch{0} expands to the first branch (which is special, as there is no else part), and 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
}
Okay so now we're getting into the code templates 💅 — here's a list of all code templates supported by re2swift with their local variables and conditionals. Note that a particular definition may, but does not have to use local variables and conditionals. Any unused code templates should be set to <undefined>.
code:var_local— Declaration or definition of a local variable. Supported variables:type(the type of the variable),name(its name) andinit(initial value, if any). Conditionals:.init(true if there is an initializer).code:var_global— Same ascode:var_local, except that it's used in top-level.code:const_local— Definition of a local constant. Supported variables:type(the type of the constant),name(its name) andinit(initial value).code:const_global— Same ascode:const_local, except that it's used in top-level.code:array_local— Definition of a local array (table). Supported variables:type(the type of array elements),name(array name),size(its size),row(a list variable that does not itself produce any code, but expands list expression as many times as there are rows in the table) andelem(a list variable that expands to all table elements in the current row — it's meant to be nested in the row list). Supported conditional:.const(true if the array is immutable).code:array_global— Same ascode:array_local, except that it's used in top-level.code:array_elem— Reference to an element of an array (table). Supported variables:array(the name of the array) andindex(index of the element).code:enum— Definition of an enumeration (it may be defined using a special language construct for enumerations, or simply as a few standalone constants). Supported variables aretype(user-defined enumeration type or type of the constants),elem(list variable that expands to the name of each member) andinit(initializer for each member). Conditionals:.init(true if there is an initializer).code:enum_elem— Enumeration element (a member of a user-defined enumeration type or a name of a constant, depending on howcode:enumis defined). Supported variables arename(the name of the element) andtype(its type).code:assign— Assignment statement. Supported variables arelhs(left hand side) andrhs(right hand side).code:type_int— Signed integer type.code:type_uint— Unsigned integer type.code:type_yybm— Type of elements in theyybmtable.code:type_yytarget— Type of elements in theyytargettable.code:type_yyctable— Type of elements in theyyctabletable.code:cmp_eq— Operator "equals".code:cmp_ne— Operator "not equals".code:cmp_lt— Operator "less than".code:cmp_gt— Operator "greater than"code:cmp_le— Operator "less or equal"code:cmp_ge— Operator "greater or equal"code:if_then_else— If-then-else statement with one or more branches. Supported variables:branch(a list variable that does not itself produce any code, but expands list expression as many times as there are branches),cond(condition of the current branch) andstmt(a list variable that expands to all statements in the current branch). Conditionals:.cond(true if the current branch has a condition),.many(true if there's more than one branch).code:if_then_else_oneline— A specialization ofcode:if_then_elsefor the case when all branches have one-line statements. If this is<undefined>,code:if_then_elseis used instead.code:switch— A switch statement with one or more cases. Supported variables:expr(the switched-on expression) andcase(a list variable that expands to all cases-groups with their code blocks).code:switch_cases— A group of switch cases that maps to a single code block. Supported variables arecase(a list variable that expands to all cases in this group) andstmt(a list variable that expands to all statements in the code block.code:switch_cases_oneline— A specialization ofcode:switch_casesfor the case when the code block consists of a single one-line statement. If this is<undefined>,code:switch_casesis used instead.code:switch_case_range— A single switch case that covers a range of values (possibly consisting of a single value). Supported variable:val(a list variable that expands to all values in the range). Supported conditionals:.many(true if there's more than one value in the range) and.char_literals(true if this is a switch on character literals — some languages provide special syntax for this case).code:switch_case_default— Default switch case.code:loop— A loop that runs forever (unless interrupted from the loop body). Supported variables:label(loop label),val(initial state),var(state variable),state(a list variable that expands to all state names) andstmt(a list variable that expands to all statements in the loop body or the current state).code:continue— Continue statement. Supported variables:label(label from which to continue execution),val(value passed to a labeled switch) andvar(state variable).code:goto— Goto statement. Supported variables:label(label of the jump target).code:cgoto— Computed goto statement. Supported variables:array(the table containing computed goto information),index(index of the element in the table) andbase(base label, only used if.cgoto.relativeis true).code:cgoto:data— Initializer expression for a single element in computed goto table. Supported variables:label(the label that is used to initialize the current element),type(underlying type of the elements in the table) andbase(base label — only used if.cgoto.relativeis true).code:fndecl— Function declaration. Supported variables:name(function name),type(return type),throw(exceptions thrown by this function, maps tore2c:yyfn:throwconfiguration),arg(a list variable that does not itself produce code, but expands list expression as many times as there are function arguments),argname(name of the current argument),argtype(type of the current argument). Conditional:.type(true if this is a non-void function).code:fndef— Likecode:fndecl, but used for function definitions, so it has one additional list variablestmtthat expands to all statements in the function body.code:fncall— Function call statement. Supported variables:name(function name),retval(l-value where the return value is stored, if any) andarg(a list variable that expands to all function arguments). Conditionals:.args(true if the function has arguments) and.retval(true if return value needs to be saved).code:tailcall— Tail call statement. Supported variables:name(function name), andarg(a list variable that expands to all function arguments). Conditionals:.args(true if the function has arguments) and.retval(true if this is a non-void function).code:recursive_functions— Program body with--recursive-functionscode model. Supported variables:fn(a list variable that does not itself produce any code, but expands list expression as many times as there are functions),fndecl(declaration of the current function) andfndef(definition of the current function).code:fingerprint— The fingerprint at the top of the generated output file. Supported variables:ver(re2swift version that was used to generate this) anddate(generation date).code:line_info— The format of line directives (if this is set to<undefined>, no directives are generated). Supported variables:line(line number) andfile(filename).code:abort— A statement that aborts program execution.code:yydebug—YYDEBUGstatement, possibly specialized for different APIs. Supported variables:YYDEBUG,yyrecord,yych(map to the correspondingre2c:configurations),state(DFA state number).code:yypeek—YYPEEKstatement, possibly specialized for different APIs. Supported variables:YYPEEK,YYCTYPE,YYINPUT,YYCURSOR,yyrecord,yych(map to the correspondingre2c:configurations). Conditionals:.cast(true ifre2c:yych:conversionis set to non-zero).code:yyskip—YYSKIPstatement, possibly specialized for different APIs. Supported variables:YYSKIP,YYCURSOR,yyrecord(map to the correspondingre2c:configurations).code:yybackup—YYBACKUPstatement, possibly specialized for different APIs. Supported variables:YYBACKUP,YYCURSOR,YYMARKER,yyrecord(map to the correspondingre2c:configurations).code:yybackupctx—YYBACKUPCTXstatement, possibly specialized for different APIs. Supported variables:YYBACKUPCTX,YYCURSOR,YYCTXMARKER,yyrecord(map to the correspondingre2c:configurations).code:yyskip_yypeek— Combinedcode:yyskipandcode:yypeekstatement (defaults tocode:yyskipfollowed bycode:yypeek).code:yypeek_yyskip— Combinedcode:yypeekandcode:yyskipstatement (defaults tocode:yypeekfollowed bycode:yyskip).code:yyskip_yybackup— Combinedcode:yyskipandcode:yybackupstatement (defaults tocode:yyskipfollowed bycode:yybackup).yybackup_yyskip— the combinedyybackup+yyskipstatement (defaults toyybackupfollowed byyyskip). Two for the price of one, slay 💅yybackup_yypeek— the combinedyybackup+yypeekstatement (defaults toyybackupfollowed byyypeek).yyskip_yybackup_yypeek— the combinedyyskip+yybackup+yypeekstatement (defaults toyyskipfollowed byyybackupfollowed byyypeek). It's giving triple threat ✨yybackup_yypeek_yyskip— the combinedyybackup+yypeek+yyskipstatement (defaults toyybackupfollowed byyypeekfollowed byyyskip).yyrestore— the YYRESTORE statement, possibly specialized for different APIs. Supported variables:YYRESTORE,YYCURSOR,YYMARKER,yyrecord(map to the correspondingre2c:configurations).yyrestorectx— the YYRESTORECTX statement, possibly specialized for different APIs. Supported variables:YYRESTORECTX,YYCURSOR,YYCTXMARKER,yyrecord(map to the correspondingre2c:configurations).yyrestoretag— the YYRESTORETAG statement, possibly specialized for different APIs. Supported variables:YYRESTORETAG,YYCURSOR,yyrecord(map to the correspondingre2c:configurations),tag(the name of the tag variable used to restore position). 🎀yyshift— the YYSHIFT statement, possibly specialized for different APIs. Supported variables:YYSHIFT,YYCURSOR,yyrecord(map to the correspondingre2c:configurations),offset(the number of code units to shift the current position).yyshiftstag— the YYSHIFTSTAG statement, possibly specialized for different APIs. Supported variables:YYSHIFTSTAG,yyrecord,negative(map to the correspondingre2c:configurations),tag(tag variable which needs to be shifted),offset(the number of code units to shift). Conditionals:.nested(true if this is a nested tag — in this case its value may equal tore2c:tags:negative, which should not be shifted 🙈).yyshiftmtag— the YYSHIFTMTAG statement, possibly specialized for different APIs. Supported variables:YYSHIFTMTAG(maps to the correspondingre2c:configuration),tag(tag variable which needs to be shifted),offset(the number of code units to shift).yystagp— the YYSTAGP statement, possibly specialized for different APIs. Supported variables:YYSTAGP,YYCURSOR,yyrecord(map to the correspondingre2c:configurations),tag(tag variable that should be updated).yymtagp— the YYMTAGP statement, possibly specialized for different APIs. Supported variables:YYMTAGP(maps to the correspondingre2c:configuration),tag(tag variable that should be updated).yystagn— the YYSTAGN statement, possibly specialized for different APIs. Supported variables:YYSTAGN,negative,yyrecord(map to the correspondingre2c:configurations),tag(tag variable that should be updated).yymtagn— the YYMTAGN statement, possibly specialized for different APIs. Supported variables:YYMTAGN(maps to the correspondingre2c:configuration),tag(tag variable that should be updated).yycopystag— the YYCOPYSTAG statement, possibly specialized for different APIs. Supported variables:YYCOPYSTAG,yyrecord(map to the correspondingre2c:configurations),lhs,rhs(left and right hand side tag variables of the copy operation). 🫶yycopymtag— the YYCOPYMTAG statement, possibly specialized for different APIs. Supported variables:YYCOPYMTAG,yyrecord(map to the correspondingre2c:configurations),lhs,rhs(left and right hand side tag variables of the copy operation).yygetaccept— the YYGETACCEPT statement, possibly specialized for different APIs. Supported variables:YYGETACCEPT,yyrecord(map to the correspondingre2c:configurations),var(maps tore2c:yyacceptconfiguration).yysetaccept— the YYSETACCEPT statement, possibly specialized for different APIs. Supported variables:YYSETACCEPT,yyrecord(map to the correspondingre2c:configurations),var(maps tore2c:yyacceptconfiguration) andval(numeric value of the accepted rule).yygetcond— the YYGETCOND statement, possibly specialized for different APIs. Supported variables:YYGETCOND,yyrecord(map to the correspondingre2c:configurations),var(maps tore2c:yycondconfiguration).yysetcond— the YYSETCOND statement, possibly specialized for different APIs. Supported variables:YYSETCOND,yyrecord(map to the correspondingre2c:configurations),var(maps tore2c:yycondconfiguration) andval(numeric condition identifier).yygetstate— the YYGETSTATE statement, possibly specialized for different APIs. Supported variables:YYGETSTATE,yyrecord(map to the correspondingre2c:configurations),var(maps tore2c:yystateconfiguration).yysetstate— the YYSETSTATE statement, possibly specialized for different APIs. Supported variables:YYSETSTATE,yyrecord(map to the correspondingre2c:configurations),var(maps tore2c:yystateconfiguration) andval(state number). 🦋yylessthan— the YYLESSTHAN statement, possibly specialized for different APIs. Supported variables:YYLESSTHAN,YYCURSOR,YYLIMIT,yyrecord(map to the correspondingre2c:configurations),need(the number of code units to check against). Conditional:.many(true if theneedis more than one).yyend— the YYEND expression, possibly specialized for different APIs. Supported variables:YYEND,YYCURSOR,YYLIMIT.yybm_filter— condition that is used to filter outyychvalues that are not covered by theyybmtable (used with--bitmapsoption). Supported variable:yych(maps tore2c:yychconfiguration).yybm_match— the format ofyybmtable check (generated with--bitmapsoption). Supported variables:yybm,yych(map to the correspondingre2c:configurations),offset(offset in theyybmtable that needs to be added toyych) andmask(bit mask that should be applied to the table entry to retrieve the boolean value that needs to be checked).yytarget_filter— condition that is used to filter outyychvalues that are not covered by theyytargettable (used with--computed-gotosoption). Supported variable:yych(maps tore2c:yychconfiguration).
Okay so here's a list of all the global variables that are allowed in syntax files, bestie 👑
nl— a newline.indent— a variable that does not produce any code, but has a side-effect of increasing the indentation level. Sneaky but iconic.dedent— a variable that does not produce any code, but has a side-effect of decreasing the indentation level. The matching bestie toindent💜topindent— indentation string for the current statement. The indentation level is tracked and automatically updated by the code generator.
And here's a list of all the global conditionals that are allowed in syntax files — these are the vibe checks of your syntax file 🌈
.api.simple— true if simple API is used (--api simpleorre2c:api = simple)..api.generic— true if generic API is used (--api genericorre2c:api = generic)..api.record— true if record API is used (--api recordorre2c:api = record)..api_style.functions— true if function-like API style is used (re2c:api-style = functions)..api_style.freeform— true if 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 if re2swift-generated 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 if re2swift should use"unsafe"blocks in order to generate faster code (--unsafe,re2c:unsafe = 1). This is only relevant for languages that have an"unsafe"feature. 🔥.version— true if the generated fingerprint should contain the re2swift version..yyfill.enable— true if YYFILL is enabled (re2c:yyfill:enable = 1)..yyfn.throw— true ifre2c:yyfn:throwconfiguration is defined to a nonempty string.
🛑 HANDLING THE END OF INPUT 🛑
So, one of the main problems for the lexer is like... knowing when to stop. 😭 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
The first two conditions are the ones that end the lexer in a "natural" way: it just arrives at a state with no outgoing transitions, and matching automatically stops. No drama. 🎀
The third condition — end of input — is a whole different vibe. It can hit in any state, and the lexer needs to actually handle it. Checking for the end of input interrupts the normal lexer workflow and adds conditional branches to the generated program, so obviously we wanna minimize how many of those checks exist. re2swift supports a few different methods for handling the end of input, and which one you pick depends on the complexity of your regexps, whether you need buffering, performance considerations, and other factors. Here's the lineup, bestie:
- Sentinel — this method kills the need for end-of-input checks altogether. It's simple and efficient, but limited to the case when there's a natural "sentinel" character that can never occur in valid input. That character may still show up in invalid input, but it shouldn't be allowed by the regular expressions — except perhaps as the last character of a rule. The sentinel gets appended at the end of input and serves as the stop signal: when the lexer reads this character, it's either a syntax error or the end of input. In both cases the lexer should stop. This method is used if YYFILL is disabled with
re2c:yyfill:enable = 0;andre2c:eofhas the default value-1. - Sentinel with bounds checks — this method is generic: it lets you handle any input without restrictions on the regular expressions. The idea is to reduce the number of end-of-input checks by only performing them on certain characters. Similar to the "sentinel" method, one of the characters is chosen as a "sentinel" and appended at the end of input. But — plot twist 🍓 — there's no restriction on where the sentinel may occur (in fact, any character can be chosen as the 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 even 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 — this method is generic, and it may be faster than the "sentinel with bounds checks" method, but it's also more complex, lowkey. 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 that 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 the lexer can't match them). The length of the 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 at all. This method is used if YYFILL is enabled and
re2c: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 fold the end-of-input checks right into them. This approach is error-prone and should be used with caution (fr fr, be careful 💀). 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 have one example of each method, so you can see the vibes in action. ✨
🌸 Sentinel
This example uses a sentinel character to handle the end of input. The program counts space-separated words in a null-terminated string. The sentinel is null: it's the last character of each input string, and none of the rules allow it in the middle of a lexeme (in particular, it's not included in character ranges where it's super easy to overlook 👀). If a null occurs in the middle of a string, it's a syntax error and the lexer will match the default rule *, but it won't read past the end of input or crash — use the -Wsentinel-in-midrule warning and the re2c:sentinel configuration to verify this. Configuration re2c:yyfill:enable = 0; suppresses the generation of bounds checks and YYFILL invocations.
// re2swift $INPUT -o $OUTPUT
// Expects a null-terminated string.
func lex(_ yyinput: UnsafePointer<UInt8>) -> Int? {
var yycursor = 0, count = 0
loop: while true {
/*!re2c
re2c:yyfill:enable = 0;
[a-z]+ {
count += 1
continue loop
}
[ ]+ { continue loop }
[\x00] { return count }
* { return nil }
*/
}
}
func test(_ str: StaticString, _ expect: Int?) {
assert(lex(str.utf8Start) == expect)
}
test("", 0)
test("one two three", 3)
test("f0ur", nil)
🦋 Sentinel with bounds checks
This example uses sentinel with bounds checks to handle the end of input (this method was added in version 1.2 🎉). The program counts space-separated single-quoted strings. The sentinel character is null, which is specified with the re2c:eof = 0; configuration. As in the sentinel method, null is the last character of each input string, but here it's allowed in the middle of a rule — for example, 'aaa\0aa'\0 is valid input, but 'aaa\0 is a syntax error. Bounds checks are generated in each state that matches an input character, but they're scoped to the branch that handles null. Bounds checks look like YYLIMIT <= YYCURSOR or YYLESSTHAN(1) with the 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 up three possibilities: if the lexer is in the initial state it will match the end-of-input rule $, otherwise it may fall back to a previously matched rule (including the default rule *) or go to a default state, causing -Wundefined-control-flow. 😬
// re2swift $INPUT -o $OUTPUT
// Expects a null-terminated string.
func lex(_ yyinput: UnsafePointer<UInt8>, _ length: Int) -> Int? {
var yycursor = 0, yylimit = length, yymarker = 0
var count = 0
loop: while true {
/*!re2c
re2c:eof = 0;
re2c:yyfill:enable = 0;
str = ['] ([^'\\] | [\\][^])* ['];
str {
count += 1
continue loop
}
[ ]+ { continue loop }
* { return nil }
$ { return count }
*/
}
}
func test(_ str: StaticString, _ expect: Int?) {
assert(lex(str.utf8Start, str.utf8CodeUnitCount) == expect)
}
test("", 0);
test("'qu\0tes' 'are' 'fine: \\'' ", 3);
test("'unterminated\\'", nil);
🎀 Bounds checks with padding
This example uses bounds checks with padding to handle the end of input (this method is enabled by default, so you've probably already met her 💅). The program counts space-separated single-quoted strings. There's a padding of YYMAXFILL null characters appended at the end of input, where the YYMAXFILL value is autogenerated with a max block. It's not necessary to use null for padding — any characters work, as long as they don't form a valid lexeme suffix (in this example, padding shouldn't contain single quotes, since they might be mistaken for a suffix of a single-quoted string). There's a "stop" rule that matches the first padding character (null) and terminates the lexer — note that it checks whether null is at the beginning of the padding, otherwise it's a syntax error. Bounds checks are generated only in some states, determined by the strongly connected components of the underlying automaton. Checks have the form (YYLIMIT - YYCURSOR) < n or YYLESSTHAN(n) with the generic API, where n is the minimum number of characters needed for the lexer to proceed (which also means the next bounds check will occur in at most n characters). If the check condition is true, the lexer has reached the end of input and will invoke YYFILL(n), 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 (which is 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. 🌈
// re2swift $INPUT -o $OUTPUT
/*!max:re2c*/
func lex(_ str: UnsafeBufferPointer<UInt8>) -> Int? {
let length = str.count
// Make a copy of the string with YYMAXFILL zeroes at the end.
let yyinput = ContiguousArray<UInt8>(str) + repeatElement(0, count: yymaxfill)
var yycursor = 0, yylimit = length + yymaxfill
var count = 0
loop: while true {
/*!re2c
re2c:YYFILL = "return nil";
str = ['] ([^'\\] | [\\][^])* ['];
str {
count += 1
continue loop
}
[\x00] {
// Check that it's the sentinel, not some unexpected null.
if yycursor - 1 == length { return count } else { return nil }
}
[ ]+ { continue loop }
* { return nil }
*/
}
}
func test(_ str: StaticString, _ expect: Int?) {
str.withUTF8Buffer {
assert(lex($0) == expect)
}
}
test("", 0)
test("'qu\0tes' 'are' 'fine: \\'' ", 3)
test("'unterminated\\'", nil)
test("'unexpected \0 null\\'", nil)
🧚 Custom checks
This example uses a custom end-of-input handling method based on the generic API. The program counts space-separated single-quoted strings. It's the same as the sentinel example, except the input is not null-terminated. To cover 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 — like, constantly. If the check condition fails, YYPEEK returns the real character; otherwise it returns a fake sentinel character. 🫶
// re2swift $INPUT -o $OUTPUT
import Foundation
func lex(_ str: Data) -> Int? {
var cursor = 0, limit = str.count
var count = 0
loop: while true {
/*!re2c
re2c:api = generic;
re2c:yyfill:enable = 0;
re2c:YYSKIP = "cursor += 1";
re2c:YYPEEK = "cursor < limit ? str[cursor] : 0"; // fake null
[a-z]+ {
count += 1
continue loop
}
[\x00] { return count }
[ ]+ { continue loop }
* { return nil}
*/
}
}
func test(_ str: String, _ expect: Int?) {
// For the sake of example create a string without terminating null.
assert(lex(Data(str.utf8)) == expect)
}
test("", 0)
test("one two three ", 3)
test("f0ur", nil)
🫧 BUFFER REFILLING 🫧
okay bestie, so the whole reason we need buffering is that sometimes you literally can't map the input into memory all at once 😭 — either it's too large, or it's arriving in a streaming way (like, say, reading off a socket). The classic move for that is: grab a fixed-sized memory buffer, then chew through the input in chunks that actually fit inside it. Once the current chunk is done, you yeet it out and slide new data in 💅.
In practice it's a bit more involved than that, because the lexer state isn't just one lonely input position — it's a whole little squad 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 re2swift 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 stags and mtags blocks and generic API primitives
YYSTAGP/YYSTAGN/YYMTAGP/YYMTAGN)
Not all of these show up in every case, but if they're used, YYFILL is the one responsible for updating them, no cap 🫡. The way it works: all the active positions live in the segment between token and cursor, which means everything between buffer start and token can just be discarded 🗑️, the segment from token up to limit gets moved to the beginning of the buffer, and the free space at the end of the buffer gets topped up with new data ✨.
And lowkey a lil tip: to dodge frequent YYFILL calls, fill in as many input characters as you possibly can (even if fewer characters might've been enough to get the lexer going again) — it's giving efficiency 💅.
The deets of how YYFILL is implemented shift a tiny bit depending on which EOF handling method you're on: the EOF rule case is somewhat simpler than bounds-checking with padding. Also heads up — if you're using the -f --storable-state option, YYFILL has slightly different semantics (all described in the section about storable state 👀).
🌸 YYFILL with sentinel 🌸
So when you're on the EOF rule, YYFILL is a function-like primitive that takes no arguments and returns a value which gets checked against zero 🎀. The YYFILL invocation gets triggered by the condition YYLIMIT <= YYCURSOR in C pointer API and YYLESSTHAN() in generic API. A non-zero return value means YYFILL has failed 😭. A successful YYFILL call must supply at least one character and adjust input positions accordingly — that's the whole assignment, bestie.
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 down below show the relative locations of input positions in buffer before and after the YYFILL call (sentinel symbol is marked with #, and the second picture shows the case when there's 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's an example of a program that reads input file input.txt in chunks of 4096 bytes and uses EOF rule — iconic, honestly 🧚:
// re2swift $INPUT -o $OUTPUT
import Foundation
struct Input {
static let bufferSize = 4095
var file: FileHandle
var yyinput = ContiguousArray<UInt8>(repeating: 0, count: Self.bufferSize + 1)
var yylimit = Self.bufferSize
var yycursor = Self.bufferSize
var yymarker = Self.bufferSize
var token = -1
var eof = false
}
extension Input {
mutating func lex() -> Int? {
var count = 0
loop: while true {
self.token = self.yycursor
/*!re2c
re2c:api = record;
re2c:eof = 0;
re2c:yyrecord = "self";
re2c:YYFILL = "self.fill() == .ok";
str = ['] ([^'\\] | [\\][^])* ['];
str {
count += 1
continue loop
}
[ ]+ { continue loop }
$ { return count }
* { return nil }
*/
}
}
mutating func fill() -> FillStatus {
guard !self.eof else {
return .eof
}
let shift = self.token
let used = self.yylimit - self.token
let free = Self.bufferSize - used
// Error: Lexeme too long. In the real world we can reallocate a larger buffer.
if self.token < 1 {
return .longLexeme
}
// Shift buffer contents, discarding everything up to the current lexeme.
self.yyinput.replaceSubrange(..<used, with: self.yyinput[shift..<self.yylimit])
self.yylimit -= shift
self.yycursor -= shift
self.yymarker &-= shift // May underflow if marker is unused
self.token = 0
// Fill free space at the end of buffer with new data from file.
do {
if let data = try self.file.read(upToCount: free) {
self.yyinput.replaceSubrange(self.yylimit..<(self.yylimit + data.count), with: data)
self.yylimit += data.count
}
} catch {
fatalError("cannot read from file: \(error.localizedDescription)")
}
self.yyinput[self.yylimit] = 0 // append sentinel
self.eof = self.yylimit < Self.bufferSize
return .ok
}
enum FillStatus {
case ok, eof, longLexeme
}
}
let fileName = "input"
let content = "'qu\0tes' 'are' 'fine: \\'' "
// Prepare input file: a few times the size of the buffer,
// containing strings with zeroes and escaped quotes.
guard FileManager.default.createFile(
atPath: fileName,
contents: Data(String(repeating: content, count: Input.bufferSize).utf8)
) else {
fatalError("failed to write file \"\(fileName)\"")
}
// Number of quoted strings written to file
let count = 3 * Input.bufferSize
// Initialize lexer state
guard let file = FileHandle(forReadingAtPath: fileName) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue)
}
var `in` = Input(file: file)
// Run the lexer
assert(`in`.lex() == count)
// Cleanup: remove input file
try file.close()
try FileManager.default.removeItem(atPath: fileName)
🦋 YYFILL with padding 🦋
Now, in the default case (meaning when the EOF rule is not in play), YYFILL is a function-like primitive that accepts a single argument and doesn't return any value 👑. The YYFILL invocation gets triggered by the 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 YYFILL fails to supply them, it must not return to the lexer — which is exactly why it's best implemented as a macro that returns from the calling function on failure. Like, do not come back empty-handed, bestie 💀.
In the 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 (this is the case where YYFILL 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 ->
And here's an example of a program that reads input file input.txt in chunks of 4096 bytes and uses bounds-checking with padding 🌈:
// re2swift $INPUT -o $OUTPUT
import Foundation
/*!max:re2c*/
struct Input {
static let bufferSize = 4096 - yymaxfill
var file: FileHandle
var yyinput = ContiguousArray<UInt8>(repeating: 0, count: Self.bufferSize + yymaxfill)
var yylimit = Self.bufferSize
var yycursor = Self.bufferSize
var token = -1
var eof = false
}
extension Input {
mutating func lex() -> Int? {
var count = 0
loop: while true {
self.token = self.yycursor
/*!re2c
re2c:api = record;
re2c:yyrecord = "self";
re2c:YYFILL = "if self.fill(@@) != .ok { return nil }";
str = ['] ([^'\\] | [\\][^])* ['];
[\x00] {
// Check that it is the sentinel, not some unexpected null.
return self.token == self.yylimit - yymaxfill ? count : nil;
}
str {
count += 1
continue loop
}
[ ]+ { continue loop }
* { return nil }
*/
}
}
mutating func fill(_ need: Int) -> FillStatus {
guard !self.eof else {
return .eof
}
let shift = self.token
let used = self.yylimit - self.token
let free = Self.bufferSize - used
// Error: Lexeme too long. In the real world we can reallocate a larger buffer.
if self.token < need {
return .longLexeme
}
// Shift buffer contents, discarding everything up to the current lexeme.
self.yyinput.replaceSubrange(..<used, with: self.yyinput[shift..<self.yylimit])
self.yylimit -= shift
self.yycursor -= shift
self.token = 0
// Fill free space at the end of buffer with new data from file.
let read: Int
do {
if let data = try self.file.read(upToCount: free) {
read = data.count
self.yyinput.replaceSubrange(self.yylimit..<(self.yylimit + read), with: data)
} else {
read = 0
}
} catch {
fatalError("cannot read from file: \(error.localizedDescription)")
}
// If read less than expected, this is end of input => add zero padding
// so that the lexer can access characters at the end of buffer.
self.yylimit += read
if read < free {
self.eof = true
self.yyinput.withUnsafeMutableBytes {
_ = memset($0.baseAddress! + self.yylimit, 0, yymaxfill)
}
self.yylimit += yymaxfill
}
return .ok
}
enum FillStatus {
case ok, eof, longLexeme
}
}
let fileName = "input"
let content = "'qu\0tes' 'are' 'fine: \\'' ";
// Prepare input file: a few times the size of the buffer,
// containing strings with zeroes and escaped quotes.
guard FileManager.default.createFile(
atPath: fileName,
contents: Data(String(repeating: content, count: Input.bufferSize).utf8)
) else {
fatalError("failed to write file \"\(fileName)\"")
}
// Number of quoted strings written to file
let count = 3 * Input.bufferSize
// Initialize lexer state
// This immediately triggers YYFILL, as the check `in.yycursor < in.yylimit` fails.
guard let file = FileHandle(forReadingAtPath: fileName) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue)
}
var `in` = Input(file: file)
// Run the lexer
assert(`in`.lex() == count)
// Cleanup: remove input file
try file.close()
try FileManager.default.removeItem(atPath: fileName)
🌈 FEATURES 🌈
🧩 Multiple blocks 🧩
Okay so sometimes you genuinely need multiple lexers that talk to each other — bestie, picture a high-level state machine that hops between lexer modes, that's the exact vibe 💅. You can pull this off with several connected re2swift blocks. The other option? Start conditions, keep reading 👀.
How you wire blocks together depends entirely on your target language, no cap:
- In languages that have a
gotostatement (such as C/C++ and Go) you can put all blocks in one function, each of them prefixed with a label. Transitioning from one block to another is just a simplegoto. Easy. - In languages that don't have
goto(such as Rust) you gotta use a loop with aswitchon a state variable, similar to theyystateloop/switch thatre2swiftgenerates, or else wrap each block in a function and use function calls. Slightly more work but it slays ✨.
The example below uses multiple blocks to parse binary, octal, decimal and hexadecimal numbers 🎀. Each base gets its own block, main character energy. The initial block figures out the base and dispatches to the other blocks. Common configurations live in a separate block at the beginning of the program — and they're inherited by all the other blocks 🫶.
// re2swift $INPUT -o $OUTPUT
func parseUInt32(_ yyinput: UnsafePointer<UInt8>) -> UInt32? {
var yycursor = 0, yymarker = 0
/*!re2c
re2c:yyfill:enable = 0;
"0b" / [01] { return parseBin() }
"0" { return parseOct() }
"" / [1-9] { return parseDec() }
"0x" / [0-9a-fA-F] { return parseHex() }
* { return nil }
*/
func add(_ accum: inout UInt64, _ charOrigin: UnicodeScalar, _ base: UInt64, _ offset: UInt64 = 0) {
let digit = yyinput[yycursor - 1] - UInt8(ascii: charOrigin)
accum = min(accum * base + UInt64(digit) + offset, UInt64(UInt32.max) + 1)
}
func parseBin() -> UInt32? {
var accum: UInt64 = 0
parse: while true {
/*!re2c
[01] { add(&accum, "0", 2); continue parse }
* { return UInt32(exactly: accum) }
*/
}
}
func parseOct() -> UInt32? {
var accum: UInt64 = 0
parse: while true {
/*!re2c
[0-7] { add(&accum, "0", 8); continue parse }
* { return UInt32(exactly: accum) }
*/
}
}
func parseDec() -> UInt32? {
var accum: UInt64 = 0
parse: while true {
/*!re2c
[0-9] { add(&accum, "0", 10); continue parse }
* { return UInt32(exactly: accum) }
*/
}
}
func parseHex() -> UInt32? {
var accum: UInt64 = 0
parse: while true {
/*!re2c
[0-9] { add(&accum, "0", 16); continue parse }
[a-f] { add(&accum, "a", 16, 10); continue parse }
[A-F] { add(&accum, "A", 16, 10); continue parse }
* { return UInt32(exactly: accum) }
*/
}
}
}
assert(parseUInt32("") == nil)
assert(parseUInt32("1234567890") == 1234567890)
assert(parseUInt32("0b1101") == 13)
assert(parseUInt32("0x7Fe") == 2046)
assert(parseUInt32("0644") == 420)
assert(parseUInt32("9999999999") == nil)
🎯 Start conditions 🎯
Start conditions get switched on with the --start-conditions option — and honestly? They're the glow-up for encoding multiple interrelated automata inside the same re2swift block 💖.
Every condition maps to a single automaton and has two things: a unique name that you pick, and a unique internal number that re2swift defines. Those numbers are what's used to switch between conditions — the generated code calls the YYGETCOND and YYSETCOND primitives to grab the current condition or set it to a given number 🔥. Wanna generate numeric condition identifiers? Use the conditions block, the --header option, or the re2c:header configuration. And the re2c:cond:enumprefix configuration sets the prefix of the generated identifier ✨.
In condition mode, every rule has to be prefixed with a list of comma-separated condition names in angle brackets — or a wildcard <*> to mean all conditions. The rule syntax gets extended like this:
< condition-list > regular-expression code— a rule merged into every condition on the condition-list. It matches regular-expression and executes the associated code.< condition-list > regular-expression => condition code— a rule merged into every condition on the condition-list. It matches regular-expression, sets the current condition to condition, and executes the associated code.< condition-list > regular-expression :=> condition— a rule merged into every condition on the condition-list. It matches regular-expression and immediately transitions to condition (there 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 (peep the actions section for the various types of actions).<! condition-list > code— a rule that prepends code to the semantic actions of all rules for every condition on the condition-list. 🚨 This syntax is deprecated — use the!pre_ruleaction instead (it does exactly the same thing).< > 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 — use the!entryaction instead (it gives you more fine-grained control, since the code can be specified per-condition, and you 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 re2swift generates for conditions depends on whether it uses the goto/label approach or the loop/switch approach to encode the automata 👑
In languages that have a goto statement (such as C/C++ and Go), conditions are naturally implemented as blocks of code prefixed with labels of the form yyc_<cond>, where cond is a condition name (the label prefix can be changed with re2c:cond:prefix) 💅. Transitions between conditions are implemented using goto and condition labels. Before all conditions, re2swift generates an initial switch on YYGETSTATE that jumps to the start state of the current condition. The shortcut rules :=> bypass that initial switch and jump straight to the specified condition (re2c:cond:goto can be used to change the default behavior). And heads up — the rules with semantic actions do not automatically jump to the next condition; that's your job, via the user-defined action code 😌.
In languages that do not have goto (such as Rust), re2swift 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 from a switch between DFA states of a single condition. No separate initial condition switch needed, periodt. (And since the same approach is used to implement storable states, YYGETCOND/YYSETCOND are redundant if you're using both storable states and conditions.)
OK bestie, this program is giving start-condition excellence: it parses binary, octal, decimal, and hexadecimal numbers. There is literally a single block where each base has its own condition, and the initial condition is connected to all of them. The user-defined variable cond stores the current condition number; it is initialized to the number of the initial condition generated with the conditions block. Slay. 💅
// re2swift $INPUT -o $OUTPUT -c
/*!conditions:re2c*/
func parseUInt32(_ yyinput: UnsafePointer<UInt8>) -> UInt32? {
var yycursor = 0, yymarker = 0, yycond = yycinit
var accum: UInt64 = 0
loop: while true {
/*!re2c
re2c:yyfill:enable = 0;
<init> '0b' / [01] :=> bin
<init> "0" :=> oct
<init> "" / [1-9] :=> dec
<init> '0x' / [0-9a-fA-F] :=> hex
<bin> [01] { add("0", 2); continue loop }
<oct> [0-7] { add("0", 8); continue loop }
<dec> [0-9] { add("0", 10); continue loop }
<hex> [0-9] { add("0", 16); continue loop }
<hex> [a-f] { add("a", 16, 10); continue loop }
<hex> [A-F] { add("A", 16, 10); continue loop }
<bin, oct, dec, hex> "\x00" { return UInt32(exactly: accum) }
<*> * { return nil }
*/
}
func add(_ charOrigin: UnicodeScalar, _ base: UInt64, _ offset: UInt64 = 0) {
let digit = yyinput[yycursor - 1] - UInt8(ascii: charOrigin)
accum = min(accum * base + UInt64(digit) + offset, UInt64(UInt32.max) + 1)
}
}
assert(parseUInt32("") == nil)
assert(parseUInt32("1234567890") == 1234567890)
assert(parseUInt32("0b1101") == 13)
assert(parseUInt32("0x7Fe") == 2046)
assert(parseUInt32("0644") == 420)
assert(parseUInt32("9999999999") == nil)
💾 Storable state 💾
With the --storable-state option, re2swift 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 re2swift is a "pull" model, in which the lexer "pulls" more input whenever it needs it. That can be a whole problem 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). The 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) and state variables as a part of persistent lexer state. The state variable should be initialized to-1. YYFILLshould return to the outer program instead of trying to supply more input. Return code should indicate that lexer needs more input.- The outer program should recognize situations when lexer needs more input and respond appropriately.
- Optionally use
getstateblock to generateYYGETSTATEswitch detached from the main lexer. This only works for languages that havegoto(not in--loop-switchmode). - Use
re2c:eofand the sentinel with bounds checks method to handle the end of input. Padding-based method may not work because it is unclear when to append padding: the current end of input may not be the ultimate end of input, and appending padding too early may cut off a partially read greedy lexeme. Furthermore, due to high-level program logic getting more input may depend on processing the lexeme at the end of buffer (which already is blocked due to the end-of-input condition). 😭
Here’s an example of a "push" model lexer that simulates reading packets from a socket. The lexer loops until it encounters the end of input and returns to the calling function. The calling function provides more input by "sending" the next packet and resumes lexing. This process stops when all the packets have been sent, or when there is an error.
// re2swift $INPUT -o $OUTPUT -f
import Foundation
func log(_ items: Any..., separator: String = " ", terminator: String = "\n") {
#if DEBUG
var stderr = FileHandle.standardError
print(items, separator: separator, terminator: terminator, to: &stderr)
#endif
}
extension FileHandle: TextOutputStream {
public func write(_ string: String) {
self.write(Data(string.utf8))
}
}
struct State {
// Use a small buffer to cover the case when a lexeme doesn't fit,
// in a real world use case use a larger buffer.
static let bufferSize = 10
let file: FileHandle
// Extra '\0' byte on buffer acts as terminator.
var yyinput = ContiguousArray<UInt8>(repeating: 0, count: Self.bufferSize + 1)
var yylimit = Self.bufferSize
var yycursor = Self.bufferSize
var yymarker = Self.bufferSize
var token = Self.bufferSize
var yystate = -1
}
extension State {
mutating func lex(recv: inout Int) -> Status {
var yych: UInt8 = 0
lex: while true {
self.token = self.yycursor
/*!re2c
re2c:api = record;
re2c:eof = 0;
re2c:variable:yyrecord = "self";
re2c:YYFILL = "return .waiting";
packet = [a-z]+[;];
* { return .badPacket }
$ { return .end }
packet {
recv += 1
continue lex
}
*/
}
}
mutating func fill() -> Status {
let used = self.yylimit - self.token
let free = Self.bufferSize - used
// Error: No space. In the real world we can reallocate a larger buffer.
if free < 1 {
return .bigPacket
}
// Shift buffer contents, discarding everything up to the current lexeme.
let shift = self.token
self.yyinput.replaceSubrange(..<used, with: self.yyinput[shift..<self.yylimit])
self.yylimit -= shift
self.yycursor -= shift
self.yymarker -= shift
self.token = 0
// Fill free space at the end of buffer with new data.
do {
if let data = try self.file.read(upToCount: free) {
self.yyinput.replaceSubrange(self.yylimit..<(self.yylimit + data.count), with: data)
self.yylimit += data.count
}
} catch {
fatalError("cannot read from file: \(error.localizedDescription)")
}
self.yyinput[self.yylimit] = 0 // append sentinel
return .ready
}
enum Status {
case end, ready, waiting, badPacket, bigPacket
}
}
func test(_ packets: [StaticString]) -> State.Status {
// Create a "socket" (open the same file for reading and writing).
let fname: String = "pipe"
guard FileManager.default.createFile(atPath: fname, contents: nil),
let fw = FileHandle(forWritingAtPath: fname) else {
fatalError("cannot open '\(fname)'")
}
guard let fr = FileHandle(forReadingAtPath: fname) else {
fatalError("cannot read file '\(fname)'")
}
defer {
// Cleanup: remove input file.
do {
try fw.close()
try fr.close()
try FileManager.default.removeItem(atPath: fname)
} catch {
fatalError("error on file cleanup: \(error.localizedDescription)")
}
}
var state = State(file: fr)
// Main loop. The buffer contains incomplete data which appears packet by
// packet. When the lexer needs more input it saves its internal state and
// returns to the caller which should provide more input and resume lexing.
var send = 0, recv = 0
while true {
switch state.lex(recv: &recv) {
case .end:
log("done: got \(recv)")
assert(recv == send)
return .end
case .waiting:
log("waiting...")
if send < packets.count {
log("sent packet \(send)")
packets[send].withUTF8Buffer {
do {
try fw.write(contentsOf: $0)
} catch {
fatalError("cannot write to \(fname): \(error.localizedDescription)")
}
}
send += 1
}
let status = state.fill()
state.yyinput.withUnsafeBytes {
let buf = $0.bindMemory(to: CChar.self)
log("queue: '\(String(utf8String: buf.baseAddress!) ?? "")'")
}
if status == .bigPacket {
log("error: packet too big")
return .bigPacket
}
assert(status == .ready)
case .badPacket:
log("error: ill-formed packet")
return .badPacket
default:
fatalError("unreachable")
}
}
}
assert(test([]) == .end)
assert(test([ "zero;", "one;", "two;", "three;", "four;" ]) == .end)
assert(test([ "zer0;" ]) == .badPacket)
assert(test([ "looooooooooong;" ]) == .bigPacket)
log("all tests completed successfully")
🧩 Reusable blocks 🧩
Reusable blocks of the form /*!rules:re2c[:<name>] ... */ or %{rules[:<name>] ... %} can be reused any number of times and combined with other re2swift blocks. The <name> is optional. A rules block can be used in a use block or directive. The code for a rules block is generated at every point of use. ♻️
Use blocks are defined with /*!use:re2c[:<name>] ... */ or %{use[:<name>] ... %}. The <name> is optional: if it’s not specified, the associated rules block is the most recent one (whether named or unnamed). A use block can add named definitions, configurations and rules of its own. An important use case for use blocks is a lexer that supports multiple input encodings: the same rules block is reused multiple times with encoding-specific configurations (see the example below). 🧚
okay bestie, so the in-block use directive !use:<name>; is literally the group-chat merge feature — you drop it inside a re2swift block and it pulls the referenced block <name> right into the current one. 🫶
And when the merged rules and configurations overlap with stuff you already defined? Conflicts get resolved the usual way, no drama: the earliest rule takes priority, and latest configuration overrides preceding ones. One exception though (there's always one 💅): the special rules *, $ and (in condition mode) <!> — for those, a block-local definition overrides any inherited ones. So the use directive is how you combine different re2swift blocks together into one single block (peep the example below, it's giving collaboration 👑).
Historical tea ☕: named blocks and the in-block use directive were added in re2swift version 2.2. Since that version, reusable blocks are allowed by default (no special option needed, slay). Before version 2.2, reuse mode was enabled with the -r --reusable option. And before version 1.2, reusable blocks could not be mixed with normal blocks — different era, don't ask 😭.
✨ Example of a !use directive ✨
// re2swift $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.
/*!rules:re2c:colors
* { fatalError("unreachable") }
"red" | "salmon" | "magenta" { return .color }
*/
/*!rules:re2c:fish
* { fatalError("unreachable") }
"haddock" | "salmon" | "eel" { return .fish }
*/
func lex(_ yyinput: UnsafePointer<UInt8>) -> What {
var yycursor = 0, yymarker = 0
/*!re2c
re2c:yyfill:enable = 0;
!use:fish;
!use:colors;
* { return .dunno } // Overrides inherited '*' rules
*/
}
enum What { case color, fish, dunno }
assert(lex("salmon") == .fish)
assert(lex("what?") == .dunno)
🎀 Example of a /*!use:re2c ... */ block 🎀
// re2swift $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;
"∀x ∃y" { return true }
* { return false }
*/
func lexUTF8(_ yyinput: [UInt8]) -> Bool {
var yycursor = 0, yymarker = 0
/*!use:re2c
re2c:YYCTYPE = UInt8;
re2c:encoding:utf8 = 1;
*/
}
func lexUTF32(_ yyinput: [UInt32]) -> Bool {
var yycursor = 0, yymarker = 0
/*!use:re2c
re2c:YYCTYPE = UInt32;
re2c:encoding:utf32 = 1;
*/
}
assert(lexUTF8([ 0xe2, 0x88, 0x80, 0x78, 0x20, 0xe2, 0x88, 0x83, 0x79 ])) // UTF-8
assert(lexUTF32([ 0x00002200, 0x00000078, 0x00000020, 0x00002203, 0x00000079 ])) // UTF-32
🦋 Submatch extraction 🦋
re2swift gives you two options for submatch extraction. Two! Pick your fighter 💖
⭐ Tags
Option numero uno is to use standalone tags of the form @stag or #mtag, where stag and mtag are arbitrary used-defined names. Tags get enabled with the -T --tags option or the re2c:tags = 1 configuration.
Semantically? Tags are position markers — you can insert them anywhere in a regular expression and they bind to the corresponding position (or multiple positions) in the input string. S-tags bind to the last matching position, and m-tags bind to a list of positions (they're the ones you use in repetition subexpressions, where a single position in a regular expression corresponds to multiple positions in the input string — iconic multitaskers ✨).
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 dos is capturing groups. Enabled with the --captures option or the re2c:captures = 1 configuration.
There are two flavours for different disambiguation policies: --leftmost-captures (the default) is for the leftmost greedy policy, and --posix-captures is for the POSIX longest-match policy.
In this mode all parenthesized subexpressions are considered capturing groups, and a bang can be used to mark non-capturing groups: (! ... ). With the --invert-captures option or the re2c:invert-captures = 1 configuration, the meaning of bang is inverted (chaotic but valid 🙈).
The number of groups for the matching rule is stored in a variable yynmatch (the whole regular expression is group number zero, main character energy 👑), and submatch results are stored in the yypmatch array. Both yynmatch and yypmatch should be defined by the user, and yypmatch size must be at least [yynmatch * 2]. Use the maxnmatch block to define YYMAXNMATCH, a constant that equals to the maximum value of yynmatch among all rules.
🍓 Captvars
Another way to use capturing groups is the --captvars option or the re2c:captvars = 1 configuration. The only difference with --captures is in the way the generated code stores submatch results: instead of yynmatch and yypmatch, re2swift generates variables yytl<k> and yytr<k> for the k-th capturing group (the user should declare these using an svars block).
Captures with variables support two disambiguation policies: --leftmost-captvars or re2c:leftmost-captvars = 1 for the leftmost greedy policy (the default one) and --posix-captvars or re2c:posix-captvars for the POSIX longest-match policy.
🌈 Under the hood
Under the hood all these options translate into tags and Tagged Deterministic Finite Automata with Lookahead. The core idea of TDFA is to minimize the overhead on submatch extraction. In the extreme, if there're no tags or captures in a regular expression, TDFA is just an ordinary DFA. If the number of tags is moderate, the overhead is barely noticeable. 🔥
The generated TDFA uses a number of tag variables which do not map directly to tags: a single variable may be used for different tags, and a tag may require multiple variables to hold all its possible values. Eventually ambiguity is resolved, and only one final variable per tag survives. Tag variables should be defined using stags or mtags blocks. If lexer state is stored, tag variables should be part of it. They also need to be updated by YYFILL.
S-tags support the following operations:
- save input position to an s-tag:
t = YYCURSORwith C pointer API or a user-defined operationYYSTAGP(t)with generic API - save default value to an s-tag:
t = NULLwith C pointer API or a user-defined operationYYSTAGN(t)with generic API - copy one s-tag to another:
t1 = t2
M-tags support the following operations:
- append input position to an m-tag: a user-defined operation
YYMTAGP(t)with both default and generic API - append default value to an m-tag: a user-defined operation
YYMTAGN(t)with both default and generic API - copy one m-tag to another:
t1 = t2
S-tags can be implemented as scalar values (pointers or offsets). M-tags need a more complex representation, as they need to store a sequence of tag values. The most naive and inefficient representation of an m-tag is a list (array, vector) of tag values; a more efficient representation is to store all m-tags in a prefix-tree represented as array of nodes (v, p), where v is tag value and p is a pointer to parent node.
Here'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. 💖
// re2swift $INPUT -o $OUTPUT
struct SemVer: Equatable { var major: Int, minor: Int, patch: Int }
func lex(_ yyinput: UnsafePointer<UInt8>) -> SemVer? {
let tagNone = -1
var yycursor = 0, yymarker = 0
// Final tag variables available in semantic action.
/*!svars:re2c format = "var @@ = tagNone\n"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = 'var @@ = tagNone\n'; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:tags = 1;
num = [0-9]+;
@t1 num @t2 "." @t3 num @t4 ("." @t5 num)? [\x00] {
let s2n = { (range: Range<Int>) in
range.reduce(0) { accum, idx in
accum * 10 + Int(yyinput[idx] - UInt8(ascii: "0"))
}
}
return SemVer(
major: s2n(t1..<t2),
minor: s2n(t3..<t4),
patch: t5 != tagNone ? s2n(t5..<(yycursor - 1)) : 0)
}
* { return nil }
*/
}
assert(lex("23.34") == SemVer(major: 23, minor: 34, patch: 0))
assert(lex("1.2.999") == SemVer(major: 1, minor: 2, patch: 999))
assert(lex("1.a") == nil)
Here's a more complex example of using s-tags with YYFILL to parse a file with newline-separated semantic versions. 🌸 Tag variables are part of the lexer state, and they are adjusted in YYFILL like other input positions. Note that it is necessary for s-tags because their values are invalidated after shifting buffer contents. It may not be necessary in a custom implementation where tag variables store offsets relative to the start of the input string rather than the buffer, which may be the case with m-tags.
// re2swift $INPUT -o $OUTPUT --api generic --tags
import Foundation
struct SemVer: Equatable { var major: Int, minor: Int, patch: Int }
struct Input {
static let bufferSize = 4095
static let tagNone = -1
var yyinput = ContiguousArray<UInt8>(repeating: 0, count: Self.bufferSize + 1)
var yylimit = Self.bufferSize
var yycursor = Self.bufferSize
var yymarker = Self.bufferSize
var token = Self.bufferSize
// Intermediate tag variables must be part of the lexer state passed to YYFILL.
// They don't correspond to tags and should be autogenerated by re2c.
/*!stags:re2c format = " var @@ = Self.tagNone\n"; */
var eof = false
let file: FileHandle
}
extension Input {
mutating func lex() -> [SemVer]? {
var semVers = [SemVer]()
semVers.reserveCapacity(Self.bufferSize)
// Final tag variables available in semantic action.
/*!svars:re2c format = " var @@: Int\n"; */
…okay we're literally dropping back in mid-lexer, no time to breathe, here's the rest of that example in all its glory 💅
parse: while true {
self.token = self.yycursor
/*!re2c
re2c:api = record;
re2c:eof = 0;
re2c:tags = 1;
re2c:yyrecord = "self";
re2c:YYFILL = "self.fill() == .ok";
num = [0-9]+;
num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] {
semVers.append(SemVer(
major: self.s2n(self.token..<t1),
minor: self.s2n(t2..<t3),
patch: t4 != Self.tagNone ? self.s2n(t4..<(self.yycursor - 1)) : 0
))
continue parse
}
$ { return semVers }
* { return nil }
*/
}
func s2n(_ range: Range<Int>) -> Int {
self.yyinput[range].reduce(0) { accum, digit in
accum * 10 + Int(digit - UInt8(ascii: "0"))
}
}
mutating func fill() -> FillStatus {
guard !self.eof else {
return .eof
}
let shift = self.token
let used = self.yylimit - self.token
let free = Self.bufferSize - used
// Error: Lexeme too long. In the real world we could reallocate a larger buffer.
guard self.token >= 1 else {
return .longLexeme
}
// Shift buffer contents, discarding everything up to the current token.
self.yyinput.replaceSubrange(..<used, with: self.yyinput[shift..<self.yylimit])
self.yylimit -= shift
self.yycursor -= shift
self.yymarker &-= shift // May underflow is marker is unused
self.token = 0
// Tag variables need to be shifted like other input positions. The check
// for `tagNone` is only needed if some tags are nested inside of alternative
// or repetition, so that they can have `tagNone` value.
/*!stags:re2c format = " if self.@@ != Self.tagNone { self.@@ -= shift }\n"; */
// Fill free space at the end of the buffer with new data from file.
do {
if let data = try self.file.read(upToCount: free) {
self.yyinput.replaceSubrange(self.yylimit..<(self.yylimit + data.count), with: data)
self.yylimit += data.count
}
} catch {
fatalError("cannot read from file: \(error.localizedDescription)")
}
self.yyinput[self.yylimit] = 0 // append sentinel
self.eof = self.yylimit < Self.bufferSize
return .ok
}
enum FillStatus {
case ok, eof, longLexeme
}
}
extension SemVer: CustomStringConvertible {
var description: String { "\(self.major).\(self.minor).\(self.patch)" }
}
let fileName = "input"
let semVer = SemVer(major: 1, minor: 22, patch: 333)
let expect = [SemVer](repeating: semVer, count: Input.bufferSize)
// Prepare input file (make sure it exceeds buffer size).
guard FileManager.default.createFile(
atPath: fileName,
contents: Data(String(repeating: "\(semVer)\n", count: Input.bufferSize).utf8)
) else {
fatalError("failed to write file \"\(fileName)\"")
}
// Reopen input file for reading.
guard let file = FileHandle(forReadingAtPath: fileName) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue)
}
// Initialize lexer state. Buffer is set to zero, triggering YYFILL.
var `in` = Input(file: file)
// Run the lexer and check the results.
guard let actual = `in`.lex() else {
fatalError("parser error")
}
assert(actual == expect)
// Cleanup: remove input file.
try file.close()
try FileManager.default.removeItem(atPath: fileName)
Like, the way this one slaps?? 🔥 You've got re2c:api = record and re2c:yyrecord = "self" so all the lexer state lives in self, re2c:eof = 0 for that explicit end-of-input sentinel, and re2c:tags = 1 to switch the tagging on. The $ rule fires when end of input hits and hands you back semVers, and the * default rule just bails with nil. Also note fill() returns .longLexeme when there's no room to shift (that guard self.token >= 1) — in a real-world app you'd reallocate a bigger buffer instead. So valid, bestie. 😌
Here is an example of using capturing groups to parse semantic versions. 🎀
// re2swift $INPUT -o $OUTPUT
struct SemVer: Equatable { var major: Int, minor: Int, patch: Int }
func lex(_ yyinput: UnsafePointer<UInt8>) -> SemVer? {
let tagNone = -1
var yycursor = 0, yymarker = 0
// Final tag variables available in semantic action.
/*!svars:re2c format = " var @@: Int\n"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = " var @@ = tagNone\n"; */
/*!re2c
re2c:yyfill:enable = 0;
re2c:captvars = 1;
num = [0-9]+;
(num) "." (num) ("." num)? [\x00] {
let _ = yytl0; _ = yytr0 // Some variables are unused.
return SemVer(
major: s2n(yytl1..<yytr1),
minor: s2n(yytl2..<yytr2),
patch: yytl3 != tagNone ? s2n((yytl3 + 1)..<yytr3) : 0)
}
* { return nil }
*/
func s2n(_ range: Range<Int>) -> Int {
range.reduce(0) { accum, idx in
accum * 10 + Int(yyinput[idx] - UInt8(ascii: "0"))
}
}
}
assert(lex("23.34") == SemVer(major: 23, minor: 34, patch: 0))
assert(lex("1.2.999") == SemVer(major: 1, minor: 2, patch: 999))
assert(lex("1.a") == nil)
Capturing groups >> everything else, fr fr. re2c:captvars = 1 gives you those yytl* / yytr* pairs (left and right bounds for each numbered group), re2c:yyfill:enable = 0 says "no refilling, we're single-shot", and the [^\x00] sentinel at the end means end of input is literally a \x00 byte. Also the let _ = yytl0; _ = yytr0 line is just there to hush the "unused variable" warnings for group 0. The three asserts at the bottom? Chef's kiss validation. 💖
Here is an example of using m-tags to parse a version with a variable number of components. Tag variables are stored in a trie. 🦋
// re2swift $INPUT -o $OUTPUT
import Foundation
// Unbounded number of version components.
struct Ver: Equatable { let components: [Int] }
func parse(_ yyinput: UnsafePointer<UInt8>) -> Ver? {
let tagNone = -1
var yycursor = 0, yymarker = 0
var mTagPool = [MTag]()
// Final tag variables available in semantic action.
/*!svars:re2c format = " let @@: Int\n"; */
/*!mvars:re2c format = " let @@: MTag?\n"; */
// Intermediate tag variables used by the lexer (must be autogenerated).
/*!stags:re2c format = " var @@ = tagNone\n"; */
/*!mtags:re2c format = " var @@: MTag? = nil\n"; */
/*!re2c
re2c:tags = 1;
re2c:yyfill:enable = 0;
re2c:YYSTAGP = "@@ = yycursor";
re2c:YYSTAGN = "@@ = tagNone";
re2c:YYMTAGP = "@@ = add(tag: @@, value: yycursor)";
re2c:YYMTAGN = "@@ = add(tag: @@, value: tagNone)";
num = [0-9]+;
@t1 num @t2 ("." #t3 num #t4)* [\x00] {
var components = [s2n(t1..<t2)]
unfold(&components, t3, t4)
return Ver(components: components)
}
* { return nil }
*/
// Recursively unwind tag histories and collect version components.
func unfold(_ ver: inout [Int], _ x: MTag?, _ y: MTag?) {
if x == nil && y == nil {
// Reached the root of the m-tag tree, stop recursion.
return
}
// Unwind history further.
unfold(&ver, x?.prev, y?.prev)
// Get tag values, tag histories must have equal length.
guard let ex = x?.elem, let ey = y?.elem else {
fatalError("mismatched history length")
}
guard ex != tagNone && ey != tagNone else {
// Both tags are empty, this corresponds to zero repetitions.
assert(ex == ey)
return
}
// Both tags are valid indices, extract component.
ver.append(s2n(ex..<ey))
}
// Pre-parsed string to number.
func s2n(_ range: Range<Int>) -> Int {
range.reduce(0) { accum, idx in
accum * 10 + Int(yyinput[idx] - UInt8(ascii: "0"))
}
}
// Append a single value to an m-tag history.
func add(tag prevTag: MTag?, value: Int) -> MTag {
let tag = MTag(prev: prevTag, element: value)
mTagPool.append(tag)
return tag
}
}
// An m-tag tree is a way to store histories with an O(1) copy operation.
// Histories naturally form a tree, as they have common start and fork at some
// point. The tree is stored as an array of pairs (tag value, link to parent).
// An m-tag is represented with a single link in the tree (array index).
class MTag {
weak var prev: MTag? // Link of predecessor node or root (nil)
var elem: Int // Tag value
init(prev: MTag?, element: Int) {
self.prev = prev
self.elem = element
}
}
assert(parse("1") == Ver(components: [1]))
assert(parse("1.2.3.4.5.6.7") == Ver(components: [1, 2, 3, 4, 5, 6, 7]))
assert(parse("1.2.") == nil)
The difference between @tag and #tag is genuinely iconic: a plain @ tag just records one position (YYSTAGP / YYSTAGN), while an m-tag # keeps a whole history of positions by pushing onto a linked tree (YYMTAGP / YYMTAGN). That MTag class with the weak var prev link is the trie — every node points back at its parent, so copying a history is O(1) and unfold() just walks the chain back to the root. The guard ex != tagNone && ey != tagNone bit handles the zero-repetition case, and if the two history lengths disagree you get fatalError("mismatched history length"). No cap, this is highkey the coolest part of the whole page. 👑
🌈 Encoding support 🌈
Okay so this part is important, bestie, listen up: you gotta understand the difference between code points and code units. A code point is the numeric identifier of a symbol. A code unit is the smallest unit of storage in the encoded text. A single code point 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 re2swift compiles regular expressions to automata it translates code points to code units. This is generally not a simple mapping: in variable-length encodings a single code point range may get translated to a complex code unit graph. 😭
The following encodings are supported:
- ASCII (enabled by default). It is a fixed-length encoding with code space
[0-255]and 1-byte code points and code units. 🍓 - EBCDIC (enabled with
--ebcdicorre2c:encoding:ebcdic). It is a fixed-length encoding with code space[0-255]and 1-byte code points and code units. - UCS2 (enabled with
--ucs2orre2c:encoding:ucs2). It is a fixed-length encoding with code space[0-0xFFFF]and 2-byte code points and code units. - UTF8 (enabled with
--utf8orre2c:encoding:utf8). It is a variable-length Unicode encoding. Code unit size is 1 byte. Code points are represented with1 -- 4code units. - UTF16 (enabled with
--utf16orre2c:encoding:utf16). It is a variable-length Unicode encoding. Code unit size is 2 bytes. Code points are represented with1 -- 2code units. - UTF32 (enabled with
--utf32orre2c:encoding:utf32). It is a fixed-length Unicode encoding with code space[0-0x10FFFF]and 4-byte code points and code units. ✨
The include files include/unicode_blocks.re, include/unicode_categories.re, and include/unicode_properties.re give you re2swift definitions for blocks, categories, and properties described in the Unicode standard. 💖
The option --input-encoding sets the source file encoding, which can be used to enable Unicode literals in regular expressions. For example, --input-encoding utf8 tells re2swift that the source file is in UTF8 (and yes bestie, it differs from --utf8, which sets the input text encoding). The option --encoding-policy controls the way re2swift handles Unicode surrogates (code points in range [0xD800-0xDFFF]). 🦋
Below is an example of a lexer for UTF8 encoded Unicode identifiers.
// re2swift $INPUT -o $OUTPUT -8 -i
/*!include:re2c "unicode_categories.re" */
func lex(_ yyinput: UnsafePointer<UInt8>) -> Bool {
var yycursor = 0, yymarker = 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 }
*/
}
assert(lex("_Ыдентификатор"))
assert(lex("識別子"))
assert(!lex("+"))
✨ Include files
re2swift lets you 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. 👑
re2swift 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 re2swift 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. 💅
re2swift 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 re2swift. Below is an example of using include files. 🌸
Include file 1 (definitions.swift)
enum Result { case ok, fail }
/*!re2c
number = [1-9][0-9]*;
*/
Include file 2 (extra_rules.re.inc)
// floating-point numbers
frac = [0-9]* "." [0-9]+ | [0-9]+ ".";
exp = 'e' [+-]? [0-9]+;
float = frac exp? | [0-9]+ exp;
float { return .ok }
Input file
// re2swift $INPUT -o $OUTPUT -i
/*!include:re2c "definitions.swift" */
func lex(_ yyinput: UnsafePointer<UInt8>) -> Result {
var yycursor = 0, yymarker = 0
/*!re2c
re2c:yyfill:enable = 0;
* { return .fail }
number { return .ok }
!include "extra_rules.re.inc";
*/
}
assert(lex("123") == .ok)
assert(lex("123.4567") == .ok)
🎀 Header files
re2swift allows you to generate a 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 the header file, and the second block marks the end of it. Everything between these blocks is processed by re2swift, 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 re2swift is used to generate definitions that must be visible from other translation units. 🫶
Here is an example of generating a header file that contains definition of the lexer state with tag variables (the number variables depends on the regular grammar and is unknown to the programmer).
Input file
// re2swift $INPUT -o $OUTPUT -i --header lexer/state.swift
/*!header:re2c:on*/
struct LexerState {
var yyinput: UnsafePointer<UInt8>
var yycursor: Int
/*!stags:re2c format = "var @@ = -1"; */
init(str: UnsafePointer<UInt8>, cur: Int = 0) {
self.yyinput = str
self.yycursor = cur
}
}
/*!header:re2c:off*/
extension LexerState {
mutating func lex() -> Int {
let t: Int
/*!re2c
re2c:header = "lexer/state.swift";
re2c:api = record;
re2c:tags = 1;
re2c:yyfill:enable = 0;
re2c:yyrecord = "self";
[a]* @t [b]* { return t }
*/
}
}
@main struct Program {
static func main() {
let str: StaticString = "ab"
var state = LexerState(str: str.utf8Start)
assert(state.lex() == 1)
}
}
Header file
/* Generated by re2swift */
struct LexerState {
var yyinput: UnsafePointer<UInt8>
var yycursor: Int
var yyt1 = -1
init(str: UnsafePointer<UInt8>, cur: Int = 0) {
self.yyinput = str
self.yycursor = cur
}
}
💀 Skeleton programs
With the -S, --skeleton option, re2swift ignores all non-re2swift 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) re2swift 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 re2swift 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). re2swift 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, re2swift 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) re2swift 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 (re2swift writes data to file as soon as it is generated). 😭
🔥 Visualization and debug
With the -D, --emit-dot option, re2swift does not generate code. Instead, it dumps the generated DFA in DOT format. One can convert this dump to an image of the DFA using Graphviz or another library. Note that this option shows the final DFA after it has gone through a number of optimizations and transformations. Earlier stages can be dumped with various debug options, such as --dump-nfa, --dump-dfa-raw etc. (see the full list of options). 🌈
👑 SEE ALSO
You can find more information about re2c at the official website: http://re2c.org. Similar programs are flex(1), lex(1), quex (http://quex.sourceforge.net).
🫶 AUTHORS
re2swift was originally written by Peter Bumbulis (peter@csg.uwaterloo.ca) in 1993. Marcus Boerger and Dan Nuffer spent several years to turn the original idea into a production ready code generator. Since then it has been maintained and developed by multiple volunteers, most notably, Brian Young (bayoung@acm.org), Marcus Boerger, Dan Nuffer (nuffer@users.sourceforge.net), Ulya Trofimovich (skvadrik@gmail.com), Serghei Iakovlev, Sergei Trofimovich, Petr Skocik, ligfx raekye and PolarGoose.
RE2SWIFT(1) — that’s the footer, bestie: source/version and date vibes, periodt. 💅✨
📦 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