-
Notifications
You must be signed in to change notification settings - Fork 74
/
filtrex.js
3536 lines (3201 loc) · 131 KB
/
filtrex.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Filtrex provides compileExpression() to compile user expressions to JavaScript.
*
* See https://github.com/joewalnes/filtrex for tutorial, reference and examples.
* MIT License.
*
* Includes Jison by Zachary Carter. See http://jison.org/
*
* -Joe Walnes
*/
function compileExpression(expression, extraFunctions /* optional */) {
var functions = {
abs: Math.abs,
ceil: Math.ceil,
floor: Math.floor,
log: Math.log,
max: Math.max,
min: Math.min,
random: Math.random,
round: Math.round,
sqrt: Math.sqrt,
};
if (extraFunctions) {
for (var name in extraFunctions) {
if (extraFunctions.hasOwnProperty(name)) {
functions[name] = extraFunctions[name];
}
}
}
if (!compileExpression.parser) {
// Building the original parser is the heaviest part. Do it
// once and cache the result in our own function.
compileExpression.parser = filtrexParser();
}
var tree = compileExpression.parser.parse(expression);
var js = [];
js.push('return ');
function toJs(node) {
if (Array.isArray(node)) {
node.forEach(toJs);
} else {
js.push(node);
}
}
tree.forEach(toJs);
js.push(';');
function unknown(funcName) {
throw 'Unknown function: ' + funcName + '()';
}
function prop(obj, name) {
return Object.prototype.hasOwnProperty.call(obj||{}, name) ? obj[name] : undefined;
}
var func = new Function('functions', 'data', 'unknown', 'prop', js.join(''));
return function(data) {
return func(functions, data, unknown, prop);
};
}
function filtrexParser() {
// Language parser powered by Jison <http://zaach.github.com/jison/>,
// which is a pure JavaScript implementation of
// Bison <http://www.gnu.org/software/bison/>.
var Jison = require('jison'),
bnf = require('jison/bnf');
function code(args, skipParentheses) {
var argsJs = args.map(function(a) {
return typeof(a) == 'number' ? ('$' + a) : JSON.stringify(a);
}).join(',');
return skipParentheses
? '$$ = [' + argsJs + '];'
: '$$ = ["(", ' + argsJs + ', ")"];';
}
var grammar = {
// Lexical tokens
lex: {
rules: [
['\\*', 'return "*";'],
['\\/', 'return "/";'],
['-' , 'return "-";'],
['\\+', 'return "+";'],
['\\^', 'return "^";'],
['\\%', 'return "%";'],
['\\(', 'return "(";'],
['\\)', 'return ")";'],
['\\,', 'return ",";'],
['==', 'return "==";'],
['\\!=', 'return "!=";'],
['\\~=', 'return "~=";'],
['>=', 'return ">=";'],
['<=', 'return "<=";'],
['<', 'return "<";'],
['>', 'return ">";'],
['\\?', 'return "?";'],
['\\:', 'return ":";'],
['and[^\\w]', 'return "and";'],
['or[^\\w]' , 'return "or";'],
['not[^\\w]', 'return "not";'],
['in[^\\w]', 'return "in";'],
['\\s+', ''], // skip whitespace
['[0-9]+(?:\\.[0-9]+)?\\b', 'return "NUMBER";'], // 212.321
['[a-zA-Z][\\.a-zA-Z0-9_]*',
`yytext = JSON.stringify(yytext);
return "SYMBOL";`
], // some.Symbol22
[`'(?:[^\'])*'`,
`yytext = JSON.stringify(
yytext.substr(1, yyleng-2)
);
return "SYMBOL";`
], // 'some-symbol'
['"(?:[^"])*"',
`yytext = JSON.stringify(
yytext.substr(1, yyleng-2)
);
return "STRING";`
], // "foo"
// End
['$', 'return "EOF";'],
]
},
// Operator precedence - lowest precedence first.
// See http://www.gnu.org/software/bison/manual/html_node/Precedence.html
// for a good explanation of how it works in Bison (and hence, Jison).
// Different languages have different rules, but this seems a good starting
// point: http://en.wikipedia.org/wiki/Order_of_operations#Programming_languages
operators: [
['left', '?', ':'],
['left', 'or'],
['left', 'and'],
['left', 'in'],
['left', '==', '!=', '~='],
['left', '<', '<=', '>', '>='],
['left', '+', '-'],
['left', '*', '/', '%'],
['left', '^'],
['left', 'not'],
['left', 'UMINUS'],
],
// Grammar
bnf: {
expressions: [ // Entry point
['e EOF', 'return $1;']
],
e: [
['e + e' , code([1, '+', 3])],
['e - e' , code([1, '-', 3])],
['e * e' , code([1, '*', 3])],
['e / e' , code([1, '/', 3])],
['e % e' , code([1, '%', 3])],
['e ^ e' , code(['Math.pow(', 1, ',', 3, ')'])],
['- e' , code(['-', 2]), {prec: 'UMINUS'}],
['e and e', code(['Number(', 1, '&&', 3, ')'])],
['e or e' , code(['Number(', 1, '||', 3, ')'])],
['not e' , code(['Number(!', 2, ')'])],
['e == e' , code(['Number(', 1, '==', 3, ')'])],
['e != e' , code(['Number(', 1, '!=', 3, ')'])],
['e ~= e' , code(['RegExp(', 3, ').test(', 1, ')'])],
['e < e' , code(['Number(', 1, '<' , 3, ')'])],
['e <= e' , code(['Number(', 1, '<=', 3, ')'])],
['e > e' , code(['Number(', 1, '> ', 3, ')'])],
['e >= e' , code(['Number(', 1, '>=', 3, ')'])],
['e ? e : e', code([1, '?', 3, ':', 5])],
['( e )' , code([2])],
['NUMBER' , code([1])],
['STRING' , code([1])],
['SYMBOL' , code(['prop(data, ', 1, ')'])],
['SYMBOL ( )', code(['(functions.hasOwnProperty(', 1, ') ? functions[', 1, ']() : unknown(', 1, '))'])],
['SYMBOL ( argsList )', code(['(functions.hasOwnProperty(', 1, ') ? functions[', 1, '](', 3, ') : unknown(', 1, '))'])],
['e in ( inSet )', code(['(function(o) { return ', 4, '; })(', 1, ')'])],
['e not in ( inSet )', code(['!(function(o) { return ', 5, '; })(', 1, ')'])],
],
argsList: [
['e', code([1], true)],
['argsList , e', code([1, ',', 3], true)],
],
inSet: [
['e', code(['o ==', 1], true)],
['inSet , e', code([1, '|| o ==', 3], true)],
],
}
};
return new Jison.Parser(grammar);
}
// ---------------------------------------------------
// Jison will be appended after this point by Makefile
// ---------------------------------------------------
var require = (function() {
var require = (function () {
var modules = {};
var factories = {};
var r = function(id) {
if (!modules[id]) {
//console.log(id);
modules[id] = {};
factories[id](r, modules[id], { id : id });
}
return modules[id];
};
r.def = function(id, params) {
//console.log('def', id);
factories[id] = params.factory;
};
return r;
})()
require.def("jison",{factory:function(require,exports,module){
// Jison, an LR(0), SLR(1), LARL(1), LR(1) Parser Generator
// Zachary Carter <[email protected]>
// MIT X Licensed
var typal = require("jison/util/typal").typal,
Set = require("jison/util/set").Set,
RegExpLexer = require("jison/lexer").RegExpLexer;
var Jison = exports.Jison = exports;
// detect prints
Jison.print = function() { }
/*
if (typeof console !== 'undefined' && console.log) {
Jison.print = console.log;
Jison.print = function print () {};
} else if (typeof puts !== 'undefined') {
Jison.print = function print () { puts([].join.call(arguments, ' ')); };
} else if (typeof print !== 'undefined') {
Jison.print = print;
} else {
Jison.print = function print () {};
}
*/
Jison.Parser = (function () {
// iterator utility
function each (obj, func) {
if (obj.forEach) {
obj.forEach(func);
} else {
var p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
func.call(obj, obj[p], p, obj);
}
}
}
}
var Nonterminal = typal.construct({
constructor: function Nonterminal (symbol) {
this.symbol = symbol;
this.productions = new Set();
this.first = [];
this.follows = [];
this.nullable = false;
},
toString: function Nonterminal_toString () {
var str = this.symbol+"\n";
str += (this.nullable ? 'nullable' : 'not nullable');
str += "\nFirsts: "+this.first.join(', ');
str += "\nFollows: "+this.first.join(', ');
str += "\nProductions:\n "+this.productions.join('\n ');
return str;
}
});
var Production = typal.construct({
constructor: function Production (symbol, handle, id) {
this.symbol = symbol;
this.handle = handle;
this.nullable = false;
this.id = id;
this.first = [];
this.precedence = 0;
},
toString: function Production_toString () {
return this.symbol+" -> "+this.handle.join(' ');
}
});
var generator = typal.beget();
generator.constructor = function Jison_Generator (grammar, opt) {
if (typeof grammar === 'string') {
grammar = require("jison/bnf").parse(grammar);
}
var options = typal.mix.call({}, grammar.options, opt);
this.terms = {};
this.operators = {};
this.productions = [];
this.conflicts = 0;
this.resolutions = [];
this.options = options;
this.yy = {}; // accessed as yy free variable in the parser/lexer actions
// source included in semantic action execution scope
if (grammar.actionInclude) {
if (typeof grammar.actionInclude === 'function') {
grammar.actionInclude = String(grammar.actionInclude).replace(/^\s*function \(\) \{/, '').replace(/\}\s*$/, '');
}
this.actionInclude = grammar.actionInclude;
}
this.moduleInclude = grammar.moduleInclude||'';
this.DEBUG = options.debug || false;
if (this.DEBUG) this.mix(generatorDebug); // mixin debug methods
this.processGrammar(grammar);
if (grammar.lex) {
this.lexer = new RegExpLexer(grammar.lex, null, this.terminals_);
}
};
generator.processGrammar = function processGrammarDef (grammar) {
var bnf = grammar.bnf,
tokens = grammar.tokens,
nonterminals = this.nonterminals = {},
productions = this.productions,
self = this;
if (!grammar.bnf && grammar.ebnf) {
bnf = grammar.bnf = require("jison/ebnf").transform(grammar.ebnf);
}
if (tokens) {
if (typeof tokens === 'string') {
tokens = tokens.trim().split(' ');
} else {
tokens = tokens.slice(0);
}
}
var symbols = this.symbols = [];
// calculate precedence of operators
var operators = this.operators = processOperators(grammar.operators);
// build productions from cfg
this.buildProductions(grammar.bnf, productions, nonterminals, symbols, operators);
if (tokens && this.terminals.length !== tokens.length) {
self.trace("Warning: declared tokens differ from tokens found in rules.");
self.trace(this.terminals);
self.trace(tokens);
}
// augment the grammar
this.augmentGrammar(grammar);
};
generator.augmentGrammar = function augmentGrammar (grammar) {
// use specified start symbol, or default to first user defined production
this.startSymbol = grammar.start || grammar.startSymbol || this.productions[0].symbol;
if (!this.nonterminals[this.startSymbol]) {
throw new Error("Grammar error: startSymbol must be a non-terminal found in your grammar.");
}
this.EOF = "$end";
// augment the grammar
var acceptProduction = new Production('$accept', [this.startSymbol, '$end'], 0);
this.productions.unshift(acceptProduction);
// prepend parser tokens
this.symbols.unshift("$accept",this.EOF);
this.symbols_.$accept = 0;
this.symbols_[this.EOF] = 1;
this.terminals.unshift(this.EOF);
this.nonterminals.$accept = new Nonterminal("$accept");
this.nonterminals.$accept.productions.push(acceptProduction);
// add follow $ to start symbol
this.nonterminals[this.startSymbol].follows.push(this.EOF);
};
// set precedence and associativity of operators
function processOperators (ops) {
if (!ops) return {};
var operators = {};
for (var i=0,k,prec;prec=ops[i]; i++) {
for (k=1;k < prec.length;k++) {
operators[prec[k]] = {precedence: i+1, assoc: prec[0]};
}
}
return operators;
}
generator.buildProductions = function buildProductions(bnf, productions, nonterminals, symbols, operators) {
var actions = [
this.actionInclude || '',
'var $0 = $$.length - 1;',
'switch (yystate) {'
];
var prods, symbol;
var productions_ = [0];
var symbolId = 1;
var symbols_ = {};
var her = false; // has error recovery
function addSymbol (s) {
if (s && !symbols_[s]) {
symbols_[s] = ++symbolId;
symbols.push(s);
}
}
// add error symbol; will be third symbol, or "2" ($accept, $end, error)
addSymbol("error");
for (symbol in bnf) {
if (!bnf.hasOwnProperty(symbol)) continue;
addSymbol(symbol);
nonterminals[symbol] = new Nonterminal(symbol);
if (typeof bnf[symbol] === 'string') {
prods = bnf[symbol].split(/\s*\|\s*/g);
} else {
prods = bnf[symbol].slice(0);
}
prods.forEach(buildProduction);
}
var sym, terms = [], terms_ = {};
each(symbols_, function (id, sym) {
if (!nonterminals[sym]) {
terms.push(sym);
terms_[id] = sym;
}
});
this.hasErrorRecovery = her;
this.terminals = terms;
this.terminals_ = terms_;
this.symbols_ = symbols_;
this.productions_ = productions_;
actions.push('}');
this.performAction = Function("yytext,yyleng,yylineno,yy,yystate,$$,_$", actions.join("\n"));
function buildProduction (handle) {
var r, rhs, i;
if (handle.constructor === Array) {
rhs = (typeof handle[0] === 'string') ?
handle[0].trim().split(' ') :
handle[0].slice(0);
for (i=0; i<rhs.length; i++) {
if (rhs[i] === 'error') her = true;
if (!symbols_[rhs[i]]) {
addSymbol(rhs[i]);
}
}
if (typeof handle[1] === 'string' || handle.length == 3) {
// semantic action specified
var action = 'case '+(productions.length+1)+':'+handle[1]+'\nbreak;';
// replace named semantic values ($nonterminal)
if (action.match(/[$@][a-zA-Z][a-zA-Z0-9_]*/)) {
var count = {},
names = {};
for (i=0;i<rhs.length;i++) {
if (names[rhs[i]]) {
names[rhs[i]+(++count[rhs[i]])] = i+1;
} else {
names[rhs[i]] = i+1;
names[rhs[i]+"1"] = i+1;
count[rhs[i]] = 1;
}
}
action = action.replace(/\$([a-zA-Z][a-zA-Z0-9_]*)/g, function (str, pl) {
return names[pl] ? '$'+names[pl] : pl;
}).replace(/@([a-zA-Z][a-zA-Z0-9_]*)/g, function (str, pl) {
return names[pl] ? '@'+names[pl] : pl;
});
}
action = action.replace(/([^'"])\$\$|^\$\$/g, '$1this.$').replace(/@[0$]/g, "this._$")
.replace(/\$(\d+)/g, function (_, n) {
return "$$[$0" + (n - rhs.length || '') + "]";
})
.replace(/@(\d+)/g, function (_, n) {
return "_$[$0" + (n - rhs.length || '') + "]";
});
actions.push(action);
r = new Production(symbol, rhs, productions.length+1);
// precedence specified also
if (handle[2] && operators[handle[2].prec]) {
r.precedence = operators[handle[2].prec].precedence;
}
} else {
// only precedence specified
r = new Production(symbol, rhs, productions.length+1);
if (operators[handle[1].prec]) {
r.precedence = operators[handle[1].prec].precedence;
}
}
} else {
rhs = handle.trim().split(' ');
for (i=0; i<rhs.length; i++) {
if (rhs[i] === 'error') her = true;
if (!symbols_[rhs[i]]) {
addSymbol(rhs[i]);
}
}
r = new Production(symbol, rhs, productions.length+1);
}
if (r.precedence === 0) {
// set precedence
for (i=r.handle.length-1; i>=0; i--) {
if (!(r.handle[i] in nonterminals) && r.handle[i] in operators) {
r.precedence = operators[r.handle[i]].precedence;
}
}
}
productions.push(r);
productions_.push([symbols_[r.symbol], r.handle[0] === '' ? 0 : r.handle.length]);
nonterminals[symbol].productions.push(r);
}
};
generator.createParser = function createParser () {
throw new Error('Calling abstract method.');
};
// noop. implemented in debug mixin
generator.trace = function trace () { };
generator.warn = function warn () {
var args = Array.prototype.slice.call(arguments,0);
console.warn('Jison Warning', args);
// Jison.print.call(null,args.join(""));
};
generator.error = function error (msg) {
throw new Error(msg);
};
// Generator debug mixin
var generatorDebug = {
trace: function trace () {
Jison.print.apply(null, arguments);
},
beforeprocessGrammar: function () {
this.trace("Processing grammar.");
},
afteraugmentGrammar: function () {
var trace = this.trace;
each(this.symbols, function (sym, i) {
trace(sym+"("+i+")");
});
}
};
/*
* Mixin for common behaviors of lookahead parsers
* */
var lookaheadMixin = {};
lookaheadMixin.computeLookaheads = function computeLookaheads () {
if (this.DEBUG) this.mix(lookaheadDebug); // mixin debug methods
this.computeLookaheads = function () {};
this.nullableSets();
this.firstSets();
this.followSets();
};
// calculate follow sets typald on first and nullable
lookaheadMixin.followSets = function followSets () {
var productions = this.productions,
nonterminals = this.nonterminals,
self = this,
cont = true;
// loop until no further changes have been made
while(cont) {
cont = false;
productions.forEach(function Follow_prod_forEach (production, k) {
//self.trace(production.symbol,nonterminals[production.symbol].follows);
// q is used in Simple LALR algorithm determine follows in context
var q;
var ctx = !!self.go_;
var set = [],oldcount;
for (var i=0,t;t=production.handle[i];++i) {
if (!nonterminals[t]) continue;
// for Simple LALR algorithm, self.go_ checks if
if (ctx)
q = self.go_(production.symbol, production.handle.slice(0, i));
var bool = !ctx || q === parseInt(self.nterms_[t], 10);
if (i === production.handle.length+1 && bool) {
set = nonterminals[production.symbol].follows;
} else {
var part = production.handle.slice(i+1);
set = self.first(part);
if (self.nullable(part) && bool) {
set.push.apply(set, nonterminals[production.symbol].follows);
}
}
oldcount = nonterminals[t].follows.length;
Set.union(nonterminals[t].follows, set);
if (oldcount !== nonterminals[t].follows.length) {
cont = true;
}
}
});
}
};
// return the FIRST set of a symbol or series of symbols
lookaheadMixin.first = function first (symbol) {
// epsilon
if (symbol === '') {
return [];
// RHS
} else if (symbol instanceof Array) {
var firsts = [];
for (var i=0,t;t=symbol[i];++i) {
if (!this.nonterminals[t]) {
if (firsts.indexOf(t) === -1)
firsts.push(t);
} else {
Set.union(firsts, this.nonterminals[t].first);
}
if (!this.nullable(t))
break;
}
return firsts;
// terminal
} else if (!this.nonterminals[symbol]) {
return [symbol];
// nonterminal
} else {
return this.nonterminals[symbol].first;
}
};
// fixed-point calculation of FIRST sets
lookaheadMixin.firstSets = function firstSets () {
var productions = this.productions,
nonterminals = this.nonterminals,
self = this,
cont = true,
symbol,firsts;
// loop until no further changes have been made
while(cont) {
cont = false;
productions.forEach(function FirstSets_forEach (production, k) {
var firsts = self.first(production.handle);
if (firsts.length !== production.first.length) {
production.first = firsts;
cont=true;
}
});
for (symbol in nonterminals) {
firsts = [];
nonterminals[symbol].productions.forEach(function (production) {
Set.union(firsts, production.first);
});
if (firsts.length !== nonterminals[symbol].first.length) {
nonterminals[symbol].first = firsts;
cont=true;
}
}
}
};
// fixed-point calculation of NULLABLE
lookaheadMixin.nullableSets = function nullableSets () {
var firsts = this.firsts = {},
nonterminals = this.nonterminals,
self = this,
cont = true;
// loop until no further changes have been made
while(cont) {
cont = false;
// check if each production is nullable
this.productions.forEach(function (production, k) {
if (!production.nullable) {
for (var i=0,n=0,t;t=production.handle[i];++i) {
if (self.nullable(t)) n++;
}
if (n===i) { // production is nullable if all tokens are nullable
production.nullable = cont = true;
}
}
});
//check if each symbol is nullable
for (var symbol in nonterminals) {
if (!this.nullable(symbol)) {
for (var i=0,production;production=nonterminals[symbol].productions.item(i);i++) {
if (production.nullable)
nonterminals[symbol].nullable = cont = true;
}
}
}
}
};
// check if a token or series of tokens is nullable
lookaheadMixin.nullable = function nullable (symbol) {
// epsilon
if (symbol === '') {
return true;
// RHS
} else if (symbol instanceof Array) {
for (var i=0,t;t=symbol[i];++i) {
if (!this.nullable(t))
return false;
}
return true;
// terminal
} else if (!this.nonterminals[symbol]) {
return false;
// nonterminal
} else {
return this.nonterminals[symbol].nullable;
}
};
// lookahead debug mixin
var lookaheadDebug = {
beforenullableSets: function () {
this.trace("Computing Nullable sets.");
},
beforefirstSets: function () {
this.trace("Computing First sets.");
},
beforefollowSets: function () {
this.trace("Computing Follow sets.");
},
afterfollowSets: function () {
var trace = this.trace;
each(this.nonterminals, function (nt, t) {
trace(nt, '\n');
});
}
};
/*
* Mixin for common LR parser behavior
* */
var lrGeneratorMixin = {};
lrGeneratorMixin.buildTable = function buildTable () {
if (this.DEBUG) this.mix(lrGeneratorDebug); // mixin debug methods
this.states = this.canonicalCollection();
this.table = this.parseTable(this.states);
this.defaultActions = findDefaults(this.table);
};
lrGeneratorMixin.Item = typal.construct({
constructor: function Item(production, dot, f, predecessor) {
this.production = production;
this.dotPosition = dot || 0;
this.follows = f || [];
this.predecessor = predecessor;
this.id = parseInt(production.id+'a'+this.dotPosition, 36);
this.markedSymbol = this.production.handle[this.dotPosition];
},
remainingHandle: function () {
return this.production.handle.slice(this.dotPosition+1);
},
eq: function (e) {
return e.id === this.id;
},
handleToString: function () {
var handle = this.production.handle.slice(0);
handle[this.dotPosition] = '.'+(handle[this.dotPosition]||'');
return handle.join(' ');
},
toString: function () {
var temp = this.production.handle.slice(0);
temp[this.dotPosition] = '.'+(temp[this.dotPosition]||'');
return this.production.symbol+" -> "+temp.join(' ') +
(this.follows.length === 0 ? "" : " #lookaheads= "+this.follows.join(' '));
}
});
lrGeneratorMixin.ItemSet = Set.prototype.construct({
afterconstructor: function () {
this.reductions = [];
this.goes = {};
this.edges = {};
this.shifts = false;
this.inadequate = false;
this.hash_ = {};
for (var i=this._items.length-1;i >=0;i--) {
this.hash_[this._items[i].id] = true; //i;
}
},
concat: function concat (set) {
var a = set._items || set;
for (var i=a.length-1;i >=0;i--) {
this.hash_[a[i].id] = true; //i;
}
this._items.push.apply(this._items, a);
return this;
},
push: function (item) {
this.hash_[item.id] = true;
return this._items.push(item);
},
contains: function (item) {
return this.hash_[item.id];
},
valueOf: function toValue () {
var v = this._items.map(function (a) {return a.id;}).sort().join('|');
this.valueOf = function toValue_inner() {return v;};
return v;
}
});
lrGeneratorMixin.closureOperation = function closureOperation (itemSet /*, closureSet*/) {
var closureSet = new this.ItemSet();
var self = this;
var set = itemSet,
itemQueue, syms = {};
do {
itemQueue = new Set();
closureSet.concat(set);
set.forEach(function CO_set_forEach (item) {
var symbol = item.markedSymbol;
// if token is a non-terminal, recursively add closures
if (symbol && self.nonterminals[symbol]) {
if(!syms[symbol]) {
self.nonterminals[symbol].productions.forEach(function CO_nt_forEach (production) {
var newItem = new self.Item(production, 0);
if(!closureSet.contains(newItem))
itemQueue.push(newItem);
});
syms[symbol] = true;
}
} else if (!symbol) {
// reduction
closureSet.reductions.push(item);
closureSet.inadequate = closureSet.reductions.length > 1 || closureSet.shifts;
} else {
// shift
closureSet.shifts = true;
closureSet.inadequate = closureSet.reductions.length > 0;
}
});
set = itemQueue;
} while (!itemQueue.isEmpty());
return closureSet;
};
lrGeneratorMixin.gotoOperation = function gotoOperation (itemSet, symbol) {
var gotoSet = new this.ItemSet(),
self = this;
itemSet.forEach(function goto_forEach(item, n) {
if (item.markedSymbol === symbol) {
gotoSet.push(new self.Item(item.production, item.dotPosition+1, item.follows, n));
}
});
return gotoSet.isEmpty() ? gotoSet : this.closureOperation(gotoSet);
};
/* Create unique set of item sets
* */
lrGeneratorMixin.canonicalCollection = function canonicalCollection () {
var item1 = new this.Item(this.productions[0], 0, [this.EOF]);
var firstState = this.closureOperation(new this.ItemSet(item1)),
states = new Set(firstState),
marked = 0,
self = this,
itemSet;
states.has = {};
states.has[firstState] = 0;
while (marked !== states.size()) {
itemSet = states.item(marked); marked++;
itemSet.forEach(function CC_itemSet_forEach (item) {
if (item.markedSymbol && item.markedSymbol !== self.EOF)
self.canonicalCollectionInsert(item.markedSymbol, itemSet, states, marked-1);
});
}
return states;
};
// Pushes a unique state into the que. Some parsing algorithms may perform additional operations
lrGeneratorMixin.canonicalCollectionInsert = function canonicalCollectionInsert (symbol, itemSet, states, stateNum) {
var g = this.gotoOperation(itemSet, symbol);
if (!g.predecessors)
g.predecessors = {};
// add g to que if not empty or duplicate
if (!g.isEmpty()) {
var gv = g.valueOf(),
i = states.has[gv];
if (i === -1 || typeof i === 'undefined') {
states.has[gv] = states.size();
itemSet.edges[symbol] = states.size(); // store goto transition for table
states.push(g);
g.predecessors[symbol] = [stateNum];
} else {
itemSet.edges[symbol] = i; // store goto transition for table
states.item(i).predecessors[symbol].push(stateNum);
}
}
};
var NONASSOC = 0;
lrGeneratorMixin.parseTable = function parseTable (itemSets) {
var NONASSOC = 0;
var states = [],
nonterminals = this.nonterminals,
operators = this.operators,
conflictedStates = {}, // array of [state, token] tuples
self = this,
s = 1, // shift
r = 2, // reduce
a = 3; // accept
// for each item set
itemSets.forEach(function (itemSet, k) {
var state = states[k] = {};
var action, stackSymbol;
// set shift and goto actions
for (stackSymbol in itemSet.edges) {
itemSet.forEach(function (item, j) {
// find shift and goto actions
if (item.markedSymbol == stackSymbol) {
var gotoState = itemSet.edges[stackSymbol];
if (nonterminals[stackSymbol]) {
// store state to go to after a reduce
//self.trace(k, stackSymbol, 'g'+gotoState);
state[self.symbols_[stackSymbol]] = gotoState;
} else {
//self.trace(k, stackSymbol, 's'+gotoState);
state[self.symbols_[stackSymbol]] = [s,gotoState];
}
}
});
}
// set accept action
itemSet.forEach(function (item, j) {
if (item.markedSymbol == self.EOF) {
// accept
state[self.symbols_[self.EOF]] = [a];
//self.trace(k, self.EOF, state[self.EOF]);
}
});
var allterms = self.lookAheads ? false : self.terminals;
// set reductions and resolve potential conflicts
itemSet.reductions.forEach(function (item, j) {