mirrored from https://chromium.googlesource.com/v8/v8.git
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
regexp.js
1248 lines (1085 loc) · 40.4 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
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function(global, utils) {
'use strict';
%CheckIsBootstrapping();
// -------------------------------------------------------------------
// Imports
var AddIndexedProperty;
var ExpandReplacement;
var GlobalArray = global.Array;
var GlobalObject = global.Object;
var GlobalRegExp = global.RegExp;
var GlobalRegExpPrototype;
var InternalArray = utils.InternalArray;
var InternalPackedArray = utils.InternalPackedArray;
var MakeTypeError;
var MaxSimple;
var MinSimple;
var matchSymbol = utils.ImportNow("match_symbol");
var replaceSymbol = utils.ImportNow("replace_symbol");
var searchSymbol = utils.ImportNow("search_symbol");
var splitSymbol = utils.ImportNow("split_symbol");
var SpeciesConstructor;
utils.Import(function(from) {
AddIndexedProperty = from.AddIndexedProperty;
ExpandReplacement = from.ExpandReplacement;
MakeTypeError = from.MakeTypeError;
MaxSimple = from.MaxSimple;
MinSimple = from.MinSimple;
SpeciesConstructor = from.SpeciesConstructor;
});
// -------------------------------------------------------------------
// Property of the builtins object for recording the result of the last
// regexp match. The property RegExpLastMatchInfo includes the matchIndices
// array of the last successful regexp match (an array of start/end index
// pairs for the match and all the captured substrings), the invariant is
// that there are at least two capture indeces. The array also contains
// the subject string for the last successful match.
var RegExpLastMatchInfo = new InternalPackedArray(
2, // REGEXP_NUMBER_OF_CAPTURES
"", // Last subject.
UNDEFINED, // Last input - settable with RegExpSetInput.
0, // REGEXP_FIRST_CAPTURE + 0
0 // REGEXP_FIRST_CAPTURE + 1
);
// -------------------------------------------------------------------
// ES#sec-isregexp IsRegExp ( argument )
function IsRegExp(o) {
if (!IS_RECEIVER(o)) return false;
var is_regexp = o[matchSymbol];
if (!IS_UNDEFINED(is_regexp)) return TO_BOOLEAN(is_regexp);
return IS_REGEXP(o);
}
// ES#sec-regexpinitialize
// Runtime Semantics: RegExpInitialize ( obj, pattern, flags )
function RegExpInitialize(object, pattern, flags) {
pattern = IS_UNDEFINED(pattern) ? '' : TO_STRING(pattern);
flags = IS_UNDEFINED(flags) ? '' : TO_STRING(flags);
%RegExpInitializeAndCompile(object, pattern, flags);
return object;
}
function PatternFlags(pattern) {
return (REGEXP_GLOBAL(pattern) ? 'g' : '') +
(REGEXP_IGNORE_CASE(pattern) ? 'i' : '') +
(REGEXP_MULTILINE(pattern) ? 'm' : '') +
(REGEXP_UNICODE(pattern) ? 'u' : '') +
(REGEXP_STICKY(pattern) ? 'y' : '');
}
// ES#sec-regexp-pattern-flags
// RegExp ( pattern, flags )
function RegExpConstructor(pattern, flags) {
var newtarget = new.target;
var pattern_is_regexp = IsRegExp(pattern);
if (IS_UNDEFINED(newtarget)) {
newtarget = GlobalRegExp;
// ES6 section 21.2.3.1 step 3.b
if (pattern_is_regexp && IS_UNDEFINED(flags) &&
pattern.constructor === newtarget) {
return pattern;
}
}
if (IS_REGEXP(pattern)) {
if (IS_UNDEFINED(flags)) flags = PatternFlags(pattern);
pattern = REGEXP_SOURCE(pattern);
} else if (pattern_is_regexp) {
var input_pattern = pattern;
pattern = pattern.source;
if (IS_UNDEFINED(flags)) flags = input_pattern.flags;
}
var object = %_NewObject(GlobalRegExp, newtarget);
return RegExpInitialize(object, pattern, flags);
}
// ES#sec-regexp.prototype.compile RegExp.prototype.compile (pattern, flags)
function RegExpCompileJS(pattern, flags) {
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.compile", this);
}
if (IS_REGEXP(pattern)) {
if (!IS_UNDEFINED(flags)) throw MakeTypeError(kRegExpFlags);
flags = PatternFlags(pattern);
pattern = REGEXP_SOURCE(pattern);
}
RegExpInitialize(this, pattern, flags);
// Return undefined for compatibility with JSC.
// See http://crbug.com/585775 for web compat details.
}
function DoRegExpExec(regexp, string, index) {
return %_RegExpExec(regexp, string, index, RegExpLastMatchInfo);
}
// This is kind of performance sensitive, so we want to avoid unnecessary
// type checks on inputs. But we also don't want to inline it several times
// manually, so we use a macro :-)
macro RETURN_NEW_RESULT_FROM_MATCH_INFO(MATCHINFO, STRING)
var numResults = NUMBER_OF_CAPTURES(MATCHINFO) >> 1;
var start = MATCHINFO[CAPTURE0];
var end = MATCHINFO[CAPTURE1];
// Calculate the substring of the first match before creating the result array
// to avoid an unnecessary write barrier storing the first result.
var first = %_SubString(STRING, start, end);
var result = %_RegExpConstructResult(numResults, start, STRING);
result[0] = first;
if (numResults == 1) return result;
var j = REGEXP_FIRST_CAPTURE + 2;
for (var i = 1; i < numResults; i++) {
start = MATCHINFO[j++];
if (start != -1) {
end = MATCHINFO[j];
result[i] = %_SubString(STRING, start, end);
}
j++;
}
return result;
endmacro
function RegExpExecNoTests(regexp, string, start) {
// Must be called with RegExp, string and positive integer as arguments.
var matchInfo = %_RegExpExec(regexp, string, start, RegExpLastMatchInfo);
if (matchInfo !== null) {
// ES6 21.2.5.2.2 step 18.
if (REGEXP_STICKY(regexp)) regexp.lastIndex = matchInfo[CAPTURE1];
RETURN_NEW_RESULT_FROM_MATCH_INFO(matchInfo, string);
}
regexp.lastIndex = 0;
return null;
}
// ES#sec-regexp.prototype.exec
// RegExp.prototype.exec ( string )
function RegExpSubclassExecJS(string) {
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
'RegExp.prototype.exec', this);
}
string = TO_STRING(string);
var lastIndex = this.lastIndex;
// Conversion is required by the ES2015 specification (RegExpBuiltinExec
// algorithm, step 4) even if the value is discarded for non-global RegExps.
var i = TO_LENGTH(lastIndex);
var global = TO_BOOLEAN(REGEXP_GLOBAL(this));
var sticky = TO_BOOLEAN(REGEXP_STICKY(this));
var updateLastIndex = global || sticky;
if (updateLastIndex) {
if (i > string.length) {
this.lastIndex = 0;
return null;
}
} else {
i = 0;
}
// matchIndices is either null or the RegExpLastMatchInfo array.
// TODO(littledan): Whether a RegExp is sticky is compiled into the RegExp
// itself, but ES2015 allows monkey-patching this property to differ from
// the internal flags. If it differs, recompile a different RegExp?
var matchIndices = %_RegExpExec(this, string, i, RegExpLastMatchInfo);
if (IS_NULL(matchIndices)) {
this.lastIndex = 0;
return null;
}
// Successful match.
if (updateLastIndex) {
this.lastIndex = RegExpLastMatchInfo[CAPTURE1];
}
RETURN_NEW_RESULT_FROM_MATCH_INFO(matchIndices, string);
}
%FunctionRemovePrototype(RegExpSubclassExecJS);
// Legacy implementation of RegExp.prototype.exec
function RegExpExecJS(string) {
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
'RegExp.prototype.exec', this);
}
string = TO_STRING(string);
var lastIndex = this.lastIndex;
// Conversion is required by the ES2015 specification (RegExpBuiltinExec
// algorithm, step 4) even if the value is discarded for non-global RegExps.
var i = TO_LENGTH(lastIndex);
var updateLastIndex = REGEXP_GLOBAL(this) || REGEXP_STICKY(this);
if (updateLastIndex) {
if (i < 0 || i > string.length) {
this.lastIndex = 0;
return null;
}
} else {
i = 0;
}
// matchIndices is either null or the RegExpLastMatchInfo array.
var matchIndices = %_RegExpExec(this, string, i, RegExpLastMatchInfo);
if (IS_NULL(matchIndices)) {
this.lastIndex = 0;
return null;
}
// Successful match.
if (updateLastIndex) {
this.lastIndex = RegExpLastMatchInfo[CAPTURE1];
}
RETURN_NEW_RESULT_FROM_MATCH_INFO(matchIndices, string);
}
// ES#sec-regexpexec Runtime Semantics: RegExpExec ( R, S )
// Also takes an optional exec method in case our caller
// has already fetched exec.
function RegExpSubclassExec(regexp, string, exec) {
if (IS_UNDEFINED(exec)) {
exec = regexp.exec;
}
if (IS_CALLABLE(exec)) {
var result = %_Call(exec, regexp, string);
if (!IS_RECEIVER(result) && !IS_NULL(result)) {
throw MakeTypeError(kInvalidRegExpExecResult);
}
return result;
}
return %_Call(RegExpExecJS, regexp, string);
}
%SetForceInlineFlag(RegExpSubclassExec);
// One-element cache for the simplified test regexp.
var regexp_key;
var regexp_val;
// Legacy implementation of RegExp.prototype.test
// Section 15.10.6.3 doesn't actually make sense, but the intention seems to be
// that test is defined in terms of String.prototype.exec. However, it probably
// means the original value of String.prototype.exec, which is what everybody
// else implements.
function RegExpTest(string) {
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
'RegExp.prototype.test', this);
}
string = TO_STRING(string);
var lastIndex = this.lastIndex;
// Conversion is required by the ES2015 specification (RegExpBuiltinExec
// algorithm, step 4) even if the value is discarded for non-global RegExps.
var i = TO_LENGTH(lastIndex);
if (REGEXP_GLOBAL(this) || REGEXP_STICKY(this)) {
if (i < 0 || i > string.length) {
this.lastIndex = 0;
return false;
}
// matchIndices is either null or the RegExpLastMatchInfo array.
var matchIndices = %_RegExpExec(this, string, i, RegExpLastMatchInfo);
if (IS_NULL(matchIndices)) {
this.lastIndex = 0;
return false;
}
this.lastIndex = RegExpLastMatchInfo[CAPTURE1];
return true;
} else {
// Non-global, non-sticky regexp.
// Remove irrelevant preceeding '.*' in a test regexp. The expression
// checks whether this.source starts with '.*' and that the third char is
// not a '?'. But see https://code.google.com/p/v8/issues/detail?id=3560
var regexp = this;
var source = REGEXP_SOURCE(regexp);
if (regexp.length >= 3 &&
%_StringCharCodeAt(regexp, 0) == 46 && // '.'
%_StringCharCodeAt(regexp, 1) == 42 && // '*'
%_StringCharCodeAt(regexp, 2) != 63) { // '?'
regexp = TrimRegExp(regexp);
}
// matchIndices is either null or the RegExpLastMatchInfo array.
var matchIndices = %_RegExpExec(regexp, string, 0, RegExpLastMatchInfo);
if (IS_NULL(matchIndices)) {
this.lastIndex = 0;
return false;
}
return true;
}
}
// ES#sec-regexp.prototype.test RegExp.prototype.test ( S )
function RegExpSubclassTest(string) {
if (!IS_RECEIVER(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
'RegExp.prototype.test', this);
}
string = TO_STRING(string);
var match = RegExpSubclassExec(this, string);
return !IS_NULL(match);
}
%FunctionRemovePrototype(RegExpSubclassTest);
function TrimRegExp(regexp) {
if (regexp_key !== regexp) {
regexp_key = regexp;
regexp_val =
new GlobalRegExp(
%_SubString(REGEXP_SOURCE(regexp), 2, REGEXP_SOURCE(regexp).length),
(REGEXP_IGNORE_CASE(regexp) ? REGEXP_MULTILINE(regexp) ? "im" : "i"
: REGEXP_MULTILINE(regexp) ? "m" : ""));
}
return regexp_val;
}
function RegExpToString() {
if (!IS_RECEIVER(this)) {
throw MakeTypeError(
kIncompatibleMethodReceiver, 'RegExp.prototype.toString', this);
}
if (this === GlobalRegExpPrototype) {
%IncrementUseCounter(kRegExpPrototypeToString);
}
return '/' + TO_STRING(this.source) + '/' + TO_STRING(this.flags);
}
function AtSurrogatePair(subject, index) {
if (index + 1 >= subject.length) return false;
var first = %_StringCharCodeAt(subject, index);
if (first < 0xD800 || first > 0xDBFF) return false;
var second = %_StringCharCodeAt(subject, index + 1);
return second >= 0xDC00 || second <= 0xDFFF;
}
// Legacy implementation of RegExp.prototype[Symbol.split] which
// doesn't properly call the underlying exec, @@species methods
function RegExpSplit(string, limit) {
// TODO(yangguo): allow non-regexp receivers.
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@split", this);
}
var separator = this;
var subject = TO_STRING(string);
limit = (IS_UNDEFINED(limit)) ? kMaxUint32 : TO_UINT32(limit);
var length = subject.length;
if (limit === 0) return [];
if (length === 0) {
if (DoRegExpExec(separator, subject, 0, 0) !== null) return [];
return [subject];
}
var currentIndex = 0;
var startIndex = 0;
var startMatch = 0;
var result = new InternalArray();
outer_loop:
while (true) {
if (startIndex === length) {
result[result.length] = %_SubString(subject, currentIndex, length);
break;
}
var matchInfo = DoRegExpExec(separator, subject, startIndex);
if (matchInfo === null || length === (startMatch = matchInfo[CAPTURE0])) {
result[result.length] = %_SubString(subject, currentIndex, length);
break;
}
var endIndex = matchInfo[CAPTURE1];
// We ignore a zero-length match at the currentIndex.
if (startIndex === endIndex && endIndex === currentIndex) {
if (REGEXP_UNICODE(this) && AtSurrogatePair(subject, startIndex)) {
startIndex += 2;
} else {
startIndex++;
}
continue;
}
result[result.length] = %_SubString(subject, currentIndex, startMatch);
if (result.length === limit) break;
var matchinfo_len = NUMBER_OF_CAPTURES(matchInfo) + REGEXP_FIRST_CAPTURE;
for (var i = REGEXP_FIRST_CAPTURE + 2; i < matchinfo_len; ) {
var start = matchInfo[i++];
var end = matchInfo[i++];
if (end != -1) {
result[result.length] = %_SubString(subject, start, end);
} else {
result[result.length] = UNDEFINED;
}
if (result.length === limit) break outer_loop;
}
startIndex = currentIndex = endIndex;
}
var array_result = [];
%MoveArrayContents(result, array_result);
return array_result;
}
// ES#sec-regexp.prototype-@@split
// RegExp.prototype [ @@split ] ( string, limit )
function RegExpSubclassSplit(string, limit) {
if (!IS_RECEIVER(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@split", this);
}
string = TO_STRING(string);
var constructor = SpeciesConstructor(this, GlobalRegExp);
var flags = TO_STRING(this.flags);
// TODO(adamk): this fast path is wrong with respect to this.global
// and this.sticky, but hopefully the spec will remove those gets
// and thus make the assumption of 'exec' having no side-effects
// more correct. Also, we doesn't ensure that 'exec' is actually
// a data property on RegExp.prototype.
var exec;
if (IS_REGEXP(this) && constructor === GlobalRegExp) {
exec = this.exec;
if (exec === RegExpSubclassExecJS) {
return %_Call(RegExpSplit, this, string, limit);
}
}
var unicode = %StringIndexOf(flags, 'u', 0) >= 0;
var sticky = %StringIndexOf(flags, 'y', 0) >= 0;
var newFlags = sticky ? flags : flags + "y";
var splitter = new constructor(this, newFlags);
var array = new GlobalArray();
var arrayIndex = 0;
var lim = (IS_UNDEFINED(limit)) ? kMaxUint32 : TO_UINT32(limit);
var size = string.length;
var prevStringIndex = 0;
if (lim === 0) return array;
var result;
if (size === 0) {
result = RegExpSubclassExec(splitter, string);
if (IS_NULL(result)) AddIndexedProperty(array, 0, string);
return array;
}
var stringIndex = prevStringIndex;
while (stringIndex < size) {
splitter.lastIndex = stringIndex;
result = RegExpSubclassExec(splitter, string, exec);
// Ensure exec will be read again on the next loop through.
exec = UNDEFINED;
if (IS_NULL(result)) {
stringIndex += AdvanceStringIndex(string, stringIndex, unicode);
} else {
var end = MinSimple(TO_LENGTH(splitter.lastIndex), size);
if (end === stringIndex) {
stringIndex += AdvanceStringIndex(string, stringIndex, unicode);
} else {
AddIndexedProperty(
array, arrayIndex,
%_SubString(string, prevStringIndex, stringIndex));
arrayIndex++;
if (arrayIndex === lim) return array;
prevStringIndex = end;
var numberOfCaptures = MaxSimple(TO_LENGTH(result.length), 0);
for (var i = 1; i < numberOfCaptures; i++) {
AddIndexedProperty(array, arrayIndex, result[i]);
arrayIndex++;
if (arrayIndex === lim) return array;
}
stringIndex = prevStringIndex;
}
}
}
AddIndexedProperty(array, arrayIndex,
%_SubString(string, prevStringIndex, size));
return array;
}
%FunctionRemovePrototype(RegExpSubclassSplit);
// Legacy implementation of RegExp.prototype[Symbol.match] which
// doesn't properly call the underlying exec method
function RegExpMatch(string) {
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@match", this);
}
var subject = TO_STRING(string);
if (!REGEXP_GLOBAL(this)) return RegExpExecNoTests(this, subject, 0);
this.lastIndex = 0;
var result = %StringMatch(subject, this, RegExpLastMatchInfo);
return result;
}
// ES#sec-regexp.prototype-@@match
// RegExp.prototype [ @@match ] ( string )
function RegExpSubclassMatch(string) {
if (!IS_RECEIVER(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@match", this);
}
string = TO_STRING(string);
var global = this.global;
if (!global) return RegExpSubclassExec(this, string);
var unicode = this.unicode;
this.lastIndex = 0;
var array = new InternalArray();
var n = 0;
var result;
while (true) {
result = RegExpSubclassExec(this, string);
if (IS_NULL(result)) {
if (n === 0) return null;
break;
}
var matchStr = TO_STRING(result[0]);
array[n] = matchStr;
if (matchStr === "") SetAdvancedStringIndex(this, string, unicode);
n++;
}
var resultArray = [];
%MoveArrayContents(array, resultArray);
return resultArray;
}
%FunctionRemovePrototype(RegExpSubclassMatch);
// Legacy implementation of RegExp.prototype[Symbol.replace] which
// doesn't properly call the underlying exec method.
// TODO(lrn): This array will survive indefinitely if replace is never
// called again. However, it will be empty, since the contents are cleared
// in the finally block.
var reusableReplaceArray = new InternalArray(4);
// Helper function for replacing regular expressions with the result of a
// function application in String.prototype.replace.
function StringReplaceGlobalRegExpWithFunction(subject, regexp, replace) {
var resultArray = reusableReplaceArray;
if (resultArray) {
reusableReplaceArray = null;
} else {
// Inside a nested replace (replace called from the replacement function
// of another replace) or we have failed to set the reusable array
// back due to an exception in a replacement function. Create a new
// array to use in the future, or until the original is written back.
resultArray = new InternalArray(16);
}
var res = %RegExpExecMultiple(regexp,
subject,
RegExpLastMatchInfo,
resultArray);
regexp.lastIndex = 0;
if (IS_NULL(res)) {
// No matches at all.
reusableReplaceArray = resultArray;
return subject;
}
var len = res.length;
if (NUMBER_OF_CAPTURES(RegExpLastMatchInfo) == 2) {
// If the number of captures is two then there are no explicit captures in
// the regexp, just the implicit capture that captures the whole match. In
// this case we can simplify quite a bit and end up with something faster.
// The builder will consist of some integers that indicate slices of the
// input string and some replacements that were returned from the replace
// function.
var match_start = 0;
for (var i = 0; i < len; i++) {
var elem = res[i];
if (%_IsSmi(elem)) {
// Integers represent slices of the original string.
if (elem > 0) {
match_start = (elem >> 11) + (elem & 0x7ff);
} else {
match_start = res[++i] - elem;
}
} else {
var func_result = replace(elem, match_start, subject);
// Overwrite the i'th element in the results with the string we got
// back from the callback function.
res[i] = TO_STRING(func_result);
match_start += elem.length;
}
}
} else {
for (var i = 0; i < len; i++) {
var elem = res[i];
if (!%_IsSmi(elem)) {
// elem must be an Array.
// Use the apply argument as backing for global RegExp properties.
var func_result = %reflect_apply(replace, UNDEFINED, elem);
// Overwrite the i'th element in the results with the string we got
// back from the callback function.
res[i] = TO_STRING(func_result);
}
}
}
var result = %StringBuilderConcat(res, len, subject);
resultArray.length = 0;
reusableReplaceArray = resultArray;
return result;
}
// Compute the string of a given regular expression capture.
function CaptureString(string, lastCaptureInfo, index) {
// Scale the index.
var scaled = index << 1;
// Compute start and end.
var start = lastCaptureInfo[CAPTURE(scaled)];
// If start isn't valid, return undefined.
if (start < 0) return;
var end = lastCaptureInfo[CAPTURE(scaled + 1)];
return %_SubString(string, start, end);
}
function StringReplaceNonGlobalRegExpWithFunction(subject, regexp, replace) {
var matchInfo = DoRegExpExec(regexp, subject, 0);
if (IS_NULL(matchInfo)) {
regexp.lastIndex = 0;
return subject;
}
var index = matchInfo[CAPTURE0];
var result = %_SubString(subject, 0, index);
var endOfMatch = matchInfo[CAPTURE1];
// Compute the parameter list consisting of the match, captures, index,
// and subject for the replace function invocation.
// The number of captures plus one for the match.
var m = NUMBER_OF_CAPTURES(matchInfo) >> 1;
var replacement;
if (m == 1) {
// No captures, only the match, which is always valid.
var s = %_SubString(subject, index, endOfMatch);
// Don't call directly to avoid exposing the built-in global object.
replacement = replace(s, index, subject);
} else {
var parameters = new InternalArray(m + 2);
for (var j = 0; j < m; j++) {
parameters[j] = CaptureString(subject, matchInfo, j);
}
parameters[j] = index;
parameters[j + 1] = subject;
replacement = %reflect_apply(replace, UNDEFINED, parameters);
}
result += replacement; // The add method converts to string if necessary.
// Can't use matchInfo any more from here, since the function could
// overwrite it.
return result + %_SubString(subject, endOfMatch, subject.length);
}
function RegExpReplace(string, replace) {
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@replace", this);
}
var subject = TO_STRING(string);
var search = this;
if (!IS_CALLABLE(replace)) {
replace = TO_STRING(replace);
if (!REGEXP_GLOBAL(search)) {
// Non-global regexp search, string replace.
var match = DoRegExpExec(search, subject, 0);
if (match == null) {
search.lastIndex = 0
return subject;
}
if (replace.length == 0) {
return %_SubString(subject, 0, match[CAPTURE0]) +
%_SubString(subject, match[CAPTURE1], subject.length)
}
return ExpandReplacement(replace, subject, RegExpLastMatchInfo,
%_SubString(subject, 0, match[CAPTURE0])) +
%_SubString(subject, match[CAPTURE1], subject.length);
}
// Global regexp search, string replace.
search.lastIndex = 0;
return %StringReplaceGlobalRegExpWithString(
subject, search, replace, RegExpLastMatchInfo);
}
if (REGEXP_GLOBAL(search)) {
// Global regexp search, function replace.
return StringReplaceGlobalRegExpWithFunction(subject, search, replace);
}
// Non-global regexp search, function replace.
return StringReplaceNonGlobalRegExpWithFunction(subject, search, replace);
}
// ES#sec-getsubstitution
// GetSubstitution(matched, str, position, captures, replacement)
// Expand the $-expressions in the string and return a new string with
// the result.
// TODO(littledan): Call this function from String.prototype.replace instead
// of the very similar ExpandReplacement in src/js/string.js
function GetSubstitution(matched, string, position, captures, replacement) {
var matchLength = matched.length;
var stringLength = string.length;
var capturesLength = captures.length;
var tailPos = position + matchLength;
var result = "";
var pos, expansion, peek, next, scaledIndex, advance, newScaledIndex;
var next = %StringIndexOf(replacement, '$', 0);
if (next < 0) {
result += replacement;
return result;
}
if (next > 0) result += %_SubString(replacement, 0, next);
while (true) {
expansion = '$';
pos = next + 1;
if (pos < replacement.length) {
peek = %_StringCharCodeAt(replacement, pos);
if (peek == 36) { // $$
++pos;
result += '$';
} else if (peek == 38) { // $& - match
++pos;
result += matched;
} else if (peek == 96) { // $` - prefix
++pos;
result += %_SubString(string, 0, position);
} else if (peek == 39) { // $' - suffix
++pos;
result += %_SubString(string, tailPos, stringLength);
} else if (peek >= 48 && peek <= 57) {
// Valid indices are $1 .. $9, $01 .. $09 and $10 .. $99
scaledIndex = (peek - 48);
advance = 1;
if (pos + 1 < replacement.length) {
next = %_StringCharCodeAt(replacement, pos + 1);
if (next >= 48 && next <= 57) {
newScaledIndex = scaledIndex * 10 + ((next - 48));
if (newScaledIndex < capturesLength) {
scaledIndex = newScaledIndex;
advance = 2;
}
}
}
if (scaledIndex != 0 && scaledIndex < capturesLength) {
var capture = captures[scaledIndex];
if (!IS_UNDEFINED(capture)) result += capture;
pos += advance;
} else {
result += '$';
}
} else {
result += '$';
}
} else {
result += '$';
}
// Go the the next $ in the replacement.
next = %StringIndexOf(replacement, '$', pos);
// Return if there are no more $ characters in the replacement. If we
// haven't reached the end, we need to append the suffix.
if (next < 0) {
if (pos < replacement.length) {
result += %_SubString(replacement, pos, replacement.length);
}
return result;
}
// Append substring between the previous and the next $ character.
if (next > pos) {
result += %_SubString(replacement, pos, next);
}
}
return result;
}
// ES#sec-advancestringindex
// AdvanceStringIndex ( S, index, unicode )
function AdvanceStringIndex(string, index, unicode) {
var increment = 1;
if (unicode) {
var first = %_StringCharCodeAt(string, index);
if (first >= 0xD800 && first <= 0xDBFF && string.length > index + 1) {
var second = %_StringCharCodeAt(string, index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
increment = 2;
}
}
}
return increment;
}
function SetAdvancedStringIndex(regexp, string, unicode) {
var lastIndex = regexp.lastIndex;
regexp.lastIndex = lastIndex +
AdvanceStringIndex(string, lastIndex, unicode);
}
// ES#sec-regexp.prototype-@@replace
// RegExp.prototype [ @@replace ] ( string, replaceValue )
function RegExpSubclassReplace(string, replace) {
if (!IS_RECEIVER(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@replace", this);
}
string = TO_STRING(string);
var length = string.length;
var functionalReplace = IS_CALLABLE(replace);
if (!functionalReplace) replace = TO_STRING(replace);
var global = TO_BOOLEAN(this.global);
if (global) {
var unicode = TO_BOOLEAN(this.unicode);
this.lastIndex = 0;
}
// TODO(adamk): this fast path is wrong with respect to this.global
// and this.sticky, but hopefully the spec will remove those gets
// and thus make the assumption of 'exec' having no side-effects
// more correct. Also, we doesn't ensure that 'exec' is actually
// a data property on RegExp.prototype, nor does the fast path
// correctly handle lastIndex setting.
var exec;
if (IS_REGEXP(this)) {
exec = this.exec;
if (exec === RegExpSubclassExecJS) {
return %_Call(RegExpReplace, this, string, replace);
}
}
var results = new InternalArray();
var result, replacement;
while (true) {
result = RegExpSubclassExec(this, string, exec);
// Ensure exec will be read again on the next loop through.
exec = UNDEFINED;
if (IS_NULL(result)) {
break;
} else {
results.push(result);
if (!global) break;
var matchStr = TO_STRING(result[0]);
if (matchStr === "") SetAdvancedStringIndex(this, string, unicode);
}
}
var accumulatedResult = "";
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var capturesLength = MaxSimple(TO_LENGTH(result.length), 0);
var matched = TO_STRING(result[0]);
var matchedLength = matched.length;
var position = MaxSimple(MinSimple(TO_INTEGER(result.index), length), 0);
var captures = new InternalArray();
for (var n = 0; n < capturesLength; n++) {
var capture = result[n];
if (!IS_UNDEFINED(capture)) capture = TO_STRING(capture);
captures[n] = capture;
}
if (functionalReplace) {
var parameters = new InternalArray(capturesLength + 2);
for (var j = 0; j < capturesLength; j++) {
parameters[j] = captures[j];
}
parameters[j] = position;
parameters[j + 1] = string;
replacement = %reflect_apply(replace, UNDEFINED, parameters, 0,
parameters.length);
} else {
replacement = GetSubstitution(matched, string, position, captures,
replace);
}
if (position >= nextSourcePosition) {
accumulatedResult +=
%_SubString(string, nextSourcePosition, position) + replacement;
nextSourcePosition = position + matchedLength;
}
}
if (nextSourcePosition >= length) return accumulatedResult;
return accumulatedResult + %_SubString(string, nextSourcePosition, length);
}
%FunctionRemovePrototype(RegExpSubclassReplace);
// Legacy implementation of RegExp.prototype[Symbol.search] which
// doesn't properly use the overridden exec method
function RegExpSearch(string) {
if (!IS_REGEXP(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@search", this);
}
var match = DoRegExpExec(this, TO_STRING(string), 0);
if (match) return match[CAPTURE0];
return -1;
}
// ES#sec-regexp.prototype-@@search
// RegExp.prototype [ @@search ] ( string )
function RegExpSubclassSearch(string) {
if (!IS_RECEIVER(this)) {
throw MakeTypeError(kIncompatibleMethodReceiver,
"RegExp.prototype.@@search", this);
}
string = TO_STRING(string);
var previousLastIndex = this.lastIndex;
this.lastIndex = 0;
var result = RegExpSubclassExec(this, string);
this.lastIndex = previousLastIndex;
if (IS_NULL(result)) return -1;
return result.index;
}
%FunctionRemovePrototype(RegExpSubclassSearch);
// Getters for the static properties lastMatch, lastParen, leftContext, and
// rightContext of the RegExp constructor. The properties are computed based
// on the captures array of the last successful match and the subject string
// of the last successful match.
function RegExpGetLastMatch() {
var regExpSubject = LAST_SUBJECT(RegExpLastMatchInfo);
return %_SubString(regExpSubject,
RegExpLastMatchInfo[CAPTURE0],
RegExpLastMatchInfo[CAPTURE1]);
}