forked from mozilla/rhino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NativeRegExp.java
2943 lines (2753 loc) · 116 KB
/
NativeRegExp.java
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
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.regexp;
import java.io.Serializable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.IdFunctionObject;
import org.mozilla.javascript.IdScriptableObject;
import org.mozilla.javascript.Kit;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Symbol;
import org.mozilla.javascript.SymbolKey;
import org.mozilla.javascript.TopLevel;
import org.mozilla.javascript.Undefined;
/**
* This class implements the RegExp native object.
*
* <p>Revision History: Implementation in C by Brendan Eich Initial port to Java by Norris Boyd from
* jsregexp.c version 1.36 Merged up to version 1.38, which included Unicode support. Merged bug
* fixes in version 1.39. Merged JSFUN13_BRANCH changes up to 1.32.2.13
*
* @author Brendan Eich
* @author Norris Boyd
*/
public class NativeRegExp extends IdScriptableObject {
private static final long serialVersionUID = 4965263491464903264L;
private static final Object REGEXP_TAG = new Object();
public static final int JSREG_GLOB = 0x1; // 'g' flag: global
public static final int JSREG_FOLD = 0x2; // 'i' flag: fold
public static final int JSREG_MULTILINE = 0x4; // 'm' flag: multiline
// type of match to perform
public static final int TEST = 0;
public static final int MATCH = 1;
public static final int PREFIX = 2;
private static final boolean debug = false;
private static final byte REOP_SIMPLE_START = 1; /* start of 'simple opcodes' */
private static final byte REOP_EMPTY = 1; /* match rest of input against rest of r.e. */
private static final byte REOP_BOL = 2; /* beginning of input (or line if multiline) */
private static final byte REOP_EOL = 3; /* end of input (or line if multiline) */
private static final byte REOP_WBDRY = 4; /* match "" at word boundary */
private static final byte REOP_WNONBDRY = 5; /* match "" at word non-boundary */
private static final byte REOP_DOT = 6; /* stands for any character */
private static final byte REOP_DIGIT = 7; /* match a digit char: [0-9] */
private static final byte REOP_NONDIGIT = 8; /* match a non-digit char: [^0-9] */
private static final byte REOP_ALNUM = 9; /* match an alphanumeric char: [0-9a-z_A-Z] */
private static final byte REOP_NONALNUM = 10; /* match a non-alphanumeric char: [^0-9a-z_A-Z] */
private static final byte REOP_SPACE = 11; /* match a whitespace char */
private static final byte REOP_NONSPACE = 12; /* match a non-whitespace char */
private static final byte REOP_BACKREF = 13; /* back-reference (e.g., \1) to a parenthetical */
private static final byte REOP_FLAT = 14; /* match a flat string */
private static final byte REOP_FLAT1 = 15; /* match a single char */
private static final byte REOP_FLATi = 16; /* case-independent REOP_FLAT */
private static final byte REOP_FLAT1i = 17; /* case-independent REOP_FLAT1 */
private static final byte REOP_UCFLAT1 = 18; /* single Unicode char */
private static final byte REOP_UCFLAT1i = 19; /* case-independent REOP_UCFLAT1 */
// private static final byte REOP_UCFLAT = 20; /* flat Unicode string; len immediate
// counts chars */
// private static final byte REOP_UCFLATi = 21; /* case-independent REOP_UCFLAT */
private static final byte REOP_CLASS = 22; /* character class with index */
private static final byte REOP_NCLASS = 23; /* negated character class with index */
private static final byte REOP_SIMPLE_END = 23; /* end of 'simple opcodes' */
private static final byte REOP_QUANT = 25; /* quantified atom: atom{1,2} */
private static final byte REOP_STAR = 26; /* zero or more occurrences of kid */
private static final byte REOP_PLUS = 27; /* one or more occurrences of kid */
private static final byte REOP_OPT = 28; /* optional subexpression in kid */
private static final byte REOP_LPAREN =
29; /* left paren bytecode: kid is u.num'th sub-regexp */
private static final byte REOP_RPAREN = 30; /* right paren bytecode */
private static final byte REOP_ALT = 31; /* alternative subexpressions in kid and next */
private static final byte REOP_JUMP = 32; /* for deoptimized closure loops */
// private static final byte REOP_DOTSTAR = 33; /* optimize .* to use a single opcode
// */
// private static final byte REOP_ANCHOR = 34; /* like .* but skips left context to
// unanchored r.e. */
// private static final byte REOP_EOLONLY = 35; /* $ not preceded by any pattern */
// private static final byte REOP_BACKREFi = 37; /* case-independent REOP_BACKREF */
// private static final byte REOP_LPARENNON = 40; /* non-capturing version of REOP_LPAREN
// */
private static final byte REOP_ASSERT = 41; /* zero width positive lookahead assertion */
private static final byte REOP_ASSERT_NOT = 42; /* zero width negative lookahead assertion */
private static final byte REOP_ASSERTTEST = 43; /* sentinel at end of assertion child */
private static final byte REOP_ASSERTNOTTEST = 44; /* sentinel at end of !assertion child */
private static final byte REOP_MINIMALSTAR = 45; /* non-greedy version of * */
private static final byte REOP_MINIMALPLUS = 46; /* non-greedy version of + */
private static final byte REOP_MINIMALOPT = 47; /* non-greedy version of ? */
private static final byte REOP_MINIMALQUANT = 48; /* non-greedy version of {} */
private static final byte REOP_ENDCHILD = 49; /* sentinel at end of quantifier child */
private static final byte REOP_REPEAT = 51; /* directs execution of greedy quantifier */
private static final byte REOP_MINIMALREPEAT =
52; /* directs execution of non-greedy quantifier */
private static final byte REOP_ALTPREREQ = 53; /* prerequisite for ALT, either of two chars */
private static final byte REOP_ALTPREREQi = 54; /* case-independent REOP_ALTPREREQ */
private static final byte REOP_ALTPREREQ2 = 55; /* prerequisite for ALT, a char or a class */
// private static final byte REOP_ENDALT = 56; /* end of final alternate */
private static final byte REOP_END = 57;
private static final int ANCHOR_BOL = -2;
public static void init(Context cx, Scriptable scope, boolean sealed) {
NativeRegExp proto = NativeRegExpInstantiator.withLanguageVersion(cx.getLanguageVersion());
proto.re = compileRE(cx, "", null, false);
proto.activatePrototypeMap(MAX_PROTOTYPE_ID);
proto.setParentScope(scope);
proto.setPrototype(getObjectPrototype(scope));
NativeRegExpCtor ctor = new NativeRegExpCtor();
// Bug #324006: ECMA-262 15.10.6.1 says "The initial value of
// RegExp.prototype.constructor is the builtin RegExp constructor."
proto.defineProperty("constructor", ctor, ScriptableObject.DONTENUM);
ScriptRuntime.setFunctionProtoAndParent(ctor, scope);
ctor.setImmunePrototypeProperty(proto);
if (sealed) {
proto.sealObject();
ctor.sealObject();
}
defineProperty(scope, "RegExp", ctor, ScriptableObject.DONTENUM);
}
NativeRegExp(Scriptable scope, RECompiled regexpCompiled) {
this.re = regexpCompiled;
setLastIndex(ScriptRuntime.zeroObj);
ScriptRuntime.setBuiltinProtoAndParent(this, scope, TopLevel.Builtins.RegExp);
}
@Override
public String getClassName() {
return "RegExp";
}
/**
* Gets the value to be returned by the typeof operator called on this object.
*
* @see org.mozilla.javascript.ScriptableObject#getTypeOf()
* @return "object"
*/
@Override
public String getTypeOf() {
return "object";
}
Scriptable compile(Context cx, Scriptable scope, Object[] args) {
if (args.length > 0 && args[0] instanceof NativeRegExp) {
if (args.length > 1 && args[1] != Undefined.instance) {
// report error
throw ScriptRuntime.typeErrorById("msg.bad.regexp.compile");
}
NativeRegExp thatObj = (NativeRegExp) args[0];
this.re = thatObj.re;
setLastIndex(thatObj.lastIndex);
return this;
}
String s = args.length == 0 || args[0] instanceof Undefined ? "" : escapeRegExp(args[0]);
String global =
args.length > 1 && args[1] != Undefined.instance
? ScriptRuntime.toString(args[1])
: null;
this.re = compileRE(cx, s, global, false);
setLastIndex(ScriptRuntime.zeroObj);
return this;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append('/');
if (re.source.length != 0) {
buf.append(re.source);
} else {
// See bugzilla 226045
buf.append("(?:)");
}
buf.append('/');
if ((re.flags & JSREG_GLOB) != 0) buf.append('g');
if ((re.flags & JSREG_FOLD) != 0) buf.append('i');
if ((re.flags & JSREG_MULTILINE) != 0) buf.append('m');
return buf.toString();
}
NativeRegExp() {}
private static RegExpImpl getImpl(Context cx) {
return (RegExpImpl) ScriptRuntime.getRegExpProxy(cx);
}
private static String escapeRegExp(Object src) {
String s = ScriptRuntime.toString(src);
// Escape any naked slashes in regexp source, see bug #510265
StringBuilder sb = null; // instantiated only if necessary
int start = 0;
int slash = s.indexOf('/');
while (slash > -1) {
if (slash == start || s.charAt(slash - 1) != '\\') {
if (sb == null) {
sb = new StringBuilder();
}
sb.append(s, start, slash);
sb.append("\\/");
start = slash + 1;
}
slash = s.indexOf('/', slash + 1);
}
if (sb != null) {
sb.append(s, start, s.length());
s = sb.toString();
}
return s;
}
Object execSub(Context cx, Scriptable scopeObj, Object[] args, int matchType) {
RegExpImpl reImpl = getImpl(cx);
String str;
if (args.length == 0) {
str = reImpl.input;
if (str == null) {
str = ScriptRuntime.toString(Undefined.instance);
}
} else {
str = ScriptRuntime.toString(args[0]);
}
double d = 0;
if ((re.flags & JSREG_GLOB) != 0) {
d = ScriptRuntime.toInteger(lastIndex);
}
Object rval;
if (d < 0 || str.length() < d) {
setLastIndex(ScriptRuntime.zeroObj);
rval = null;
} else {
int indexp[] = {(int) d};
rval = executeRegExp(cx, scopeObj, reImpl, str, indexp, matchType);
if ((re.flags & JSREG_GLOB) != 0) {
if (rval == null || rval == Undefined.instance) {
setLastIndex(ScriptRuntime.zeroObj);
} else {
setLastIndex(Double.valueOf(indexp[0]));
}
}
}
return rval;
}
static RECompiled compileRE(Context cx, String str, String global, boolean flat) {
RECompiled regexp = new RECompiled(str);
int length = str.length();
int flags = 0;
if (global != null) {
for (int i = 0; i < global.length(); i++) {
char c = global.charAt(i);
int f = 0;
if (c == 'g') {
f = JSREG_GLOB;
} else if (c == 'i') {
f = JSREG_FOLD;
} else if (c == 'm') {
f = JSREG_MULTILINE;
} else {
reportError("msg.invalid.re.flag", String.valueOf(c));
}
if ((flags & f) != 0) {
reportError("msg.invalid.re.flag", String.valueOf(c));
}
flags |= f;
}
}
regexp.flags = flags;
CompilerState state = new CompilerState(cx, regexp.source, length, flags);
if (flat && length > 0) {
if (debug) {
System.out.println("flat = \"" + str + "\"");
}
state.result = new RENode(REOP_FLAT);
state.result.chr = state.cpbegin[0];
state.result.length = length;
state.result.flatIndex = 0;
state.progLength += 5;
} else {
if (!parseDisjunction(state)) return null;
// Need to reparse if pattern contains invalid backreferences:
// "Note: if the number of left parentheses is less than the number
// specified in \#, the \# is taken as an octal escape"
if (state.maxBackReference > state.parenCount) {
state = new CompilerState(cx, regexp.source, length, flags);
state.backReferenceLimit = state.parenCount;
if (!parseDisjunction(state)) return null;
}
}
regexp.program = new byte[state.progLength + 1];
if (state.classCount != 0) {
regexp.classList = new RECharSet[state.classCount];
regexp.classCount = state.classCount;
}
int endPC = emitREBytecode(state, regexp, 0, state.result);
regexp.program[endPC++] = REOP_END;
if (debug) {
System.out.println("Prog. length = " + endPC);
for (int i = 0; i < endPC; i++) {
System.out.print(regexp.program[i]);
if (i < (endPC - 1)) System.out.print(", ");
}
System.out.println();
}
regexp.parenCount = state.parenCount;
// If re starts with literal, init anchorCh accordingly
switch (regexp.program[0]) {
case REOP_UCFLAT1:
case REOP_UCFLAT1i:
regexp.anchorCh = (char) getIndex(regexp.program, 1);
break;
case REOP_FLAT1:
case REOP_FLAT1i:
regexp.anchorCh = (char) (regexp.program[1] & 0xFF);
break;
case REOP_FLAT:
case REOP_FLATi:
int k = getIndex(regexp.program, 1);
regexp.anchorCh = regexp.source[k];
break;
case REOP_BOL:
regexp.anchorCh = ANCHOR_BOL;
break;
case REOP_ALT:
RENode n = state.result;
if (n.kid.op == REOP_BOL && n.kid2.op == REOP_BOL) {
regexp.anchorCh = ANCHOR_BOL;
}
break;
}
if (debug) {
if (regexp.anchorCh >= 0) {
System.out.println("Anchor ch = '" + (char) regexp.anchorCh + "'");
}
}
return regexp;
}
static boolean isDigit(char c) {
return '0' <= c && c <= '9';
}
private static boolean isWord(char c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || isDigit(c) || c == '_';
}
private static boolean isControlLetter(char c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
}
private static boolean isLineTerm(char c) {
return ScriptRuntime.isJSLineTerminator(c);
}
private static boolean isREWhiteSpace(int c) {
return ScriptRuntime.isJSWhitespaceOrLineTerminator(c);
}
/*
*
* 1. If IgnoreCase is false, return ch.
* 2. Let u be ch converted to upper case as if by calling
* String.prototype.toUpperCase on the one-character string ch.
* 3. If u does not consist of a single character, return ch.
* 4. Let cu be u's character.
* 5. If ch's code point value is greater than or equal to decimal 128 and cu's
* code point value is less than decimal 128, then return ch.
* 6. Return cu.
*/
private static char upcase(char ch) {
if (ch < 128) {
if ('a' <= ch && ch <= 'z') {
return (char) (ch + ('A' - 'a'));
}
return ch;
}
char cu = Character.toUpperCase(ch);
return (cu < 128) ? ch : cu;
}
private static char downcase(char ch) {
if (ch < 128) {
if ('A' <= ch && ch <= 'Z') {
return (char) (ch + ('a' - 'A'));
}
return ch;
}
char cl = Character.toLowerCase(ch);
return (cl < 128) ? ch : cl;
}
/*
* Validates and converts hex ascii value.
*/
private static int toASCIIHexDigit(int c) {
if (c < '0') return -1;
if (c <= '9') {
return c - '0';
}
c |= 0x20;
if ('a' <= c && c <= 'f') {
return c - 'a' + 10;
}
return -1;
}
/*
* Top-down regular expression grammar, based closely on Perl4.
*
* regexp: altern A regular expression is one or more
* altern '|' regexp alternatives separated by vertical bar.
*/
private static boolean parseDisjunction(CompilerState state) {
if (!parseAlternative(state)) return false;
char[] source = state.cpbegin;
int index = state.cp;
if (index != source.length && source[index] == '|') {
RENode result;
++state.cp;
result = new RENode(REOP_ALT);
result.kid = state.result;
if (!parseDisjunction(state)) return false;
result.kid2 = state.result;
state.result = result;
/*
* Look at both alternates to see if there's a FLAT or a CLASS at
* the start of each. If so, use a prerequisite match.
*/
if (result.kid.op == REOP_FLAT && result.kid2.op == REOP_FLAT) {
result.op = (state.flags & JSREG_FOLD) == 0 ? REOP_ALTPREREQ : REOP_ALTPREREQi;
result.chr = result.kid.chr;
result.index = result.kid2.chr;
/* ALTPREREQ, uch1, uch2, <next>, ...,
JUMP, <end> ... JUMP, <end> */
state.progLength += 13;
} else if (result.kid.op == REOP_CLASS
&& result.kid.index < 256
&& result.kid2.op == REOP_FLAT
&& (state.flags & JSREG_FOLD) == 0) {
result.op = REOP_ALTPREREQ2;
result.chr = result.kid2.chr;
result.index = result.kid.index;
/* ALTPREREQ2, uch1, uch2, <next>, ...,
JUMP, <end> ... JUMP, <end> */
state.progLength += 13;
} else if (result.kid.op == REOP_FLAT
&& result.kid2.op == REOP_CLASS
&& result.kid2.index < 256
&& (state.flags & JSREG_FOLD) == 0) {
result.op = REOP_ALTPREREQ2;
result.chr = result.kid.chr;
result.index = result.kid2.index;
/* ALTPREREQ2, uch1, uch2, <next>, ...,
JUMP, <end> ... JUMP, <end> */
state.progLength += 13;
} else {
/* ALT, <next>, ..., JUMP, <end> ... JUMP, <end> */
state.progLength += 9;
}
}
return true;
}
/*
* altern: item An alternative is one or more items,
* item altern concatenated together.
*/
private static boolean parseAlternative(CompilerState state) {
RENode headTerm = null;
RENode tailTerm = null;
char[] source = state.cpbegin;
while (true) {
if (state.cp == state.cpend
|| source[state.cp] == '|'
|| (state.parenNesting != 0 && source[state.cp] == ')')) {
if (headTerm == null) {
state.result = new RENode(REOP_EMPTY);
} else state.result = headTerm;
return true;
}
if (!parseTerm(state)) return false;
if (headTerm == null) {
headTerm = state.result;
tailTerm = headTerm;
} else tailTerm.next = state.result;
while (tailTerm.next != null) tailTerm = tailTerm.next;
}
}
/* calculate the total size of the bitmap required for a class expression */
private static boolean calculateBitmapSize(
CompilerState state, RENode target, char[] src, int index, int end) {
char rangeStart = 0;
char c;
int n;
int nDigits;
int i;
int max = 0;
boolean inRange = false;
target.bmsize = 0;
target.sense = true;
if (index == end) return true;
if (src[index] == '^') {
++index;
target.sense = false;
}
while (index != end) {
int localMax = 0;
nDigits = 2;
switch (src[index]) {
case '\\':
++index;
c = src[index++];
switch (c) {
case 'b':
localMax = 0x8;
break;
case 'f':
localMax = 0xC;
break;
case 'n':
localMax = 0xA;
break;
case 'r':
localMax = 0xD;
break;
case 't':
localMax = 0x9;
break;
case 'v':
localMax = 0xB;
break;
case 'c':
if ((index < end) && isControlLetter(src[index]))
localMax = (char) (src[index++] & 0x1F);
else --index;
localMax = '\\';
break;
case 'u':
nDigits += 2;
// fall through
case 'x':
n = 0;
for (i = 0; (i < nDigits) && (index < end); i++) {
c = src[index++];
n = Kit.xDigitToInt(c, n);
if (n < 0) {
// Back off to accepting the original
// '\' as a literal
index -= (i + 1);
n = '\\';
break;
}
}
localMax = n;
break;
case 'd':
if (inRange) {
target.bmsize = 65536;
return true;
}
localMax = '9';
break;
case 'D':
case 'w':
case 'W':
case 'S':
case 's':
target.bmsize = 65536;
return true;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
/*
* This is a non-ECMA extension - decimal escapes (in this
* case, octal!) are supposed to be an error inside class
* ranges, but supported here for backwards compatibility.
*
*/
n = (c - '0');
c = src[index];
if ('0' <= c && c <= '7') {
index++;
n = 8 * n + (c - '0');
c = src[index];
if ('0' <= c && c <= '7') {
index++;
i = 8 * n + (c - '0');
if (i <= 0377) n = i;
else index--;
}
}
localMax = n;
break;
default:
localMax = c;
break;
}
break;
default:
localMax = src[index++];
break;
}
if (inRange) {
if (rangeStart > localMax) {
reportError("msg.bad.range", "");
return false;
}
inRange = false;
} else {
if (index < (end - 1)) {
if (src[index] == '-') {
++index;
inRange = true;
rangeStart = (char) localMax;
continue;
}
}
}
if ((state.flags & JSREG_FOLD) != 0) {
char cu = upcase((char) localMax);
char cd = downcase((char) localMax);
localMax = (cu >= cd) ? cu : cd;
}
if (localMax > max) max = localMax;
}
target.bmsize = max + 1;
return true;
}
/*
* item: assertion An item is either an assertion or
* quantatom a quantified atom.
*
* assertion: '^' Assertions match beginning of string
* (or line if the class static property
* RegExp.multiline is true).
* '$' End of string (or line if the class
* static property RegExp.multiline is
* true).
* '\b' Word boundary (between \w and \W).
* '\B' Word non-boundary.
*
* quantatom: atom An unquantified atom.
* quantatom '{' n ',' m '}'
* Atom must occur between n and m times.
* quantatom '{' n ',' '}' Atom must occur at least n times.
* quantatom '{' n '}' Atom must occur exactly n times.
* quantatom '*' Zero or more times (same as {0,}).
* quantatom '+' One or more times (same as {1,}).
* quantatom '?' Zero or one time (same as {0,1}).
*
* any of which can be optionally followed by '?' for ungreedy
*
* atom: '(' regexp ')' A parenthesized regexp (what matched
* can be addressed using a backreference,
* see '\' n below).
* '.' Matches any char except '\n'.
* '[' classlist ']' A character class.
* '[' '^' classlist ']' A negated character class.
* '\f' Form Feed.
* '\n' Newline (Line Feed).
* '\r' Carriage Return.
* '\t' Horizontal Tab.
* '\v' Vertical Tab.
* '\d' A digit (same as [0-9]).
* '\D' A non-digit.
* '\w' A word character, [0-9a-z_A-Z].
* '\W' A non-word character.
* '\s' A whitespace character, [ \b\f\n\r\t\v].
* '\S' A non-whitespace character.
* '\' n A backreference to the nth (n decimal
* and positive) parenthesized expression.
* '\' octal An octal escape sequence (octal must be
* two or three digits long, unless it is
* 0 for the null character).
* '\x' hex A hex escape (hex must be two digits).
* '\c' ctrl A control character, ctrl is a letter.
* '\' literalatomchar Any character except one of the above
* that follow '\' in an atom.
* otheratomchar Any character not first among the other
* atom right-hand sides.
*/
private static void doFlat(CompilerState state, char c) {
state.result = new RENode(REOP_FLAT);
state.result.chr = c;
state.result.length = 1;
state.result.flatIndex = -1;
state.progLength += 3;
}
private static int getDecimalValue(
char c, CompilerState state, int maxValue, String overflowMessageId) {
boolean overflow = false;
int start = state.cp;
char[] src = state.cpbegin;
int value = c - '0';
for (; state.cp != state.cpend; ++state.cp) {
c = src[state.cp];
if (!isDigit(c)) {
break;
}
if (!overflow) {
int v = value * 10 + (c - '0');
if (v < maxValue) {
value = v;
} else {
overflow = true;
value = maxValue;
}
}
}
if (overflow) {
reportError(overflowMessageId, String.valueOf(src, start, state.cp - start));
}
return value;
}
private static boolean parseTerm(CompilerState state) {
char[] src = state.cpbegin;
char c = src[state.cp++];
int nDigits = 2;
int parenBaseCount = state.parenCount;
int num;
RENode term;
int termStart;
switch (c) {
/* assertions and atoms */
case '^':
state.result = new RENode(REOP_BOL);
state.progLength++;
return true;
case '$':
state.result = new RENode(REOP_EOL);
state.progLength++;
return true;
case '\\':
if (state.cp < state.cpend) {
c = src[state.cp++];
switch (c) {
/* assertion escapes */
case 'b':
state.result = new RENode(REOP_WBDRY);
state.progLength++;
return true;
case 'B':
state.result = new RENode(REOP_WNONBDRY);
state.progLength++;
return true;
/* Decimal escape */
case '0':
/*
* We're deliberately violating the ECMA 5.1 specification and allow octal
* escapes to follow spidermonkey and general 'web reality':
* http://wiki.ecmascript.org/doku.php?id=harmony:regexp_match_web_reality
* http://wiki.ecmascript.org/doku.php?id=strawman:match_web_reality_spec
*/
reportWarning(state.cx, "msg.bad.backref", "");
/* octal escape */
num = 0;
// follow spidermonkey and allow multiple leading zeros,
// e.g. let /\0000/ match the string "\0"
while (num < 040 && state.cp < state.cpend) {
c = src[state.cp];
if ((c >= '0') && (c <= '7')) {
state.cp++;
num = 8 * num + (c - '0');
} else break;
}
c = (char) (num);
doFlat(state, c);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
termStart = state.cp - 1;
num = getDecimalValue(c, state, 0xFFFF, "msg.overlarge.backref");
if (num > state.backReferenceLimit)
reportWarning(state.cx, "msg.bad.backref", "");
/*
* n > count of parentheses, then treat as octal instead.
* Also see note above concerning 'web reality'
*/
if (num > state.backReferenceLimit) {
state.cp = termStart;
if (c >= '8') {
// invalid octal escape, follow spidermonkey and
// treat as \\8 resp. \\9
c = '\\';
doFlat(state, c);
break;
}
state.cp++;
num = c - '0';
while (num < 040 && state.cp < state.cpend) {
c = src[state.cp];
if ((c >= '0') && (c <= '7')) {
state.cp++;
num = 8 * num + (c - '0');
} else break;
}
c = (char) (num);
doFlat(state, c);
break;
}
/* otherwise, it's a back-reference */
state.result = new RENode(REOP_BACKREF);
state.result.parenIndex = num - 1;
state.progLength += 3;
if (state.maxBackReference < num) {
state.maxBackReference = num;
}
break;
/* Control escape */
case 'f':
c = 0xC;
doFlat(state, c);
break;
case 'n':
c = 0xA;
doFlat(state, c);
break;
case 'r':
c = 0xD;
doFlat(state, c);
break;
case 't':
c = 0x9;
doFlat(state, c);
break;
case 'v':
c = 0xB;
doFlat(state, c);
break;
/* Control letter */
case 'c':
if ((state.cp < state.cpend) && isControlLetter(src[state.cp]))
c = (char) (src[state.cp++] & 0x1F);
else {
/* back off to accepting the original '\' as a literal */
--state.cp;
c = '\\';
}
doFlat(state, c);
break;
/* UnicodeEscapeSequence */
case 'u':
nDigits += 2;
/* fall through */ case 'x': /* HexEscapeSequence */
{
int n = 0;
int i;
for (i = 0; (i < nDigits) && (state.cp < state.cpend); i++) {
c = src[state.cp++];
n = Kit.xDigitToInt(c, n);
if (n < 0) {
// Back off to accepting the original
// 'u' or 'x' as a literal
state.cp -= (i + 2);
n = src[state.cp++];
break;
}
}
c = (char) (n);
}
doFlat(state, c);
break;
/* Character class escapes */
case 'd':
state.result = new RENode(REOP_DIGIT);
state.progLength++;
break;
case 'D':
state.result = new RENode(REOP_NONDIGIT);
state.progLength++;
break;
case 's':
state.result = new RENode(REOP_SPACE);
state.progLength++;
break;
case 'S':
state.result = new RENode(REOP_NONSPACE);
state.progLength++;
break;
case 'w':
state.result = new RENode(REOP_ALNUM);
state.progLength++;
break;
case 'W':
state.result = new RENode(REOP_NONALNUM);
state.progLength++;
break;
/* IdentityEscape */
default:
state.result = new RENode(REOP_FLAT);
state.result.chr = c;
state.result.length = 1;
state.result.flatIndex = state.cp - 1;
state.progLength += 3;
break;
}
break;
}
/* a trailing '\' is an error */
reportError("msg.trail.backslash", "");
return false;
case '(':
{
RENode result = null;
termStart = state.cp;
if (state.cp + 1 < state.cpend
&& src[state.cp] == '?'
&& ((c = src[state.cp + 1]) == '=' || c == '!' || c == ':')) {
state.cp += 2;
if (c == '=') {
result = new RENode(REOP_ASSERT);
/* ASSERT, <next>, ... ASSERTTEST */
state.progLength += 4;
} else if (c == '!') {
result = new RENode(REOP_ASSERT_NOT);
/* ASSERTNOT, <next>, ... ASSERTNOTTEST */
state.progLength += 4;
}
} else {
result = new RENode(REOP_LPAREN);
/* LPAREN, <index>, ... RPAREN, <index> */
state.progLength += 6;
result.parenIndex = state.parenCount++;
}
++state.parenNesting;
if (!parseDisjunction(state)) return false;
if (state.cp == state.cpend || src[state.cp] != ')') {
reportError("msg.unterm.paren", "");
return false;
}
++state.cp;
--state.parenNesting;
if (result != null) {
result.kid = state.result;
state.result = result;
}
break;
}
case ')':
reportError("msg.re.unmatched.right.paren", "");
return false;
case '[':
state.result = new RENode(REOP_CLASS);
termStart = state.cp;
state.result.startIndex = termStart;
while (true) {
if (state.cp == state.cpend) {
reportError("msg.unterm.class", "");
return false;
}
if (src[state.cp] == '\\') state.cp++;
else {
if (src[state.cp] == ']') {
state.result.kidlen = state.cp - termStart;
break;
}