-
Notifications
You must be signed in to change notification settings - Fork 0
/
FSEmit.cs
272 lines (232 loc) · 9.7 KB
/
FSEmit.cs
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
namespace ParserGen;
internal static class FSEmit {
internal class FSharpSemanticAction {
public string Action { get; }
public string[] Args { get; }
public int MaxArg { get; }
internal FSharpSemanticAction(Production p) {
string action = p.SemanticInput;
this.MaxArg = p.Rhs.Length;
int argc = 0;
List<string> args = new List<string>();
for (int i = 0; i < this.MaxArg; i++) {
string pattern = $"${i + 1}";
int count = CountSubstring(action, pattern);
if (count > 0) {
string c = ((char)('a' + (char)argc++)).ToString();
args.Add(c);
action = action.Replace(pattern, c);
}
}
this.Args = args.ToArray();
this.Action = action;
}
public static int CountSubstring(string text, string value) {
int count = 0, minIndex = text.IndexOf(value, 0);
while (minIndex != -1) {
minIndex = text.IndexOf(value, minIndex + value.Length);
count++;
}
return count;
}
public override string ToString() {
return this.Action;
}
}
internal static bool indentAll = false;
internal static void Emit(Table<LR1Action> table, Grammar G, string parseOutput) {
// Open .fs
using var src_fs = File.Open(parseOutput, FileMode.Create);
using var src_sw = new StreamWriter(src_fs);
// Open .fsi
using var sig_fs = File.Open(parseOutput.Replace(".fs", ".fsi"), FileMode.Create);
using var sig_sw = new StreamWriter(sig_fs);
// Write header
WriteHead(src_sw, sig_sw, G.Namespace);
// Write using
foreach (string ln in G.Using) {
WriteDual(src_sw, sig_sw, ln);
}
// Write types
WriteTypes(src_sw, sig_sw, G);
// Write parse table to .fs file
WriteTable(src_sw, sig_sw, table, G.EmptySymbol.Index, Grammar.EndOfInput.Index);
// Write semantics
WriteDual(src_sw, sig_sw, "// Semantic dispatcher");
WriteLine(sig_sw, "val sem_dispatch : StackElement list -> int * int -> int -> SemanticAction");
WriteLine(src_sw, "let sem_dispatch stack (sl,sc) = function");
for (int i = 0; i < G.Productions.Count; i++) {
WriteLine(src_sw, $"| {i} -> {{ nodeType = {new FSharpSemanticAction(G.Productions[i])}; stack = stack; srcline=sl; srccol=sc }}");
}
WriteLine(src_sw, $"| _ -> failwith \"Invalid semantic action ID\"");
WriteLine(src_sw);
// Write symbols
WriteLine(src_sw, "// Symbols");
WriteLine(src_sw, $"let symbol_pattern = function");
foreach (var sym in G.Symbols.OrderBy(x => x.Value.Index)) {
WriteLine(src_sw, $"| \"{sym.Key}\" -> ({sym.Value.Index}, {sym.Value.IsTerminal.ToString().ToLowerInvariant()}, {sym.Value.IsNullable.ToString().ToLowerInvariant()})");
}
WriteLine(src_sw, $"| _ -> (-1, false, false)");
WriteLine(src_sw);
// Write index fetcher
WriteLine(sig_sw);
WriteDual(src_sw, sig_sw, "// Symb ID fetcher");
WriteFunc(src_sw, sig_sw, "symbolStr2ID", "string -> int", "str", "let (i, _, _) = symbol_pattern str in i");
WriteDual(src_sw, sig_sw, "");
// Write productions
WriteLine(src_sw, "// Productions");
WriteLine(src_sw, "let prod_list = [");
int j = 0;
foreach (var p in G.Productions.OrderBy(x => x.Index)) {
if (indentAll)
src_sw.Write(" ");
src_sw.Write($" ({p.Lhs.Index}, [{string.Join(';', p.Rhs.Select(x => x.Index))}])");
if (j + 1 < G.Productions.Count) {
src_sw.WriteLine(";");
}
j++;
}
WriteLine(src_sw, "]");
WriteLine(src_sw, "");
// Write production tuple fetcher
WriteDual(src_sw, sig_sw, "// Production fetcher");
WriteFunc(src_sw, sig_sw, "prod_lookup", "int -> int * int list", "i", "prod_list[i]");
WriteDual(src_sw, sig_sw, "");
}
internal static void WriteDual(StreamWriter src, StreamWriter sig, string content) {
if (indentAll) {
src.Write(" ");
sig.Write(" ");
}
src.WriteLine(content);
sig.WriteLine(content);
}
internal static void WriteHead(StreamWriter src, StreamWriter sig, string ns) {
WriteDual(src, sig, "// This file was auto-generated by an LALR(1) - Parse Table generator.");
if (!string.IsNullOrEmpty(ns)) {
WriteDual(src, sig, $"namespace {ns}");
WriteDual(src, sig, "");
WriteDual(src, sig, "module ParserSemantics =");
indentAll = true;
} else {
WriteDual(src, sig, "module ParserSemantics");
indentAll = false;
}
WriteDual(src, sig, string.Empty);
}
internal static void WriteSemant(StreamWriter src, int index, FSharpSemanticAction semanticAction) {
if (indentAll) {
src.Write(" ");
}
src.WriteLine($"let sem{index:000} stack (sl, sc) = {{ nodeType = {semanticAction}; stack = stack; srcline=sl; srccol=sc }}");
}
internal static void WriteFunc(StreamWriter src, StreamWriter sig, string name, string types, string args, string body, bool export = true) {
if (export) {
if (indentAll) {
sig.Write(" ");
}
sig.WriteLine($"val {name} : {types}");
}
if (indentAll) {
src.Write(" ");
}
src.WriteLine($"let {name} {args} = {body}");
}
internal static void WriteLine(StreamWriter w, string str) {
if (indentAll) {
w.Write(" ");
}
w.WriteLine(str);
}
internal static void WriteLine(StreamWriter w) {
if (indentAll) {
w.Write(" ");
}
w.WriteLine();
}
internal static void WriteTypes(StreamWriter src, StreamWriter sig, Grammar G) {
// Write action type
WriteDual(src, sig, "// Parser actions");
WriteDual(src, sig, "type Action = ");
WriteDual(src, sig, "| Accept of uint");
WriteDual(src, sig, "| Shift of uint");
WriteDual(src, sig, "| Reduce of uint");
WriteDual(src, sig, "| Goto of uint");
WriteDual(src, sig, "| Error");
WriteDual(src, sig, "");
// Write stack element
WriteDual(src, sig, "// Parser Stack element");
WriteDual(src, sig, "type StackElement = ");
WriteDual(src, sig, "| Token of LexToken");
WriteDual(src, sig, "| Action of SemanticAction");
WriteDual(src, sig, "| ParserAction of obj list");
WriteDual(src, sig, "and SemanticAction = { nodeType: SemanticActionType; stack: StackElement list; srcline: int; srccol: int }");
WriteDual(src, sig, "");
// Write a default error
/*WriteLine(src, "// Basic helpers error");
WriteLine(src, "let a = Accept 1");
WriteLine(src, "let r p = Reduce (int p)");
WriteLine(src, "let s t = Shift (int t)");
WriteLine(src, "let g s = Goto (int s)");
WriteLine(src, "let e = Error");
WriteLine(src);*/
// Write class
foreach (string ln in G.InClass) {
WriteLine(src, ln);
}
}
internal static void WriteTable(StreamWriter src, StreamWriter sig, Table<LR1Action> table, int eps, int eof) {
// Loop over
/*WriteLine(src, "// Lookup table");
WriteLine(src, "let _table =");
WriteLine(src, " [");
for (int row = 0; row < table.Rows; row++) {
if (indentAll)
src.Write(" ");
src.Write(" ");
for (int col = 0; col < table.Columns; col++) {
// Get cell
var cell = table[row, col];
// Action type
var arg = cell.Action switch {
ActionType.Accept => $"a",
ActionType.Reduce => $"r {cell.ActionArgument}",
ActionType.Shift => $"s {cell.ActionArgument}",
ActionType.Error => "e",
ActionType.Goto => $"g {cell.ActionArgument}",
_ => ""
};
// Check
if (arg.Length > 0) {
src.Write(arg);
if (col + 1 < table.Columns) {
src.Write("; ");
}
}
}
if (row + 1 < table.Rows) {
WriteLine(src, ";");
} else {
WriteLine(src);
}
}
WriteLine(src, " ]");
WriteLine(src, "");*/
// Write lookup
//WriteDual(src, sig, "// Lookup function for lookup up the next action in table");
//WriteFunc(src, sig, "table_lookup", "int -> int -> Action", "(state: int) (sym: int)", $"_table[(int state) * {table.Columns} + sym]");
//WriteDual(src, sig, "");
// Write columns
WriteDual(src, sig, "// amount of table columns (Used to calculate table position when doing a lookup) ");
WriteFunc(src, sig, "table_columns", "int", "", table.Columns.ToString());
WriteDual(src, sig, "");
// Write eps ID
WriteDual(src, sig, "// index of eps ");
WriteFunc(src, sig, "eps_id", "int", "", eps.ToString());
WriteDual(src, sig, "");
// Write eof ID
WriteDual(src, sig, "// index of EOF ");
WriteFunc(src, sig, "eof_id", "int", "", eof.ToString());
WriteDual(src, sig, "");
}
}