RE2ZIG(1) RE2ZIG(1) (NAME) re2zig - Zig (SYNOPSIS) re2zig [ OPTIONS ] [ WARNINGS ] INPUT - stdin . (INTRODUCTION) re2zig . ( Zig ) / . . re2zig . Zig . : // re2zig $INPUT -o $OUTPUT const std = @import("std"); fn lex(yyinput: [:0]const u8) bool { var yycursor: u32 = 0; %{ re2c:yyfill:enable = 0; [1-9][0-9]* { return true; } * { return false; } %} } test { try std.testing.expect(lex("1234")); } re2zig : // Generated by re2zig // re2zig $INPUT -o $OUTPUT const std = @import("std"); fn lex(yyinput: [:0]const u8) bool { var yycursor: u32 = 0; var yych: u8 = 0; var yystate: u32 = 0; yyl: while (true) { switch (yystate) { 0 => { yych = yyinput[yycursor]; yycursor += 1; switch (yych) { 0x31...0x39 => { yystate = 2; continue :yyl; }, else => { yystate = 1; continue :yyl; }, } }, 1 => { return false; }, 2 => { yych = yyinput[yycursor]; switch (yych) { 0x30...0x39 => { yycursor += 1; yystate = 2; continue :yyl; }, else => { yystate = 3; continue :yyl; }, } }, 3 => { return true; }, else => { @panic("internal lexer error"); }, } } } test { try std.testing.expect(lex("1234")); } (BASICS) re2zig . : name = regular-expression ; name regular-expression . . regular expressions re2zig . name . . . . configuration = value ; re2zig . re2zig configurations . value . . . regular-expression code regular-expression ( := ) . regular-expression code . . . : * $. ( encoding support ). handling the end of input . start conditions . !action code code ( ). actions . !directive ; . . directives . (Blocks) /*!re2c */ %{ %} ( ). . . : /*!re2c[:] ... */ %{[:] ... %} . re2zig (DFA) . . . /*!local:re2c[:] ... */ %{local[:] ... %} ( ). /*!rules:re2c[:] ... */ %{rules[:] ... %} -- . ( ). . re2zig -r --reusable . /*!use:re2c[:] ... */ %{use[:] ... %} use . re2zig ( ) . use . . re2zig use -r --reusable . /*!max:re2c[:[:...]] ... */ %{max[:[:...]] ... %} YYMAXFILL . YYMAXFILL ( ). C (#define YYMAXFILL ) Go (var YYMAXFILL int = ) . format @@{max} ( @@) YYMAXFILL . /*!maxnmatch:re2c[:[:...]] ... */ %{maxnmatch[:[:...]] ... %} YYMAXNMATCH ( -P --posix-captures ). YYMAXNMATCH ( ). C (#define YYMAXNMATCH ) Go (var YYMAXNMATCH int = ) . format @@{max} ( @@) YYMAXNMATCH . /*!stags:re2c[:[:...]] ... */, /*!mtags:re2c[:[:...]] ... */ %{stags[:[:...]] ... %}, %{mtags[:[:...]] ... %{ s-tag/m-tag re2zig . ( ). : format separator. format @@{tag} ( @@) . separator format . /*!svars:re2c[:[:...]] ... */, /*!mvars:re2c[:[:...]] ... */ %{svars[:[:...]] ... %}, %{mvars[:[:...]] ... %{ s-tag/m-tag ( --tags) re2zig ( --captvars --posix-captvars) . ( ). : format separator. format @@{tag} ( @@) . separator format . /*!getstate:re2c[:[:...]] ... */ %{getstate[:[:...]] ... %} ( --storable-state ). . . . --loop-switch goto . /*!conditions:re2c[:[:...]] ... */, /*!types:re2c... */ %{conditions[:[:...]] ... %}, %{types... %} ( --conditions ). ( ). YYCONDTYPE . format separator . format @@{cond} ( @@) @@{num} . separator format . /*!include:re2c */ %{include %} (double-quoted) . #include C/C++ . --depfile . /*!header:re2c:on*/ %{header:on %} . header:off re2zig -t --type-header . /*!header:re2c:off*/ %{header:off %} header:on*/ . /*!ignore:re2c ... */ %{ignore ... %} . (Configurations) re2zig : re2c:api, re2c:input --api. re2c:api:sigil ("sigil") API . @@ . . $ ${name} . API . API re2c:YYFILL@len YYFILL. re2c:api:style API . functions ( C) free-form ( Go Rust). functions API . ( YYFILL) C/C++ (closures) Go Rust . free-form API : @@{var} @@ ( ). API re2c:YYFILL:naked YYFILL . re2c:bit-vectors, re2c:flags:bit-vectors, re2c:flags:b --bit-vectors . re2c:captures, re2c:leftmost-captures --leftmost-captures . re2c:captvars, re2c:leftmost-captvars --leftmost-captvars . re2c:case-insensitive, re2c:flags:case-insensitive --case-insensitive . re2c:case-inverted, re2c:flags:case-inverted --case-inverted . re2c:case-ranges, re2c:flags:case-ranges --case-ranges . re2c:computed-gotos, re2c:flags:computed-gotos, re2c:flags:g --computed-gotos . re2c:computed-gotos:relative, re2c:cgoto:relative --computed-gotos-relative . re2c:computed-gotos:threshold, re2c:cgoto:threshold goto if . 9 . re2c:cond:abort (abort) . re2c:cond:goto :=> . goto @@; . @@ ( re2c:api:sigil re2c:cond:goto@cond ). re2c:cond:goto@cond re2c:cond:goto . @@ . re2c:api:sigil . re2c:cond:divider . /* *********************************** */ . ( re2c:api;sigil re2c:cond:divider@cond ). re2c:cond:divider@cond re2c:cond:divider . @@ . re2c:api:sigil . re2c:cond:prefix, re2c:condprefix . yyc_ . re2c:cond:enumprefix, re2c:condenumprefix . yyc . re2c:debug-output, re2c:flags:debug-output, re2c:flags:d --debug-output . re2c:empty-class, re2c:flags:empty-class --empty-class . re2c:encoding:ebcdic, re2c:flags:ecb, re2c:flags:e --ebcdic . re2c:encoding:ucs2, re2c:flags:wide-chars, re2c:flags:w --ucs2 . re2c:encoding:utf8, re2c:flags:utf-8, re2c:flags:8 --utf8 . re2c:encoding:utf16, re2c:flags:utf-16, re2c:flags:x --utf16 . re2c:encoding:utf32, re2c:flags:unicode, re2c:flags:u --utf32 . re2c:encoding-policy, re2c:flags:encoding-policy --encoding-policy . re2c:eof $ . -1 ( $ ). . . re2c:header, re2c:flags:type-header, re2c:flags:t . --header . re2c:indent:string . "\t" . . . re2c:indent:top . . . re2c:invert-captures --invert-captures . re2c:label:prefix, re2c:labelprefix DFA . yy . re2c:label:start, re2c:startlabel . . . . ( ). re2c:label:yyFillLabel YYFILL re2c:eof . re2c:label:yyloop --loop-switch . yyloop . re2c:label:yyNext YYGETSTATE ( re2c:state:nextlabel) . yyNext . re2c:lookahead, re2c:flags:lookahead ( --no-lookahead ). re2c:monadic ( Haskell ). re2c:nested-ifs, re2c:flags:nested-ifs, re2c:flags:s --nested-ifs . re2c:posix-captures, re2c:flags:posix-captures, re2c:flags:P --posix-captures . re2c:posix-captvars --posix-captvars . re2c:tags, re2c:flags:tags, re2c:flags:T --tags . re2c:tags:expression . re2zig yyt . struct . @@{tag} @@ . re2c:tags:expression = "s.@@"; s.yyt . re2c:api:sigil ..TP re2c:tags:negative ( -1 (null pointer) ). re2c:tags:prefix . yyt . re2c:sentinel ( re2c:yyfill:enable = 0; re2c:eof ). : . -1` ( re2zig ). . re2c:state:abort (abort) -1 . re2c:state:nextlabel switch YYGETSTATE yyNext ( ). re2c:label:start getstate switch YYGETSTATE . re2c:unsafe, re2c:flags:unsafe --no-unsafe . unsafe YYPEEK . ( ). Rust . re2c:YYBACKUP, re2c:define:YYBACKUP API YYBACKUP . re2c:YYBACKUPCTX, re2c:define:YYBACKUPCTX API YYBACKUPCTX . re2c:YYCONDTYPE, re2c:define:YYCONDTYPE API YYCONDTYPE . re2c:YYCTYPE, re2c:define:YYCTYPE API YYCTYPE . re2c:YYCTXMARKER, re2c:define:YYCTXMARKER API YYCTXMARKER . re2c:YYCURSOR, re2c:define:YYCURSOR API YYCURSOR . re2c:YYDEBUG, re2c:define:YYDEBUG API YYDEBUG . re2c:YYFILL, re2c:define:YYFILL API YYFILL . re2c:YYFILL@len, re2c:define:YYFILL@len (sigil) YYFILL . @@ . re2c:api:sigil . re2c:YYFILL:naked, re2c:define:YYFILL:naked re2c:api:style YYFILL . API (free-form) . re2c:YYFN API YYFN . re2c:YYINPUT API YYINPUT . re2c:YYGETCOND, re2c:define:YYGETCONDITION API YYGETCOND . re2c:YYGETCOND:naked, re2c:define:YYGETCONDITION:naked re2c:api:style YYGETCOND . API . re2c:YYGETSTATE, re2c:define:YYGETSTATE API YYGETSTATE . re2c:YYGETSTATE:naked, re2c:define:YYGETSTATE:naked re2c:api:style YYGETSTATE . API . re2c:YYGETACCEPT, re2c:define:YYGETACCEPT API YYGETACCEPT . re2c:YYLESSTHAN, re2c:define:YYLESSTHAN API YYLESSTHAN . re2c:YYLIMIT, re2c:define:YYLIMIT API YYLIMIT . re2c:YYMARKER, re2c:define:YYMARKER API YYMARKER . re2c:YYMTAGN, re2c:define:YYMTAGN API YYMTAGN . re2c:YYMTAGP, re2c:define:YYMTAGP API YYMTAGP . re2c:YYPEEK, re2c:define:YYPEEK API YYPEEK . re2c:YYRESTORE, re2c:define:YYRESTORE API YYRESTORE . re2c:YYRESTORECTX, re2c:define:YYRESTORECTX API YYRESTORECTX . re2c:YYRESTORETAG, re2c:define:YYRESTORETAG API YYRESTORETAG . re2c:YYSETCOND, re2c:define:YYSETCONDITION API YYSETCOND . re2c:YYSETCOND@cond, re2c:define:YYSETCONDITION@cond (sigil) YYSETCOND . @@ . re2c:api:sigil . re2c:YYSETCOND:naked, re2c:define:YYSETCONDITION:naked re2c:api:style YYSETCOND . API . re2c:YYSETSTATE, re2c:define:YYSETSTATE API YYSETSTATE . re2c:YYSETSTATE@state, re2c:define:YYSETSTATE@state (sigil) YYSETSTATE . @@ . re2c:api:sigil . re2c:YYSETSTATE:naked, re2c:define:YYSETSTATE:naked re2c:api:style YYSETSTATE . API . re2c:YYSETACCEPT, re2c:define:YYSETACCEPT API YYSETACCEPT . re2c:YYSKIP, re2c:define:YYSKIP API YYSKIP . re2c:YYSHIFT, re2c:define:YYSHIFT API YYSHIFT . re2c:YYCOPYMTAG, re2c:define:YYCOPYMTAG API YYCOPYMTAG . re2c:YYCOPYSTAG, re2c:define:YYCOPYSTAG API YYCOPYSTAG . re2c:YYSHIFTMTAG, re2c:define:YYSHIFTMTAG API YYSHIFTMTAG . re2c:YYSHIFTSTAG, re2c:define:YYSHIFTSTAG API YYSHIFTSTAG . re2c:YYSTAGN, re2c:define:YYSTAGN API YYSTAGN . re2c:YYSTAGP, re2c:define:YYSTAGP API YYSTAGP . re2c:yyaccept, re2c:variable:yyaccept API yyaccept . re2c:yybm, re2c:variable:yybm API yybm . re2c:yybm:hex, re2c:variable:yybm:hex (bitmaps) --bit-vectors . ( ). re2c:yych, re2c:variable:yych API yych . re2c:yych:emit, re2c:variable:yych:emit yych . . re2c:yych:conversion, re2c:variable:yych:conversion re2zig yych YYCTYPE . ( ). re2c:yych:literals, re2c:variable:yych:literals yych . : char ( ) hex ( ) char_or_hex ( ). re2c:yyctable, re2c:variable:yyctable API yyctable ..TP re2c:yynmatch, re2c:variable:yynmatch API yynmatch . re2c:yypmatch, re2c:variable:yypmatch API yypmatch . re2c:yytarget, re2c:variable:yytarget API yytarget . re2c:yystable, re2c:variable:yystable . re2c:yystate, re2c:variable:yystate API yystate . re2c:yyfill, re2c:variable:yyfill API yyfill . re2c:yyfill:check YYFILL ( YYLESSTHAN API YYLIMIT API C) . ( ). re2c:yyfill:enable YYFILL ( ) . ( ) YYFILL ( (sentinel) ). ( -W) re2c:sentinel (lexer) . (YYFILL ). re2c:yyfill:parameter YYFILL . . ( ). re2c:YYFILL:naked re2c:api:style . re2c:yyfn:sep YYFN ( - ). re2c:yyfn:throw YYFN ( ). (Regular expressions) re2zig : "foo" . 'foo' . [a-xyz], [^a-xyz] ( ). . (newline). R \ S R S. R* R. R+ R. R? R . R{n} R n . R{n,} R n . R{n,m} R n m . (R) R . (submatch) --invert-captures (R) . (!R) --invert-captures (!R) . R S : R S. R | S : R S. R / S (Lookahead): R S S . name name ( "name" Flex). {name} name Flex. @stag s-tag: @stag stag . #mtag m-tag: #mtag mtag . $ . : \a \b \f \n \r \t \v \\ \ooo \xhh \uhhhh \Uhhhhhhhh. (Actions) re2zig : !entry code (Entry action) code . start conditions . (lexeme). !pre_rule code (Pre-rule action) code ( start conditions) . ( ) . !post_rule code (Post-rule action) code ( start conditions) . (trap statements) . (Directives) re2zig : !use:name ; use name . . : . * $ . use use . !include file ; include : file . (Program interface) (primitives) API . . . re2zig ( ) . API . re2zig API : Simple API API Zig . YYCURSOR YYMARKER YYCTXMARKER YYLIMIT YYCTYPE* . Record API Record API struct . --api record re2c:api = record . API yyrecord ( re2c:yyrecord ) struct yycursor yymarker yyctxmarker yylimit ( ). Generic API API . --api generic re2c:api = generic . : YYPEEK YYSKIP YYBACKUP YYBACKUPCTX YYSTAGP YYSTAGN YYMTAGP YYMTAGN YYRESTORE YYRESTORECTX YYRESTORETAG YYSHIFT YYSHIFTSTAG YYSHIFTMTAG YYLESSTHAN YYEND. API . YYCTYPE (code units). ASCII EBCDIC UTF-8 . UTF-16 UCS-2 . UTF-32 . YYCURSOR l-value ( YYINPUT). YYCURSOR . YYCURSOR . YYLIMIT r-value ( YYINPUT). YYLIMIT . . YYCURSOR YYLIMIT . YYMARKER l-value ( YYINPUT). (rollback) YYCURSOR . . YYCTXMARKER l-value (trailing context) ( YYINPUT). . YYCTXMARKER / . YYFILL API len. YYFILL len . re2c:eof len 1 YYFILL . re2c:eof YYFILL . len YYMAXFILL . YYFN --recursive-functions . re2c:fn:sep ( ) . ( void ). : ( ) ( - ). YYINPUT r-value ( ) . YYMAXFILL YYFILL. max . YYLESSTHAN API len. r-value boolean true len . YYEND API . r-value boolean true ( ). YYEND $ . YYLESSTHAN . YYPEEK API . r-value YYCTYPE . YYSKIP API (code unit) . YYBACKUP API ( YYRESTORE ). YYRESTORE API YYBACKUP . YYBACKUPCTX API (trailing context) ( YYRESTORECTX )..TP YYRESTORECTX API YYBACKUPCTX . YYRESTORETAG API tag tag . YYSTAGP API tag tag YYINPUT ( ). YYSTAGP tag . YYSTAGN API tag tag YYINPUT ( ). YYSTAGN tag . YYMTAGP API tag. YYMTAGP tag ( ). YYMTAGN API tag. YYMTAGN tag ( ). YYSHIFT API shift shift ( ). YYCOPYSTAG API lhs rhs s-tag rhs s-tag lhs . lhs rhs . YYCOPYMTAG API lhs rhs m-tag rhs m-tag lhs . lhs rhs . YYSHIFTSTAG API tag shift tag shift ( ). YYSHIFTMTAG API tag shift tag shift ( ). YYMAXNMATCH POSIX . maxnmatch . YYCONDTYPE (enum) . conditions --header . YYGETACCEPT var . var . YYSETACCEPT : var ( l-value ) val ( ). var val . YYGETCOND r-value YYCONDTYPE . YYSETCOND cond cond . YYGETSTATE r-value . -1 . YYSETSTATE state state . YYDEBUG -d --debug-output . ( YYDEBUG ). YYDEBUG : state ( DFA -1) symbol ( ). yyaccept l-value . --storable-state . yybm ( --bitmaps ). . . k- n- (true) n- k- . if switch . yych l-value YYCTYPE . -f --storable-state . yyctable ( --conditions --computed-gotos ). yyfill l-value YYFILL ( YYFILL ). yynmatch l-value POSIX . -P --posix-captures . yypmatch l-value . yynmatch * 2 ( YYMAXNMATCH * 2 ). -P --posix-captures . yystable . yystate l-value --loop-switch DFA . yytarget ( ) . () . yytarget --computed-gotos . (Options) re2c . re2c . re2c . -? --help -h . --api API . simple (lexer) . record (struct class ) . generic API . --bit-vectors -b (bit masks). --nested-ifs . --captures, --leftmost-captures (leftmost greedy). yybmatch 2 * YYMAXNMATCH yynmatch . --captvars, --leftmost-captvars . yytl yytr k- . --case-insensitive . --case-inverted : . --case-ranges case switch low ... high. C/C++ GCC Clang Tcc . case Tcc (binary) . --computed-gotos -g "computed goto" ( ). re2zig . cgoto:threshold . cgoto:relative . --bit-vectors . --computed-gotos-relative --computed-gotos ( ). --computed-gotos . --conditions --start-conditions -c "conditions" Flex: . re2zig goto . --depfile FILE FILE Makefile : [include-file ...]. / include include . --output . --ebcdic --ecb -e EBCDIC . re2zig 0 -- 0xFF . --empty-class re2zig . match-empty () ( ). match-none . error . --encoding-policy re2zig (surrogates). fail surrogate re2zig . substitute re2zig 0xFFFD . ignore () re2zig . . --flex-syntax -F Flex: . . --goto-label "goto/label": DFA goto . goto . --header --type-header -t HEADER HEADER. header:on header:off . condition enum ( conditions ). -I PATH PATH include . include . re2zig FILE include -I . --input --api. default simple ( backend ). custom generic . --input-encoding re2zig. ascii () re2zig ASCII : (code units) . utf8 re2zig UTF8 . --invert-captures (capturing) (non-capturing). (...) (! ...) . (! ...) (...) . --lang . C D Go Haskell Java JS OCaml Python Rust Swift V Zig ( --syntax ). none . --location-format . gnu 'filename:line:column: ...' . msvc 'filename(line,column) ...' . gnu . --loop-switch "loop/switch": DFA switch case switch . yystate . yystate case . --nested-ifs -s if switch . . --no-debug-info -i (line directives) . ( ). --no-generation-date . --no-version . --no-unsafe unsafe YYPEEK ( Rust ). YYPEEK (bounds-checking) . YYPEEK release --no-unsafe unsafe . --output -o OUTPUT OUTPUT. --posix-captures, -P POSIX. yybmatch 2 * YYMAXNMATCH yynmatch . --posix-captvars POSIX. yytl yytr k- . --recursive-functions (co-recursive) DFA . --reusable -r 2.2 ( ). --skeleton -S "" (skeleton). "" . . C ..TP --storable-state -f lexer . lexer push . YYGETSTATE YYSETSTATE yych yyaccept state lexer . --syntax FILE FILE (syntax) . FILE ( ) backend ( --lang none ). --tags -T . --ucs2 --wide-chars -w lexer UCS2 . re2zig 0 -- 0xFFFF . --nested-ifs . --utf8 --utf-8 -8 lexer UTF-8 . re2zig 0 -- 0x10FFFF . --utf16 --utf-16 -x lexer UTF16 . re2zig 0 -- 0x10FFFF . --nested-ifs . --utf32 --unicode -u lexer UTF32 . re2zig 0 -- 0x10FFFF . --nested-ifs . --verbose . --vernum -V MMmmpp ( ). --version -v . --single-pass -1 . ( ). --debug-output -d YYDEBUG . lexer . --dump-adfa : DFA ( .dot). --dump-cfg : ( .dot). --dump-closure-stats : (closure). --dump-dfa-det : DFA ( .dot). --dump-dfa-min : DFA ( .dot). --dump-dfa-tagopt : DFA ( .dot). --dump-dfa-tree : DFA ( .dot). --dump-dfa-raw : DFA ( .dot). --dump-interf : . --dump-nfa : NFA ( .dot). --emit-dot -D lexer .dot . Graphviz ( dot -Tpng -odfa.png dfa.dot). --dfa-minimization : DFA re2zig. moore (Moore) ( ). table " " . DFA . --eager-skip : lexer -- . -- . --no-lookahead . TDFA(0) . TDFA(1) TDFA(0) . . TDFA(0) TDFA(1) . --no-optimize-tags : ( ). --posix-closure : (epsilon-closure) POSIX: gor1 () Goldberg-Radzik gtop " " . --posix-prectable : POSIX. complex TNFA . naive TNFA complex . --stadfa . staDFA TDFA . staDFA TDFA . --fixed-tags : (fixed-tag) (all) (none) (toplevel) . all . "" ( "" ) . . (no-match) ( no-match ). . (Warnings) . -W . -Werror . . -W warning . -Wno- warning . -Werror- warning ( -W ). -Wno-error- warning . . -Wcondition-order . --header conditions . -Wempty-character-class . : . re2zig . --empty-class . -Wmatch-empty-string ( ) . . -Wswapped-range . . -Wundefined-control-flow ( ). . * . -Wunreachable-rules . -Wdeprecated-eof_rule $ . $ . -Wuseless-escape (escape) . re2zig (escape sequence) . -Wnondeterministic-tags n n . -Wsentinel-in-midrule (sentinel) --- (crash) . . re2c:sentinel . -Wundefined-syntax-config --syntax . : . . (Syntax files) re2c . -- . re2c re2c: : . ( include/syntax ) re2zig . ( --lang none ). : . (Feature lists) re2zig : supported_apis API simple record generic. supported_api_styles API functions free-form. supported_code_models goto-label loop-switch recursive-functions. supported_targets code dot skeleton. supported_features nested-ifs bitmaps computed-gotos case-ranges monadic unsafe tags captures captvars. (Language configurations) re2zig : semicolons (semicolon) . backtick_quoted_strings (backtick) . single_quoted_strings (single-quote) . indentation_sensitive . wrap_blocks_in_braces . (Inplace configurations) re2c: . . (Code templates) . - : code-template :: name '=' code-exprs ';' | CODE_TEMPLATE ';' | '' ';' code-exprs :: | 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 ']' . . : re2zig . ( -1 ). . ( ) ( ) . re2zig . if-then-else C : 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; branch : branch{0} ( else ) branch{1:-1} ( ) . stmt : [stmt: stmt] . topindent indent dedent nl .cond ( ). : if x { // do something } else if y { // do something else } else { // don't do anything } re2zig . . . code:var_local . : type ( ) name ( ) init ( ). : .init ( ). code:var_global code:var_local top-level . code:const_local . : type ( ) name ( ) init ( ). code:const_global code:const_local top-level . code:array_local () . : type ( ) name ( ) size ( ) row ( ) elem ( -- row ). : .const ( ). code:array_global code:array_local top-level . code:array_elem (). : array ( ) index ( ). code:enum enum ( ). : type ( ) elem ( ) init ( ). : .init ( ). code:enum_elem ( code:enum). : name ( ) type ( ). code:assign . : lhs ( ) rhs ( ). code:type_int (signed). code:type_uint (unsigned). code:type_yybm yybm. code:type_yytarget yytarget. code:type_yyctable yyctable. code:cmp_eq " " (equals). code:cmp_ne " " (not equals). code:cmp_lt " " (less than). code:cmp_gt " " (greater than). code:cmp_le " " (less or equal). code:cmp_ge " " (greater or equal). code:if_then_else if-then-else . : branch ( ) cond ( ) stmt ( ). : .cond ( ) .many ( ). code:if_then_else_oneline code:if_then_else . code:if_then_else . code:switch switch (case). : expr ( switch) case ( case ). code:switch_cases switch . : case ( ) stmt ( ). code:switch_cases_oneline code:switch_cases . code:switch_cases . code:switch_case_range switch ( ). : val ( ). : .many ( ) .char_literals ( switch -- ). code:switch_case_default (default) switch. code:loop ( ). : label ( ) stmt ( ). code:continue continue. : label ( ). code:goto goto. : label ( ). code:cgoto goto (computed goto). : array ( goto ) index ( ) base ( .cgoto.relative ). code:cgoto:data goto . : label ( ) type ( ) base ( - .cgoto.relative ). code:fndecl . : name ( ) type ( ) throw ( re2c:yyfn:throw ) arg ( ) argname ( ) argtype ( ). : .type ( void ). code:fndef code:fndecl stmt . code:fncall . : name ( ) retval ( l-value ) arg ( ). : .args ( ) .retval ( ). code:tailcall (tail call). : name ( ) arg ( ). : .args ( ) .retval ( void ). code:recursive_functions --recursive-functions. : fn ( ) fndecl ( ) fndef ( ). code:fingerprint (fingerprint) . : ver ( re2zig ) date ( ). code:line_info (line directives) ( ). : line ( ) file ( ). code:abort (abort) . code:yydebug YYDEBUG (API) . : YYDEBUG yyrecord yych ( re2c:) state ( DFA)..TP code:yypeek YYPEEK API . : YYPEEK YYCTYPE YYINPUT YYCURSOR yyrecord yych ( re2c: ). : .cast ( re2c:yych:conversion ). code:yyskip YYSKIP API . : YYSKIP YYCURSOR yyrecord ( re2c: ). code:yybackup YYBACKUP API . : YYBACKUP YYCURSOR YYMARKER yyrecord ( re2c: ). code:yybackupctx YYBACKUPCTX API . : YYBACKUPCTX YYCURSOR YYCTXMARKER yyrecord ( re2c: ). code:yyskip_yypeek code:yyskip code:yypeek ( code:yyskip code:yypeek ). code:yypeek_yyskip code:yypeek code:yyskip ( code:yypeek code:yyskip ). code:yyskip_yybackup code:yyskip code:yybackup ( code:yyskip code:yybackup ). code:yybackup_yyskip code:yybackup code:yyskip ( code:yybackup code:yyskip ). code:yybackup_yypeek code:yybackup code:yypeek ( code:yybackup code:yypeek ). code:yyskip_yybackup_yypeek code:yyskip code:yybackup code:yypeek ( ``code:yyskip`` code:yybackup code:yypeek ). code:yybackup_yypeek_yyskip code:yybackup code:yypeek code:yyskip ( ``code:yybackup`` code:yypeek code:yyskip ). code:yyrestore YYRESTORE API . : YYRESTORE YYCURSOR YYMARKER yyrecord ( re2c: ). code:yyrestorectx YYRESTORECTX API . : YYRESTORECTX YYCURSOR YYCTXMARKER yyrecord ( re2c: ). code:yyrestoretag YYRESTORETAG API . : YYRESTORETAG YYCURSOR yyrecord ( re2c: ) tag ( ). code:yyshift YYSHIFT API . : YYSHIFT YYCURSOR yyrecord ( re2c: ) offset ( ). code:yyshiftstag YYSHIFTSTAG API . : YYSHIFTSTAG yyrecord negative ( re2c: ) tag ( ) offset ( ). : .nested ( -- re2c:tags:negative ). code:yyshiftmtag YYSHIFTMTAG API . : YYSHIFTMTAG ( re2c: ) tag ( ) offset ( ). code:yystagp YYSTAGP API . : YYSTAGP YYCURSOR yyrecord ( re2c: ) tag ( ). code:yymtagp YYMTAGP API . : YYMTAGP ( re2c: ) tag ( ). code:yystagn YYSTAGN API . : YYSTAGN negative yyrecord ( re2c: ) tag ( ). code:yymtagn YYMTAGN API . : YYMTAGN ( re2c: ) tag ( ). code:yycopystag YYCOPYSTAG API . : YYCOPYSTAG yyrecord ( re2c: ) lhs rhs ( ). code:yycopymtag YYCOPYMTAG API . : YYCOPYMTAG yyrecord ( re2c: ) lhs rhs ( ). code:yygetaccept YYGETACCEPT API . : YYGETACCEPT yyrecord ( re2c: ) var ( re2c:yyaccept ). code:yysetaccept YYSETACCEPT API . : YYSETACCEPT yyrecord ( re2c: ) var ( re2c:yyaccept ) val ( ). code:yygetcond YYGETCOND API . : YYGETCOND yyrecord ( re2c: ) var ( re2c:yycond ). code:yysetcond YYSETCOND API . : YYSETCOND yyrecord ( re2c: ) var ( re2c:yycond ) val ( ). code:yygetstate YYGETSTATE API . : YYGETSTATE yyrecord ( re2c: ) var ( re2c:yystate ). code:yysetstate YYSETSTATE API . : YYSETSTATE yyrecord ( re2c: ) var ( re2c:yystate ) val ( ). code:yylessthan YYLESSTHAN API . : YYLESSTHAN YYCURSOR YYLIMIT yyrecord ( re2c: ) need ( ). : .many ( need ). code:yyend YYEND API . : YYEND YYCURSOR YYLIMIT. code:yybm_filter yych yybm ( --bitmaps ). : yych ( re2c:yych ). code:yybm_match yybm ( --bitmaps). : yybm yych ( re2c: ) offset ( yybm yych ) mask ( ). code:yytarget_filter yych yytarget ( --computed-gotos ). : yych ( re2c:yych ). (syntax files) : nl (newline). indent ..TP dedent . topindent . . (syntax) : .api.simple API (--api simple re2c:api = simple). .api.generic API (--api generic re2c:api = generic). .api.record API (--api record re2c:api = record). .api_style.functions API (re2c:api-style = functions). .api_style.freeform API (free-form) (re2c:api-style = free-form). .case_ranges case (--case-ranges re2c:case-ranges = 1). .cgoto.relative goto (--computed-gotos-relative re2c:cgoto:relative = 1). .code_model.goto_label goto/label (--goto-label). .code_model.loop_switch loop/switch (--loop-switch). .code_model.recursive_functions (--recursive-function). .date (fingerprint) . .loop_label re2zig (re2c:label:yyloop ). .monadic (re2c:monadic = 1). . .start_conditions (start conditions) (--start-conditions). .storable_state (--storable-state). .unsafe re2zig "unsafe" (--unsafe re2c:unsafe = 1). "unsafe" . .version (fingerprint) re2zig . .yyfill.enable YYFILL (re2c:yyfill:enable = 1). .yyfn.throw re2c:yyfn:throw . (HANDLING THE END OF INPUT) (lexer) . : o ( *) o o <<>> : . : . . re2zig . . : o (Sentinel). . <<>> . . : . . YYFILL re2c:yyfill:enable = 0; re2c:eof -1 . o (Sentinel with bounds checks). : . . <<>> <<>> . ( ). . . YYFILL ( ). . . re2c:eof ( ). YYFILL . o (Bounds checks with padding). << >> . DFA (SCC) SCC SCC . . (padding) ( ) . YYMAXFILL max . YYFILL . YYFILL re2c:eof -1 ( ). o (Custom checks). (Generic API) . . Generic API --api custom re2c:api = custom; re2c:yyfill:enable = 0; re2c:yyfill:check = 0; . . (Sentinel) (sentinel) . null . null : (lexeme) ( ). null * ( -Wsentinel-in-midrule re2c:sentinel ). re2c:yyfill:enable = 0; YYFILL . // re2zig $INPUT -o $OUTPUT const std = @import("std"); // Expects a null-terminated string. fn lex(yyinput: [:0]const u8) i32 { var yycursor: u32 = 0; var count: i32 = 0; loop: while (true) { %{ re2c:yyfill:enable = 0; * { return -1; } [\x00] { return count; } [a-z]+ { count += 1; continue :loop; } [ ]+ { continue :loop; } %} } } test { try std.testing.expectEqual(lex(""), 0); try std.testing.expectEqual(lex("one two three"), 3); try std.testing.expectEqual(lex("f0ur"), -1); } (Sentinel with bounds checks) ( 1.2 ). . null re2c:eof = 0; . sentinel null ( 'aaa\0aa'\0 'aaa\0 ). null . YYLIMIT <= YYCURSOR API YYLESSTHAN(1) . (YYFILL re2c:yyfill:enable = 0; YYFILL YYFILL with sentinel ). : $ ( *) -Wundefined-control-flow . // re2zig $INPUT -o $OUTPUT const std = @import("std"); // Expects a null-terminated string. fn lex(yyinput: [:0]const u8) i32 { var yycursor: usize = 0; var yymarker: usize = 0; const yylimit: usize = yyinput.len; // points at the terminating null var count: i32 = 0; loop: while (true) { %{ re2c:yyfill:enable = 0; re2c:eof = 0; str = ['] ([^'\\] | [\\][^])* [']; * { return -1; } $ { return count; } str { count += 1; continue :loop; } [ ]+ { continue :loop; } %} } } test { try std.testing.expectEqual(lex(""), 0); try std.testing.expectEqual(lex("'qu\x00tes' 'are' 'fine: \\'' "), 3); try std.testing.expectEqual(lex("'unterminated\\'"), -1); } (Bounds checks with padding) ( ). . YYMAXFILL null YYMAXFILL max . null --- (lexeme) ( ). "stop" (null) ( null ). (strongly connected components) . (YYLIMIT - YYCURSOR) < n API YYLESSTHAN(n) n ( n ). YYFILL(n) n . YYFILL ( ). YYFILL YYFILL with padding . // re2zig $INPUT -o $OUTPUT const std = @import("std"); %{max %} fn lex(str: []const u8) !i32 { // Create a copy of the input string padded with yymaxfill zeroes at the end. var yyinput = try std.testing.allocator.alloc(u8, str.len + yymaxfill); defer std.testing.allocator.free(yyinput); std.mem.copyForwards(u8, yyinput[0..], str); std.mem.copyForwards(u8, yyinput[str.len..], &[_]u8{0} ** yymaxfill); // zero padding var yycursor: usize = 0; const yylimit: usize = yyinput.len; var count: i32 = 0; loop: while (true) { %{ re2c:YYFILL = "return -1;"; str = ['] ([^'\\] | [\\][^])* [']; [\x00] { // Check that it is the sentinel, not some unexpected null. return if (yycursor - 1 == str.len) count else -1; } str { count += 1; continue :loop; } [ ]+ { continue :loop; } * { return -1; } %} } } test { try std.testing.expectEqual(lex(""), 0); try std.testing.expectEqual(lex("'qu\x00tes' 'are' 'fine: \\'' "), 3); try std.testing.expectEqual(lex("'unterminated\\'"), -1); try std.testing.expectEqual(lex("'unexpected \x00 null\\'"), -1); } (Custom checks) generic API . . sentinel (null-terminated) . YYPEEK (bounds check) . . YYPEEK . // re2zig $INPUT -o $OUTPUT const std = @import("std"); // Expects a string without terminating null. fn lex(str: []const u8) i32 { var cur: usize = 0; var count: i32 = 0; loop: while (true) { %{ re2c:api = generic; re2c:yyfill:enable = 0; // YYPEEK returns "fake" terminating null if cursor has reached limit. re2c:YYPEEK = "if (cur >= str.len) 0 else str[cur]"; re2c:YYSKIP = "cur += 1;"; * { return -1; } [\x00] { return count; } [a-z]+ { count += 1; continue :loop; } [ ]+ { continue :loop; } %} } } test { try std.testing.expectEqual(lex(""), 0); try std.testing.expectEqual(lex("one two three"), 3); try std.testing.expectEqual(lex("f0ur"), -1); } (BUFFER REFILLING) : ( ) . . . (lexer) : o (cursor): (YYCURSOR API C YYSKIP/YYPEEK generic API) o (limit): (YYLIMIT API C YYLESSTHAN generic API ) o (marker): (YYMARKER API YYBACKUP/YYRESTORE generic API) o (token): (lexeme) ( API re2zig lexer ) o (context marker): (YYCTXMARKER API C YYBACKUPCTX/YYRESTORECTX generic API) o (tag variables): ( stags mtags generic API YYSTAGP/YYSTAGN/YYMTAGP/YYMTAGN) YYFILL . token cursor token token limit . YYFILL ( lexer ). YYFILL EOF : EOF (padding) . -f --storable-state YYFILL ( ). YYFILL (YYFILL with sentinel) EOF YYFILL . YYFILL YYLIMIT <= YYCURSOR API C YYLESSTHAN() generic API . YYFILL . YYFILL . Limit limit re2c:eof . YYFILL ( # ). <-- 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 input.txt EOF . // re2zig $INPUT -o $OUTPUT const std = @import("std"); const bufsize = 4095; const State = struct { file: *std.Io.Reader, yyinput: [bufsize + 1]u8, yycursor: usize, yymarker: usize, yylimit: usize, token: usize, eof: bool }; fn fill(st: *State) i32 { if (st.eof) { return -1; } // unexpected EOF // Error: lexeme too long. In real life can reallocate a larger buffer. if (st.token < 1) { return -2; } // Shift buffer contents (discard everything up to the current token). std.mem.copyBackwards( u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]); st.yycursor -= st.token; st.yymarker = @subWithOverflow(st.yymarker, st.token)[0]; st.yylimit -= st.token; st.token = 0; // Fill free space at the end of buffer with new data from file. st.yylimit += st.file.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0; st.yyinput[st.yylimit] = 0; // append sentinel symbol // If read less than expected, this is the end of input. st.eof = st.yylimit < bufsize; return 0; } fn lex(yyrecord: *State) i32 { var count: i32 = 0; loop: while (true) { yyrecord.token = yyrecord.yycursor; %{ re2c:api = record; re2c:eof = 0; re2c:YYFILL = "fill(yyrecord) == 0"; str = ['] ([^'\\] | [\\][^])* [']; * { return -1; } $ { return count; } str { count += 1; continue :loop; } [ ]+ { continue :loop; } %} } } test { const fname = "input"; const content = "'qu\x00tes' 'are' 'fine: \\'' " ** bufsize; const count = 3 * bufsize; // number of quoted strings written to file // Prepare input file: a few times the size of the buffer, containing // strings with zeroes and escaped quotes. var fw = try std.fs.cwd().createFile(fname, .{}); try fw.writeAll(content); fw.close(); // Prepare lexer state: all offsets are at the end of buffer. // Use unbuffered reader - lexer does its own buffering. const zerobuf: [0]u8 = undefined; var fr = try std.fs.cwd().openFile(fname, .{.mode = .read_only}); var reader = fr.reader(&zerobuf); var st = State{ .file = &reader.interface, .yyinput = undefined, .yycursor = bufsize, .yymarker = bufsize, .yylimit = bufsize, .token = bufsize, .eof = false, }; // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL. st.yyinput[st.yylimit] = 0; // Run the lexer. try std.testing.expectEqual(lex(&st), count); // Cleanup: remove input file. fr.close(); try std.fs.cwd().deleteFile(fname); } YYFILL (padding) ( EOF ) YYFILL (primitive) . YYFILL (YYLIMIT - YYCURSOR) < n API C YYLESSTHAN(n) API (generic) . YYFILL . YYFILL lexer ( ). YYFILL (limit) YYMAXFILL ( YYFILL n ). YYFILL ( YYMAXFILL # ). <-- 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 -> input.txt (bounds-checking) . // re2zig $INPUT -o $OUTPUT const std = @import("std"); %{max %} const bufsize = 4096; const State = struct { file: *std.Io.Reader, yyinput: [bufsize + yymaxfill]u8, yycursor: usize, yymarker: usize, yylimit: usize, token: usize, eof: bool }; fn fill(st: *State, need: usize) i32 { if (st.eof) { return -1; } // unexpected EOF // Error: lexeme too long. In real life can reallocate a larger buffer. if (st.token < need) { return -2; } // Shift buffer contents (discard everything up to the current token). std.mem.copyBackwards( u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]); st.yycursor -= st.token; st.yymarker = @subWithOverflow(st.yymarker, st.token)[0]; st.yylimit -= st.token; st.token = 0; // Fill free space at the end of buffer with new data from file. st.yylimit += st.file.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0; // If read less than expected, this is the end of input. if (st.yylimit < bufsize) { st.eof = true; @memset(st.yyinput[st.yylimit..st.yylimit + yymaxfill], 0); st.yylimit += yymaxfill; } return 0; } fn lex(yyrecord: *State) i32 { var count: i32 = 0; loop: while (true) { yyrecord.token = yyrecord.yycursor; %{ re2c:api = record; re2c:YYFILL = "{ if (fill(yyrecord, @@) != 0) return -2; }"; str = ['] ([^'\\] | [\\][^])* [']; [\x00] { // Check that it is the sentinel, not some unexpected null. return if (yyrecord.token == yyrecord.yylimit - yymaxfill) count else -1; } str { count += 1; continue :loop; } [ ]+ { continue :loop; } * { return -1; } %} } } test { const fname = "input"; const content = "'qu\x00tes' 'are' 'fine: \\'' " ** bufsize; const count = 3 * bufsize; // number of quoted strings written to file // Prepare input file: a few times the size of the buffer, containing // strings with zeroes and escaped quotes. var fw = try std.fs.cwd().createFile(fname, .{}); try fw.writeAll(content); fw.close(); // Prepare lexer state: all offsets are at the end of buffer. // This immediately triggers YYFILL, as the YYLESSTHAN condition is true. // Use unbuffered reader - lexer does its own buffering. const zerobuf: [0]u8 = undefined; var fr = try std.fs.cwd().openFile(fname, .{.mode = .read_only}); var reader = fr.reader(&zerobuf); var st = State{ .file = &reader.interface, .yyinput = undefined, .yycursor = bufsize, .yymarker = bufsize, .yylimit = bufsize, .token = bufsize, .eof = false, }; @memset(st.yyinput[st.yylimit..st.yylimit + yymaxfill], 0); // zero-padding at the end // Run the lexer. try std.testing.expectEqual(lex(&st), count); // Cleanup: remove input file. fr.close(); try std.fs.cwd().deleteFile(fname); } (FEATURES) (Multiple blocks) (lexer) ( ). re2zig . (start conditions) . . goto ( C/C++ Go) (label) . goto . goto ( Rust) switch /switch yystate re2zig . (binary) (octal) (decimal) (hexadecimal) . . . . // re2zig $INPUT -o $OUTPUT const std = @import("std"); // Store u32 number in u64 during parsing to simplify overflow handling. const State = struct { yyinput: [:0]const u8, yycursor: usize, yymarker: usize, num: u64, }; // Common re2c definitions shared between all functions. %{ re2c:api = record; re2c:yyrecord = st; re2c:yyfill:enable = 0; %} const ERROR: u64 = @as(u64, std.math.maxInt(u32)) + 1; // overflow // Add digit with the given base, checking for overflow. fn add(st: *State, offs: u8, base: u64) void { const digit = st.yyinput[st.yycursor - 1] - offs; st.num = @min(st.num * base + digit, ERROR); } // Convert u64 to optional u32 (null meaning overflow or parse error). fn maybeU32(num: u64) ?u32 { return if (num < ERROR) @intCast(num) else null; } fn parse_u32(s: [:0]const u8) ?u32 { var st = State {.yyinput = s, .yycursor = 0, .yymarker = 0, .num = 0}; %{ '0b' / [01] { return parse_bin(&st); } "0" { return parse_oct(&st); } "" / [1-9] { return parse_dec(&st); } '0x' / [0-9a-fA-F] { return parse_hex(&st); } * { return null; } %} } fn parse_bin(st: *State) ?u32 { bin: while (true) {%{ [01] { add(st, 48, 2); continue :bin; } * { return maybeU32(st.num); } %}} } fn parse_oct(st: *State) ?u32 { oct: while (true) {%{ [0-7] { add(st, 48, 8); continue :oct; } * { return maybeU32(st.num); } %}} } fn parse_dec(st: *State) ?u32 { dec: while (true) {%{ [0-9] { add(st, 48, 10); continue :dec; } * { return maybeU32(st.num); } %}} } fn parse_hex(st: *State) ?u32 { hex: while (true) {%{ [0-9] { add(st, 48, 16); continue :hex; } [a-f] { add(st, 87, 16); continue :hex; } [A-F] { add(st, 55, 16); continue :hex; } * { return maybeU32(st.num); } %}} } test { try std.testing.expectEqual(parse_u32(""), null); try std.testing.expectEqual(parse_u32("1234567890"), 1234567890); try std.testing.expectEqual(parse_u32("0b1101"), 13); try std.testing.expectEqual(parse_u32("0x7Fe"), 2046); try std.testing.expectEqual(parse_u32("0644"), 420); try std.testing.expectEqual(parse_u32("9999999999"), null); } (Start conditions) --start-conditions . re2zig . re2zig . : YYGETCOND YYSETCOND . conditions --header re2c:header . re2c:cond:enumprefix . (< >) <*> . : < condition-list > regular-expression code condition-list . regular-expression code . < condition-list > regular-expression => condition code condition-list . regular-expression condition code . < condition-list > regular-expression :=> condition condition-list . regular-expression condition ( ). < condition-list > !action code code action condition-list ( actions ). code code condition-list . !pre_rule ( ). < > code "0" code . !entry ( ). < > => condition code condition . < > :=> condition condition . re2zig re2zig goto/label loop/switch . goto ( C/C++ Go) yyc_ cond ( re2c:cond:prefix ). goto . re2zig switch YYGETSTATE . :=> switch ( re2c:cond:goto ). . goto ( Rust) re2zig yystate . switch DFA . switch . ( YYGETCOND/YYSETCOND ). . . cond conditions . // re2zig $INPUT -o $OUTPUT -c const std = @import("std"); %{conditions %} const ERROR: u64 = @as(u64, std.math.maxInt(u32)) + 1; // overflow // Add digit with the given base, checking for overflow. fn add(num: *u64, str: [:0]const u8, cur: usize, offs: u8, base: u64) void { num.* = @min(num.* * base + (str[cur - 1] - offs), ERROR); } fn parse_u32(yyinput: [:0]const u8) ?u32 { var yycursor: usize = 0; var yymarker: usize = 0; var yycond = yycinit; var num: u64 = 0; // Store number in u64 to simplify overflow checks. loop: while(true) { %{ re2c:yyfill:enable = 0; '0b' / [01] :=> bin "0" :=> oct "" / [1-9] :=> dec '0x' / [0-9a-fA-F] :=> hex * { return null; } [01] { add(&num, yyinput, yycursor, 48, 2); continue :loop; } [0-7] { add(&num, yyinput, yycursor, 48, 8); continue :loop; } [0-9] { add(&num, yyinput, yycursor, 48, 10); continue :loop; } [0-9] { add(&num, yyinput, yycursor, 48, 16); continue :loop; } [a-f] { add(&num, yyinput, yycursor, 87, 16); continue :loop; } [A-F] { add(&num, yyinput, yycursor, 55, 16); continue :loop; } * { return if (num < ERROR) @intCast(num) else null; } %}} } test { try std.testing.expectEqual(parse_u32(""), null); try std.testing.expectEqual(parse_u32("1234567890"), 1234567890); try std.testing.expectEqual(parse_u32("0b1101"), 13); try std.testing.expectEqual(parse_u32("0x7Fe"), 2046); try std.testing.expectEqual(parse_u32("0644"), 420); try std.testing.expectEqual(parse_u32("9999999999"), null); } (Storable state) --storable-state re2zig . re2zig <<>> ("pull") <<>> ( ). ( (parser) ). : <<>> ("push") . . . <<>> : o YYSETSTATE() YYGETSTATE(state) . o yych yyaccept ( ) state (persistent) . state -1 . o YYFILL . . o . o getstate YYGETSTATE . goto ( --loop-switch). o re2c:eof sentinel with bounds checks ( ) . (padding) : (lexeme) . ( ). <<>> . . <<>> . . // re2zig $INPUT -o $OUTPUT -f const std = @import("std"); const Status = enum { end, ready, waiting, bad_packet, big_packet }; // Use a small buffer to cover the case when a lexeme doesn't fit. // In real world use a larger buffer. const bufsize = 10; const State = struct { file: std.fs.File.Reader, yyinput: [bufsize + 1]u8, yycursor: usize, yymarker: usize, yylimit: usize, token: usize, yystate: i32, received: usize, }; fn fill(st: *State) Status { // Error: lexeme too long. In real life can reallocate a larger buffer. if (st.token < 1) { return Status.big_packet; } // Shift buffer contents (discard everything up to the current token). std.mem.copyBackwards( u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]); st.yycursor -= st.token; st.yymarker = @subWithOverflow(st.yymarker, st.token)[0]; st.yylimit -= st.token; st.token = 0; // Fill free space at the end of buffer with new data from file. st.yylimit += st.file.interface.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0; st.yyinput[st.yylimit] = 0; // append sentinel symbol return Status.ready; } fn lex(yyrecord: *State) Status { var yych: u8 = 0; loop: while (true) { yyrecord.token = yyrecord.yycursor; %{ re2c:api = record; re2c:eof = 0; re2c:YYFILL = "return Status.waiting;"; packet = [a-z]+[;]; * { return Status.bad_packet; } $ { return Status.end; } packet { yyrecord.received += 1; continue :loop; } %} } } fn run(expect: Status, packets: []const []const u8) !void { // Create a "pipe" (open the same file for reading and writing). const fname = "input"; var fw = try std.fs.cwd().createFile(fname, .{}); var fr = try std.fs.cwd().openFile(fname, .{ .mode = .read_only}); // Initialize lexer state: `state` value is -1, all offsets are at the end // of buffer. Use unbuffered reader - lexer does its own buffering. const zerobuf: [0]u8 = undefined; var st = State{ .file = fr.reader(&zerobuf), .yyinput = undefined, .yycursor = bufsize, .yymarker = bufsize, .yylimit = bufsize, .token = bufsize, .yystate = -1, .received = 0, }; // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL. st.yyinput[st.yylimit] = 0; // Main loop. The buffer contains incomplete data which appears packet by // packet. When the lexer needs more input it saves its internal state and // returns to the caller which should provide more input and resume lexing. var status = Status.ready; var send: usize = 0; while (true) { status = lex(&st); if (status == Status.end) { break; } else if (status == Status.waiting) { if (send < packets.len) { std.log.debug("sending packet {}", .{send}); try fw.writeAll(packets[send]); send += 1; } status = fill(&st); std.log.debug("filled buffer [{s}], status {}", .{st.yyinput, status}); if (status != Status.ready) { break; } } else if (status == Status.bad_packet) { break; } } // Check results. try std.testing.expectEqual(status, expect); if (status == Status.end) { try std.testing.expectEqual(st.received, send); } // Cleanup: remove input file. fw.close(); fr.close(); try std.fs.cwd().deleteFile(fname); } test { try run(Status.end, &[_][]const u8{}); try run(Status.end, &[_][]const u8{"zero;", "one;", "two;", "three;", "four;"}); try run(Status.bad_packet, &[_][]const u8{"??;"}); try run(Status.big_packet, &[_][]const u8{"looooooooooooong;"}); } (Reusable blocks) /*!rules:re2c[:] ... */ %{rules[:] ... %} re2zig . . (rules block) use . . use /*!use:re2c[:] ... */ %{use[:] ... %} . : ( ). use . use (lexer) : ( ). !use:; re2zig . . : ( ). * $ ( ) . use re2zig ( ). use 2.2 re2zig . ( ). 2.2 -r --reusable . 1.2 . !use // re2zig $INPUT -o $OUTPUT // This example shows how to combine reusable re2c blocks: two blocks // ('colors' and 'fish') are merged into one. The 'salmon' rule occurs // in both blocks; the 'fish' block takes priority because it is used // earlier. Default rule * occurs in all three blocks; the local (not // inherited) definition takes priority. const std = @import("std"); const Ans = enum {color, fish, dunno}; %{rules:colors * { @panic("ah"); } "red" | "salmon" | "magenta" { return Ans.color; } %} %{rules:fish * { @panic("oh"); } "haddock" | "salmon" | "eel" { return Ans.fish; } %} fn lex(yyinput: [:0]const u8) Ans { var yycursor: usize = 0; var yymarker: usize = 0; %{ re2c:yyfill:enable = 0; !use:fish; !use:colors; * { return Ans.dunno; } // overrides inherited '*' rules %} } test { try std.testing.expectEqual(lex("salmon"), Ans.fish); try std.testing.expectEqual(lex("what?"), Ans.dunno); } /*!use:re2c ... */ // re2zig $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. const std = @import("std"); %{rules re2c:yyfill:enable = 0; "x y" { return yycursor; } * { return null; } %} fn lex_utf8(yyinput: []const u8) ?usize { var yycursor: usize = 0; var yymarker: usize = 0; %{use re2c:encoding:utf8 = 1; re2c:YYCTYPE = u8; // the default %} } fn lex_utf32(yyinput: []const u32) ?usize { var yycursor: usize = 0; var yymarker: usize = 0; %{use re2c:encoding:utf32 = 1; re2c:YYCTYPE = u32; %} } test { const s8 = [_]u8{0xe2, 0x88, 0x80, 0x78, 0x20, 0xe2, 0x88, 0x83, 0x79}; try std.testing.expectEqual(lex_utf8(&s8), s8.len); const s32 = [_]u32{0x2200, 0x78, 0x20, 0x2203, 0x79}; try std.testing.expectEqual(lex_utf32(&s32), s32.len); } (Submatch extraction) re2zig (submatch extraction) . Tags (tags) @stag #mtag stag mtag . -T --tags re2c:tags = 1 . : ( ) . S-tag m-tag ( ). svars mvars . (leftmost greedy) . Captures (capturing groups) . --captures re2c:captures = 1 . --leftmost-captures () --posix-captures POSIX (POSIX longest-match) . : (! ... ). --invert-captures re2c:invert-captures = 1 . yynmatch ( ) yypmatch . yynmatch yypmatch yypmatch [yynmatch * 2] . maxnmatch YYMAXNMATCH yynmatch . Captvars --captvars re2c:captvars = 1 . --captures : yynmatch yypmatch re2zig yytl yytr k- ( svars ). : --leftmost-captvars re2c:leftmost-captvars = 1 () --posix-captvars re2c:posix-captvars POSIX. Tagged Deterministic Finite Automata with Lookahead ( TDFA) . TDFA . TDFA DFA . . TDFA (tag variables) : . . stags mtags . (lexer state) . YYFILL . S-tag : o s-tag: t = YYCURSOR API C YYSTAGP(t) API (generic API) o s-tag: t = NULL API C YYSTAGN(t) API o s-tag : t1 = t2 M-tag : o m-tag: YYMTAGP(t) API o m-tag: YYMTAGN(t) API o m-tag : t1 = t2 S-tag ( ) . M-tag . m-tag ( ) m-tag (prefix-tree) (v, p) v p . s-tag (semantic versions) : major minor patch ( ). YYFILL . // re2zig $INPUT -o $OUTPUT const std = @import("std"); const SemVer = struct { major: u32, minor: u32, patch: u32, }; const none = std.math.maxInt(usize); fn s2n(str: []const u8) u32 { // convert a pre-parsed string to a number var n: u32 = 0; for (str) |c| { n = n * 10 + (c - 48); } return n; } fn parse(yyinput: [:0]const u8) ?SemVer { var yycursor: usize = 0; var yymarker: usize = 0; // Final tag variables available in semantic action. %{svars format = "var @@: usize = none;"; %} // Intermediate tag variables used by the lexer (must be autogenerated). %{stags format = "var @@: usize = none;"; %} %{ re2c:yyfill:enable = 0; re2c:tags = 1; num = [0-9]+; @t1 num @t2 "." @t3 num @t4 ("." @t5 num)? [\x00] { return SemVer { .major = s2n(yyinput[t1..t2]), .minor = s2n(yyinput[t3..t4]), .patch = if (t5 == none) 0 else s2n(yyinput[t5..yycursor - 1]), }; } * { return null; } %} } test { try std.testing.expectEqual(parse("23.34"), SemVer{.major = 23, .minor = 34, .patch = 0}); try std.testing.expectEqual(parse("1.2.99999"), SemVer{.major = 1, .minor = 2, .patch = 99999}); try std.testing.expectEqual(parse("1.a"), null); } s-tag YYFILL . YYFILL . s-tag . m-tag . // re2zig $INPUT -o $OUTPUT const std = @import("std"); const bufsize = 4095; const none = std.math.maxInt(usize); const err = error.SyntaxError; const SemVer = struct { major: u32, minor: u32, patch: u32, }; fn s2n(str: []const u8) u32 { // convert a pre-parsed string to a number var n: u32 = 0; for (str) |c| { n = n * 10 + (c - 48); } return n; } const State = struct { file: *std.Io.Reader, yyinput: [bufsize + 1]u8, yycursor: usize, yymarker: usize, yylimit: usize, token: usize, // 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 format = "@@: usize,\n"; %} eof: bool }; fn fill(st: *State) i32 { if (st.eof) { return -1; } // unexpected EOF // Error: lexeme too long. In real life can reallocate a larger buffer. if (st.token < 1) { return -2; } // Shift buffer contents (discard everything up to the current token). std.mem.copyBackwards( u8, st.yyinput[0..st.yylimit - st.token], st.yyinput[st.token..st.yylimit]); st.yycursor -= st.token; st.yymarker = @subWithOverflow(st.yymarker, st.token)[0]; st.yylimit -= st.token; // Tag variables need to be shifted like other input positions. The check // for NONE is only needed if some tags are nested inside of alternative or // repetition, so that they can have NONE value. %{stags format = "if (st.@@ != none) st.@@ = @subWithOverflow(st.@@, st.token)[0];\n"; %} st.token = 0; // Fill free space at the end of buffer with new data from file. st.yylimit += st.file.readSliceShort(st.yyinput[st.yylimit..bufsize]) catch 0; st.yyinput[st.yylimit] = 0; // append sentinel symbol // If read less than expected, this is the end of input. st.eof = st.yylimit < bufsize; return 0; } fn parse(st: *State) !std.ArrayList(SemVer) { var vers = try std.ArrayList(SemVer).initCapacity(std.testing.allocator, 0); // Final tag variables available in semantic action. %{svars format = "var @@: usize = 0;\n"; %} loop: while (true) { st.token = st.yycursor; %{ re2c:api = record; re2c:eof = 0; re2c:tags = 1; re2c:yyrecord = st; re2c:YYFILL = "fill(st) == 0"; num = [0-9]+; num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] { try vers.append(std.testing.allocator, SemVer { .major = s2n(st.yyinput[st.token..t1]), .minor = s2n(st.yyinput[t2..t3]), .patch = if (t4 == none) 0 else s2n(st.yyinput[t4..st.yycursor - 1]), }); continue :loop; } $ { return vers; } * { return error.SyntaxError; } %} } } test { const fname = "input"; const content = "1.22.333\n" ** bufsize; // Prepare input file: a few times the size of the buffer, containing // strings with zeroes and escaped quotes. var fw = try std.fs.cwd().createFile(fname, .{}); try fw.writeAll(content); fw.close(); // Prepare lexer state: all offsets are at the end of buffer. // Use unbuffered reader - lexer does its own buffering. const zerobuf: [0]u8 = undefined; var fr = try std.fs.cwd().openFile(fname, .{.mode = .read_only}); var reader = fr.reader(&zerobuf); var st = State{ .file = &reader.interface, .yyinput = undefined, .yycursor = bufsize, .yymarker = bufsize, .yylimit = bufsize, .token = bufsize, %{stags format = ".@@ = none,\n"; %} .eof = false, }; // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL. st.yyinput[st.yylimit] = 0; // Manually construct expected result. var expect = [_]SemVer{SemVer{.major = 1, .minor = 22, .patch = 333}} ** bufsize; // Run the lexer. var result = try parse(&st); try std.testing.expectEqualDeep(&expect, result.items); // Cleanup: free memory and remove input file. result.deinit(std.testing.allocator); fr.close(); try std.fs.cwd().deleteFile(fname); } (capturing groups) . // re2zig $INPUT -o $OUTPUT const std = @import("std"); const none = std.math.maxInt(usize); const SemVer = struct { major: u32, minor: u32, patch: u32, }; fn s2n(str: []const u8) u32 { // convert pre-parsed string to a number var n: u32 = 0; for (str) |c| { n = n * 10 + (c - 48); } return n; } fn parse(yyinput: [:0]const u8) ?SemVer { var yycursor: usize = 0; var yymarker: usize = 0; // Final tag variables available in semantic action. %{svars format = "var @@: usize = none;"; %} // Intermediate tag variables used by the lexer (must be autogenerated). %{stags format = "var @@: usize = none;"; %} %{ re2c:yyfill:enable = 0; re2c:captvars = 1; num = [0-9]+; (num) "." (num) ("." num)? [\x00] { return SemVer { .major = s2n(yyinput[yytl1..yytr1]), .minor = s2n(yyinput[yytl2..yytr2]), .patch = if (yytl3 == none) 0 else s2n(yyinput[yytl3 + 1..yytr3]) }; } * { return null; } %} } test { try std.testing.expectEqual(parse("23.34"), SemVer{.major = 23, .minor = 34, .patch = 0}); try std.testing.expectEqual(parse("1.2.99999"), SemVer{.major = 1, .minor = 2, .patch = 99999}); try std.testing.expectEqual(parse("1.a"), null); } m-tag . (trie) . // re2zig $INPUT -o $OUTPUT const std = @import("std"); const none = std.math.maxInt(usize); const mtag_root = none - 1; const err = error.SyntaxError; // 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). const MtagElem = struct { elem: usize, // tag value pred: usize, // index of the predecessor node or root }; // Append a single value to an m-tag history. fn add_mtag(trie: *std.ArrayList(MtagElem), mtag: usize, value: usize) !usize { try trie.append(std.testing.allocator, MtagElem{.elem = value, .pred = mtag}); return trie.items.len - 1; } // Recursively unwind tag histories and collect version components. fn unwind(trie: *std.ArrayList(MtagElem), x: usize, y: usize, str: []const u8, ver: *std.ArrayList(u32)) !void { // Reached the root of the m-tag tree, stop recursion. if (x == mtag_root and y == mtag_root) return; // Unwind history further. try unwind(trie, trie.items[x].pred, trie.items[y].pred, str, ver); // Get tag values. Tag histories must have equal length. std.debug.assert(x != mtag_root and y != mtag_root); const ex = trie.items[x].elem; const ey = trie.items[y].elem; if (ex != none and ey != none) { // Both tags are valid string indices, extract component. try ver.append(std.testing.allocator, s2n(str[ex..ey])); } else { // Both tags are none (this corresponds to zero repetitions). std.debug.assert(ex == none and ey == none); } } fn s2n(str: []const u8) u32 { // convert a pre-parsed string to a number var n: u32 = 0; for (str) |c| { n = n * 10 + (c - 48); } return n; } fn parse(yyinput: [:0]const u8) !std.ArrayList(u32) { var yycursor: usize = 0; var yymarker: usize = 0; var mt = try std.ArrayList(MtagElem).initCapacity(std.testing.allocator, 0); defer mt.deinit(std.testing.allocator); // Final tag variables available in semantic action. %{svars format = "var @@: usize = none;"; %} %{mvars format = "var @@: usize = mtag_root;"; %} // Intermediate tag variables used by the lexer (must be autogenerated). %{stags format = "var @@: usize = none;"; %} %{mtags format = "var @@: usize = mtag_root;"; %} %{ re2c:YYMTAGP = "@@ = add_mtag(&mt, @@, yycursor) catch none;"; re2c:YYMTAGN = "@@ = add_mtag(&mt, @@, none) catch none;"; re2c:yyfill:enable = 0; re2c:tags = 1; num = [0-9]+; @t1 num @t2 ("." #t3 num #t4)* [\x00] { var ver = try std.ArrayList(u32).initCapacity(std.testing.allocator, 0); try ver.append(std.testing.allocator, s2n(yyinput[t1..t2])); try unwind(&mt, t3, t4, yyinput, &ver); return ver; } * { return error.SyntaxError; } %} } test { var result = try parse("1"); var expect = [_]u32{1}; try std.testing.expectEqualDeep(&expect, result.items); result.deinit(std.testing.allocator); } test { var result = try parse("1.2.3.4.5.6.7"); var expect = [_]u32{1, 2, 3, 4, 5, 6, 7}; try std.testing.expectEqualDeep(&expect, result.items); result.deinit(std.testing.allocator); } test { const result = parse("1.2.") catch null; try std.testing.expectEqualDeep(result, null); } (Encoding support) code point code unit . code point . code unit . code point code unit . (fixed-length) code point code unit . (variable-length) code point code unit . << >> ("any") [^] code point code unit ( code unit * ). code unit : yych code unit YYCTYPE code unit . code point . re2zig code point code unit . : code point code unit . : o ASCII ( ). [0-255] code point code unit - . o EBCDIC ( --ebcdic re2c:encoding:ebcdic). [0-255] code point code unit - . o UCS2 ( --ucs2 re2c:encoding:ucs2). [0-0xFFFF] code point code unit - . o UTF8 ( --utf8 re2c:encoding:utf8). . code unit . code point -- code unit . o UTF16 ( --utf16 re2c:encoding:utf16). . code unit . code point -- code unit . o UTF32 ( --utf32 re2c:encoding:utf32). [0-0x10FFFF] code point code unit - . include/unicode_blocks.re include/unicode_categories.re include/unicode_properties.re re2zig . --input-encoding . --input-encoding utf8 re2zig UTF8 ( --utf8 ). --encoding-policy (code point [0xD800-0xDFFF]) re2zig . UTF8 . // re2zig $INPUT -o $OUTPUT --utf8 const std = @import("std"); %{include "unicode_categories.re" %} fn lex(yyinput: [:0]const u8) bool { var yycursor: u32 = 0; var yymarker: u32 = 0; %{ 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; } %} } test { try std.testing.expect(lex("_")); } (Include files) re2zig /*!include:re2c FILE */ %{include FILE %} !include FILE ; FILE . re2zig -I . / re2zig #include C/C++ : FILE / . . --depfile . re2zig include/ . ( ) re2zig . . (definitions.zig) const Num = enum { integer, floating, nan }; %{ number = [1-9][0-9]*; %} include (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 Num.floating; } // re2zig $INPUT -o $OUTPUT const std = @import("std"); %{include "definitions.zig" %} fn lex(yyinput: [:0]const u8) Num { var yycursor: u32 = 0; var yymarker: u32 = 0; %{ re2c:yyfill:enable = 0; * { return Num.nan; } number { return Num.integer; } !include "extra_rules.re.inc"; %} } test { try std.testing.expectEqual(lex("123"), Num.integer); try std.testing.expectEqual(lex("123.4567"), Num.floating); } re2zig --header re2c:header /*!header:re2c:on*/ /*!header:re2c:off*/ %{header:on%} %{header:off%} .re . . re2zig --header re2c:header ( stdout) . re2zig (translation units) . (tag variables) ( ). // re2zig $INPUT -o $OUTPUT --header lexer/state.zig const std = @import("std"); const state = @import("lexer/state.zig"); // the module is generated by re2c %{header:on %} pub const State = struct { yyinput: [:0]const u8, yycursor: usize, %{stags format = "@@: usize,"; %} }; %{header:off %} fn lex(yyrecord: *state.State) usize { var t: usize = 0; %{ re2c:header = "lexer/state.zig"; re2c:api = record; re2c:yyfill:enable = 0; re2c:tags = 1; [a]* @t [b]* { return t; } %} } test { var st = state.State { .yyinput = "ab", .yycursor = 0, %{stags format = ".@@ = 0,"; %} }; try std.testing.expectEqual(lex(&st), 1); } // Generated by re2c pub const State = struct { yyinput: [:0]const u8, yycursor: usize, yyt1: usize, }; (Skeleton programs) -S, --skeleton re2zig re2zig C . (lexer) . DFA ( ) re2zig lexer : .input DFA .keys . lexer .input . : o re2zig ( DFA ). o . o (minimized test cases) ( ). ( ). re2zig DFA . : DFA . ( ASCII UTF-8 EBCDIC) DFA . DFA : re2zig DFA . . re2zig ( ) lexer . 1Gb (re2zig ). (Visualization and debug) -D, --emit-dot re2zig DFA DOT (dump) . Graphviz DFA . DFA . --dump-nfa --dump-dfa-raw ( ). (SEE ALSO) re2c : http://re2c.org. flex(1) lex(1) quex(http://quex.sourceforge.net). (AUTHORS) re2zig Peter Bumbulis (peter@csg.uwaterloo.ca) . Marcus Boerger Dan Nuffer . : Brian Young (bayoung@acm.org) Marcus Boerger Dan Nuffer (nuffer@users.sourceforge.net) Ulya Trofimovich (skvadrik@gmail.com) Serghei Iakovlev Sergei Trofimovich Petr Skocik ligfx raekye PolarGoose. RE2ZIG(1)