-
-
Notifications
You must be signed in to change notification settings - Fork 774
/
Copy pathregexcmp.cpp
4673 lines (4106 loc) · 179 KB
/
regexcmp.cpp
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
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
//
// file: regexcmp.cpp
//
// Copyright (C) 2002-2016 International Business Machines Corporation and others.
// All Rights Reserved.
//
// This file contains the ICU regular expression compiler, which is responsible
// for processing a regular expression pattern into the compiled form that
// is used by the match finding engine.
//
#include "unicode/utypes.h"
#if !UCONFIG_NO_REGULAR_EXPRESSIONS
#include "unicode/ustring.h"
#include "unicode/unistr.h"
#include "unicode/uniset.h"
#include "unicode/uchar.h"
#include "unicode/uchriter.h"
#include "unicode/parsepos.h"
#include "unicode/parseerr.h"
#include "unicode/regex.h"
#include "unicode/utf.h"
#include "unicode/utf16.h"
#include "patternprops.h"
#include "putilimp.h"
#include "cmemory.h"
#include "cstr.h"
#include "cstring.h"
#include "uvectr32.h"
#include "uvectr64.h"
#include "uassert.h"
#include "uinvchar.h"
#include "regeximp.h"
#include "regexcst.h" // Contains state table for the regex pattern parser.
// generated by a Perl script.
#include "regexcmp.h"
#include "regexst.h"
#include "regextxt.h"
U_NAMESPACE_BEGIN
//------------------------------------------------------------------------------
//
// Constructor.
//
//------------------------------------------------------------------------------
RegexCompile::RegexCompile(RegexPattern *rxp, UErrorCode &status) :
fParenStack(status), fSetStack(uprv_deleteUObject, nullptr, status), fSetOpStack(status)
{
// Lazy init of all shared global sets (needed for init()'s empty text)
RegexStaticSets::initGlobals(&status);
fStatus = &status;
fRXPat = rxp;
fScanIndex = 0;
fLastChar = -1;
fPeekChar = -1;
fLineNum = 1;
fCharNum = 0;
fQuoteMode = false;
fInBackslashQuote = false;
fModeFlags = fRXPat->fFlags | 0x80000000;
fEOLComments = true;
fMatchOpenParen = -1;
fMatchCloseParen = -1;
fCaptureName = nullptr;
fLastSetLiteral = U_SENTINEL;
if (U_SUCCESS(status) && U_FAILURE(rxp->fDeferredStatus)) {
status = rxp->fDeferredStatus;
}
}
static const char16_t chAmp = 0x26; // '&'
static const char16_t chDash = 0x2d; // '-'
//------------------------------------------------------------------------------
//
// Destructor
//
//------------------------------------------------------------------------------
RegexCompile::~RegexCompile() {
delete fCaptureName; // Normally will be nullptr, but can exist if pattern
// compilation stops with a syntax error.
}
static inline void addCategory(UnicodeSet *set, int32_t value, UErrorCode& ec) {
set->addAll(UnicodeSet().applyIntPropertyValue(UCHAR_GENERAL_CATEGORY_MASK, value, ec));
}
//------------------------------------------------------------------------------
//
// Compile regex pattern. The state machine for rexexp pattern parsing is here.
// The state tables are hand-written in the file regexcst.txt,
// and converted to the form used here by a perl
// script regexcst.pl
//
//------------------------------------------------------------------------------
void RegexCompile::compile(
const UnicodeString &pat, // Source pat to be compiled.
UParseError &pp, // Error position info
UErrorCode &e) // Error Code
{
fRXPat->fPatternString = new UnicodeString(pat);
UText patternText = UTEXT_INITIALIZER;
utext_openConstUnicodeString(&patternText, fRXPat->fPatternString, &e);
if (U_SUCCESS(e)) {
compile(&patternText, pp, e);
utext_close(&patternText);
}
}
//
// compile, UText mode
// All the work is actually done here.
//
void RegexCompile::compile(
UText *pat, // Source pat to be compiled.
UParseError &pp, // Error position info
UErrorCode &e) // Error Code
{
fStatus = &e;
fParseErr = &pp;
fStackPtr = 0;
fStack[fStackPtr] = 0;
if (U_FAILURE(*fStatus)) {
return;
}
// There should be no pattern stuff in the RegexPattern object. They can not be reused.
U_ASSERT(fRXPat->fPattern == nullptr || utext_nativeLength(fRXPat->fPattern) == 0);
// Prepare the RegexPattern object to receive the compiled pattern.
fRXPat->fPattern = utext_clone(fRXPat->fPattern, pat, false, true, fStatus);
if (U_FAILURE(*fStatus)) {
return;
}
// Initialize the pattern scanning state machine
fPatternLength = utext_nativeLength(pat);
uint16_t state = 1;
const RegexTableEl *tableEl;
// UREGEX_LITERAL force entire pattern to be treated as a literal string.
if (fModeFlags & UREGEX_LITERAL) {
fQuoteMode = true;
}
nextChar(fC); // Fetch the first char from the pattern string.
//
// Main loop for the regex pattern parsing state machine.
// Runs once per state transition.
// Each time through optionally performs, depending on the state table,
// - an advance to the the next pattern char
// - an action to be performed.
// - pushing or popping a state to/from the local state return stack.
// file regexcst.txt is the source for the state table. The logic behind
// recongizing the pattern syntax is there, not here.
//
for (;;) {
// Bail out if anything has gone wrong.
// Regex pattern parsing stops on the first error encountered.
if (U_FAILURE(*fStatus)) {
break;
}
U_ASSERT(state != 0);
// Find the state table element that matches the input char from the pattern, or the
// class of the input character. Start with the first table row for this
// state, then linearly scan forward until we find a row that matches the
// character. The last row for each state always matches all characters, so
// the search will stop there, if not before.
//
tableEl = &gRuleParseStateTable[state];
REGEX_SCAN_DEBUG_PRINTF(("char, line, col = (\'%c\', %d, %d) state=%s ",
fC.fChar, fLineNum, fCharNum, RegexStateNames[state]));
for (;;) { // loop through table rows belonging to this state, looking for one
// that matches the current input char.
REGEX_SCAN_DEBUG_PRINTF(("."));
if (tableEl->fCharClass < 127 && fC.fQuoted == false && tableEl->fCharClass == fC.fChar) {
// Table row specified an individual character, not a set, and
// the input character is not quoted, and
// the input character matched it.
break;
}
if (tableEl->fCharClass == 255) {
// Table row specified default, match anything character class.
break;
}
if (tableEl->fCharClass == 254 && fC.fQuoted) {
// Table row specified "quoted" and the char was quoted.
break;
}
if (tableEl->fCharClass == 253 && fC.fChar == static_cast<UChar32>(-1)) {
// Table row specified eof and we hit eof on the input.
break;
}
if (tableEl->fCharClass >= 128 && tableEl->fCharClass < 240 && // Table specs a char class &&
fC.fQuoted == false && // char is not escaped &&
fC.fChar != static_cast<UChar32>(-1)) { // char is not EOF
U_ASSERT(tableEl->fCharClass <= 137);
if (RegexStaticSets::gStaticSets->fRuleSets[tableEl->fCharClass-128].contains(fC.fChar)) {
// Table row specified a character class, or set of characters,
// and the current char matches it.
break;
}
}
// No match on this row, advance to the next row for this state,
tableEl++;
}
REGEX_SCAN_DEBUG_PRINTF(("\n"));
//
// We've found the row of the state table that matches the current input
// character from the rules string.
// Perform any action specified by this row in the state table.
if (doParseActions(tableEl->fAction) == false) {
// Break out of the state machine loop if the
// the action signalled some kind of error, or
// the action was to exit, occurs on normal end-of-rules-input.
break;
}
if (tableEl->fPushState != 0) {
fStackPtr++;
if (fStackPtr >= kStackSize) {
error(U_REGEX_INTERNAL_ERROR);
REGEX_SCAN_DEBUG_PRINTF(("RegexCompile::parse() - state stack overflow.\n"));
fStackPtr--;
}
fStack[fStackPtr] = tableEl->fPushState;
}
//
// NextChar. This is where characters are actually fetched from the pattern.
// Happens under control of the 'n' tag in the state table.
//
if (tableEl->fNextChar) {
nextChar(fC);
}
// Get the next state from the table entry, or from the
// state stack if the next state was specified as "pop".
if (tableEl->fNextState != 255) {
state = tableEl->fNextState;
} else {
state = fStack[fStackPtr];
fStackPtr--;
if (fStackPtr < 0) {
// state stack underflow
// This will occur if the user pattern has mis-matched parentheses,
// with extra close parens.
//
fStackPtr++;
error(U_REGEX_MISMATCHED_PAREN);
}
}
}
if (U_FAILURE(*fStatus)) {
// Bail out if the pattern had errors.
return;
}
//
// The pattern has now been read and processed, and the compiled code generated.
//
//
// The pattern's fFrameSize so far has accumulated the requirements for
// storage for capture parentheses, counters, etc. that are encountered
// in the pattern. Add space for the two variables that are always
// present in the saved state: the input string position (int64_t) and
// the position in the compiled pattern.
//
allocateStackData(RESTACKFRAME_HDRCOUNT);
//
// Optimization pass 1: NOPs, back-references, and case-folding
//
stripNOPs();
//
// Get bounds for the minimum and maximum length of a string that this
// pattern can match. Used to avoid looking for matches in strings that
// are too short.
//
fRXPat->fMinMatchLen = minMatchLength(3, fRXPat->fCompiledPat->size()-1);
//
// Optimization pass 2: match start type
//
matchStartType();
//
// Set up fast latin-1 range sets
//
int32_t numSets = fRXPat->fSets->size();
fRXPat->fSets8 = new Regex8BitSet[numSets];
// Null pointer check.
if (fRXPat->fSets8 == nullptr) {
e = *fStatus = U_MEMORY_ALLOCATION_ERROR;
return;
}
int32_t i;
for (i=0; i<numSets; i++) {
UnicodeSet* s = static_cast<UnicodeSet*>(fRXPat->fSets->elementAt(i));
fRXPat->fSets8[i].init(s);
}
}
//------------------------------------------------------------------------------
//
// doParseAction Do some action during regex pattern parsing.
// Called by the parse state machine.
//
// Generation of the match engine PCode happens here, or
// in functions called from the parse actions defined here.
//
//
//------------------------------------------------------------------------------
UBool RegexCompile::doParseActions(int32_t action)
{
UBool returnVal = true;
switch (static_cast<Regex_PatternParseAction>(action)) {
case doPatStart:
// Start of pattern compiles to:
//0 SAVE 2 Fall back to position of FAIL
//1 jmp 3
//2 FAIL Stop if we ever reach here.
//3 NOP Dummy, so start of pattern looks the same as
// the start of an ( grouping.
//4 NOP Resreved, will be replaced by a save if there are
// OR | operators at the top level
appendOp(URX_STATE_SAVE, 2);
appendOp(URX_JMP, 3);
appendOp(URX_FAIL, 0);
// Standard open nonCapture paren action emits the two NOPs and
// sets up the paren stack frame.
doParseActions(doOpenNonCaptureParen);
break;
case doPatFinish:
// We've scanned to the end of the pattern
// The end of pattern compiles to:
// URX_END
// which will stop the runtime match engine.
// Encountering end of pattern also behaves like a close paren,
// and forces fixups of the State Save at the beginning of the compiled pattern
// and of any OR operations at the top level.
//
handleCloseParen();
if (fParenStack.size() > 0) {
// Missing close paren in pattern.
error(U_REGEX_MISMATCHED_PAREN);
}
// add the END operation to the compiled pattern.
appendOp(URX_END, 0);
// Terminate the pattern compilation state machine.
returnVal = false;
break;
case doOrOperator:
// Scanning a '|', as in (A|B)
{
// Generate code for any pending literals preceding the '|'
fixLiterals(false);
// Insert a SAVE operation at the start of the pattern section preceding
// this OR at this level. This SAVE will branch the match forward
// to the right hand side of the OR in the event that the left hand
// side fails to match and backtracks. Locate the position for the
// save from the location on the top of the parentheses stack.
int32_t savePosition = fParenStack.popi();
int32_t op = static_cast<int32_t>(fRXPat->fCompiledPat->elementAti(savePosition));
U_ASSERT(URX_TYPE(op) == URX_NOP); // original contents of reserved location
op = buildOp(URX_STATE_SAVE, fRXPat->fCompiledPat->size()+1);
fRXPat->fCompiledPat->setElementAt(op, savePosition);
// Append an JMP operation into the compiled pattern. The operand for
// the JMP will eventually be the location following the ')' for the
// group. This will be patched in later, when the ')' is encountered.
appendOp(URX_JMP, 0);
// Push the position of the newly added JMP op onto the parentheses stack.
// This registers if for fixup when this block's close paren is encountered.
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus);
// Append a NOP to the compiled pattern. This is the slot reserved
// for a SAVE in the event that there is yet another '|' following
// this one.
appendOp(URX_NOP, 0);
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus);
}
break;
case doBeginNamedCapture:
// Scanning (?<letter.
// The first letter of the name will come through again under doConinueNamedCapture.
fCaptureName = new UnicodeString();
if (fCaptureName == nullptr) {
error(U_MEMORY_ALLOCATION_ERROR);
}
break;
case doContinueNamedCapture:
fCaptureName->append(fC.fChar);
break;
case doBadNamedCapture:
error(U_REGEX_INVALID_CAPTURE_GROUP_NAME);
break;
case doOpenCaptureParen:
// Open Capturing Paren, possibly named.
// Compile to a
// - NOP, which later may be replaced by a save-state if the
// parenthesized group gets a * quantifier, followed by
// - START_CAPTURE n where n is stack frame offset to the capture group variables.
// - NOP, which may later be replaced by a save-state if there
// is an '|' alternation within the parens.
//
// Each capture group gets three slots in the save stack frame:
// 0: Capture Group start position (in input string being matched.)
// 1: Capture Group end position.
// 2: Start of Match-in-progress.
// The first two locations are for a completed capture group, and are
// referred to by back references and the like.
// The third location stores the capture start position when an START_CAPTURE is
// encountered. This will be promoted to a completed capture when (and if) the corresponding
// END_CAPTURE is encountered.
{
fixLiterals();
appendOp(URX_NOP, 0);
int32_t varsLoc = allocateStackData(3); // Reserve three slots in match stack frame.
appendOp(URX_START_CAPTURE, varsLoc);
appendOp(URX_NOP, 0);
// On the Parentheses stack, start a new frame and add the positions
// of the two NOPs. Depending on what follows in the pattern, the
// NOPs may be changed to SAVE_STATE or JMP ops, with a target
// address of the end of the parenthesized group.
fParenStack.push(fModeFlags, *fStatus); // Match mode state
fParenStack.push(capturing, *fStatus); // Frame type.
fParenStack.push(fRXPat->fCompiledPat->size()-3, *fStatus); // The first NOP location
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus); // The second NOP loc
// Save the mapping from group number to stack frame variable position.
fRXPat->fGroupMap->addElement(varsLoc, *fStatus);
// If this is a named capture group, add the name->group number mapping.
if (fCaptureName != nullptr) {
if (!fRXPat->initNamedCaptureMap()) {
if (U_SUCCESS(*fStatus)) {
error(fRXPat->fDeferredStatus);
}
break;
}
int32_t groupNumber = fRXPat->fGroupMap->size();
int32_t previousMapping = uhash_puti(fRXPat->fNamedCaptureMap, fCaptureName, groupNumber, fStatus);
fCaptureName = nullptr; // hash table takes ownership of the name (key) string.
if (previousMapping > 0 && U_SUCCESS(*fStatus)) {
error(U_REGEX_INVALID_CAPTURE_GROUP_NAME);
}
}
}
break;
case doOpenNonCaptureParen:
// Open non-caputuring (grouping only) Paren.
// Compile to a
// - NOP, which later may be replaced by a save-state if the
// parenthesized group gets a * quantifier, followed by
// - NOP, which may later be replaced by a save-state if there
// is an '|' alternation within the parens.
{
fixLiterals();
appendOp(URX_NOP, 0);
appendOp(URX_NOP, 0);
// On the Parentheses stack, start a new frame and add the positions
// of the two NOPs.
fParenStack.push(fModeFlags, *fStatus); // Match mode state
fParenStack.push(plain, *fStatus); // Begin a new frame.
fParenStack.push(fRXPat->fCompiledPat->size()-2, *fStatus); // The first NOP location
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus); // The second NOP loc
}
break;
case doOpenAtomicParen:
// Open Atomic Paren. (?>
// Compile to a
// - NOP, which later may be replaced if the parenthesized group
// has a quantifier, followed by
// - STO_SP save state stack position, so it can be restored at the ")"
// - NOP, which may later be replaced by a save-state if there
// is an '|' alternation within the parens.
{
fixLiterals();
appendOp(URX_NOP, 0);
int32_t varLoc = allocateData(1); // Reserve a data location for saving the state stack ptr.
appendOp(URX_STO_SP, varLoc);
appendOp(URX_NOP, 0);
// On the Parentheses stack, start a new frame and add the positions
// of the two NOPs. Depending on what follows in the pattern, the
// NOPs may be changed to SAVE_STATE or JMP ops, with a target
// address of the end of the parenthesized group.
fParenStack.push(fModeFlags, *fStatus); // Match mode state
fParenStack.push(atomic, *fStatus); // Frame type.
fParenStack.push(fRXPat->fCompiledPat->size()-3, *fStatus); // The first NOP
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus); // The second NOP
}
break;
case doOpenLookAhead:
// Positive Look-ahead (?= stuff )
//
// Note: Addition of transparent input regions, with the need to
// restore the original regions when failing out of a lookahead
// block, complicated this sequence. Some combined opcodes
// might make sense - or might not, lookahead aren't that common.
//
// Caution: min match length optimization knows about this
// sequence; don't change without making updates there too.
//
// Compiles to
// 1 LA_START dataLoc Saves SP, Input Pos, Active input region.
// 2. STATE_SAVE 4 on failure of lookahead, goto 4
// 3 JMP 6 continue ...
//
// 4. LA_END Look Ahead failed. Restore regions.
// 5. BACKTRACK and back track again.
//
// 6. NOP reserved for use by quantifiers on the block.
// Look-ahead can't have quantifiers, but paren stack
// compile time conventions require the slot anyhow.
// 7. NOP may be replaced if there is are '|' ops in the block.
// 8. code for parenthesized stuff.
// 9. LA_END
//
// Four data slots are reserved, for saving state on entry to the look-around
// 0: stack pointer on entry.
// 1: input position on entry.
// 2: fActiveStart, the active bounds start on entry.
// 3: fActiveLimit, the active bounds limit on entry.
{
fixLiterals();
int32_t dataLoc = allocateData(4);
appendOp(URX_LA_START, dataLoc);
appendOp(URX_STATE_SAVE, fRXPat->fCompiledPat->size()+ 2);
appendOp(URX_JMP, fRXPat->fCompiledPat->size()+ 3);
appendOp(URX_LA_END, dataLoc);
appendOp(URX_BACKTRACK, 0);
appendOp(URX_NOP, 0);
appendOp(URX_NOP, 0);
// On the Parentheses stack, start a new frame and add the positions
// of the NOPs.
fParenStack.push(fModeFlags, *fStatus); // Match mode state
fParenStack.push(lookAhead, *fStatus); // Frame type.
fParenStack.push(fRXPat->fCompiledPat->size()-2, *fStatus); // The first NOP location
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus); // The second NOP location
}
break;
case doOpenLookAheadNeg:
// Negated Lookahead. (?! stuff )
// Compiles to
// 1. LA_START dataloc
// 2. SAVE_STATE 7 // Fail within look-ahead block restores to this state,
// // which continues with the match.
// 3. NOP // Std. Open Paren sequence, for possible '|'
// 4. code for parenthesized stuff.
// 5. LA_END // Cut back stack, remove saved state from step 2.
// 6. BACKTRACK // code in block succeeded, so neg. lookahead fails.
// 7. END_LA // Restore match region, in case look-ahead was using
// an alternate (transparent) region.
// Four data slots are reserved, for saving state on entry to the look-around
// 0: stack pointer on entry.
// 1: input position on entry.
// 2: fActiveStart, the active bounds start on entry.
// 3: fActiveLimit, the active bounds limit on entry.
{
fixLiterals();
int32_t dataLoc = allocateData(4);
appendOp(URX_LA_START, dataLoc);
appendOp(URX_STATE_SAVE, 0); // dest address will be patched later.
appendOp(URX_NOP, 0);
// On the Parentheses stack, start a new frame and add the positions
// of the StateSave and NOP.
fParenStack.push(fModeFlags, *fStatus); // Match mode state
fParenStack.push(negLookAhead, *fStatus); // Frame type
fParenStack.push(fRXPat->fCompiledPat->size()-2, *fStatus); // The STATE_SAVE location
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus); // The second NOP location
// Instructions #5 - #7 will be added when the ')' is encountered.
}
break;
case doOpenLookBehind:
{
// Compile a (?<= look-behind open paren.
//
// Compiles to
// 0 URX_LB_START dataLoc
// 1 URX_LB_CONT dataLoc
// 2 MinMatchLen
// 3 MaxMatchLen
// 4 URX_NOP Standard '(' boilerplate.
// 5 URX_NOP Reserved slot for use with '|' ops within (block).
// 6 <code for LookBehind expression>
// 7 URX_LB_END dataLoc # Check match len, restore input len
// 8 URX_LA_END dataLoc # Restore stack, input pos
//
// Allocate a block of matcher data, to contain (when running a match)
// 0: Stack ptr on entry
// 1: Input Index on entry
// 2: fActiveStart, the active bounds start on entry.
// 3: fActiveLimit, the active bounds limit on entry.
// 4: Start index of match current match attempt.
// The first four items must match the layout of data for LA_START / LA_END
// Generate match code for any pending literals.
fixLiterals();
// Allocate data space
int32_t dataLoc = allocateData(5);
// Emit URX_LB_START
appendOp(URX_LB_START, dataLoc);
// Emit URX_LB_CONT
appendOp(URX_LB_CONT, dataLoc);
appendOp(URX_RESERVED_OP, 0); // MinMatchLength. To be filled later.
appendOp(URX_RESERVED_OP, 0); // MaxMatchLength. To be filled later.
// Emit the NOPs
appendOp(URX_NOP, 0);
appendOp(URX_NOP, 0);
// On the Parentheses stack, start a new frame and add the positions
// of the URX_LB_CONT and the NOP.
fParenStack.push(fModeFlags, *fStatus); // Match mode state
fParenStack.push(lookBehind, *fStatus); // Frame type
fParenStack.push(fRXPat->fCompiledPat->size()-2, *fStatus); // The first NOP location
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus); // The 2nd NOP location
// The final two instructions will be added when the ')' is encountered.
}
break;
case doOpenLookBehindNeg:
{
// Compile a (?<! negated look-behind open paren.
//
// Compiles to
// 0 URX_LB_START dataLoc # Save entry stack, input len
// 1 URX_LBN_CONT dataLoc # Iterate possible match positions
// 2 MinMatchLen
// 3 MaxMatchLen
// 4 continueLoc (9)
// 5 URX_NOP Standard '(' boilerplate.
// 6 URX_NOP Reserved slot for use with '|' ops within (block).
// 7 <code for LookBehind expression>
// 8 URX_LBN_END dataLoc # Check match len, cause a FAIL
// 9 ...
//
// Allocate a block of matcher data, to contain (when running a match)
// 0: Stack ptr on entry
// 1: Input Index on entry
// 2: fActiveStart, the active bounds start on entry.
// 3: fActiveLimit, the active bounds limit on entry.
// 4: Start index of match current match attempt.
// The first four items must match the layout of data for LA_START / LA_END
// Generate match code for any pending literals.
fixLiterals();
// Allocate data space
int32_t dataLoc = allocateData(5);
// Emit URX_LB_START
appendOp(URX_LB_START, dataLoc);
// Emit URX_LBN_CONT
appendOp(URX_LBN_CONT, dataLoc);
appendOp(URX_RESERVED_OP, 0); // MinMatchLength. To be filled later.
appendOp(URX_RESERVED_OP, 0); // MaxMatchLength. To be filled later.
appendOp(URX_RESERVED_OP, 0); // Continue Loc. To be filled later.
// Emit the NOPs
appendOp(URX_NOP, 0);
appendOp(URX_NOP, 0);
// On the Parentheses stack, start a new frame and add the positions
// of the URX_LB_CONT and the NOP.
fParenStack.push(fModeFlags, *fStatus); // Match mode state
fParenStack.push(lookBehindN, *fStatus); // Frame type
fParenStack.push(fRXPat->fCompiledPat->size()-2, *fStatus); // The first NOP location
fParenStack.push(fRXPat->fCompiledPat->size()-1, *fStatus); // The 2nd NOP location
// The final two instructions will be added when the ')' is encountered.
}
break;
case doConditionalExpr:
// Conditionals such as (?(1)a:b)
case doPerlInline:
// Perl inline-conditionals. (?{perl code}a|b) We're not perl, no way to do them.
error(U_REGEX_UNIMPLEMENTED);
break;
case doCloseParen:
handleCloseParen();
if (fParenStack.size() <= 0) {
// Extra close paren, or missing open paren.
error(U_REGEX_MISMATCHED_PAREN);
}
break;
case doNOP:
break;
case doBadOpenParenType:
case doRuleError:
error(U_REGEX_RULE_SYNTAX);
break;
case doMismatchedParenErr:
error(U_REGEX_MISMATCHED_PAREN);
break;
case doPlus:
// Normal '+' compiles to
// 1. stuff to be repeated (already built)
// 2. jmp-sav 1
// 3. ...
//
// Or, if the item to be repeated can match a zero length string,
// 1. STO_INP_LOC data-loc
// 2. body of stuff to be repeated
// 3. JMP_SAV_X 2
// 4. ...
//
// Or, if the item to be repeated is simple
// 1. Item to be repeated.
// 2. LOOP_SR_I set number (assuming repeated item is a set ref)
// 3. LOOP_C stack location
{
int32_t topLoc = blockTopLoc(false); // location of item #1
int32_t frameLoc;
// Check for simple constructs, which may get special optimized code.
if (topLoc == fRXPat->fCompiledPat->size() - 1) {
int32_t repeatedOp = static_cast<int32_t>(fRXPat->fCompiledPat->elementAti(topLoc));
if (URX_TYPE(repeatedOp) == URX_SETREF) {
// Emit optimized code for [char set]+
appendOp(URX_LOOP_SR_I, URX_VAL(repeatedOp));
frameLoc = allocateStackData(1);
appendOp(URX_LOOP_C, frameLoc);
break;
}
if (URX_TYPE(repeatedOp) == URX_DOTANY ||
URX_TYPE(repeatedOp) == URX_DOTANY_ALL ||
URX_TYPE(repeatedOp) == URX_DOTANY_UNIX) {
// Emit Optimized code for .+ operations.
int32_t loopOpI = buildOp(URX_LOOP_DOT_I, 0);
if (URX_TYPE(repeatedOp) == URX_DOTANY_ALL) {
// URX_LOOP_DOT_I operand is a flag indicating ". matches any" mode.
loopOpI |= 1;
}
if (fModeFlags & UREGEX_UNIX_LINES) {
loopOpI |= 2;
}
appendOp(loopOpI);
frameLoc = allocateStackData(1);
appendOp(URX_LOOP_C, frameLoc);
break;
}
}
// General case.
// Check for minimum match length of zero, which requires
// extra loop-breaking code.
if (minMatchLength(topLoc, fRXPat->fCompiledPat->size()-1) == 0) {
// Zero length match is possible.
// Emit the code sequence that can handle it.
insertOp(topLoc);
frameLoc = allocateStackData(1);
int32_t op = buildOp(URX_STO_INP_LOC, frameLoc);
fRXPat->fCompiledPat->setElementAt(op, topLoc);
appendOp(URX_JMP_SAV_X, topLoc+1);
} else {
// Simpler code when the repeated body must match something non-empty
appendOp(URX_JMP_SAV, topLoc);
}
}
break;
case doNGPlus:
// Non-greedy '+?' compiles to
// 1. stuff to be repeated (already built)
// 2. state-save 1
// 3. ...
{
int32_t topLoc = blockTopLoc(false);
appendOp(URX_STATE_SAVE, topLoc);
}
break;
case doOpt:
// Normal (greedy) ? quantifier.
// Compiles to
// 1. state save 3
// 2. body of optional block
// 3. ...
// Insert the state save into the compiled pattern, and we're done.
{
int32_t saveStateLoc = blockTopLoc(true);
int32_t saveStateOp = buildOp(URX_STATE_SAVE, fRXPat->fCompiledPat->size());
fRXPat->fCompiledPat->setElementAt(saveStateOp, saveStateLoc);
}
break;
case doNGOpt:
// Non-greedy ?? quantifier
// compiles to
// 1. jmp 4
// 2. body of optional block
// 3 jmp 5
// 4. state save 2
// 5 ...
// This code is less than ideal, with two jmps instead of one, because we can only
// insert one instruction at the top of the block being iterated.
{
int32_t jmp1_loc = blockTopLoc(true);
int32_t jmp2_loc = fRXPat->fCompiledPat->size();
int32_t jmp1_op = buildOp(URX_JMP, jmp2_loc+1);
fRXPat->fCompiledPat->setElementAt(jmp1_op, jmp1_loc);
appendOp(URX_JMP, jmp2_loc+2);
appendOp(URX_STATE_SAVE, jmp1_loc+1);
}
break;
case doStar:
// Normal (greedy) * quantifier.
// Compiles to
// 1. STATE_SAVE 4
// 2. body of stuff being iterated over
// 3. JMP_SAV 2
// 4. ...
//
// Or, if the body is a simple [Set],
// 1. LOOP_SR_I set number
// 2. LOOP_C stack location
// ...
//
// Or if this is a .*
// 1. LOOP_DOT_I (. matches all mode flag)
// 2. LOOP_C stack location
//
// Or, if the body can match a zero-length string, to inhibit infinite loops,
// 1. STATE_SAVE 5
// 2. STO_INP_LOC data-loc
// 3. body of stuff
// 4. JMP_SAV_X 2
// 5. ...
{
// location of item #1, the STATE_SAVE
int32_t topLoc = blockTopLoc(false);
int32_t dataLoc = -1;
// Check for simple *, where the construct being repeated
// compiled to single opcode, and might be optimizable.
if (topLoc == fRXPat->fCompiledPat->size() - 1) {
int32_t repeatedOp = static_cast<int32_t>(fRXPat->fCompiledPat->elementAti(topLoc));
if (URX_TYPE(repeatedOp) == URX_SETREF) {
// Emit optimized code for a [char set]*
int32_t loopOpI = buildOp(URX_LOOP_SR_I, URX_VAL(repeatedOp));
fRXPat->fCompiledPat->setElementAt(loopOpI, topLoc);
dataLoc = allocateStackData(1);
appendOp(URX_LOOP_C, dataLoc);
break;
}
if (URX_TYPE(repeatedOp) == URX_DOTANY ||
URX_TYPE(repeatedOp) == URX_DOTANY_ALL ||
URX_TYPE(repeatedOp) == URX_DOTANY_UNIX) {
// Emit Optimized code for .* operations.
int32_t loopOpI = buildOp(URX_LOOP_DOT_I, 0);
if (URX_TYPE(repeatedOp) == URX_DOTANY_ALL) {
// URX_LOOP_DOT_I operand is a flag indicating . matches any mode.
loopOpI |= 1;
}
if ((fModeFlags & UREGEX_UNIX_LINES) != 0) {
loopOpI |= 2;
}
fRXPat->fCompiledPat->setElementAt(loopOpI, topLoc);
dataLoc = allocateStackData(1);
appendOp(URX_LOOP_C, dataLoc);
break;
}
}
// Emit general case code for this *
// The optimizations did not apply.
int32_t saveStateLoc = blockTopLoc(true);
int32_t jmpOp = buildOp(URX_JMP_SAV, saveStateLoc+1);
// Check for minimum match length of zero, which requires
// extra loop-breaking code.
if (minMatchLength(saveStateLoc, fRXPat->fCompiledPat->size()-1) == 0) {
insertOp(saveStateLoc);
dataLoc = allocateStackData(1);
int32_t op = buildOp(URX_STO_INP_LOC, dataLoc);
fRXPat->fCompiledPat->setElementAt(op, saveStateLoc+1);
jmpOp = buildOp(URX_JMP_SAV_X, saveStateLoc+2);
}
// Locate the position in the compiled pattern where the match will continue
// after completing the *. (4 or 5 in the comment above)
int32_t continueLoc = fRXPat->fCompiledPat->size()+1;
// Put together the save state op and store it into the compiled code.
int32_t saveStateOp = buildOp(URX_STATE_SAVE, continueLoc);
fRXPat->fCompiledPat->setElementAt(saveStateOp, saveStateLoc);
// Append the URX_JMP_SAV or URX_JMPX operation to the compiled pattern.
appendOp(jmpOp);
}
break;
case doNGStar:
// Non-greedy *? quantifier
// compiles to
// 1. JMP 3
// 2. body of stuff being iterated over
// 3. STATE_SAVE 2
// 4 ...
{
int32_t jmpLoc = blockTopLoc(true); // loc 1.
int32_t saveLoc = fRXPat->fCompiledPat->size(); // loc 3.
int32_t jmpOp = buildOp(URX_JMP, saveLoc);
fRXPat->fCompiledPat->setElementAt(jmpOp, jmpLoc);
appendOp(URX_STATE_SAVE, jmpLoc+1);