-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathmodule-include.cs.g
More file actions
116 lines (102 loc) · 2.85 KB
/
module-include.cs.g
File metadata and controls
116 lines (102 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
* Module includes. C# version.
*
* The "moduleInclude" directive allows including an arbitrary code at the
* beginning of the generated parser file. As an example, can be the code
* to require modules for corresponding AST nodes, or direct AST nodes
* definitions.
*
* The code may define callbacks for several parse events, in particular
* `onParseBegin`, and `onParseEnd`, attaching to `yyparse`:
*
* yyparse.onParseBegin = (string code) =>
* {
* Console.WriteLine("Parsing: " + code);
* };
*
* ./bin/syntax -g ./examples/module-include.cs.g -m slr1 -o './CalcParser.cs'
*
* using SyntaxParser;
*
* var parser = new CalcParser();
*
* Console.WriteLine(parser.parse("2 + 2 * 2"));
*
* > Custom hook on parse begin. Parsing: 2 + 2 * 2
* > Custom hook on parse end. Parsed: SyntaxParser.BinaryExpression
* > SyntaxParser.BinaryExpression
*/
{
"lex": {
"rules": [
["\\s+", '/* skip whitespace */ return null'],
["\\d+", 'return "NUMBER"'],
["\\*", 'return "*"'],
["\\+", 'return "+"'],
["\\(", 'return "("'],
["\\)", 'return ")"'],
]
},
"moduleInclude": `
// Can be "using" statments, or direct declarations.
namespace SyntaxParser
{
public class Node
{
public string Type;
public Node(string type)
{
Type = type;
}
}
public class BinaryExpression : Node
{
public object Left;
public object Right;
public string Op;
public BinaryExpression(object left, object right, string op): base("Binary")
{
Left = left;
Right = right;
Op = op;
}
}
public class PrimaryExpression : Node
{
public int Value;
public PrimaryExpression(string value) : base("Primary")
{
Value = Convert.ToInt32(value);
}
}
// Setup of the parser hooks is done via Init.run();
public class Init
{
public static void run()
{
// Standard hook on parse beging, and end:
yyparse.onParseBegin = (string code) =>
{
Console.WriteLine("Custom hook on parse begin. Parsing: " + code);
};
yyparse.onParseEnd = (object parsed) =>
{
Console.WriteLine("Custom hook on parse end. Parsed: " + parsed);
};
}
}
}
`,
"operators": [
["left", "+"],
["left", "*"],
],
"bnf": {
"E": [
["E + E", "$$ = new BinaryExpression($1, $3, $2)"],
["E * E", "$$ = new BinaryExpression($1, $3, $2)"],
["NUMBER", "$$ = new PrimaryExpression($1)"],
["( E )", "$$ = $2"],
],
},
}