-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathregexp.js
1328 lines (1251 loc) · 37.3 KB
/
regexp.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
/* -*- indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */
var util = require('util');
var _ = require('underscore');
var assert = require('assert').ok;
var MIN_CHAR=String.fromCharCode(0);
var MAX_CHAR=String.fromCharCode(65535);
var FLAG_UNIFIED = 1;
var FLAG_CAPTURE_ALL = 1;
var epsilonPrintable = "\u03F5";
var epsilon = 'eps';
// Create a new NFA node. Ids are assigned to nodes later
function NFANode() {
// Each element of this.transitions is an object of the form:
// { cmpKey: ub+lb, key: { lb: .., ub: .. }, nodes: [ .. ] }
this.transitions = [ ];
this.epsilonTransitions = [ ];
// Always copy the capture set when we move from one thread to
// another.
this.captures = [ ];
// Optional attributes:
this.id = -2;
this.isFinal = false;
this.groupNum = -2;
this.startIndex = -2;
this.endIndex = -2;
}
NFANode.prototype = {
on: function(toNode, input) {
var isEpsilonTransition = !input || input == epsilon;
if (isEpsilonTransition) {
this.epsilonTransitions.push(toNode);
return this;
}
// console.log("Got Transition on:", input);
if (typeof(input) === "string") {
var tmp = { lb: input, ub: input };
input = tmp;
}
// console.log(input);
var cmpKey = input.lb + input.ub;
// Assume that we don't have multiple transitions on the same
// input. That should be performed using epsilon transitions.
this.transitions.push({ cmpKey: cmpKey,
key: input,
nodes: [ toNode ]
});
return this;
},
getTransitionsOn: function(input) {
if (input == epsilon) {
return this.epsilonTransitions;
}
var i;
var ret = [ ];
for (i = 0; i < this.transitions.length; ++i) {
var tr = this.transitions[i];
if (input >= tr.key.lb && input <= tr.key.ub) {
if (ret.length === 0) {
ret = tr.nodes;
} else {
ret = ret.concat(tr.nodes);
}
}
}
return ret;
},
hasTransitionOn: function(input) {
return this.getTransitionsOn(input).length > 0;
},
numTransitionSymbols: function() {
// The number of distinct characters (code-points) on which
// there is a transition from this node, outwards.
var numSyms = 0;
var i;
for (i = 0; i < this.transitions.length; ++i) {
var tr = this.transitions[i];
numSyms += (tr.ub.charCodeAt(0) - tr.lb.charCodeAt(0) + 1);
}
return numSyms;
},
getTransitionSymbols: function() {
// Return all transition symbols except for epsilon.
//
// Note: This can be a fairly expensive function, so always
// use the cheaper numTransitionSymbols() before calling this
// function instead of calling this function and checking the
// length of the returned array.
var syms = [ ];
var i, j;
for (i = 0; i < this.transitions.length; ++i) {
var tr = this.transitions[i];
for (j = tr.lb; j <= tr.ub; ++j) {
syms.push(j);
}
}
return syms;
},
getAllTransitionNodes: function() {
// Returns all nodes that can be reached from the current node
// with a single hop.
var nodes = [ ];
var i;
for (i = 0; i < this.transitions.length; ++i) {
var tr = this.transitions[i];
nodes = nodes.concat(tr.nodes);
}
nodes = nodes.concat(this.epsilonTransitions);
return nodes;
},
getAllTransitions: function() {
var tr = [ ];
tr = tr.concat(this.transitions);
tr.push({ keyCmp: epsilonPrintable + epsilonPrintable,
key: { lb: epsilonPrintable, ub: epsilonPrintable },
nodes: this.epsilonTransitions
});
return tr;
},
isCaptureStart: function() {
return this.startIndex != -2;
},
isCaptureEnd: function() {
return this.endIndex != -2;
},
clone: function(captures) {
var nn = new NFANode();
var node = this;
nn.transitions = node.transitions;
nn.epsilonTransitions = node.epsilonTransitions;
nn.id = node.id;
nn.isFinal = node.isFinal;
nn.groupNum = node.groupNum;
nn.startIndex = node.startIndex;
nn.endIndex = node.endIndex;
// The capture set is deep copied.
nn.captures = captures.slice(0);
return nn;
}
};
function NFACaptureNode(groupNum, startIndex, endIndex) {
assert(groupNum == 0 || startIndex != endIndex);
assert(startIndex == -2 || endIndex == -2);
var captureNode = new NFANode();
captureNode.groupNum = groupNum;
captureNode.startIndex = startIndex;
captureNode.endIndex = endIndex;
return captureNode;
}
function DFANode(id) {
// Each element of this.transitions is a DFANode
this.transitions = { };
this.id = id;
}
DFANode.prototype = {
on: function(toNode, input) {
if (!toNode || !input) {
throw new Error("Usage: on(node, input)");
}
if (this.transitions.hasOwnProperty(input)) {
throw new Error(
util.format("You already have a transition on input '%s'",
input));
}
this.transitions[input] = toNode;
return this;
}
};
function RegExpParser(expression) {
this.expression = expression;
this.root = null;
this.index = 0;
this.expLen = this.expression.length;
this.error = '';
this.groupNum = 1;
}
function ParenthesizedNode(groupNum, startIndex, endIndex, node) {
this.groupNum = groupNum;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.node = node;
}
ParenthesizedNode.prototype = {
toNFA: function() {
var lhs = new NFANode();
var rhs = new NFANode();
var parenOpen = new NFACaptureNode(this.groupNum, this.startIndex, -2);
var parenClose = new NFACaptureNode(this.groupNum, -2, this.endIndex);
var npair = this.node.toNFA();
lhs.on(parenOpen);
parenOpen.on(npair[0]);
npair[1].on(parenClose);
parenClose.on(rhs);
return [ lhs, rhs ];
}
};
function AnchoredNode(node, leftAnchored, rightAnchored) {
this.node = node;
this.leftAnchored = leftAnchored;
this.rightAnchored = rightAnchored;
}
AnchoredNode.prototype = {
toNFA: function() {
var node = new ParenthesizedNode(0, -1, 1024, this.node);
// console.log("Generated group 0");
if (!this.leftAnchored) {
var opNode = new OpNode('*');
var symNode = new SingleChar('.');
var acceptAny = new ApplyOpsNode(symNode, opNode);
node = new SequenceNode(acceptAny, node);
}
return node.toNFA();
}
};
function UnionNode(node1, node2) {
this.node1 = node1;
this.node2 = node2;
}
UnionNode.prototype = {
toNFA: function() {
var lhs = new NFANode();
var rhs = new NFANode();
var n1pair = this.node1.toNFA();
var n2pair = this.node2.toNFA();
// Add epsilon transitions from lhs -> [node1, node2]
lhs.on(n1pair[0]).on(n2pair[0]);
// Add epsilon transitions from [node1, node2] -> rhs
n1pair[1].on(rhs);
n2pair[1].on(rhs);
return [lhs, rhs];
}
};
function EmptyNode() { }
EmptyNode.prototype = {
toNFA: function() {
var lhs = new NFANode();
var rhs = new NFANode();
return [lhs, rhs];
}
};
function SequenceNode(node1, node2) {
this.node1 = node1;
this.node2 = node2;
}
SequenceNode.prototype = {
toNFA: function() {
var lhs = this.node1.toNFA();
var rhs = this.node2.toNFA();
// Add an epsilon transition
lhs[1].on(rhs[0]);
return [lhs[0], rhs[1]];
}
};
function ApplyOpsNode(sym, ops) {
this.sym = sym;
this.ops = ops;
}
ApplyOpsNode.prototype = {
toNFA: function() {
return this.ops.toNFA(this.sym.toNFA());
}
};
function OpNode(op) {
this.op = op;
}
OpNode.prototype = {
toNFA: function(symNodePair) {
var sopsNode = new SequentialOpsNode(this);
return sopsNode.toNFA(symNodePair);
}
};
function SequentialOpsNode(op, ops) {
this.op = op;
this.ops = ops;
}
SequentialOpsNode.prototype = {
toNFA: function(symNodePair) {
var nodePair = [new NFANode(), new NFANode()];
switch (this.op.op) {
case '*':
// Add a self epsilon transition
symNodePair[0].on(symNodePair[1]);
nodePair[1].on(nodePair[0]);
nodePair[0].on(symNodePair[0]);
symNodePair[1].on(nodePair[1]);
break;
case '+':
nodePair[1].on(nodePair[0]);
nodePair[0].on(symNodePair[0]);
symNodePair[1].on(nodePair[1]);
break;
case '?':
nodePair[0].on(nodePair[1]);
nodePair[0].on(symNodePair[0]);
symNodePair[1].on(nodePair[1]);
break;
default:
throw new Error(util.format("Invalid operation '%s'", this.op.op));
break;
}
if (this.ops) {
console.log("This: ", this);
return this.ops.toNFA(nodePair);
}
return nodePair;
}
};
function NFANodeFromCharList(charList, flags) {
var lhs = new NFANode();
var rhs = new NFANode();
if (!(flags & FLAG_UNIFIED)) {
charList = unifiedCharList(charList);
}
// console.log("Unified charlist:", charList);
for (var i = 0; i < charList.length; ++i) {
lhs.on(rhs, charList[i]);
}
return [ lhs, rhs ];
}
function CharListNode(one, many) {
this.one = one;
this.many = many;
this.type = 'charlist';
}
CharListNode.prototype = {
getCharList: function() {
var ret = [ ];
ret = ret.concat(this.one.getCharList());
ret = ret.concat(this.many.getCharList());
return ret;
},
toNFA: function() {
return NFANodeFromCharList(this.getCharList());
}
};
function unifiedCharList(charList) {
var unified = [ ];
var i;
var inflections = [ ];
var started = [ ];
var TYPE_START = 1;
var TYPE_END = 2;
for (i = 0; i < charList.length; ++i) {
charList.id = i;
inflections.push({ ch: charList[i].lb, id: i, type: TYPE_START });
inflections.push({ ch: charList[i].ub, id: i, type: TYPE_END });
started[i] = false;
}
inflections.sort(function(lhs, rhs) {
if (lhs.ch == rhs.ch) {
return lhs.type - rhs.type;
}
return lhs.ch - rhs.ch;
});
// console.log("inflections:", inflections);
var stk = [ ];
var point;
for (i = 0; i < inflections.length; ++i) {
point = inflections[i];
if (!started[point.id]) {
stk.push(point.ch);
started[point.id] = true;
} else {
if (stk.length == 1) {
unified.push({ lb: stk[0], ub: point.ch });
}
stk.pop();
}
}
return unified;
}
function negateCharList(charList) {
// First find all the inclusive ranges (since input ranges may
// overlap), and then negate the inclusive range to get the
// negated range.
var negated = [ ];
var i;
var ch = MIN_CHAR;
var unified = unifiedCharList(charList);
for (i = 0; i < unified.length; ++i) {
var nextCh = String.fromCharCode(unified[i].ub.charCodeAt(0) + 1)
var endCh = String.fromCharCode(unified[i].lb.charCodeAt(0) - 1)
if (unified[i].lb > ch) {
negated.push({ lb: ch, ub: endCh });
}
ch = nextCh;
}
if (ch < MAX_CHAR) {
negated.push({ lb: ch, ub: MAX_CHAR });
}
return negated;
}
function CharRangeNode(lhs, rhs) {
this.lhs = lhs.ch;
this.rhs = rhs.ch;
}
CharRangeNode.prototype = {
getCharList: function() {
var ret;
if (this.lhs.toLowerCase() === this.lhs && this.rhs.toLowerCase() === this.rhs) {
if (this.lhs > this.rhs) {
throw new Error(util.format("CharRangeNode: %s not <= %s", this.lhs, this.rhs));
}
ret = { lb: this.lhs, ub: this.rhs };
} else if (this.lhs.toUpperCase() === this.lhs && this.rhs.toUpperCase() === this.rhs) {
if (this.lhs > this.rhs) {
throw new Error(util.format("CharRangeNode: %s not <= %s", this.lhs, this.rhs));
}
ret = { lb: this.lhs, ub: this.rhs };
} else {
throw new Error("Character range must be in the same case (lower or upper)");
}
// console.log("Returning:", ret);
return [ ret ];
},
toNFA: function() {
return NFANodeFromCharList(this.getCharList());
}
}
function SingleChar(ch) {
this.ch = ch;
}
SingleChar.prototype = {
getCharList: function() {
if (this.ch == '.') {
return negateCharList([ { lb: '\n', ub: '\n' } ]);
}
return [ { lb: this.ch, ub: this.ch } ];
},
toNFA: function() {
var charList = this.getCharList();
if (charList.length == 1) {
var lhs = new NFANode();
var rhs = new NFANode();
lhs.on(rhs, this.ch);
return [lhs, rhs];
} else {
return NFANodeFromCharList(charList);
}
}
};
var allChars = [ ];
var wsChars = [ '\n', ' ', '\t', '\0' ];
do {
for (var i = 0; i < 256; ++i) {
allChars.push(String.fromCharCode(i));
}
} while (false);
function charsToCharList(chars) {
var ret = [ ];
var i;
for (i = 0; i < chars.length; ++i) {
ret.push({ lb: chars[i], ub: chars[i] });
}
return ret;
}
function EscapedChar(ch) {
this.ch = ch;
}
EscapedChar.prototype = {
getCharList: function() {
var ret = [];
switch (this.ch) {
case 's':
ret = charsToCharList(wsChars);
break;
case 'S':
ret = negateCharList(charsToCharList(wsChars));
break;
default:
ret = [ { lb: this.ch, ub: this.ch } ];
break;
}
return ret;
},
toNFA: function() {
var charList = this.getCharList();
return NFANodeFromCharList(charList);
}
};
function NegationNode(node) {
this.node = node;
}
NegationNode.prototype = {
toNFA: function() {
var charList = negateCharList(this.node.getCharList());
return NFANodeFromCharList(charList, FLAG_UNIFIED);
}
};
RegExpParser.prototype = {
peek: function() {
return this.expression[this.index];
},
hasMore: function() {
return this.index < this.expLen;
},
nextIs: function(ch) {
return this.hasMore() && this.peek() == ch;
},
get: function() {
return this.expression[this.index++];
},
parse: function() {
this.index = 0;
this.groupNum = 1;
this.error = '';
var parsed = this.regexpTopLevel();
return parsed;
},
regexpTopLevel: function() {
var index = this.index;
var leftAnchored = false;
var rightAnchored = true;
if (this.nextIs('^')) {
leftAnchored = true;
this.get();
}
var node = this.regexp();
if (this.nextIs('$')) {
rightAnchored = true;
this.get();
}
if (this.hasMore()) {
this.error = util.format(
"Premature end of input. Stray '%s' found at index '%d'",
this.peek(),
this.index
);
return null;
}
return new AnchoredNode(node, leftAnchored, rightAnchored);
},
regexp: function() {
var index = this.index;
var node = this.regexpNoUnion();
if (!node) {
this.index = index;
return null;
}
if (this.hasMore()) {
if (this.nextIs('|')) {
this.get();
var node2 = this.regexp();
if (!node2) {
this.index = index;
return null;
}
return new UnionNode(node, node2);
} else {
// Maybe bracketed subexpression or end of RE with a $
// at the end??
return node;
}
} else {
return node;
}
},
regexpNoUnion: function() {
var index = this.index;
var node = this.regexpNoConcat();
if (!node) {
if (!this.hasMore() || this.nextIs('|')) {
return new EmptyNode();
}
this.index = index;
return null;
}
if (this.hasMore()) {
index = this.index;
var node2 = this.regexpNoUnion();
if (!node2 || node2 instanceof EmptyNode) {
return node;
}
return new SequenceNode(node, node2);
} else {
return node;
}
},
regexpNoConcat: function() {
var index = this.index;
var node = this.regexpBasic();
if (!node) {
this.index = index;
return null;
}
var node2 = this.regexpOp();
if (!node2) {
// Getting no ops is perfectly okay. We assume it to be a
// single application of 'node'
return node;
}
return new ApplyOpsNode(node, node2);
},
regexpOp: function() {
if (this.hasMore()) {
var nextToken = this.peek();
var node = null;
switch (nextToken) {
case '*':
this.get();
node = new OpNode('*');
break;
case '+':
this.get();
node = new OpNode('+');
break;
case '?':
this.get();
node = new OpNode('?');
break;
}
if (!node) {
this.error = 'Expected [*+?], Got: [' + nextToken + ']';
return null;
}
var node2 = this.regexpOp();
if (!node2) {
return node;
}
return new SequentialOpsNode(node, node2);
} else {
this.error = 'Expected [*+?], Got: { end of input }';
return null;
}
},
regexpBasic: function() {
var index = this.index;
var nextToken = this.peek();
var node = null;
var parenStartIndex, parenEndIndex;
var groupNum;
switch (nextToken) {
case '[':
this.get();
node = this.charClass();
if (!this.nextIs(']')) {
// Parse error
this.error = "Expcted ']', got '" + this.peek() + "'";
this.index = index;
return null;
}
this.get();
break;
case '(':
parenStartIndex = this.index;
groupNum = this.groupNum++;
this.get();
node = this.regexp();
if (!node) break;
if (!this.nextIs(')')) {
// Parse error
this.error = "Expected ')', got '" + this.peek() + "'";
this.index = index;
return null;
}
parenEndIndex = this.index;
node = new ParenthesizedNode(groupNum,
parenStartIndex,
parenEndIndex,
node);
this.get();
break;
default:
node = this.singleEscapedChar();
if (!node) {
node = this.singleChar();
}
if (!node) {
this.index = index;
return null;
}
}
return node;
},
charClass: function() {
var index = this.index;
var node = null;
var negated = false;
if (this.nextIs('^')) {
this.get();
negated = true;
}
node = this.charRangesOrSingles();
if (!node) {
this.index = index;
return null;
}
if (negated) {
node = new NegationNode(node);
}
return node;
},
charRangesOrSingles: function() {
var index = this.index;
var node = this.charRange();
if (!node) {
node = this.singleEscapedChar();
}
if (!node) {
node = this.singleChar();
}
if (!node) {
this.index = index;
return null;
}
var node2 = this.charRangesOrSingles();
if (node2) {
return new CharListNode(node, node2);
}
return node;
},
charRange: function() {
var index = this.index;
var char1 = this.singleChar();
if (!char1) {
return null;
}
if (!this.nextIs('-')) {
this.index = index;
return null;
}
this.get();
var char2 = this.singleChar();
if (!char2) {
this.index = index;
return null;
}
return new CharRangeNode(char1, char2);
},
singleChar: function() {
var nextToken = this.peek();
var disallowedTokens = "\\()[]|^$";
if (disallowedTokens.indexOf(nextToken) != -1) {
return null;
} else {
return new SingleChar(this.get());
}
},
singleEscapedChar: function() {
var index = this.index;
var nextToken = this.peek();
if (nextToken != '\\') {
this.error = "Expected '\\', Got: '" + nextToken + "'";
return null;
}
this.get();
if (!this.hasMore()) {
this.error = "Expected { escape character after \\ }, Got: { end of input }";
this.index = index;
return null;
}
return new EscapedChar(this.get());
}
};
function RegExpNFA(expression) {
this.parser = new RegExpParser(expression);
this.nfa = null;
}
function processNode(node, nodeNum) {
if (node.id != -2) {
return nodeNum;
}
node.id = nodeNum++;
var children = node.getAllTransitionNodes(); // Object.keys(node.transitions);
children.forEach(function(n) {
nodeNum = processNode(n, nodeNum);
});
return nodeNum;
}
/**
* Label (assigns numbers) [ids] to nodes in a finite automaton.
*
*/
function labelNodes(nfa, nodeNum) {
var keys;
nodeNum = processNode(nfa[0], nodeNum);
nodeNum = processNode(nfa[1], nodeNum);
return nodeNum;
}
function resetIndexes(node) {
var q = [ node ];
var top;
while (q.length != 0) {
top = q.shift();
top.index = -2;
// Process child nodes
var children = top.getAllTransitionNodes();
children.forEach(function(n) {
if (!n.hasOwnProperty('index') || n.index != -2) {
n.index = -2;
q.push(n);
}
});
} // while (q.length != 0)
}
RegExpNFA.prototype = {
toNFA: function() {
var parsed = this.parser.parse();
this.nfa = parsed.toNFA();
labelNodes(this.nfa, 1);
this.nfa[1].isFinal = true;
return this.nfa;
},
toDot: function(attrs) {
var nfa = this.toNFA();
resetIndexes(nfa[0]);
var q = [ nfa[0] ];
var dot = [ 'digraph NFA {' ];
var dotAttrs = [ ];
for (var attr in attrs) {
dotAttrs.push(util.format('%s=%s', attr, attrs[attr]));
}
if (dotAttrs.length > 0) {
dot.push(util.format(' %s', dotAttrs.join(', ')));
}
while (q.length != 0) {
var top = q.shift();
top.index = 1;
if (top.isFinal) {
dot.push(util.format(' %s[style=bold]', top.id));
}
var transitions = top.getAllTransitions();
transitions.forEach(function(tr) {
var keyRange = tr.key;
var nodes = tr.nodes;
var label = toPrettyKey(keyRange);
if (top.isCaptureStart()) {
label = util.format("%s[%s (]", label, top.groupNum);
} else if (top.isCaptureEnd()) {
label = util.format("%s[%s )]", label, top.groupNum);
}
nodes.forEach(function(n) {
dot.push(util.format(' %s -> %s[label=" %s"]',
top.id, n.id, label));
if (n.index == -2) {
n.index = 1;
q.push(n);
}
});
});
} // while (q.length != 0)
dot.push('}');
return dot.join('\n');
}
};
/**
* Holds information about a sub-match capture and indicates the range
* of input that matched that capture.
*
* The actual index in the input is [start+1..end] if start != end. If
* start == end, then the capture is an empty match.
*
*/
function CaptureRange(start, end) {
this.start = start;
this.end = end;
}
CaptureRange.prototype = {
clone: function() {
return new CaptureRange(this.start, this.end);
}
}
function leftmostLongest(cr1, cr2) {
// console.log("COMPARING:", cr1, cr2);
if (cr1.start == cr2.start) {
if (cr2.end > cr1.end) {
return 2;
} else {
return 1;
}
} else {
if (cr2.end < cr1.end) {
return 2;
} else {
return 1;
}
}
}
/**
* Add 'node' to the queue and expands all epsilon transitions
* originating from 'node'. It the applies recursively the same
* operation on all the expanded nodes.
*
* 'addedNodes' is a map that indicates whether the node
* 'node' has already been added to the queue 'q'.
*
* This function recursively expands all epsilon transitions till it
* can not expand any more or all nodes have been added.
*
*/
function addNode(node, q, addedNodes, strIndex) {
if (addedNodes[node.id]) {
return;
}
// console.log(util.format("addNode(%d): captures:", node.id, node.captures));
addedNodes[node.id] = node;
q.push(node)
if (!node.hasTransitionOn(epsilon)) {
return;
}
var tr = node.getTransitionsOn(epsilon);
var i, n, nn;
for (i = 0; i < tr.length; ++i) {
n = tr[i];
// console.log(util.format("Expanding node# %d", n.id));
nn = n.clone(node.captures);
if (node.isCaptureStart()) {
// console.log("setting captures[", node.groupNum, "] to a valid object");
nn.captures[node.groupNum] = new CaptureRange(strIndex, -1);
} else if (node.isCaptureEnd()) {
// console.log("node.groupNum:", node.groupNum, "node.id:", node.id);
// console.log("nn.captures:", nn.captures);
assert(nn.captures[node.groupNum].start <= strIndex);
nn.captures[node.groupNum].end = strIndex;
}
addNode(nn, q, addedNodes, strIndex);
}
}
function cloneCaptures(captures) {
var newCaptures = [];
for (j = 0; j < captures.length; ++j) {
if (captures[j]) {
newCaptures[j] = captures[j].clone();
}
}
return newCaptures;
}
function addCaptures(captures, addedNodes, strIndex, flags) {
var i, j, node;
for (i = 0; i < addedNodes.length; ++i) {
node = addedNodes[i];
if (!(node && node.isFinal)) {
continue;
}
// console.log("Len capTures:", node.captures.length);
if (flags & FLAG_CAPTURE_ALL) {
captures.push(cloneCaptures(node.captures));
} else {
if ((captures.length > 0 &&
(leftmostLongest(captures[0][0], node.captures[0]) == 2)) ||
(captures.length === 0)) {
if (captures.length > 0) {
// console.log("Existing captures:", captures);
}
// console.log("Before cloning. Captures:", node.captures);
captures[0] = cloneCaptures(node.captures);
}
}
}
}
/**
* Searches string 'str' using automation 'nfa' using Thompson's
* searching algorithm by maintaining 2 queues.
*
* Since we also support sub-match captures, the actual running time