-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.js
588 lines (509 loc) · 17.6 KB
/
compiler.js
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// Production rule class
const Rule = function(symbol, definition) {
// non-terminal symbol
if (symbol == null) {
this.symbol = "";
} else {
this.symbol = symbol;
}
// definition symbols
this.definition = [];
if (definition != null) {
if (Array.isArray(definition)) {
Array.prototype.push.apply(this.definition, definition);
} else {
this.definition.push(definition);
}
}
}
// Production rule prototype
Rule.prototype = {
// convert to string
"toString": function() {
const symbols = [ this.symbol, "::=" ].concat(this.definition);
symbols.push(";");
return symbols.join(" ");
},
}
// LR item class
const LrItem = function(rule, position) {
// properties
this.rule = rule;
this.position = Math.max(0, Math.min(position, rule.definition.length));
if (this.position < rule.definition.length) {
this.next = rule.definition[this.position];
} else {
this.next = "";
}
this.look = new Set();
// LR(0) item
const symbols = [ rule.symbol, "::=" ];
Array.prototype.push.apply(symbols, rule.definition.slice(0, this.position));
symbols.push("•");
Array.prototype.push.apply(symbols, rule.definition.slice(this.position));
this._lr0 = symbols.join(" ");
}
// LR item prototype
LrItem.prototype = {
// go to the next position
"goAhead": function() {
// confirm current position
if (this.rule.length <= this.position) {
return null;
}
// create next LR item
return new LrItem(this.rule, this.position + 1);
},
// add lookahead symbols
"addLook": function(collection) {
collection.forEach(this.look.add, this.look);
},
// get item string
"getItem": function() {
return this._lr0;
},
// whether another instance is equal to this instance
"equals": function(other) {
return other.getItem() == this.getItem();
},
}
// Closure class
const Closure = function(rules, represent) {
// fields
this._rules = rules;
if (Array.isArray(represent)) {
this.represent = represent;
} else {
this.represent = [ represent ];
}
// properties
this.items = [];
for (const item of this.represent) {
this._setItems(item);
}
// get the next items for each item
this._creation = new Map();
for (const key of this.items) {
const value = this.items.filter(elem => elem.rule.symbol == key.next);
this._creation.set(key, value);
}
}
// Closure prototype
Closure.prototype = {
// go to the next position
"goAhead": function(symbol) {
if (symbol == "") {
return null;
}
// get next LR items
const nexts = [];
for (const item of this.items.filter(elem => elem.next == symbol)) {
const ahead = item.goAhead();
if (ahead != null) {
nexts.push(ahead);
}
}
if (nexts.length == 0) {
return null;
}
// create next closure
return new Closure(this._rules, nexts);
},
// add lookahead set
"addLookSet": function(collections, first) {
// set lookahead set for representative items
for (const item of this.represent) {
if (!collections.has(item)) {
return;
}
item.addLook(collections.get(item));
}
// propagate to derived items
for (const current of this.items) {
const look = this._getNextLook(current, first);
const items = this._creation.get(current);
items.forEach(elem => elem.addLook(look));
}
},
// whether another instance is equal to this instance
"equals": function(other) {
if (other.items.length != this.items.length) {
return false;
}
for (let i = 0; i < other.items.length; i++) {
if (!other.items[i].equals(this.items[i])) {
return false;
}
}
return true;
},
// set LR items
"_setItems": function(current) {
// whether it is the same as an existing item
if (this.items.some(elem => elem.equals(current))) {
return;
}
// add the current LR item
this.items.push(current);
// production rule starting with the following symbol
for (const rule of this._rules) {
if (rule.symbol == current.next) {
this._setItems(new LrItem(rule, 0));
}
}
},
// get the next lookahead set
"_getNextLook": function(current, first) {
// is the next symbol non-terminal?
const follow = new Set();
if (!first.has(current.next)) {
return follow;
}
// get next next symbols
let index = current.position + 1;
while (index < current.rule.definition.length) {
const next = current.rule.definition[index];
if (!first.has(next)) {
// terminal symbol
follow.add(next);
return follow;
}
// non-terminal symbol
const symbols = first.get(next);
symbols.forEach(follow.add, follow);
if (!symbols.has("ε")) {
// when not including epsilon transition
return follow;
}
// remove epsilon
follow.delete("ε");
index++;
}
// reach the end of production rule
current.look.forEach(follow.add, follow);
return follow;
},
}
// State transition class
const Transition = function(symbol, from, to) {
// properties
this.symbol = symbol;
this.from = from;
this.to = to;
this.relation = this._createRelation();
}
// State transition prototype
Transition.prototype = {
// create transition item relationships
"_createRelation": function() {
const relation = new Map();
const items = this.from.items.filter(elem => elem.next == this.symbol);
for (const prev of items) {
// before transition
let next = null;
let i = 0;
while (next == null && i < this.to.items.length) {
const candidate = this.to.items[i];
if (candidate.rule == prev.rule && candidate.position == prev.position + 1) {
// after transition
next = candidate;
}
i++;
}
relation.set(prev, next);
}
return relation;
},
}
// Set of symbols class
const SymbolSet = function(rules) {
// non-terminal symbols
const first = new Map();
rules.forEach(elem => first.set(elem.symbol, new Set()));
const nrs = rules.filter(elem => 0 < elem.definition.length && first.has(elem.definition[0]));
const trs = rules.filter(elem => nrs.indexOf(elem) < 0);
// FIRST set whose definition symbol starts with a terminal symbol
for (const rule of trs) {
let term = "ε";
if (0 < rule.definition.length) {
// terminal symbol
term = rule.definition[0];
}
// add a symbol
const symbols = first.get(rule.symbol);
symbols.add(term);
}
// FIRST set whose definition symbol starts with a non-terminal symbol
let before = 0;
let after = 0;
first.forEach(elem => after += elem.size);
while (before < after) {
for (const rule of nrs) {
this._addFirsts(first, rule);
}
before = after;
after = 0;
first.forEach(elem => after += elem.size);
}
this.first = first;
}
// Set of symbols prototype
SymbolSet.prototype = {
// add FIRST set
"_addFirsts": function(first, rule) {
// FIRST set of the production rule
const self = first.get(rule.symbol);
let i = 0;
while (i < rule.definition.length) {
const symbol = rule.definition[i];
if (!first.has(symbol)) {
// terminal symbol
self.add(symbol);
return;
}
// non-terminal symbol
const other = first.get(symbol);
other.forEach(self.add, self);
if (!other.has("ε")) {
// when not including epsilon transition
return;
}
i++;
}
},
}
// Compiler class
const Compiler = function() {
this._clear();
}
// Compiler prototype
Compiler.prototype = {
// compile execution
"execute": function(rules) {
this._clear();
if (!Array.isArray(rules)) {
return "There is no production rule.";
}
// minimize production rules
const rest = this._createMinRules(rules.concat());
const message = this._extractSymbols(rest);
if (message != "") {
return message;
}
// create closures
const start = new Closure(this.rules, new LrItem(this.rules[0], 0));
this._createClosures(start, []);
this._setLookAhead();
// create the parsing table
return this._createTable();
},
// clear properties
"_clear": function() {
this.rules = [];
this.closures = [];
this.transitions = [];
this.table = [];
this.symbols = [];
this.terminals = [];
this.nonterminals = [];
this.dummies = [];
},
// create a minimal production rules
"_createMinRules": function(rules) {
// add start rule
const start = new Rule("#0#", rules[0].symbol);
rules.unshift(start);
// get all definition symbols
const all = this._getRuleSymbols(rules);
all.push("#0#");
// get only rules where non-terminal symbol appears in definition
this.rules = rules.filter(elem => 0 <= all.indexOf(elem.symbol));
// returns the remaining invalid production rules
return rules.filter(elem => all.indexOf(elem.symbol) < 0);
},
// get all definition symbols
"_getRuleSymbols": function(rules) {
const symbols = [];
for (const rule of rules) {
Array.prototype.push.apply(symbols, rule.definition);
}
return symbols.filter(this._distinctArray);
},
// extract symbols
"_extractSymbols": function(rest) {
if (this.rules.length == 0) {
return "There is no valid production rule.";
}
// non-terminal symbols
let nonterms = this.rules.map(elem => elem.symbol);
nonterms = nonterms.filter(this._distinctArray);
this.nonterminals = nonterms;
// terminal symbols
const used = this._getRuleSymbols(this.rules);
const terms = used.filter(elem => nonterms.indexOf(elem) < 0);
const fix = terms.filter(elem => elem.charAt(0) == "'");
const flex = terms.filter(elem => elem.charAt(0) == "\"");
const find = elem => elem.charAt(0) != "'" && elem.charAt(0) != "\"";
const unknown = terms.filter(find);
if (0 < unknown.length) {
return "no definition of non-terminal symbol: " + unknown.join(" ");
}
this.terminals = fix.concat(flex);
this.symbols = this.terminals.concat(nonterms);
this.symbols[this.terminals.length] = "$";
// definition symbols not used
const dummies = this._getRuleSymbols(rest);
const unused = dummies.filter(find);
if (0 < unused.length) {
return "no definition of non-terminal symbol: " + unused.join(" ");
}
this.dummies = dummies;
return "";
},
// create closures
"_createClosures": function(start, exists) {
// whether it is the same as an existing closure
if (this.closures.some(elem => elem.equals(start))) {
return;
}
this.closures.push(start);
// get next symbols
const nexts = start.items.map(elem => elem.next);
const symbols = nexts.filter(this._distinctArray);
// create a state transition
for (const symbol of symbols) {
let ahead = start.goAhead(symbol);
if (ahead != null) {
// whether the closure already exists
let past = null;
let index = 0;
while (past == null && index < exists.length) {
if (exists[index].equals(ahead)) {
past = exists[index];
}
index++;
}
if (past == null) {
exists.push(ahead);
} else {
ahead = past;
}
// state transition
const trans = new Transition(symbol, start, ahead);
this.transitions.push(trans);
// next closure
this._createClosures(ahead, exists);
}
}
},
// set the lookahead set
"_setLookAhead": function() {
const symbols = new SymbolSet(this.rules);
// get all items
const all = [];
for (const closure of this.closures) {
Array.prototype.push.apply(all, closure.items);
}
// add a lookahead set to the first closure
const collections = new Map();
const look = new Set();
look.add("$");
collections.set(all[0], look);
this.closures[0].addLookSet(collections, symbols.first);
// handle all state transitions
let before = 0;
let after = all.reduce(this._sumLookSize, 0);
while (before < after) {
for (const trans of this.transitions) {
collections.clear();
trans.relation.forEach((value, key) => collections.set(value, key.look));
trans.to.addLookSet(collections, symbols.first);
}
// whether the lookahead set has been added
before = after;
after = all.reduce(this._sumLookSize, 0);
}
},
// create the parsing table
"_createTable": function() {
// create an empty table
const row = [];
for (let i = 0; i < this.symbols.length; i++) {
row.push("");
}
for (let i = 0; i < this.closures.length; i++) {
this.table.push(row.concat());
}
// set the action
const error = new Map();
this._setReduce(error);
this._setShift(error);
// are there any errors?
if (0 < error.size) {
return "There are collisions.";
}
const action = this.table[0].filter(elem => elem.charAt(0) == "s" || elem.charAt(0) == "r");
if (action.length == 0) {
return "There is no shift or reduction from the start symbol.";
}
return "";
},
// set reductions and an acceptance
"_setReduce": function(error) {
for (let i = 0; i < this.closures.length; i++) {
// closure number is line number
const reduce = this.closures[i].items.filter(elem => elem.next == "");
for (const item of reduce) {
for (const symbol of item.look) {
const index = this.symbols.indexOf(symbol);
const action = "r" + this.rules.indexOf(item.rule);
if (this.table[i][index] == "") {
// reduce or accept
this.table[i][index] = action;
} else {
// collision
this.table[i][index] += "/" + action;
if (!error.has(i)) {
error.set(i, []);
}
const list = error.get(i);
list.push(symbol);
}
}
}
}
},
// set shifts and transitions
"_setShift": function(error) {
for (const trans of this.transitions) {
const from = this.closures.indexOf(trans.from);
const index = this.symbols.indexOf(trans.symbol);
let action = this.closures.indexOf(trans.to);
if (this.nonterminals.indexOf(trans.symbol) < 0) {
action = "s" + action;
} else {
action = "g" + action;
}
if (this.table[from][index] == "") {
// shift or transition
this.table[from][index] = action;
} else {
// collision
this.table[from][index] += "/" + action;
if (!error.has(from)) {
error.set(from, []);
}
const list = error.get(from);
list.push(trans.symbol);
}
}
},
// remove duplicate elements in array
"_distinctArray": function(elem, idx, arr) {
return arr.indexOf(elem) == idx;
},
// sum of the number of lookahead symbols
"_sumLookSize": function(acc, cur) {
return acc + cur.look.size;
},
}