forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYarrParser.h
More file actions
2186 lines (1857 loc) · 76.4 KB
/
YarrParser.h
File metadata and controls
2186 lines (1857 loc) · 76.4 KB
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 (C) 2009-2020 Apple Inc. All rights reserved.
* Copyright (C) 2020 Alexey Shvayka <shvaikalesh@gmail.com>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "Yarr.h"
#include "YarrPattern.h"
#include "YarrUnicodeProperties.h"
#include <wtf/ASCIICType.h>
#include <wtf/HashSet.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>
namespace JSC { namespace Yarr {
enum class CreateDisjunctionPurpose : uint8_t { NotForNextAlternative, ForNextAlternative };
enum class CharacterClassSetOp : uint8_t {
Default,
Union,
Intersection,
Subtraction
};
// The Parser class should not be used directly - only via the Yarr::parse() method.
template<class Delegate, typename CharType>
class Parser {
private:
static constexpr char32_t errorCodePoint = 0xFFFFFFFFu;
template<class FriendDelegate>
friend ErrorCode parse(FriendDelegate&, StringView pattern, CompileMode, unsigned backReferenceLimit, bool isNamedForwardReferenceAllowed);
enum class UnicodeParseContext : uint8_t { PatternCodePoint, GroupName };
enum class ParseEscapeMode : uint8_t { Normal, CharacterClass, ClassSet, ClassStringDisjunction };
enum class TokenType : uint8_t {
NotAtom = 0,
Atom = 1,
Lookbehind = 2,
SetDisjunction = 3,
SetDisjunctionMayContainStrings = 4,
};
class NamedCaptureGroups {
typedef HashSet<String> GroupNameHashSet;
public:
NamedCaptureGroups()
{
m_nestedCaptureGroupNames.grow(1);
m_activeCaptureGroupNames.grow(1);
}
bool contains(String name)
{
return m_captureGroupNames.contains(name);
}
bool isEmpty()
{
return m_captureGroupNames.isEmpty();
}
void reset()
{
m_captureGroupNames.clear();
m_nestedCaptureGroupNames.clear();
m_nestedCaptureGroupNames.grow(1);
m_activeCaptureGroupNames.clear();
m_activeCaptureGroupNames.grow(1);
}
void nextAlternative()
{
m_nestedCaptureGroupNames.last().formUnion(m_activeCaptureGroupNames.last());
m_activeCaptureGroupNames.last().clear();
// For nested parenthesis, we need to seed the new alternative with the already seen
// named captures from the containing alternative.
if (m_activeCaptureGroupNames.size() > 1)
m_activeCaptureGroupNames.last().formUnion(m_activeCaptureGroupNames[m_activeCaptureGroupNames.size() - 2]);
}
void pushParenthesis()
{
auto currentTop = m_activeCaptureGroupNames.last();
m_nestedCaptureGroupNames.append(GroupNameHashSet());
m_activeCaptureGroupNames.append(currentTop);
}
void popParenthesis()
{
ASSERT(m_nestedCaptureGroupNames.size() > 1);
ASSERT(m_activeCaptureGroupNames.size() > 1);
m_nestedCaptureGroupNames.last().formUnion(m_activeCaptureGroupNames.last());
// Add all the names seen in this parenthesis to the containing alternative.
m_activeCaptureGroupNames[m_activeCaptureGroupNames.size() - 2].formUnion(m_nestedCaptureGroupNames.last());
m_nestedCaptureGroupNames.removeLast();
m_activeCaptureGroupNames.removeLast();
}
GroupNameHashSet::AddResult add(String name)
{
m_captureGroupNames.add(name);
// If the name is not new, the caller should flag a syntax error.
return m_activeCaptureGroupNames.last().add(name);
}
private:
// Names seen in the whole expression up to this point.
GroupNameHashSet m_captureGroupNames;
// All active names from prior alternatives at this nesting level.
Vector<GroupNameHashSet, 1> m_nestedCaptureGroupNames;
// Names seen in containing disjunction / alternative and the current alternative.
Vector<GroupNameHashSet, 1> m_activeCaptureGroupNames;
};
/*
* CharacterClassParserDelegate:
*
* The class CharacterClassParserDelegate is used in the parsing of character
* classes. This class handles detection of character ranges. This class
* implements enough of the delegate interface such that it can be passed to
* parseEscape() as an EscapeDelegate. This allows parseEscape() to be reused
* to perform the parsing of escape characters in character sets.
*/
class CharacterClassParserDelegate {
public:
CharacterClassParserDelegate(Delegate& delegate, ErrorCode& err, CompileMode compileMode)
: m_delegate(delegate)
, m_errorCode(err)
, m_isUnicode(compileMode == CompileMode::Unicode)
, m_state(CharacterClassConstructionState::Empty)
, m_character(0)
{
}
/*
* begin():
*
* Called at beginning of construction.
*/
void begin(bool invert)
{
m_delegate.atomCharacterClassBegin(invert);
}
/*
* atomPatternCharacter():
*
* This method is called either from parseCharacterClass() (for an unescaped
* character in a character class), or from parseEscape(). In the former case
* the value true will be passed for the argument 'hyphenIsRange', and in this
* mode we will allow a hypen to be treated as indicating a range (i.e. /[a-z]/
* is different to /[a\-z]/).
*/
void atomPatternCharacter(char32_t ch, bool hyphenIsRange = false)
{
switch (m_state) {
case CharacterClassConstructionState::AfterCharacterClass:
// Following a built-in character class we need look out for a hyphen.
// We're looking for invalid ranges, such as /[\d-x]/ or /[\d-\d]/.
// If we see a hyphen following a character class then unlike usual
// we'll report it to the delegate immediately, and put ourself into
// a poisoned state. In a unicode pattern, any following calls to add
// another character or character class will result in syntax error.
// A hypen following a character class is itself valid, but only at
// the end of a regex.
if (hyphenIsRange && ch == '-') {
m_delegate.atomCharacterClassAtom('-');
m_state = CharacterClassConstructionState::AfterCharacterClassHyphen;
return;
}
// Otherwise just fall through - cached character so treat this as CharacterClassConstructionState::Empty.
FALLTHROUGH;
case CharacterClassConstructionState::Empty:
m_character = ch;
m_state = CharacterClassConstructionState::CachedCharacter;
return;
case CharacterClassConstructionState::CachedCharacter:
if (hyphenIsRange && ch == '-')
m_state = CharacterClassConstructionState::CachedCharacterHyphen;
else {
m_delegate.atomCharacterClassAtom(m_character);
m_character = ch;
}
return;
case CharacterClassConstructionState::CachedCharacterHyphen:
if (ch < m_character) {
m_errorCode = ErrorCode::CharacterClassRangeOutOfOrder;
return;
}
m_delegate.atomCharacterClassRange(m_character, ch);
m_state = CharacterClassConstructionState::Empty;
return;
// If we hit this case, we have an invalid range like /[\d-a]/.
// See coment in atomBuiltInCharacterClass() below.
case CharacterClassConstructionState::AfterCharacterClassHyphen:
if (m_isUnicode) {
m_errorCode = ErrorCode::CharacterClassRangeInvalid;
return;
}
m_delegate.atomCharacterClassAtom(ch);
m_state = CharacterClassConstructionState::Empty;
return;
}
}
/*
* atomBuiltInCharacterClass():
*
* Adds a built-in character class, called by parseEscape().
*/
void atomBuiltInCharacterClass(BuiltInCharacterClassID classID, bool invert)
{
switch (m_state) {
case CharacterClassConstructionState::CachedCharacter:
// Flush the currently cached character, then fall through.
m_delegate.atomCharacterClassAtom(m_character);
FALLTHROUGH;
case CharacterClassConstructionState::Empty:
case CharacterClassConstructionState::AfterCharacterClass:
m_delegate.atomCharacterClassBuiltIn(classID, invert);
m_state = CharacterClassConstructionState::AfterCharacterClass;
return;
// If we hit either of these cases, we have an invalid range that
// looks something like /[a-\d]/ or /[\d-\d]/.
// Since ES2015, this should be syntax error in a unicode pattern,
// yet gracefully handled in a regular regex to avoid breaking the web.
// Effectively we handle the hyphen as if it was (implicitly) escaped,
// e.g. /[\d-a-z]/ is treated as /[\d\-a\-z]/.
// See usages of CharacterRangeOrUnion abstract op in
// https://tc39.es/ecma262/#sec-regular-expression-patterns-semantics
case CharacterClassConstructionState::CachedCharacterHyphen:
m_delegate.atomCharacterClassAtom(m_character);
m_delegate.atomCharacterClassAtom('-');
FALLTHROUGH;
case CharacterClassConstructionState::AfterCharacterClassHyphen:
if (m_isUnicode) {
m_errorCode = ErrorCode::CharacterClassRangeInvalid;
return;
}
m_delegate.atomCharacterClassBuiltIn(classID, invert);
m_state = CharacterClassConstructionState::Empty;
return;
}
}
/*
* end():
*
* Called at end of construction.
*/
void end()
{
if (m_state == CharacterClassConstructionState::CachedCharacter)
m_delegate.atomCharacterClassAtom(m_character);
else if (m_state == CharacterClassConstructionState::CachedCharacterHyphen) {
m_delegate.atomCharacterClassAtom(m_character);
m_delegate.atomCharacterClassAtom('-');
}
m_delegate.atomCharacterClassEnd();
}
// parseEscape() should never call these delegate methods when
// invoked with inCharacterClass set.
NO_RETURN_DUE_TO_ASSERT void assertionWordBoundary(bool) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomBackReference(unsigned) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomNamedBackReference(const String&) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomNamedForwardReference(const String&) { RELEASE_ASSERT_NOT_REACHED(); }
private:
Delegate& m_delegate;
ErrorCode& m_errorCode;
bool m_isUnicode;
enum class CharacterClassConstructionState {
Empty,
CachedCharacter,
CachedCharacterHyphen,
AfterCharacterClass,
AfterCharacterClassHyphen,
};
CharacterClassConstructionState m_state;
char32_t m_character;
};
/*
* ClassSetParserDelegate:
*
* The class ClassSetParserDelegate is used in the parsing of class sets
* This class handles detection of class set ops and character ranges.
* This class implements enough of the delegate interface such that it can be passed to
* parseEscape() as an EscapeDelegate. This allows parseEscape() to be reused
* to perform the parsing of escape characters in character sets.
*/
class ClassSetParserDelegate {
private:
struct NestingState {
public:
NestingState(CharacterClassSetOp setOp, bool mayContainStrings, bool inverted)
: m_setOp(setOp)
, m_mayContainStrings(mayContainStrings)
, m_inverted(inverted)
{ }
CharacterClassSetOp m_setOp;
bool m_mayContainStrings;
bool m_inverted;
};
public:
ClassSetParserDelegate(Delegate& delegate, ErrorCode& err)
: m_delegate(delegate)
, m_errorCode(err)
, m_state(ClassSetConstructionState::Empty)
, m_setOp(CharacterClassSetOp::Default)
, m_mayContainStrings(false)
, m_inverted(false)
, m_processingEscape(false)
, m_character(0)
{
}
/*
* begin():
*
* Called at beginning of construction.
*/
void begin(bool invert)
{
m_inverted = invert;
m_delegate.atomCharacterClassBegin(invert);
}
void nestedClassBegin(bool invert)
{
m_delegate.atomCharacterClassPushNested();
nestedParseState.append(NestingState(m_setOp, m_mayContainStrings, m_inverted));
m_setOp = CharacterClassSetOp::Default;
m_mayContainStrings = false;
m_inverted = invert;
}
bool nestedClassEnd()
{
flushCachedCharacterIfNeeded();
if (m_inverted && m_mayContainStrings)
m_errorCode = ErrorCode::NegatedClassSetMayContainStrings;
if (nestedParseState.isEmpty()) {
end();
return true;
}
bool rhsMayContainStrings = m_mayContainStrings;
NestingState lastState = nestedParseState.takeLast();
m_setOp = lastState.m_setOp;
m_inverted = lastState.m_inverted;
m_mayContainStrings = lastState.m_mayContainStrings;
m_delegate.atomCharacterClassPopNested();
m_state = ClassSetConstructionState::AfterSetOperand;
computeMayContainStrings(rhsMayContainStrings);
return false;
}
void setUnionOp()
{
if (m_setOp != CharacterClassSetOp::Default && m_setOp != CharacterClassSetOp::Union) {
m_errorCode = ErrorCode::InvalidClassSetOperation;
return;
}
flushCachedCharacterIfNeeded();
m_setOp = CharacterClassSetOp::Union;
m_delegate.atomCharacterClassSetOp(m_setOp);
}
void switchFromDefaultOpToUnionOpIfNeeded()
{
if (m_setOp == CharacterClassSetOp::Default) {
m_setOp = CharacterClassSetOp::Union;
m_delegate.atomCharacterClassSetOp(m_setOp);
}
}
void setSubtractOp()
{
if (m_state == ClassSetConstructionState::Empty || (m_setOp != CharacterClassSetOp::Default && m_setOp != CharacterClassSetOp::Subtraction)) {
m_errorCode = ErrorCode::InvalidClassSetOperation;
return;
}
flushCachedCharacterIfNeeded();
m_setOp = CharacterClassSetOp::Subtraction;
m_delegate.atomCharacterClassSetOp(m_setOp);
m_state = ClassSetConstructionState::AfterSetOperator;
}
void setIntersectionOp()
{
if (m_state == ClassSetConstructionState::Empty || (m_setOp != CharacterClassSetOp::Default && m_setOp != CharacterClassSetOp::Intersection)) {
m_errorCode = ErrorCode::InvalidClassSetOperation;
return;
}
flushCachedCharacterIfNeeded();
m_setOp = CharacterClassSetOp::Intersection;
m_delegate.atomCharacterClassSetOp(m_setOp);
m_state = ClassSetConstructionState::AfterSetOperator;
}
void computeMayContainStrings(bool rhsMayContainStrings)
{
switch (m_setOp) {
case CharacterClassSetOp::Default:
case CharacterClassSetOp::Union:
m_mayContainStrings |= rhsMayContainStrings;
break;
case CharacterClassSetOp::Intersection:
m_mayContainStrings = m_mayContainStrings && rhsMayContainStrings;
break;
case CharacterClassSetOp::Subtraction:
// Result is the value of the LHS
break;
}
}
void flushCachedCharacterIfNeeded()
{
if (m_state == ClassSetConstructionState::CachedCharacter) {
m_delegate.atomCharacterClassAtom(m_character);
m_state = ClassSetConstructionState::Empty;
}
}
void afterSetOperand()
{
flushCachedCharacterIfNeeded();
m_state = ClassSetConstructionState::AfterSetOperand;
}
bool canTakeSetOperand()
{
bool unionOpActive = m_setOp == CharacterClassSetOp::Default || m_setOp == CharacterClassSetOp::Union;
switch (m_state) {
case ClassSetConstructionState::Empty:
case ClassSetConstructionState::AfterSetOperator:
return true;
case ClassSetConstructionState::CachedCharacter:
if (!unionOpActive)
return false;
flushCachedCharacterIfNeeded();
return true;
case ClassSetConstructionState::CachedCharacterHyphen:
case ClassSetConstructionState::AfterCharacterClassHyphen:
case ClassSetConstructionState::AfterCharacterClass:
case ClassSetConstructionState::AfterSetRange:
case ClassSetConstructionState::AfterSetOperand:
return unionOpActive;
}
return false;
}
void setProcessingEscape()
{
m_processingEscape = true;
}
/*
* atomPatternCharacter():
*
* This method is called either from parseCharacterClass() (for an unescaped
* character in a character class), or from parseEscape(). In the former case
* the value true will be passed for the argument 'hyphenIsRange', and in this
* mode we will allow a hypen to be treated as indicating a range (i.e. /[a-z]/
* is different to /[a\-z]/).
*/
void atomPatternCharacter(char32_t ch)
{
bool unionOpActive = m_setOp == CharacterClassSetOp::Default || m_setOp == CharacterClassSetOp::Union;
bool processingEscape = m_processingEscape;
m_processingEscape = false;
auto processCharacter = [&] () {
m_character = ch;
m_state = ClassSetConstructionState::CachedCharacter;
return;
};
switch (m_state) {
case ClassSetConstructionState::AfterCharacterClass:
// Following a built-in character class we need look out for a hyphen.
// We're looking for invalid ranges, such as /[\d-x]/ or /[\d-\d]/.
// If we see a hyphen following a character class then unlike usual
// we'll report it to the delegate immediately, and put ourself into
// a poisoned state. In a unicode pattern, any following calls to add
// another character or character class will result in syntax error.
// A hypen following a character class is itself valid, but only at
// the end of a regex.
if (unionOpActive && ch == '-') {
m_delegate.atomCharacterClassAtom('-');
m_state = ClassSetConstructionState::AfterCharacterClassHyphen;
return;
}
// Otherwise just fall through - cached character so treat this as ClassSetConstructionState::Empty.
FALLTHROUGH;
case ClassSetConstructionState::AfterSetRange:
switchFromDefaultOpToUnionOpIfNeeded();
// Continue processing the current character.
FALLTHROUGH;
case ClassSetConstructionState::Empty:
case ClassSetConstructionState::AfterSetOperator:
if (!processingEscape && ch == '-') {
m_errorCode = ErrorCode::InvalidClassSetCharacter;
return;
}
processCharacter();
return;
case ClassSetConstructionState::CachedCharacter:
if (!unionOpActive) {
m_errorCode = ErrorCode::InvalidClassSetOperation;
return;
}
if (ch == '-')
m_state = ClassSetConstructionState::CachedCharacterHyphen;
else {
m_delegate.atomCharacterClassAtom(m_character);
switchFromDefaultOpToUnionOpIfNeeded();
processCharacter();
}
return;
case ClassSetConstructionState::CachedCharacterHyphen:
if (ch < m_character) {
m_errorCode = ErrorCode::CharacterClassRangeOutOfOrder;
return;
}
m_delegate.atomCharacterClassRange(m_character, ch);
switchFromDefaultOpToUnionOpIfNeeded();
m_state = ClassSetConstructionState::AfterSetRange;
return;
// If we hit this case, we have an invalid range like /[\d-a]/.
// See coment in atomBuiltInCharacterClass() below.
case ClassSetConstructionState::AfterCharacterClassHyphen:
m_errorCode = ErrorCode::CharacterClassRangeInvalid;
return;
case ClassSetConstructionState::AfterSetOperand:
if (!unionOpActive)
m_errorCode = ErrorCode::InvalidClassSetOperation;
if (ch == '-')
m_errorCode = ErrorCode::InvalidClassSetOperation;
else {
m_delegate.atomCharacterClassAtom(m_character);
switchFromDefaultOpToUnionOpIfNeeded();
processCharacter();
}
return;
}
}
/*
* atomBuiltInCharacterClass():
*
* Adds a built-in character class, called by parseEscape().
*/
void atomBuiltInCharacterClass(BuiltInCharacterClassID classID, bool invert)
{
bool unionOpActive = m_setOp == CharacterClassSetOp::Default || m_setOp == CharacterClassSetOp::Union;
auto processBuiltInCharacterClass = [&] () {
computeMayContainStrings(characterClassMayContainStrings(classID));
m_delegate.atomCharacterClassBuiltIn(classID, invert);
m_state = ClassSetConstructionState::AfterCharacterClass;
return;
};
switch (m_state) {
case ClassSetConstructionState::CachedCharacter:
if (!unionOpActive) {
m_errorCode = ErrorCode::InvalidClassSetOperation;
return;
}
// Flush the currently cached character, then fall through.
m_delegate.atomCharacterClassAtom(m_character);
// Yes, we really want to fall through to the AfterSetRange case to switch from Default to Union op
// and then handle the built in class by falling through again.
FALLTHROUGH;
case ClassSetConstructionState::AfterSetRange:
switchFromDefaultOpToUnionOpIfNeeded();
// Continue processing the current character.
FALLTHROUGH;
case ClassSetConstructionState::Empty:
case ClassSetConstructionState::AfterCharacterClass:
case ClassSetConstructionState::AfterSetOperator:
processBuiltInCharacterClass();
return;
// If we hit either of these cases, we have an invalid range that
// looks something like /[a-\d]/ or /[\d-\d]/.
// Since ES2015, this should be syntax error in a unicode pattern,
// yet gracefully handled in a regular regex to avoid breaking the web.
// Effectively we handle the hyphen as if it was (implicitly) escaped,
// e.g. /[\d-a-z]/ is treated as /[\d\-a\-z]/.
// See usages of CharacterRangeOrUnion abstract op in
// https://tc39.es/ecma262/#sec-regular-expression-patterns-semantics
case ClassSetConstructionState::CachedCharacterHyphen:
m_delegate.atomCharacterClassAtom(m_character);
m_delegate.atomCharacterClassAtom('-');
FALLTHROUGH;
case ClassSetConstructionState::AfterCharacterClassHyphen:
m_errorCode = ErrorCode::CharacterClassRangeInvalid;
return;
case ClassSetConstructionState::AfterSetOperand:
if (!unionOpActive)
m_errorCode = ErrorCode::InvalidClassSetOperation;
processBuiltInCharacterClass();
return;
}
}
/*
* end():
*
* Called at end of construction.
*/
void end()
{
if (m_state == ClassSetConstructionState::CachedCharacter)
m_delegate.atomCharacterClassAtom(m_character);
else if (m_state == ClassSetConstructionState::CachedCharacterHyphen) {
m_delegate.atomCharacterClassAtom(m_character);
m_delegate.atomCharacterClassAtom('-');
} else if (m_state == ClassSetConstructionState::AfterSetOperator)
m_errorCode = ErrorCode::InvalidClassSetCharacter;
if (isInverted() && m_mayContainStrings)
m_errorCode = ErrorCode::NegatedClassSetMayContainStrings;
m_delegate.atomCharacterClassEnd();
}
bool isInverted() { return m_inverted; }
ErrorCode error() { return m_errorCode; }
// parseEscape() should never call these delegate methods when
// invoked with inCharacterClass set.
NO_RETURN_DUE_TO_ASSERT void assertionWordBoundary(bool) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomBackReference(unsigned) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomNamedBackReference(const String&) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomNamedForwardReference(const String&) { RELEASE_ASSERT_NOT_REACHED(); }
private:
Delegate& m_delegate;
ErrorCode& m_errorCode;
enum class ClassSetConstructionState {
Empty,
CachedCharacter,
CachedCharacterHyphen,
AfterCharacterClass,
AfterCharacterClassHyphen,
AfterSetRange,
AfterSetOperand,
AfterSetOperator,
};
ClassSetConstructionState m_state;
CharacterClassSetOp m_setOp;
bool m_mayContainStrings;
bool m_inverted;
bool m_processingEscape;
char32_t m_character;
Vector<NestingState> nestedParseState;
};
/*
* ClassStringDisjunctionParserDelegate:
*
* The class ClassStringDisjunctionParserDelegate is used in the parsing of class string disjunctions,
* e.g \q{...}. This class builds strings from the alternatives and passes them on to
* character class delegate.
*/
class ClassStringDisjunctionParserDelegate {
public:
ClassStringDisjunctionParserDelegate(Delegate& delegate, ErrorCode& err)
: m_delegate(delegate)
, m_mayContainStrings(false)
, m_errorCode(err)
{
}
void atomPatternCharacter(char32_t ch, bool = false)
{
m_stringInProgress.append(ch);
if (m_stringInProgress.size() > 1)
m_mayContainStrings = true;
}
void newAlternative()
{
m_strings.append(m_stringInProgress);
m_stringInProgress.clear();
}
/*
* end():
*
* Called at end of construction.
*/
void end()
{
newAlternative();
m_delegate.atomClassStringDisjunction(m_strings);
}
bool mayContainStrings() { return m_mayContainStrings; }
// parseEscape() should never call these delegate methods when parsing a class string disjunction.
NO_RETURN_DUE_TO_ASSERT void assertionWordBoundary(bool) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomBackReference(unsigned) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomNamedBackReference(const String&) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomNamedForwardReference(const String&) { RELEASE_ASSERT_NOT_REACHED(); }
NO_RETURN_DUE_TO_ASSERT void atomBuiltInCharacterClass(BuiltInCharacterClassID, bool) { RELEASE_ASSERT_NOT_REACHED(); }
private:
Delegate& m_delegate;
bool m_mayContainStrings;
ErrorCode& m_errorCode;
Vector<char32_t> m_stringInProgress;
Vector<Vector<char32_t>> m_strings;
};
Parser(Delegate& delegate, StringView pattern, CompileMode compileMode, unsigned backReferenceLimit, bool isNamedForwardReferenceAllowed)
: m_delegate(delegate)
, m_data(pattern.span<CharType>().data())
, m_size(pattern.length())
, m_compileMode(compileMode)
, m_backReferenceLimit(backReferenceLimit)
, m_isNamedForwardReferenceAllowed(isNamedForwardReferenceAllowed)
{
}
// The handling of IdentityEscapes is different depending on which unicode flag if any is active.
// For both Unicode and UnicodeSet patterns, IdentityEscapes only include SyntaxCharacters or '/'.
// For UnicodeSet patterns when parsing ClassSet expressions and ClassStringDisjunctions, escapes include SyntaxCharacters, '/'
// and ClassSetReservedPunctionation, which is any of &-!#%,:;<=>@`~
// For non-unicode patterns, most any character can be escaped.
template<ParseEscapeMode parseEscapeMode>
bool isIdentityEscapeAnError(char32_t ch)
{
if (isEitherUnicodeCompilation()
&& ((isASCII(ch) && !strchr((parseEscapeMode == ParseEscapeMode::ClassSet || parseEscapeMode == ParseEscapeMode::ClassStringDisjunction) ? "^$\\.*+?()[]{}|/&-!#%,:;<=>@`~" : "^$\\.*+?()[]{}|/", ch)) || !ch)) {
m_errorCode = ErrorCode::InvalidIdentityEscape;
return true;
}
return false;
}
/*
* parseEscape():
*
* Helper for parseTokens(), parseAtomEscape(), parseCharacterClassEscape(),
* parseClassSetEscape() and parseClassStringDisjunctionEscape().
*
* Unlike the other parser methods, this function does not report tokens
* directly to the member delegate (m_delegate), instead tokens are
* emitted to the delegate provided as an argument. In the case of atom
* escapes, parseTokens() will call parseEscape() passing m_delegate as
* an argument, and as such the escape will be reported to the delegate.
*
* However this method may also be used by parseCharacterClass(), parseClassSet(), or
* parseClassStringDisjunctionEscape() in which case a CharacterClassParserDelegate,
* ClassSetParserDelegate or ClassStringDisjunctionParserDelegate respectively will be
* passed as the delegate that tokens should be added to. Delegate should have the
* following methods:
*
* Required methods:
* void atomPatternCharacter(char32_t ch);
*
* Optional methods based on parseEscapeMode:
* void assertionWordBoundary(bool invert);
* void atomBuiltInCharacterClass(BuiltInCharacterClassID classID, bool invert);
* void atomBackReference(unsigned subpatternId);
* void atomNamedBackReference(const String& subpatternName);
* void atomNamedForwardReference(const String& subpatternName);
*/
template<ParseEscapeMode parseEscapeMode, class EscapeDelegate>
TokenType parseEscape(EscapeDelegate& delegate)
{
ASSERT(!hasError(m_errorCode));
ASSERT(peek() == '\\');
consume();
if (atEndOfPattern()) {
m_errorCode = ErrorCode::EscapeUnterminated;
return TokenType::NotAtom;
}
switch (peek()) {
// Assertions
case 'b':
consume();
if (parseEscapeMode != ParseEscapeMode::Normal)
delegate.atomPatternCharacter('\b');
else {
delegate.assertionWordBoundary(false);
return TokenType::NotAtom;
}
break;
case 'B':
consume();
if (parseEscapeMode != ParseEscapeMode::Normal) {
if (isIdentityEscapeAnError<parseEscapeMode>('B'))
break;
delegate.atomPatternCharacter('B');
} else {
delegate.assertionWordBoundary(true);
return TokenType::NotAtom;
}
break;
// CharacterClassEscape
case 'd':
consume();
if (parseEscapeMode == ParseEscapeMode::ClassStringDisjunction) {
delegate.atomPatternCharacter('d');
break;
}
delegate.atomBuiltInCharacterClass(BuiltInCharacterClassID::DigitClassID, false);
break;
case 's':
consume();
if (parseEscapeMode == ParseEscapeMode::ClassStringDisjunction) {
delegate.atomPatternCharacter('s');
break;
}
delegate.atomBuiltInCharacterClass(BuiltInCharacterClassID::SpaceClassID, false);
break;
case 'w':
consume();
if (parseEscapeMode == ParseEscapeMode::ClassStringDisjunction) {
delegate.atomPatternCharacter('w');
break;
}
delegate.atomBuiltInCharacterClass(BuiltInCharacterClassID::WordClassID, false);
break;
case 'D':
consume();
if (parseEscapeMode == ParseEscapeMode::ClassStringDisjunction) {
delegate.atomPatternCharacter('D');
break;
}
delegate.atomBuiltInCharacterClass(BuiltInCharacterClassID::DigitClassID, true);
break;
case 'S':
consume();
if (parseEscapeMode == ParseEscapeMode::ClassStringDisjunction) {
delegate.atomPatternCharacter('S');
break;
}
delegate.atomBuiltInCharacterClass(BuiltInCharacterClassID::SpaceClassID, true);
break;
case 'W':
consume();
if (parseEscapeMode == ParseEscapeMode::ClassStringDisjunction) {
delegate.atomPatternCharacter('W');
break;
}
delegate.atomBuiltInCharacterClass(BuiltInCharacterClassID::WordClassID, true);
break;
case '0': {
consume();
if (!peekIsDigit()) {
delegate.atomPatternCharacter(0);
break;
}
if (isEitherUnicodeCompilation()) {
m_errorCode = ErrorCode::InvalidOctalEscape;
break;
}
delegate.atomPatternCharacter(consumeOctal(2));
break;
}
// DecimalEscape
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
// For non-Unicode patterns, invalid backreferences are parsed as octal or decimal escapes.
// First, try to parse this as backreference.
if (parseEscapeMode == ParseEscapeMode::Normal) {
ParseState state = saveState();
unsigned backReference = consumeNumber();
if (backReference <= m_backReferenceLimit) {
m_maxSeenBackReference = std::max(m_maxSeenBackReference, backReference);
delegate.atomBackReference(backReference);
break;
}
restoreState(state);
if (isEitherUnicodeCompilation()) {
m_errorCode = ErrorCode::InvalidBackreference;
break;
}
}
if (isEitherUnicodeCompilation()) {
m_errorCode = ErrorCode::InvalidOctalEscape;
break;
}
delegate.atomPatternCharacter(peek() < '8' ? consumeOctal(3) : consume());
break;
}
// ControlEscape
case 'f':
consume();
delegate.atomPatternCharacter('\f');
break;
case 'n':
consume();
delegate.atomPatternCharacter('\n');
break;
case 'r':
consume();
delegate.atomPatternCharacter('\r');