RE2V(1) RE2V(1) (NAME) re2v - V (SYNOPSIS) re2v [ OPTIONS ] [ WARNINGS ] INPUT - stdin . (INTRODUCTION) re2v . ( V ) / . . re2v . V . () : // re2v $INPUT -o $OUTPUT -i fn lex(yyinput string) { mut yycursor := 0 /*!re2c re2c:yyfill:enable = 0; [1-9][0-9]* { return } * { panic("error!") } */ } fn main() { lex("1234\x00") } re2v : // Code generated by re2v, DO NOT EDIT. // re2v $INPUT -o $OUTPUT -i fn lex(yyinput string) { mut yycursor := 0 mut yych := u8(0) yych = yyinput[yycursor] match yych { 0x31...0x39 { unsafe { goto yy2 } } else { unsafe { goto yy1 } } } yy1: yycursor += 1 panic("error!") yy2: yycursor += 1 yych = yyinput[yycursor] match yych { 0x30...0x39 { unsafe { goto yy2 } } else { unsafe { goto yy3 } } } yy3: return } fn main() { lex("1234\x00") } re2v . : name = regular-expression ; name regular-expression . - . regular expressions re2v . name . . (global scope) . . configuration = value ; re2v . re2v configurations . value - . . . regular-expression code regular-expression ( := ). regular-expression code . . . : * $. (code unit) ( encoding support ). handling the end of input . start conditions . !action code code ( ). actions . !directive ; . . directives . (Blocks) /*!re2c */ %{ %} ( ). 2.2 . : /*!re2c[:] ... */ or %{[:] ... %} . re2v . . options . /*!local:re2c[:] ... */ or %{local[:] ... %} ( ). /*!rules:re2c[:] ... */ or %{rules[:] ... %} -- . ( reusable blocks). 2.2 re2v -r --reusable . /*!use:re2c[:] ... */ or %{use[:] ... %} use . re2v . ( ). use . 2.2 re2v use -r --reusable . /*!max:re2c[:[:...]] ... */ or %{max[:[:...]] ... %} YYMAXFILL . YYMAXFILL ( ). C (#define YYMAXFILL ) Go (var YYMAXFILL int = ). format @@{max} ( @@) YYMAXFILL . /*!maxnmatch:re2c[:[:...]] ... */ or %{maxnmatch[:[:...]] ... %} YYMAXNMATCH ( -P --posix-captures ). YYMAXNMATCH ( ). C (#define YYMAXNMATCH ) Go (var YYMAXNMATCH int = ). format @@{max} ( @@) YYMAXNMATCH . /*!stags:re2c[:[:...]] ... */, /*!mtags:re2c[:[:...]] ... */ or %{stags[:[:...]] ... %}, %{mtags[:[:...]] ... %{ s-tag/m-tag re2v . ( ). : format separator. format @@{tag} ( @@) . separator format . /*!svars:re2c[:[:...]] ... */, /*!mvars:re2c[:[:...]] ... */ or %{svars[:[:...]] ... %}, %{mvars[:[:...]] ... %{ s-tag/m-tag ( --tags) re2v ( --captvars --posix-captvars) . ( ). : format separator. format @@{tag} ( @@) . separator format . /*!getstate:re2c[:[:...]] ... */ or %{getstate[:[:...]] ... %} ( --storable-state ). . . . --loop-switch goto . /*!conditions:re2c[:[:...]] ... */, /*!types:re2c... */ or %{conditions[:[:...]] ... %}, %{types... %} ( --conditions ). ( ). YYCONDTYPE . format separator . format @@{cond} ( @@) @@{num} . separator format . /*!include:re2c */ or %{include %} . #include C/C++. --depfile . /*!header:re2c:on*/ or %{header:on %} . header:off re2v -t --type-header . /*!header:re2c:off*/ or %{header:off %} header:on*/ . /*!ignore:re2c ... */ or %{ignore ... %} . re2v : re2c:api, re2c:input --api. re2c:api:sigil ("" "sigil") API . @@ . . $ ${name} . . 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 (bitmaps) . 9 . re2c:cond:abort (default case) (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 (sentinel) $ . -1 ( $ ). . . re2c:header, re2c:flags:type-header, re2c:flags:t (header) . --header . re2c:indent:string . "\t" . (whitespace) . . 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 )..TP 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 . re2v yyt . struct . @@{tag} @@ . re2c:tags:expression = "s.@@"; s.yyt . re2c:api:sigil . re2c:tags:negative ( -1 (null pointer) ). re2c:tags:prefix . yyt . re2c:sentinel (sentinel) ( re2c:yyfill:enable = 0; re2c:eof ). : . -1` ( re2v ). . re2c:state:abort (default case) (state dispatch) (abort) -1 . re2c:state:nextlabel YYGETSTATE yyNext ( ). re2c:label:start getstate 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 . (free-form) API . 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 . (free-form) API . re2c:YYGETSTATE, re2c:define:YYGETSTATE API YYGETSTATE . re2c:YYGETSTATE:naked, re2c:define:YYGETSTATE:naked re2c:api:style YYGETSTATE . (free-form) 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 . (free-form) 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 . (free-form) 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 ..TP re2c:YYSHIFTMTAG, re2c:define:YYSHIFTMTAG generic API YYSHIFTMTAG . re2c:YYSHIFTSTAG, re2c:define:YYSHIFTSTAG generic API YYSHIFTSTAG . re2c:YYSTAGN, re2c:define:YYSTAGN generic API YYSTAGN . re2c:YYSTAGP, re2c:define:YYSTAGP generic API YYSTAGP . re2c:yyaccept, re2c:variable:yyaccept API yyaccept . re2c:yybm, re2c:variable:yybm API yybm . re2c:yybm:hex, re2c:variable:yybm:hex --bit-vectors (hexadecimal) . ( ). re2c:yych, re2c:variable:yych API yych . re2c:yych:emit, re2c:variable:yych:emit yych . . re2c:yych:conversion, re2c:variable:yych:conversion re2v yych YYCTYPE . ( ). re2c:yych:literals, re2c:variable:yych:literals yych . : char ( ) hex ( ) char_or_hex ( ). re2c:yyctable, re2c:variable:yyctable API yyctable . 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 generic API YYLIMIT C pointer API) . ( ). re2c:yyfill:enable YYFILL ( ) . ( ) YYFILL ( ). (lexer) ( -W) re2c:sentinel . (YYFILL ). re2c:yyfill:parameter YYFILL . . ( ). re2c:YYFILL:naked re2c:api:style . re2c:yyfn:sep YYFN ( ). re2c:yyfn:throw YYFN ( ). re2v : "foo" . 'foo' . [a-xyz], [^a-xyz] ( ). . . 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 . --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) re2v : !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) . re2v : !use:name ; use name . . : . * $ . use use . !include file ; include : file . (Program interface) (primitives) API . . . re2v ( ) (compile-time) (run-time) . API . re2v (flavor) API : Simple API API V . : YYINPUT ( ) YYCURSOR YYMARKER YYCTXMARKER YYLIMIT ( YYINPUT ). Record API Record API struct . --api record re2c:api = record . API yyrecord ( re2c:yyrecord ) struct yyinput 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 ( ). 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). YYCURSOR (rollback) . . YYCTXMARKER l-value (trailing context) ( YYINPUT). . YYCTXMARKER / . YYFILL Generic API len. YYFILL len . re2c:eof len 1 YYFILL . re2c:eof YYFILL . len YYMAXFILL . YYFN (function prototype) --recursive-functions . re2c:fn:sep ( ) . ( void ). : ( ) ( - ). YYINPUT r-value ( ) . YYMAXFILL YYFILL. max . YYLESSTHAN Generic API len. r-value true len . YYEND Generic API . r-value true ( ). YYEND $ . YYLESSTHAN . YYPEEK Generic API . r-value YYCTYPE . YYSKIP Generic API . YYBACKUP Generic API ( YYRESTORE ). YYRESTORE Generic API YYBACKUP . YYBACKUPCTX Generic API (trailing context) ( YYRESTORECTX ). YYRESTORECTX Generic API YYBACKUPCTX ..TP YYRESTORETAG API tag (trailing context) 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 (code unit) ( ). YYSHIFTMTAG API tag shift tag shift ( ). YYMAXNMATCH POSIX . maxnmatch . YYCONDTYPE (condition 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 . re2c . re2c . re2c . -? --help -h . --api API . simple . record ( struct class ) . generic API . --bit-vectors -b . --nested-ifs . --captures, --leftmost-captures (leftmost greedy). yybmatch 2 * YYMAXNMATCH yynmatch . --captvars, --leftmost-captvars . k- yytl yytr . --case-insensitive . --case-inverted : . --case-ranges case switch low ... high. C/C++ GCC Clang Tcc . case Tcc . --computed-gotos -g "computed goto" ( ). re2v . cgoto:threshold . cgoto:relative . --bit-vectors . --computed-gotos-relative --computed-gotos ( ). --computed-gotos . --conditions --start-conditions -c "conditions" Flex: . re2v goto . --depfile FILE FILE Makefile : [include-file ...]. / include include . --output . --ebcdic --ecb -e EBCDIC . re2v 0 -- 0xFF . --empty-class re2v . match-empty () ( ). match-none . error . --encoding-policy re2v (Unicode surrogates). fail re2v . substitute re2v 0xFFFD . ignore () re2v . . --flex-syntax -F Flex: . . --goto-label "goto/label": DFA goto . goto . --header --type-header -t HEADER HEADER. header:on header:off . enum ( conditions ). -I PATH PATH include . include . re2v FILE include -I . --input --api. default simple ( backend ). custom generic . --input-encoding re2v. ascii () re2v ASCII : . utf8 re2v UTF8 . --invert-captures . (...) (! ...) . (! ...) (...) . --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). ( diff ). --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 ..TP --posix-captvars POSIX. yytl yytr k- . --recursive-functions (co-recursive) DFA . --reusable -r 2.2 ( ). --skeleton -S "" . "" . . C . --storable-state -f . push . YYGETSTATE YYSETSTATE yych yyaccept state . --syntax FILE FILE . FILE ( ) ( --lang none ). --tags -T . --ucs2 --wide-chars -w UCS2 . re2v 0 -- 0xFFFF . --nested-ifs . --utf8 --utf-8 -8 UTF-8 . re2v 0 -- 0x10FFFF . --utf16 --utf-16 -x UTF16 . re2v 0 -- 0x10FFFF . --nested-ifs . --utf32 --unicode -u UTF32 . re2v 0 -- 0x10FFFF . --nested-ifs . --verbose . --vernum -V MMmmpp ( ). --version -v . --single-pass -1 . ( ). --debug-output -d YYDEBUG . . --dump-adfa : DFA ( .dot). --dump-cfg : ( .dot). --dump-closure-stats : . --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 .dot . Graphviz ( dot -Tpng -odfa.png dfa.dot). --dfa-minimization : DFA re2v. moore () . table " " . DFA . --eager-skip : -- . (lazily) -- -- . --no-lookahead . TDFA(0) . TDFA(1) TDFA(0) . . TDFA(0) TDFA(1) . --no-optimize-tags : ( ). --posix-closure : POSIX: gor1 () - gtop " " . --posix-prectable : POSIX. complex TNFA . naive TNFA complex . --stadfa . staDFA TDFA . staDFA TDFA . --fixed-tags : (all) (none) (toplevel) . all . "" ( "") . (offset) . ( ). . . -W . -Werror . . -W warning. -Wno- warning. -Werror- warning ( -W ). -Wno-error- warning . . -Wcondition-order . --header conditions . -Wempty-character-class . : . re2v . --empty-class . -Wmatch-empty-string ( ). . -Wswapped-range . . -Wundefined-control-flow ( ). . * . -Wunreachable-rules . -Wdeprecated-eof_rule $ . $ . -Wuseless-escape (escape) . re2v . -Wnondeterministic-tags n- n . -Wsentinel-in-midrule --- . . re2c:sentinel . -Wundefined-syntax-config --syntax . : . . re2c (syntax files) . -- . re2c re2c: : (lexer) . ( include/syntax ) re2v . ( --lang none ). : . (Feature lists) backend re2v : supported_apis API simple record generic. supported_api_styles API functions free-form. supported_code_models goto-label loop-switch recursive-functions. supported_targets (codegen) code dot skeleton. supported_features nested-ifs bitmaps computed-gotos case-ranges monadic unsafe tags captures captvars. (Language configurations) (parser) re2v : semicolons (statements) - . backtick_quoted_strings . single_quoted_strings . indentation_sensitive . wrap_blocks_in_braces . (Inplace configurations) re2c: . . (Code templates) . (DSL) : 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 ']' . (placeholders) . : re2v . ( -1 ). . ( ) ( ) . re2v . 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 } re2v . . . 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 ( ). type ( ) elem ( ) init ( ). : .init ( ). code:enum_elem ( code:enum). name ( ) type ( ). code:assign . lhs ( ) rhs ( ). code:type_int . code:type_uint . code:type_yybm yybm. code:type_yytarget yytarget. code:type_yyctable yyctable. code:cmp_eq "". code:cmp_ne "". code:cmp_lt " ". code:cmp_gt " ". code:cmp_le " ". code:cmp_ge " ". 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 case switch ( ). : val ( ). : .many ( ) .char_literals ( switch -- ). code:switch_case_default switch ( default). code:loop ( ). : label ( ) stmt ( ). code:continue continue. : label ( ). code:goto goto. : label ( ). code:cgoto 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 ( )..TP code:fingerprint . : ver ( re2v ) date ( ). code:line_info ( ). : line ( ) file ( ). code:abort (abort) . code:yydebug YYDEBUG API . : YYDEBUG yyrecord yych ( re2c:) state ( DFA). 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 )..TP 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 ). : nl (newline). indent . dedent . topindent . . : .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 (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 . .loop_label re2v (re2c:label:yyloop ). .monadic (re2c:monadic = 1). . .start_conditions (--start-conditions). .storable_state (--storable-state). .unsafe re2v "unsafe" (--unsafe re2c:unsafe = 1). "unsafe" . .version re2v . .yyfill.enable YYFILL (re2c:yyfill:enable = 1). .yyfn.throw re2c:yyfn:throw . (lexer) . : o ( *) o o <<>> : . : . . re2v . (regular expressions) . : o Sentinel (). . <<>> . . : . . YYFILL re2c:yyfill:enable = 0; re2c:eof -1 . o Sentinel with bounds checks ( ). : . . <<>> <<>> . ( ). (bounds check) . . YYFILL ( ). . . re2c:eof ( ). YYFILL . o Bounds checks with padding ( ). << >> . DFA (SCC) SCC SCC . (lexemes) . (padding) ( ) . YYMAXFILL max . YYFILL . YYFILL re2c:eof -1 ( ). o Custom checks ( ). (Generic API) . . API --api custom re2c:api = custom; re2c:yyfill:enable = 0; re2c:yyfill:check = 0; . ..SS (Sentinel) (sentinel) . null . null : (lexeme) ( ). null * (crash) ( -Wsentinel-in-midrule re2c:sentinel ). re2c:yyfill:enable = 0; YYFILL . // re2v $INPUT -o $OUTPUT // Expect a null-terminated string. fn lex(yyinput string) int { mut yycursor := 0 mut count := 0 loop: /*!re2c re2c:yyfill:enable = 0; * { return -1 } [\x00] { return count } [a-z]+ { count += 1; unsafe { goto loop } } [ ]+ { unsafe { goto loop } } */ } fn main() { assert lex("\0") == 0 assert lex("one two three\0") == 3 assert lex("f0ur\0") == -1 } (Sentinel with bounds checks) ( 1.2 ). (single-quoted) . null re2c:eof = 0; . sentinel null ( 'aaa\0aa'\0 'aaa\0 ). null . API YYLIMIT <= YYCURSOR YYLESSTHAN(1) . (YYFILL re2c:yyfill:enable = 0; YYFILL YYFILL with sentinel ). : $ ( *) -Wundefined-control-flow . // re2v $INPUT -o $OUTPUT // Expects a null-terminated string. fn lex(yyinput string) int { mut yycursor, mut yymarker := 0, 0 yylimit := yyinput.len - 1 // yylimit points at the terminating null mut count := 0 loop: /*!re2c re2c:eof = 0; re2c:yyfill:enable = 0; str = ['] ([^'\\] | [\\][^])* [']; * { return -1 } $ { return count } str { count += 1; unsafe { goto loop } } [ ]+ { unsafe { goto loop } } */ } fn main() { assert lex("\0") == 0 assert lex("'qu\0tes' 'are' 'fine: \\'' \0") == 3 assert lex("'unterminated\\'\0") == -1 } ( ). . YYMAXFILL null YYMAXFILL max . null --- (lexeme) ( ). <<>> ("stop") (null) (lexer) ( null ). () . (YYLIMIT - YYCURSOR) < n API YYLESSTHAN(n) n ( n ). () YYFILL(n) n . YYFILL ( ). YYFILL YYFILL with padding . // re2v $INPUT -o $OUTPUT /*!max:re2c*/ // Expects yymaxfill-padded string. fn lex(str string) int { // Pad string with yymaxfill zeroes at the end. mut yyinput := []u8{len: str.len + yymaxfill} copy(mut &yyinput, str.bytes()) mut yycursor := 0 yylimit := yyinput.len mut count := 0 loop: /*!re2c re2c:YYFILL = "return -1"; str = ['] ([^'\\] | [\\][^])* [']; [\x00] { // Check that it is the sentinel, not some unexpected null. if yycursor - 1 == str.len { return count } else { return -1 } } str { count += 1; unsafe { goto loop } } [ ]+ { unsafe { goto loop } } * { return -1 } */ } fn main() { assert lex("") == 0 assert lex("'qu\0tes' 'are' 'fine: \\'' ") == 3 assert lex("'unterminated\\'") == -1 assert lex("'unexpected \00 null\\'") == -1 } (Custom checks) API . . sentinel null . (sentinel) YYPEEK . . YYPEEK . // re2v $INPUT -o $OUTPUT // Returns "fake" terminating null if cursor has reached limit. fn peek(str string, cur int) u8 { return if cur >= str.len { u8(0) } /* fake null */ else { return str[cur] } } // Expects a string without terminating null. fn lex(str string) int { mut cur := 0 mut count := 0 loop: /*!re2c re2c:api = generic; re2c:yyfill:enable = 0; re2c:YYPEEK = "peek(str, cur)"; re2c:YYSKIP = "cur += 1"; * { return -1 } [\x00] { return count } [a-z]+ { count += 1; unsafe { goto loop } } [ ]+ { unsafe { goto loop } } */ } fn main() { assert lex("") == 0 assert lex("one two three") == 3 assert lex("f0ur") == -1 } : ( ). . . (lexer) : o (cursor): (YYCURSOR API C YYSKIP/YYPEEK API ) o (limit): (YYLIMIT API C YYLESSTHAN API ) o (marker): (YYMARKER API YYBACKUP/YYRESTORE API ) o (token): (lexeme) ( API re2v ) o (context marker): (YYCTXMARKER API C YYBACKUPCTX/YYRESTORECTX API ) o (tag variables): ( stags mtags API YYSTAGP/YYSTAGN/YYMTAGP/YYMTAGN) YYFILL . token cursor token token limit . YYFILL ( ). YYFILL EOF : EOF (bounds-checking with padding) . -f --storable-state YYFILL ( ). YYFILL (YYFILL with sentinel) EOF YYFILL (function-like primitive) . YYFILL YYLIMIT <= YYCURSOR API C YYLESSTHAN() API . YYFILL . YYFILL . (Limit) limit (sentinel) 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 . // re2v $INPUT -o $OUTPUT import os import strings const bufsize = 4096 struct State { file os.File mut: yyinput []u8 yycursor int yymarker int yylimit int token int eof bool } fn fill(mut st &State) int { 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). copy(mut &st.yyinput, st.yyinput[st.token..st.yylimit]) st.yycursor -= st.token st.yymarker -= st.token st.yylimit -= st.token st.token = 0 // Fill free space at the end of buffer with new data from file. pos := st.file.tell() or { 0 } if n := st.file.read_bytes_into(u64(pos), mut st.yyinput[st.yylimit..bufsize]) { st.yylimit += n } 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(mut yyrecord &State) int { mut count := 0 loop: yyrecord.token = yyrecord.yycursor /*!re2c re2c:api = record; re2c:eof = 0; re2c:YYFILL = "fill(mut yyrecord) == 0"; str = ['] ([^'\\] | [\\][^])* [']; * { return -1 } $ { return count } str { count += 1; unsafe { goto loop } } [ ]+ { unsafe { goto loop } } */ } fn main() { fname := "input" content := "'qu\0tes' 'are' 'fine: \\'' "; // Prepare input file: a few times the size of the buffer, containing // strings with zeroes and escaped quotes. mut fw := os.create(fname)! fw.write_string(strings.repeat_string(content, bufsize))! fw.close() count := 3 * bufsize // number of quoted strings written to file // Prepare lexer state: all offsets are at the end of buffer. mut fr := os.open(fname)! mut st := &State{ file: fr, // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL. yyinput: []u8{len: bufsize + 1}, yycursor: bufsize, yymarker: bufsize, yylimit: bufsize, token: bufsize, eof: false, } // Run the lexer. n := lex(mut &st) if n != count { panic("expected $count, got $n") } // Cleanup: remove input file. fr.close() os.rm(fname)! } ( EOF ) YYFILL . YYFILL (YYLIMIT - YYCURSOR) < n C YYLESSTHAN(n) (generic API) . 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) . // re2v $INPUT -o $OUTPUT import os import strings /*!max:re2c*/ const bufsize = 4096 struct State { file os.File mut: yyinput []u8 yycursor int yylimit int token int eof bool } fn fill(mut st &State, need int) int { 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). copy(mut &st.yyinput, st.yyinput[st.token..st.yylimit]) st.yycursor -= st.token st.yylimit -= st.token st.token = 0 // Fill free space at the end of buffer with new data from file. pos := st.file.tell() or { 0 } if n := st.file.read_bytes_into(u64(pos), mut st.yyinput[st.yylimit..bufsize]) { st.yylimit += n } // If read less than expected, this is the end of input. if st.yylimit < bufsize { st.eof = true for i := 0; i < yymaxfill; i += 1 { st.yyinput[st.yylimit + i] = 0 } st.yylimit += yymaxfill } return 0 } fn lex(mut yyrecord &State) int { mut count := 0 loop: yyrecord.token = yyrecord.yycursor /*!re2c re2c:api = record; re2c:YYFILL = "r := fill(mut yyrecord, @@); if r != 0 { return r }"; 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; unsafe { goto loop } } [ ]+ { unsafe { goto loop } } * { return -1 } */ } fn main() { fname := "input" content := "'qu\0tes' 'are' 'fine: \\'' "; // Prepare input file: a few times the size of the buffer, containing // strings with zeroes and escaped quotes. mut fw := os.create(fname)! fw.write_string(strings.repeat_string(content, bufsize))! fw.close() count := 3 * bufsize // number of quoted strings written to file // Prepare lexer state: all offsets are at the end of buffer. // This immediately triggers YYFILL, as the YYLESSTHAN condition is true. mut fr := os.open(fname)! mut st := &State{ file: fr, yyinput: []u8{len: bufsize + yymaxfill}, yycursor: bufsize, yylimit: bufsize, token: bufsize, eof: false, } // Run the lexer. n := lex(mut &st) if n != count { panic("expected $count, got $n") } // Cleanup: remove input file. fr.close() os.rm(fname)! } (lexer) ( ). re2v . start conditions . . goto ( C/C++ Go) (label) . goto . goto ( Rust) switch /switch yystate re2v . (binary) (octal) (decimal) (hexadecimal) . . . . // re2v $INPUT -o $OUTPUT -i const u32_lim = u64(1) << 32 fn parse_u32(yyinput string) ?u32 { mut yycursor, mut yymarker := 0, 0 mut n := u64(0) mut yych := 0 adddgt := fn (num u64, base u64, digit u8) u64 { n := num * base + u64(digit) return if n >= u32_lim { u32_lim } else { n } } /*!re2c re2c:yyfill:enable = 0; re2c:yych:emit = 0; end = "\x00"; '0b' / [01] { unsafe{ goto bin } } "0" { unsafe{ goto oct } } "" / [1-9] { unsafe{ goto dec } } '0x' / [0-9a-fA-F] { unsafe{ goto hex } } * { return none } */ bin: /*!re2c end { unsafe{ goto end } } [01] { n = adddgt(n, 2, yyinput[yycursor-1] - 48); unsafe{ goto bin } } * { return none } */ oct: /*!re2c end { unsafe{ goto end } } [0-7] { n = adddgt(n, 8, yyinput[yycursor-1] - 48); unsafe{ goto oct } } * { return none } */ dec: /*!re2c end { unsafe{ goto end } } [0-9] { n = adddgt(n, 10, yyinput[yycursor-1] - 48); unsafe{ goto dec } } * { return none } */ hex: /*!re2c end { unsafe{ goto end } } [0-9] { n = adddgt(n, 16, yyinput[yycursor-1] - 48); unsafe{ goto hex } } [a-f] { n = adddgt(n, 16, yyinput[yycursor-1] - 87); unsafe{ goto hex } } [A-F] { n = adddgt(n, 16, yyinput[yycursor-1] - 55); unsafe{ goto hex } } * { return none } */ end: if n < u32_lim { return u32(n) } return none } fn main() { test := fn (num ?u32, str string) { if n := parse_u32(str) { if m := num { if n != m { panic("wrong number") } } } else { if _ := num { panic("expected none") } } } test(1234567890, "1234567890\0") test(13, "0b1101\0") test(0x7fe, "0x007Fe\0") test(0o644, "0644\0") test(none, "9999999999\0") test(none, "123??\0") } --start-conditions . re2v . re2v . : 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 . re2v re2v goto/label loop/switch . goto ( C/C++ Go) yyc_ cond ( re2c:cond:prefix ). goto . re2v switch YYGETSTATE . :=> switch ( re2c:cond:goto ). . goto ( Rust) re2v yystate . DFA . switch . ( YYGETCOND/YYSETCOND ). . . cond conditions . // re2v $INPUT -o $OUTPUT -ci /*!conditions:re2c*/ const u32_lim = u64(1) << 32 fn parse_u32(yyinput string) ?u32 { mut yycursor, mut yymarker := 0, 0 mut n := u64(0) mut yycond := YYCONDTYPE.yycinit adddgt := fn (num u64, base u64, digit u8) u64 { n := num * base + u64(digit) return if n >= u32_lim { u32_lim } else { n } } /*!re2c re2c:yyfill:enable = 0; <*> * { return none } '0b' / [01] :=> bin "0" :=> oct "" / [1-9] :=> dec '0x' / [0-9a-fA-F] :=> hex "\x00" { return if n < u32_lim { u32(n) } else { none } } [01] { n = adddgt(n, 2, yyinput[yycursor-1] - 48); unsafe{ goto yyc_bin } } [0-7] { n = adddgt(n, 8, yyinput[yycursor-1] - 48); unsafe{ goto yyc_oct } } [0-9] { n = adddgt(n, 10, yyinput[yycursor-1] - 48); unsafe{ goto yyc_dec } } [0-9] { n = adddgt(n, 16, yyinput[yycursor-1] - 48); unsafe{ goto yyc_hex } } [a-f] { n = adddgt(n, 16, yyinput[yycursor-1] - 87); unsafe{ goto yyc_hex } } [A-F] { n = adddgt(n, 16, yyinput[yycursor-1] - 55); unsafe{ goto yyc_hex } } */ } fn main() { test := fn (num ?u32, str string) { if n := parse_u32(str) { if m := num { if n != m { panic("wrong number") } } } else { if _ := num { panic("expected none") } } } test(1234567890, "1234567890\0") test(13, "0b1101\0") test(0x7fe, "0x007Fe\0") test(0o644, "0644\0") test(none, "9999999999\0") test(none, "123??\0") } --storable-state re2v (lexer) . re2v <<>> ("pull") <<>>. ( (parser) ). : <<>> ("push") . . . <<>> ("pull") : o YYSETSTATE() YYGETSTATE(state). o yych yyaccept ( ) state . state -1 . o YYFILL . . o . o getstate switch YYGETSTATE . goto ( --loop-switch). o re2c:eof sentinel with bounds checks . (padding) padding : padding (greedy lexeme) . ( ). <<>> ("push") . . <<>> . . // re2v -f $INPUT -o $OUTPUT import log import os // Use a small buffer to cover the case when a lexeme doesn't fit. // In real world use a larger buffer. const bufsize = 10 struct State { mut: file os.File yyinput []u8 yycursor int yymarker int yylimit int token int yystate int } enum Status { lex_end lex_ready lex_waiting lex_bad_packet lex_big_packet } fn fill(mut st &State) Status { shift := st.token used := st.yylimit - st.token free := bufsize - used // Error: no space. In real life can reallocate a larger buffer. if free < 1 { return .lex_big_packet } // Shift buffer contents (discard already processed data). copy(mut &st.yyinput, st.yyinput[shift..shift+used]) st.yycursor -= shift st.yymarker -= shift st.yylimit -= shift st.token -= shift // Fill free space at the end of buffer with new data. pos := st.file.tell() or { 0 } if n := st.file.read_bytes_into(u64(pos), mut st.yyinput[st.yylimit..bufsize]) { st.yylimit += n } st.yyinput[st.yylimit] = 0 // append sentinel symbol return .lex_ready } fn lex(mut yyrecord &State, mut recv &int) Status { mut yych := u8(0) /*!getstate:re2c*/ loop: yyrecord.token = yyrecord.yycursor /*!re2c re2c:api = record; re2c:eof = 0; re2c:YYFILL = "return .lex_waiting"; packet = [a-z]+[;]; * { return .lex_bad_packet } $ { return .lex_end } packet { recv += 1; unsafe{ goto loop } } */ } fn test(expect Status, packets []string) { // Create a pipe (open the same file for reading and writing). fname := "pipe" mut fw := os.create(fname) or { panic("cannot create file") } mut fr := os.open(fname) or { panic("cannot open file") } // Initialize lexer state: `state` value is -1, all offsets are at the end // of buffer. mut st := &State{ file: fr, // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL. yyinput: []u8{len: bufsize + 1}, yycursor: bufsize, yymarker: bufsize, yylimit: bufsize, token: bufsize, yystate: -1, } // Main loop. The buffer contains incomplete data which appears packet by // packet. When the lexer needs more input it saves its internal state and // returns to the caller which should provide more input and resume lexing. mut status := Status.lex_ready mut send := 0 mut recv := 0 for { status = lex(mut &st, mut &recv) if status == .lex_end { break } else if status == .lex_waiting { if send < packets.len { log.debug("sending packet $send") fw.write_string(packets[send]) or { panic("cannot write to file") } fw.flush() send += 1 } status = fill(mut &st) log.debug("filled buffer $st.yyinput, status $status") if status != .lex_ready { break } } else if status == .lex_bad_packet { break } } // Check results. if status != expect || (status == .lex_end && recv != send) { panic("expected $expect with $send packet(s), got $status with $recv packet(s)") } // Cleanup: remove input file. fr.close() fw.close() os.rm(fname) or { panic("cannot remove file") } } fn main() { //log.set_level(.debug) test(.lex_end, []) test(.lex_end, ["zero;", "one;", "two;", "three;", "four;"]) test(.lex_bad_packet, ["??;"]) test(.lex_big_packet, ["looooooooooooong;"]) } /*!rules:re2c[:] ... */ %{rules[:] ... %} re2v . . rules use . rules . use /*!use:re2c[:] ... */ %{use[:] ... %} . : rules ( ). use . use (lexer) : rules ( ). !use:; re2v . . : . * $ ( ) . use re2v ( ). use 2.2 re2v . ( ). 2.2 -r --reusable . 1.2 . !use (Example of a !use directive) // re2v $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. enum What { color fish dunno } /*!rules:re2c:colors * { panic("eh!") } "red" | "salmon" | "magenta" { return .color } */ /*!rules:re2c:fish * { panic("oh!") } "haddock" | "salmon" | "eel" { return .fish } */ fn lex(yyinput string) What { mut yycursor, mut yymarker := 0, 0 /*!re2c re2c:yyfill:enable = 0; !use:fish; !use:colors; * { return .dunno } // overrides inherited '*' rules */ } fn main() { assert lex("salmon") == .fish assert lex("what?") == .dunno } // re2v $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 0 } * { return 1 } */ fn lex_utf8(yyinput []u8) int { mut yycursor, mut yymarker := 0, 0 /*!use:re2c re2c:encoding:utf8 = 1; re2c:YYCTYPE = u8; // the default */ } fn lex_utf32(yyinput []u32) int { mut yycursor, mut yymarker := 0, 0 /*!use:re2c re2c:encoding:utf32 = 1; re2c:YYCTYPE = u32; */ } fn main() { s8 := [u8(0xe2), u8(0x88), u8(0x80), u8(0x78), u8(0x20), u8(0xe2), u8(0x88), u8(0x83), u8(0x79)] s32 := [u32(0x2200), u32(0x78), u32(0x20), u32(0x2203), u32(0x79)] assert lex_utf8(s8) == 0 assert lex_utf32(s32) == 0 } (Submatch extraction) re2v . 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 . : (! ... ). --invert-captures re2c:invert-captures = 1 . yynmatch ( ) yypmatch . yynmatch yypmatch yypmatch [yynmatch * 2] . maxnmatch YYMAXNMATCH yynmatch . Captvars --captvars re2c:captvars = 1 . --captures : yynmatch yypmatch re2v yytl yytr k- ( svars ). : --leftmost-captvars re2c:leftmost-captvars = 1 () --posix-captvars re2c:posix-captvars POSIX. Tagged Deterministic Finite Automata with Lookahead . TDFA (overhead) . TDFA DFA . . TDFA : . . stags mtags . (lexer state) . YYFILL . S-tag : o s-tag: t = YYCURSOR API C YYSTAGP(t) 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 : major minor patch ( ). YYFILL . // re2v $INPUT -o $OUTPUT struct SemVer { major int minor int patch int } fn s2n(s string) int { // convert pre-parsed string to number mut n := 0 for c in s { n = n * 10 + int(c - 48) } return n } fn parse(yyinput string) ?SemVer { mut yycursor, mut yymarker := 0, 0 // Final tag variables available in semantic action. /*!svars:re2c format = 'mut @@ := 0\n'; */ // Intermediate tag variables used by the lexer (must be autogenerated). /*!stags:re2c format = 'mut @@ := -1\n'; */ /*!re2c 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 == -1 { 0 } else { s2n(yyinput[t5..yycursor - 1]) } } } * { return none } */ } fn main() { test := fn (result ?SemVer, expect ?SemVer) { if r := result { if e := expect { if r != e { panic("expected $e, got $r") } } } else { if _ := result { panic("expected none") } } } test(parse("23.34\0"), SemVer{23, 34, 0}) test(parse("1.2.9999\0"), SemVer{1, 2, 9999}) test(parse("1.a\0"), none) } s-tag YYFILL (semantic versions) . (lexer) YYFILL . s-tag . m-tag . // re2v $INPUT -o $OUTPUT import arrays import os import strings const bufsize = 4096 const tag_none = -1 struct State { file os.File mut: yyinput []u8 yycursor int yymarker int yylimit int token int // Intermediate tag variables must be part of the lexer state passed to YYFILL. // They don't correspond to tags and should be autogenerated by re2c. /*!stags:re2c format = "\t@@ int\n"; */ eof bool } struct SemVer { major int minor int patch int } fn s2n(s []u8) int { // convert pre-parsed string to number mut n := 0 for c in s { n = n * 10 + int(c - 48) } return n } fn fill(mut st &State) int { 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). copy(mut &st.yyinput, st.yyinput[st.token..st.yylimit]) st.yycursor -= st.token st.yymarker -= st.token st.yylimit -= st.token // Tag variables need to be shifted like other input positions. The check // for -1 is only needed if some tags are nested inside of alternative or // repetition, so that they can have -1 value. /*!stags:re2c format = "\tif st.@@ != -1 { st.@@ -= st.token }\n"; */ st.token = 0 // Fill free space at the end of buffer with new data from file. pos := st.file.tell() or { 0 } if n := st.file.read_bytes_into(u64(pos), mut st.yyinput[st.yylimit..bufsize]) { st.yylimit += n } 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(mut st &State) ?[]SemVer { // Final tag variables available in semantic action. /*!svars:re2c format = "mut @@ := tag_none\n"; */ mut vers := []SemVer{} loop: st.token = st.yycursor /*!re2c re2c:api = record; re2c:yyrecord = st; re2c:YYFILL = "fill(mut st) == 0"; re2c:tags = 1; re2c:eof = 0; num = [0-9]+; num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] { ver := SemVer { major: s2n(st.yyinput[st.token..t1]), minor: s2n(st.yyinput[t2..t3]), patch: if t4 == -1 { 0 } else { s2n(st.yyinput[t4..st.yycursor - 1]) } } vers = arrays.concat(vers, ver) unsafe { goto loop } } $ { return vers } * { return none } */ } fn main() { fname := "input" content := "1.22.333\n"; // Prepare input file: a few times the size of the buffer, containing // strings with zeroes and escaped quotes. mut fw := os.create(fname)! fw.write_string(strings.repeat_string(content, bufsize))! fw.close() // Prepare lexer state: all offsets are at the end of buffer. mut fr := os.open(fname)! mut st := &State{ file: fr, // Sentinel at `yylimit` offset is set to zero, which triggers YYFILL. yyinput: []u8{len: bufsize + 1}, yycursor: bufsize, yymarker: bufsize, yylimit: bufsize, token: bufsize, eof: false, } // Run the lexer. expect := []SemVer{len: bufsize, init: SemVer{1, 22, 333}} result := parse(mut &st) or { panic("parse failed") } if result != expect { panic("error") } // Cleanup: remove input file. fr.close() os.rm(fname)! } (capturing groups) . // re2v $INPUT -o $OUTPUT struct SemVer { major int minor int patch int } fn s2n(s string) int { // convert pre-parsed string to number mut n := 0 for c in s { n = n * 10 + int(c - 48) } return n } fn parse(yyinput string) ?SemVer { mut yycursor, mut yymarker := 0, 0 // Final tag variables available in semantic action. /*!svars:re2c format = 'mut @@ := 0\n'; */ // Intermediate tag variables used by the lexer (must be autogenerated). /*!stags:re2c format = 'mut @@ := 0\n'; */ /*!re2c re2c:yyfill:enable = 0; re2c:captvars = 1; num = [0-9]+; (num) "." (num) ("." num)? [\x00] { _ := yytl0; _ := yytr0 // some variables are unused return SemVer { major: s2n(yyinput[yytl1..yytr1]), minor: s2n(yyinput[yytl2..yytr2]), patch: if yytl3 == -1 {0} else {s2n(yyinput[yytl3 + 1..yytr3])} } } * { return none } */ } fn main() { test := fn (result ?SemVer, expect ?SemVer) { if r := result { if e := expect { if r != e { panic("expected $e, got $r") } } } else { if _ := result { panic("expected none") } } } test(parse("23.34\0"), SemVer{23, 34, 0}) test(parse("1.2.9999\0"), SemVer{1, 2, 9999}) test(parse("1.a\0"), none) } m-tag . trie . // re2v $INPUT -o $OUTPUT import arrays const mtag_root = -1 const tag_none = -1 // An m-tag tree is a way to store histories with an O(1) copy operation. // Histories naturally form a tree, as they have common start and fork at some // point. The tree is stored as an array of pairs (tag value, link to parent). // An m-tag is represented with a single link in the tree (array index). struct MtagElem { elem int pred int } type MtagTrie = []MtagElem // Append a single value to an m-tag history. fn add_mtag(mut trie MtagTrie, mtag int, value int) int { trie = arrays.concat(trie, MtagElem{value, mtag}) return trie.len - 1 } // Recursively unwind tag histories and collect version components. fn unwind(trie MtagTrie, x int, y int, str string) []int { // Reached the root of the m-tag tree, stop recursion. if x == mtag_root && y == mtag_root { return [] } // Unwind history further. mut result := unwind(trie, trie[x].pred, trie[y].pred, str) // Get tag values. Tag histories must have equal length. if x == mtag_root || y == mtag_root { panic("tag histories have different length") } ex := trie[x].elem ey := trie[y].elem if ex != tag_none && ey != tag_none { // Both tags are valid string indices, extract component. result = arrays.concat(result, s2n(str[ex..ey])) } else if !(ex == tag_none && ey == tag_none) { panic("both tags should be tag_none") } return result } fn s2n(s string) int { // convert pre-parsed string to number mut n := 0 for c in s { n = n * 10 + int(c - 48) } return n } fn parse(yyinput string) ?[]int { mut yycursor, mut yymarker := 0, 0 // mut trie := []MtagElem{} mut trie := MtagTrie{} // Final tag variables available in semantic action. /*!svars:re2c format = 'mut @@ := tag_none\n'; */ /*!mvars:re2c format = "mut @@ := mtag_root\n"; */ // Intermediate tag variables used by the lexer (must be autogenerated). /*!stags:re2c format = 'mut @@ := tag_none\n'; */ /*!mtags:re2c format = "mut @@ := mtag_root\n"; */ /*!re2c re2c:tags = 1; re2c:yyfill:enable = 0; re2c:YYMTAGP = "@@ = add_mtag(mut trie, @@, yycursor)"; re2c:YYMTAGN = "@@ = add_mtag(mut trie, @@, tag_none)"; num = [0-9]+; @t1 num @t2 ("." #t3 num #t4)* [\x00] { mut ver := []int{} ver = arrays.concat(ver, s2n(yyinput[t1..t2])) ver = arrays.append(ver, unwind(trie, t3, t4, yyinput)) return ver } * { return none } */ } fn main() { test := fn (result ?[]int, expect ?[]int) { if r := result { if e := expect { if r != e { panic("expected $e, got $r") } } } else { if _ := result { panic("expected none") } } } test(parse("1\0"), [1]) test(parse("1.2.3.4.5.6.7\0"), [1, 2, 3, 4, 5, 6, 7]) test(parse("1.\0"), none) } (code points) (code units) . . . . . . << >> [^] ( * ). : yych YYCTYPE . . re2v . : . : o ASCII ( ). [0-255] . o EBCDIC ( --ebcdic re2c:encoding:ebcdic ). [0-255] . o UCS2 ( --ucs2 re2c:encoding:ucs2 ). [0-0xFFFF] . o UTF8 ( --utf8 re2c:encoding:utf8 ). . . . o UTF16 ( --utf16 re2c:encoding:utf16 ). . . . o UTF32 ( --utf32 re2c:encoding:utf32 ). [0-0x10FFFF] . include/unicode_blocks.re include/unicode_categories.re include/unicode_properties.re re2v . --input-encoding . --input-encoding utf8 re2v UTF8 ( --utf8 ). --encoding-policy (Unicode surrogates [0xD800-0xDFFF]) re2v . UTF8 . // re2v $INPUT -o $OUTPUT --utf8 -si /*!include:re2c "unicode_categories.re" */ fn lex(yyinput string) int { mut yycursor, mut yymarker := 0, 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 0 } * { return 1 } */ } fn main() { if lex("_\0") != 0 { panic("error") } } re2v /*!include:re2c FILE */ %{include FILE %} !include FILE ; FILE . re2v -I . / include re2v #include C/C++ : FILE / . include . --depfile . re2v include/ . ( ) re2v . . (definitions.v) enum Result { ok fail } /*!re2c number = [1-9][0-9]*; */ (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) // re2v $INPUT -o $OUTPUT -i /*!include:re2c "definitions.v" */ fn lex(yyinput string) Result { mut yycursor, mut yymarker := 0, 0 /*!re2c re2c:yyfill:enable = 0; * { return .fail } number { return .ok } !include "extra_rules.re.inc"; */ } fn main() { assert lex("123\0") == .ok assert lex("123.4567\0") == .ok } re2v --header re2c:header /*!header:re2c:on*/ /*!header:re2c:off*/ %{header:on%} %{header:off%} .re . . re2v --header re2c:header ( stdout ) . re2v (translation units) . (lexer state) (tag variables) ( ). (Input file) // re2v $INPUT -o $OUTPUT -i --header lexer/state.v module main import lexer // the package is generated by re2c /*!header:re2c:on*/ module lexer pub struct State { pub mut: yyinput string yycursor int /*!stags:re2c format="@@ int\n"; */ } /*!header:re2c:off*/ fn lex(mut yyrecord &lexer.State) int { mut t := 0 /*!re2c re2c:header = "lexer/state.v"; re2c:api = record; re2c:yyfill:enable = 0; re2c:tags = 1; [a]* @t [b]* { return t } */ } fn main() { mut st := &lexer.State{yyinput:"ab\0",} if lex(mut st) != 1 { panic("error") } } (Header file) // Code generated by re2c, DO NOT EDIT. module lexer pub struct State { pub mut: yyinput string yycursor int yyt1 int } -S, --skeleton re2v re2v C . (lexer) . DFA ( ) re2v : .input DFA .keys . .input . : o re2v ( DFA ). o (benchmarking) . o ( ). ( ). re2v DFA . : DFA . ( ASCII UTF-8 EBCDIC) DFA . DFA : re2v DFA . . re2v ( ) . (re2v ). (Visualization and debug) -D, --emit-dot re2v 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) re2v 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. RE2V(1)