ReCode
The Fast Regular Expression compiler for C#.
Introduction
Inspired by RE2C, this library can be referenced from a T4 text template for the purpose of generating
code for parallel matching of a block of regular expressions.
Supported inputs for matching are pointers to a sequence of bytes or chars. This enables generation of fast scanners/tokenizers for almost any
purpose (even binary data).
Usage
ReCode is enabled in a text template by referencing the dll:
<#@ assembly name="$(SolutionDir)packages\\ReCode.1.0.3\\lib\\452\\ReCode.dll" #>
<#@ import namespace="ReCode" #>
Example
As an example of a compiled block of expressions, consider the following example:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="$(SolutionDir)packages\\ReCode.1.0.3\\lib\\452\\ReCode.dll" #>
<#@ import namespace="ReCode" #>
<#@ output extension=".cs" #>
using System.Collections.Generic;
namespace ReCodeTest {
public class TestParser2 {
public static unsafe KeyValuePair<ushort, int>? Parse(char * start, int len){
var pNext = start;
var pLimit = start + len;
var pEnd = start;
<#
foreach(var token in ReCode.RegularExpressionTokens(WriteLine)) {
for(var i=0;i<10;i++)
if(token.Matches($"'{25*i}'")) { #> return new KeyValuePair<ushort,int>(<#=i#>, (int)(pEnd - start)); <#}
if(token.Matches(@"[+\-]?[0-9]*[\.][0-9]+[E][+\-]?[0-9]+")) { #> return new KeyValuePair<ushort,int>(10, (int)(pEnd - start)); <# }
if(token.Matches(@"[+\-]?[0-9]*[\.][0-9]+")) { #> return new KeyValuePair<ushort,int>(11, (int)(pEnd - start)); <# }
if(token.Matches(@"[+\-]?[0-9]+")) { #> return new KeyValuePair<ushort,int>(12, (int)(pEnd - start)); <# }
if(token.Fails) { #> return null; <# }
}
#>
}
}
}
The resulting function matches the following sequences
- 0 maps to 0
- 25 maps to 1
- 50 maps to 2
- 75 maps to 3
- 100 maps to 4
- 125 maps to 5
- 150 maps to 6
- 175 maps to 7
- 200 maps to 8
- 225 maps to 9
- [+\-]?[0-9]*[\.][0-9]+[E][+\-]?[0-9]+ maps to 10
- [+\-]?[0-9]*[\.][0-9]+ maps to 11
- [+\-]?[0-9]+ maps to 12
The block is executed with semantics corresponding to executing the expressions one by one
in the listed order until a match is reached. If nothing was matched, the token.Fails block
is executed.
Internal Scanning and Parsing
ReCode internally uses a pre-compiled version of ReCode for constructing the scanner for the
regular expression syntax.
The library also contains logic for constructing LR(1) grammar parsers from
a T4 template. This logic is used for parsing the regular expression patterns.
This part of the library seems to work very well, but has not been extensively tested.
Generated Code
The resulting code executes a deterministic finite automaton (DFA) for recognizing the
supplied regular expressions (with documentation).
As of version 1, the generated code for the above example would be the following:
using System.Collections.Generic;
namespace ReCodeTest {
public class TestParser2 {
public static unsafe KeyValuePair<ushort, int>? Parse(char * start, int len){
var pNext = start;
var pLimit = start + len;
var pEnd = start;
{
/*
* Union
* +-Accept(0)
* | +-Sequence(CaseInsensitive,'0')
* +-Accept(1)
* | +-Sequence(CaseInsensitive,'25')
* +-Accept(2)
* | +-Sequence(CaseInsensitive,'50')
* +-Accept(3)
* | +-Sequence(CaseInsensitive,'75')
* +-Accept(4)
* | +-Sequence(CaseInsensitive,'100')
* +-Accept(5)
* | +-Sequence(CaseInsensitive,'125')
* +-Accept(6)
* | +-Sequence(CaseInsensitive,'150')
* +-Accept(7)
* | +-Sequence(CaseInsensitive,'175')
* +-Accept(8)
* | +-Sequence(CaseInsensitive,'200')
* +-Accept(9)
* | +-Sequence(CaseInsensitive,'225')
* +-Accept(10)
* | +-Concat
* | +-Repeat(ZeroOrOne)
* | | +-Ranges('+','-')
* | +-Repeat(ZeroOrMore)
* | | +-Ranges(['0'-'9'])
* | +-Ranges('.')
* | +-Repeat(OneOrMore)
* | | +-Ranges(['0'-'9'])
* | +-Ranges('E')
* | +-Repeat(ZeroOrOne)
* | | +-Ranges('+','-')
* | +-Repeat(OneOrMore)
* | +-Ranges(['0'-'9'])
* +-Accept(11)
* | +-Concat
* | +-Repeat(ZeroOrOne)
* | | +-Ranges('+','-')
* | +-Repeat(ZeroOrMore)
* | | +-Ranges(['0'-'9'])
* | +-Ranges('.')
* | +-Repeat(OneOrMore)
* | +-Ranges(['0'-'9'])
* +-Accept(12)
* +-Concat
* +-Repeat(ZeroOrOne)
* | +-Ranges('+','-')
* +-Repeat(OneOrMore)
* +-Ranges(['0'-'9'])
*/
/*
* DFA STATE 0
* '+' -> 1
* '-' -> 1
* '.' -> 2
* '0' -> 3
* '1' -> 4
* '2' -> 5
* ['3'-'4'] -> 6
* '5' -> 7
* '6' -> 6
* '7' -> 8
* ['8'-'9'] -> 6
*/
if(pNext >= pLimit) goto nonaccept0;
var current = *pNext++;
if(current < 0x31) /* ('0') '1' */ {
if(current < 0x2D) /* (',') '-' */ {
if(current < 0x2B) /* ('*') '+' */
goto nonaccept0;
if(current < 0x2C) /* ('+') ',' */
goto state0_1;
goto nonaccept0;
}
if(current < 0x2F) /* ('.') '/' */ {
if(current < 0x2E) /* ('-') '.' */
goto state0_1;
goto state0_2;
}
if(current < 0x30) /* ('/') '0' */
goto nonaccept0;
goto state0_3;
}
if(current < 0x36) /* ('5') '6' */ {
if(current < 0x33) /* ('2') '3' */ {
if(current < 0x32) /* ('1') '2' */
goto state0_4;
goto state0_5;
}
if(current < 0x35) /* ('4') '5' */
goto state0_6;
goto state0_7;
}
if(current < 0x38) /* ('7') '8' */ {
if(current < 0x37) /* ('6') '7' */
goto state0_6;
goto state0_8;
}
if(current < 0x3A) /* ('9') ':' */
goto state0_6;
goto nonaccept0;
/*
* DFA STATE 1
* '.' -> 2
* ['0'-'9'] -> 6
*/
state0_1:
if(pNext >= pLimit) goto nonaccept0;
current = *pNext++;
if(current < 0x2F) /* ('.') '/' */ {
if(current < 0x2E) /* ('-') '.' */
goto nonaccept0;
goto state0_2;
}
if(current < 0x30) /* ('/') '0' */
goto nonaccept0;
if(current < 0x3A) /* ('9') ':' */
goto state0_6;
goto nonaccept0;
/*
* DFA STATE 2
* ['0'-'9'] -> 9
*/
state0_2:
if(pNext >= pLimit) goto nonaccept0;
current = *pNext++;
if(current < 0x30) /* ('/') '0' */
goto nonaccept0;
if(current < 0x3A) /* ('9') ':' */
goto state0_9;
goto nonaccept0;
/*
* DFA STATE 3 (accepts to 0)
*/
state0_3:
pEnd = pNext;
goto accept0_0;
/*
* DFA STATE 4 (accepts to 12)
* '.' -> 10
* '0' -> 11
* '1' -> 6
* '2' -> 12
* ['3'-'4'] -> 6
* '5' -> 13
* '6' -> 6
* '7' -> 14
* ['8'-'9'] -> 6
*/
state0_4:
pEnd = pNext;
if(pNext >= pLimit) goto accept0_12;
current = *pNext++;
if(current < 0x33) /* ('2') '3' */ {
if(current < 0x30) /* ('/') '0' */ {
if(current < 0x2E) /* ('-') '.' */
goto accept0_12;
if(current < 0x2F) /* ('.') '/' */
goto state0_10;
goto accept0_12;
}
if(current < 0x31) /* ('0') '1' */
goto state0_11;
if(current < 0x32) /* ('1') '2' */
goto state0_6;
goto state0_12;
}
if(current < 0x37) /* ('6') '7' */ {
if(current < 0x35) /* ('4') '5' */
goto state0_6;
if(current < 0x36) /* ('5') '6' */
goto state0_13;
goto state0_6;
}
if(current < 0x38) /* ('7') '8' */
goto state0_14;
if(current < 0x3A) /* ('9') ':' */
goto state0_6;
goto accept0_12;
/*
* DFA STATE 5 (accepts to 12)
* '.' -> 10
* '0' -> 15
* '1' -> 6
* '2' -> 16
* ['3'-'4'] -> 6
* '5' -> 17
* ['6'-'9'] -> 6
*/
state0_5:
pEnd = pNext;
if(pNext >= pLimit) goto accept0_12;
current = *pNext++;
if(current < 0x32) /* ('1') '2' */ {
if(current < 0x2F) /* ('.') '/' */ {
if(current < 0x2E) /* ('-') '.' */
goto accept0_12;
goto state0_10;
}
if(current < 0x30) /* ('/') '0' */
goto accept0_12;
if(current < 0x31) /* ('0') '1' */
goto state0_15;
goto
提示:代码过长已自动截断
The Parser Generator
As a free benefit, the library includes a LR(1) parser generator as well.
We can consider the source code used in ReCode for parsing regular expression syntax:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="$(SolutionDir)packages\\ReCode.1.0.3\\lib\\452\\ReCode.dll" #>
<#@ import namespace="ReCode" #>
<#@ output extension=".cs" #>
using System;
using System.Collections.Generic;
using ReCode.RegularExpressions.Parsing.Nodes;
namespace ReCode.RegularExpressions.Parsing {
public partial class RegExParser {
<#
foreach (var language in ReCode.ParserTokens(WriteLine, "RegExNode"))
{
var g = language.GrammarFromTokens("Expr", "Phrase", "Range", "Star", "Plus", "Question", "ParBegin", "ParEnd", "Bar", "Accept", "Name", "Except");
var g1 = g.WithPrecedenceGroup();
if(g1.Matches("Expr", "ParBegin", "Expr", "ParEnd")) {#> res = arg1; <# }
if(g1.Matches("Expr", "Phrase")) {#> res = arg0; <# }
if(g1.Matches("Expr", "Range")) {#> res = arg0; <# }
if(g1.Matches("Expr", "Name")) {#> res = _namedExpressions[(arg0 as RegExNodeName).Name]; <# }
if(g1.MatchesLeft("Expr", "Expr", "Expr")) {#> res = new RegExNodeConcat(arg0,arg1); <# }
if(g1.MatchesLeft("Expr", "Expr", "Bar", "Expr")) {#> res = RegExNodeUnion.Of(arg0,arg2); <# }
var g2 = g.WithPrecedenceGroup();
if(g2.Matches("Expr", "Expr", "Accept")) {#> res = new RegExNodeAccept(arg0, (arg1 as RegExNodeAccept).AcceptState); <# }
if(g2.Matches("Expr", "Expr", "Plus")) {#> res = new RegExNodeRepeat(arg0, RegExRepeatType.OneOrMore); <# }
if(g2.Matches("Expr", "Expr", "Star")) {#> res = new RegExNodeRepeat(arg0, RegExRepeatType.ZeroOrMore);<# }
if(g2.Matches("Expr", "Expr", "Question")) {#> res = new RegExNodeRepeat(arg0, RegExRepeatType.ZeroOrOne); <# }
var g3 = g.WithPrecedenceGroup();
if(g3.MatchesRight("Expr", "Expr", "Except", "Expr")) {#> res = RegExNodeRanges.Except(arg0, arg2); <# }
}
#>
}
}
While this code does not look like much, it translates into the following:
using System;
using System.Collections.Generic;
using ReCode.RegularExpressions.Parsing.Nodes;
namespace ReCode.RegularExpressions.Parsing {
public partial class RegExParser {
private class ArrayStack<TElm>
{
public readonly TElm[] Elements;
public int Top;
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public void Reset() { Top = -1; }
public ArrayStack(int capacity) { Elements = new TElm[capacity]; Top=-1; }
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public void Push(TElm elm) { Elements[++Top] = elm; }
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public void Pop(int count = 1) { Top -= count; }
}
const int DefaultStackSize = 50;
private readonly ArrayStack<int> _stateStack = new ArrayStack<int>(2 * DefaultStackSize);
private readonly ArrayStack<RegExNode> _valueStack = new ArrayStack<RegExNode>(DefaultStackSize);
public enum Token {
END = 1,
Phrase = 3,
Range = 4,
Star = 5,
Plus = 6,
Question = 7,
ParBegin = 8,
ParEnd = 9,
Bar = 10,
Accept = 11,
Name = 12,
Except = 13,
}
public RegExNode Parse() {
RegExNode res = default(RegExNode);
var targetTokenType = 0;
_stateStack.Reset();
_valueStack.Reset();
KeyValuePair<Token,RegExNode> currentToken = NextToken();
_stateStack.Push(0); goto __state_0;
__postReduce:
/* find on the stack the state where we need to handle post-reduce goto. */
var gotoState = _stateStack.Elements[_stateStack.Top];
/* put information on the stack regarding the reduced type. */
_stateStack.Push(targetTokenType);
/* jump to the resulting state. */
switch(gotoState){
case 0:
switch(targetTokenType){
case 2: _stateStack.Push(1); goto __state_1;
default: goto __syntaxError;
}
case 1:
switch(targetTokenType){
case 2: _stateStack.Push(6); goto __state_6;
default: goto __syntaxError;
}
case 4:
switch(targetTokenType){
case 2: _stateStack.Push(13); goto __state_13;
default: goto __syntaxError;
}
case 6:
switch(targetTokenType){
case 2: _stateStack.Push(6); goto __state_6;
default: goto __syntaxError;
}
case 10:
switch(targetTokenType){
case 2: _stateStack.Push(18); goto __state_18;
default: goto __syntaxError;
}
case 12:
switch(targetTokenType){
case 2: _stateStack.Push(19); goto __state_19;
default: goto __syntaxError;
}
case 13:
switch(targetTokenType){
case 2: _stateStack.Push(20); goto __state_20;
default: goto __syntaxError;
}
case 16:
switch(targetTokenType){
case 2: _stateStack.Push(28); goto __state_28;
default: goto __syntaxError;
}
case 18:
switch(targetTokenType){
case 2: _stateStack.Push(6); goto __state_6;
default: goto __syntaxError;
}
case 19:
switch(targetTokenType){
case 2: _stateStack.Push(6); goto __state_6;
default: goto __syntaxError;
}
case 20:
switch(targetTokenType){
case 2: _stateStack.Push(20); goto __state_20;
default: goto __syntaxError;
}
case 25:
switch(targetTokenType){
case 2: _stateStack.Push(29); goto __state_29;
default: goto __syntaxError;
}
case 27:
switch(targetTokenType){
case 2: _stateStack.Push(30); goto __state_30;
default: goto __syntaxError;
}
case 28:
switch(targetTokenType){
case 2: _stateStack.Push(20); goto __state_20;
default: goto __syntaxError;
}
case 29:
switch(targetTokenType){
case 2: _stateStack.Push(20); goto __state_20;
default: goto __syntaxError;
}
case 30:
switch(targetTokenType){
case 2: _stateStack.Push(20); goto __state_20;
default: goto __syntaxError;
}
default:
goto __syntaxError;
}
__state_0:
switch((int)currentToken.Key){
case 3:
/* perform shift to state {action.Target} */
_valueStack.Push(currentToken.Value);
_stateStack.Push((int)currentToken.Key);
currentToken = NextToken();
_stateStack.Push(2); goto __state_2;
case 4:
/* perform shift to state {action.Target} */
_valueStack.Push(currentToken.Value);
_stateStack.Push((int)currentToken.Key);
currentToken = NextToken();
_stateStack.Push(3); goto __state_3;
case 8:
/* perform shift to state {action.Target} */
_valueStack.Push(currentToken.Value);
_stateStack.Push((int)currentToken.Key);
currentToken = NextToken();
_stateStack.Push(4); goto __state_4;
case 12:
/* perform shift to state {action.Target} */
_valueStack.Push(currentToken.Value);
_stateStack.Push((int)currentToken.Key);
currentToken = NextToken();
_stateStack.Push(5); goto __state_5;
default:
goto __syntaxError;
}
__state_1:
switch((int)currentToken.Key){
提示:代码过长已自动截断
评论