-
Notifications
You must be signed in to change notification settings - Fork 2k
/
matcher.go
1671 lines (1486 loc) · 46.4 KB
/
matcher.go
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.
Copyright (C) 2004-2015, International Business Machines Corporation and others.
Copyright 2023 The Vitess Authors.
This file contains code derived from the Unicode Project's ICU library.
License & terms of use for the original code: http://www.unicode.org/copyright.html
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package icuregex
import (
"fmt"
"io"
"vitess.io/vitess/go/mysql/icuregex/internal/ucase"
"vitess.io/vitess/go/mysql/icuregex/internal/uchar"
"vitess.io/vitess/go/mysql/icuregex/internal/uprops"
)
const timerInitialValue = 10000
const defaultTimeout = 3
const defaultStackLimit = 0
type Matcher struct {
pattern *Pattern
input []rune
regionStart int // Start of the input region, default = 0.
regionLimit int // End of input region, default to input.length.
anchorStart int // Region bounds for anchoring operations (^ or $).
anchorLimit int // See useAnchoringBounds
lookStart int // Region bounds for look-ahead/behind and
lookLimit int // and other boundary tests. See
// useTransparentBounds
activeStart int // Currently active bounds for matching.
activeLimit int // Usually is the same as region, but
// is changed to fLookStart/Limit when
// entering look around regions.
match bool // True if the last attempted match was successful.
matchStart int // Position of the start of the most recent match
matchEnd int // First position after the end of the most recent match
// Zero if no previous match, even when a region
// is active.
lastMatchEnd int // First position after the end of the previous match,
// or -1 if there was no previous match.
appendPosition int // First position after the end of the previous
// appendReplacement(). As described by the
// JavaDoc for Java Matcher, where it is called
// "append position"
hitEnd bool // True if the last match touched the end of input.
requireEnd bool // True if the last match required end-of-input
// (matched $ or Z)
stack stack
frame stackFrame // After finding a match, the last active stack frame,
// which will contain the capture group results.
// NOT valid while match engine is running.
data []int // Data area for use by the compiled pattern.
timeLimit int32 // Max time (in arbitrary steps) to let the
// match engine run. Zero for unlimited.
time int32 // Match time, accumulates while matching.
tickCounter int32 // Low bits counter for time. Counts down StateSaves.
// Kept separately from fTime to keep as much
// code as possible out of the inline
// StateSave function.
dumper io.Writer
}
func NewMatcher(pat *Pattern) *Matcher {
m := &Matcher{
pattern: pat,
data: make([]int, pat.dataSize),
stack: stack{
frameSize: pat.frameSize,
stackLimit: defaultStackLimit,
},
timeLimit: defaultTimeout,
}
m.reset()
return m
}
func (m *Matcher) MatchAt(startIdx int, toEnd bool) error {
//--------------------------------------------------------------------------------
//
// MatchAt This is the actual matching engine.
//
// startIdx: begin matching a this index.
// toEnd: if true, match must extend to end of the input region
//
//--------------------------------------------------------------------------------
var err error
var isMatch bool // True if the we have a match.
if m.dumper != nil {
fmt.Fprintf(m.dumper, "MatchAt(startIdx=%d)\n", startIdx)
fmt.Fprintf(m.dumper, "Original Pattern: \"%s\"\n", m.pattern.pattern)
fmt.Fprintf(m.dumper, "Input String: \"%s\"\n\n", string(m.input))
}
pat := m.pattern.compiledPat
inputText := m.input
litText := m.pattern.literalText
sets := m.pattern.sets
fp := m.resetStack()
*fp.inputIdx() = startIdx
*fp.patIdx() = 0
for i := 0; i < len(m.data); i++ {
m.data[i] = 0
}
for {
op := pat[*fp.patIdx()]
if m.dumper != nil {
fmt.Fprintf(m.dumper, "inputIdx=%d inputChar=%x sp=%3d activeLimit=%d ", *fp.inputIdx(),
charAt(inputText, *fp.inputIdx()), m.stack.sp(), m.activeLimit)
m.pattern.dumpOp(m.dumper, *fp.patIdx())
}
*fp.patIdx()++
switch op.typ() {
case urxNop:
// Nothing to do.
case urxBacktrack:
// Force a backtrack. In some circumstances, the pattern compiler
// will notice that the pattern can't possibly match anything, and will
// emit one of these at that point.
fp = m.stack.popFrame()
case urxOnechar:
if *fp.inputIdx() < m.activeLimit {
c := charAt(inputText, *fp.inputIdx())
*fp.inputIdx()++
if c == rune(op.value()) {
break
}
} else {
m.hitEnd = true
}
fp = m.stack.popFrame()
case urxString:
// Test input against a literal string.
// Strings require two slots in the compiled pattern, one for the
// offset to the string text, and one for the length.
stringStartIdx := op.value()
nextOp := pat[*fp.patIdx()] // Fetch the second operand
*fp.patIdx()++
stringLen := nextOp.value()
patternString := litText[stringStartIdx:]
var patternStringIndex int
success := true
for patternStringIndex < stringLen {
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
success = false
break
}
if charAt(patternString, patternStringIndex) != charAt(inputText, *fp.inputIdx()) {
success = false
break
}
patternStringIndex++
*fp.inputIdx()++
}
if !success {
fp = m.stack.popFrame()
}
case urxStateSave:
fp, err = m.stateSave(*fp.inputIdx(), op.value())
if err != nil {
return err
}
case urxEnd:
// The match loop will exit via this path on a successful match,
// when we reach the end of the pattern.
if toEnd && *fp.inputIdx() != m.activeLimit {
// The pattern matched, but not to the end of input. Try some more.
fp = m.stack.popFrame()
break
}
isMatch = true
goto breakFromLoop
// Start and End Capture stack frame variables are laid out out like this:
// fp->fExtra[opValue] - The start of a completed capture group
// opValue+1 - The end of a completed capture group
// opValue+2 - the start of a capture group whose end
// has not yet been reached (and might not ever be).
case urxStartCapture:
*fp.extra(op.value() + 2) = *fp.inputIdx()
case urxEndCapture:
*fp.extra(op.value()) = *fp.extra(op.value() + 2) // Tentative start becomes real.
*fp.extra(op.value() + 1) = *fp.inputIdx() // End position
case urxDollar: // $, test for End of line
if *fp.inputIdx() < m.anchorLimit-2 {
fp = m.stack.popFrame()
break
}
// or for position before new line at end of input
if *fp.inputIdx() >= m.anchorLimit {
// We really are at the end of input. Success.
m.hitEnd = true
m.requireEnd = true
break
}
if *fp.inputIdx() == m.anchorLimit-1 {
c := m.input[*fp.inputIdx()]
if isLineTerminator(c) {
if !(c == 0x0a && *fp.inputIdx() > m.anchorStart && m.input[*fp.inputIdx()-1] == 0x0d) {
// At new-line at end of input. Success
m.hitEnd = true
m.requireEnd = true
break
}
}
} else if *fp.inputIdx() == m.anchorLimit-2 && m.input[*fp.inputIdx()] == 0x0d && m.input[*fp.inputIdx()+1] == 0x0a {
m.hitEnd = true
m.requireEnd = true
break // At CR/LF at end of input. Success
}
fp = m.stack.popFrame()
case urxDollarD: // $, test for End of Line, in UNIX_LINES mode.
if *fp.inputIdx() >= m.anchorLimit {
// Off the end of input. Success.
m.hitEnd = true
m.requireEnd = true
break
}
c := charAt(inputText, *fp.inputIdx())
*fp.inputIdx()++
// Either at the last character of input, or off the end.
if c == 0x0a && *fp.inputIdx() == m.anchorLimit {
m.hitEnd = true
m.requireEnd = true
break
}
// Not at end of input. Back-track out.
fp = m.stack.popFrame()
case urxDollarM: // $, test for End of line in multi-line mode
if *fp.inputIdx() >= m.anchorLimit {
// We really are at the end of input. Success.
m.hitEnd = true
m.requireEnd = true
break
}
// If we are positioned just before a new-line, succeed.
// It makes no difference where the new-line is within the input.
c := charAt(inputText, *fp.inputIdx())
if isLineTerminator(c) {
// At a line end, except for the odd chance of being in the middle of a CR/LF sequence
// In multi-line mode, hitting a new-line just before the end of input does not
// set the hitEnd or requireEnd flags
if !(c == 0x0a && *fp.inputIdx() > m.anchorStart && charAt(inputText, *fp.inputIdx()-1) == 0x0d) {
break
}
}
// not at a new line. Fail.
fp = m.stack.popFrame()
case urxDollarMd: // $, test for End of line in multi-line and UNIX_LINES mode
if *fp.inputIdx() >= m.anchorLimit {
// We really are at the end of input. Success.
m.hitEnd = true
m.requireEnd = true // Java set requireEnd in this case, even though
break // adding a new-line would not lose the match.
}
// If we are not positioned just before a new-line, the test fails; backtrack out.
// It makes no difference where the new-line is within the input.
if charAt(inputText, *fp.inputIdx()) != 0x0a {
fp = m.stack.popFrame()
}
case urxCaret: // ^, test for start of line
if *fp.inputIdx() != m.anchorStart {
fp = m.stack.popFrame()
}
case urxCaretM: // ^, test for start of line in mulit-line mode
if *fp.inputIdx() == m.anchorStart {
// We are at the start input. Success.
break
}
// Check whether character just before the current pos is a new-line
// unless we are at the end of input
c := charAt(inputText, *fp.inputIdx()-1)
if (*fp.inputIdx() < m.anchorLimit) && isLineTerminator(c) {
// It's a new-line. ^ is true. Success.
// TODO: what should be done with positions between a CR and LF?
break
}
// Not at the start of a line. Fail.
fp = m.stack.popFrame()
case urxCaretMUnix: // ^, test for start of line in mulit-line + Unix-line mode
if *fp.inputIdx() <= m.anchorStart {
// We are at the start input. Success.
break
}
c := charAt(inputText, *fp.inputIdx()-1)
if c != 0x0a {
// Not at the start of a line. Back-track out.
fp = m.stack.popFrame()
}
case urxBackslashB: // Test for word boundaries
success := m.isWordBoundary(*fp.inputIdx())
success = success != (op.value() != 0) // flip sense for \B
if !success {
fp = m.stack.popFrame()
}
case urxBackslashBu: // Test for word boundaries, Unicode-style
success := m.isUWordBoundary(*fp.inputIdx())
success = success != (op.value() != 0) // flip sense for \B
if !success {
fp = m.stack.popFrame()
}
case urxBackslashD: // Test for decimal digit
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
c := charAt(inputText, *fp.inputIdx())
success := m.isDecimalDigit(c)
success = success != (op.value() != 0) // flip sense for \D
if success {
*fp.inputIdx()++
} else {
fp = m.stack.popFrame()
}
case urxBackslashG: // Test for position at end of previous match
if !((m.match && *fp.inputIdx() == m.matchEnd) || (!m.match && *fp.inputIdx() == m.activeStart)) {
fp = m.stack.popFrame()
}
case urxBackslashH: // Test for \h, horizontal white space.
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
c := charAt(inputText, *fp.inputIdx())
success := m.isHorizWS(c) || c == 9
success = success != (op.value() != 0) // flip sense for \H
if success {
*fp.inputIdx()++
} else {
fp = m.stack.popFrame()
}
case urxBackslashR: // Test for \R, any line break sequence.
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
c := charAt(inputText, *fp.inputIdx())
if isLineTerminator(c) {
if c == 0x0d && charAt(inputText, *fp.inputIdx()+1) == 0x0a {
*fp.inputIdx()++
}
*fp.inputIdx()++
} else {
fp = m.stack.popFrame()
}
case urxBackslashV: // \v, any single line ending character.
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
c := charAt(inputText, *fp.inputIdx())
success := isLineTerminator(c)
success = success != (op.value() != 0) // flip sense for \V
if success {
*fp.inputIdx()++
} else {
fp = m.stack.popFrame()
}
case urxBackslashX:
// Match a Grapheme, as defined by Unicode UAX 29.
// Fail if at end of input
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
*fp.inputIdx() = m.followingGCBoundary(*fp.inputIdx())
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
*fp.inputIdx() = m.activeLimit
}
case urxBackslashZ: // Test for end of Input
if *fp.inputIdx() < m.anchorLimit {
fp = m.stack.popFrame()
} else {
m.hitEnd = true
m.requireEnd = true
}
case urxStaticSetref:
// Test input character against one of the predefined sets
// (Word Characters, for example)
// The high bit of the op value is a flag for the match polarity.
// 0: success if input char is in set.
// 1: success if input char is not in set.
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
success := (op.value() & urxNegSet) == urxNegSet
negOp := op.value() & ^urxNegSet
c := charAt(inputText, *fp.inputIdx())
s := staticPropertySets[negOp]
if s.ContainsRune(c) {
success = !success
}
if success {
*fp.inputIdx()++
} else {
// the character wasn't in the set.
fp = m.stack.popFrame()
}
case urxStatSetrefN:
// Test input character for NOT being a member of one of
// the predefined sets (Word Characters, for example)
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
c := charAt(inputText, *fp.inputIdx())
s := staticPropertySets[op.value()]
if !s.ContainsRune(c) {
*fp.inputIdx()++
break
}
// the character wasn't in the set.
fp = m.stack.popFrame()
case urxSetref:
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
// There is input left. Pick up one char and test it for set membership.
c := charAt(inputText, *fp.inputIdx())
s := sets[op.value()]
if s.ContainsRune(c) {
*fp.inputIdx()++
break
}
// the character wasn't in the set.
fp = m.stack.popFrame()
case urxDotany:
// . matches anything, but stops at end-of-line.
if *fp.inputIdx() >= m.activeLimit {
m.hitEnd = true
fp = m.stack.popFrame()
break
}
c := charAt(inputText, *fp.inputIdx())
if isLineTerminator(c) {
// End of line in normal mode. . does not match.
fp = m.stack.popFrame()
break
}
*fp.inputIdx()++
case urxDotanyAll:
// ., in dot-matches-all (including new lines) mode
if *fp.inputIdx() >= m.activeLimit {
// At end of input. Match failed. Backtrack out.
m.hitEnd = true
fp = m.stack.popFrame()
break
}
c := charAt(inputText, *fp.inputIdx())
*fp.inputIdx()++
if c == 0x0d && *fp.inputIdx() < m.activeLimit {
// In the case of a CR/LF, we need to advance over both.
nextc := charAt(inputText, *fp.inputIdx())
if nextc == 0x0a {
*fp.inputIdx()++
}
}
case urxDotanyUnix:
// '.' operator, matches all, but stops at end-of-line.
// UNIX_LINES mode, so 0x0a is the only recognized line ending.
if *fp.inputIdx() >= m.activeLimit {
// At end of input. Match failed. Backtrack out.
m.hitEnd = true
fp = m.stack.popFrame()
break
}
// There is input left. Advance over one char, unless we've hit end-of-line
c := charAt(inputText, *fp.inputIdx())
if c == 0x0a {
// End of line in normal mode. '.' does not match the \n
fp = m.stack.popFrame()
} else {
*fp.inputIdx()++
}
case urxJmp:
*fp.patIdx() = op.value()
case urxFail:
isMatch = false
goto breakFromLoop
case urxJmpSav:
fp, err = m.stateSave(*fp.inputIdx(), *fp.patIdx()) // State save to loc following current
if err != nil {
return err
}
*fp.patIdx() = op.value() // Then JMP.
case urxJmpSavX:
// This opcode is used with (x)+, when x can match a zero length string.
// Same as JMP_SAV, except conditional on the match having made forward progress.
// Destination of the JMP must be a URX_STO_INP_LOC, from which we get the
// data address of the input position at the start of the loop.
stoOp := pat[op.value()-1]
frameLoc := stoOp.value()
prevInputIdx := *fp.extra(frameLoc)
if prevInputIdx < *fp.inputIdx() {
// The match did make progress. Repeat the loop.
fp, err = m.stateSave(*fp.inputIdx(), *fp.patIdx()) // State save to loc following current
if err != nil {
return err
}
*fp.patIdx() = op.value() // Then JMP.
*fp.extra(frameLoc) = *fp.inputIdx()
}
// If the input position did not advance, we do nothing here,
// execution will fall out of the loop.
case urxCtrInit:
*fp.extra(op.value()) = 0 // Set the loop counter variable to zero
// Pick up the three extra operands that CTR_INIT has, and
// skip the pattern location counter past
instOperandLoc := *fp.patIdx()
*fp.patIdx() += 3 // Skip over the three operands that CTR_INIT has.
loopLoc := pat[instOperandLoc].value()
minCount := int(pat[instOperandLoc+1])
maxCount := int(pat[instOperandLoc+2])
if minCount == 0 {
fp, err = m.stateSave(*fp.inputIdx(), loopLoc+1)
if err != nil {
return err
}
}
if maxCount == -1 {
*fp.extra(op.value() + 1) = *fp.inputIdx() // For loop breaking.
} else if maxCount == 0 {
fp = m.stack.popFrame()
}
case utxCtrLoop:
initOp := pat[op.value()]
opValue := initOp.value()
pCounter := fp.extra(opValue)
minCount := int(pat[op.value()+2])
maxCount := int(pat[op.value()+3])
*pCounter++
if *pCounter >= maxCount && maxCount != -1 {
break
}
if *pCounter >= minCount {
if maxCount == -1 {
// Loop has no hard upper bound.
// Check that it is progressing through the input, break if it is not.
pLastIntputIdx := fp.extra(opValue + 1)
if *pLastIntputIdx == *fp.inputIdx() {
break
}
*pLastIntputIdx = *fp.inputIdx()
}
fp, err = m.stateSave(*fp.inputIdx(), *fp.patIdx())
if err != nil {
return err
}
} else {
// Increment time-out counter. (StateSave() does it if count >= minCount)
m.tickCounter--
if m.tickCounter <= 0 {
if err = m.incrementTime(*fp.inputIdx()); err != nil {
return err
} // Re-initializes fTickCounter
}
}
*fp.patIdx() = op.value() + 4 // Loop back.
case urxCtrInitNg:
*fp.extra(op.value()) = 0 // Set the loop counter variable to zero
// Pick up the three extra operands that CTR_INIT_NG has, and
// skip the pattern location counter past
instrOperandLoc := *fp.patIdx()
*fp.patIdx() += 3
loopLoc := pat[instrOperandLoc].value()
minCount := pat[instrOperandLoc+1].value()
maxCount := pat[instrOperandLoc+2].value()
if maxCount == -1 {
*fp.extra(op.value() + 1) = *fp.inputIdx() // Save initial input index for loop breaking.
}
if minCount == 0 {
if maxCount != 0 {
fp, err = m.stateSave(*fp.inputIdx(), *fp.patIdx())
if err != nil {
return err
}
}
*fp.patIdx() = loopLoc + 1
}
case urxCtrLoopNg:
initOp := pat[op.value()]
pCounter := fp.extra(initOp.value())
minCount := int(pat[op.value()+2])
maxCount := int(pat[op.value()+3])
*pCounter++
if *pCounter >= maxCount && maxCount != -1 {
// The loop has matched the maximum permitted number of times.
// Break out of here with no action. Matching will
// continue with the following pattern.
break
}
if *pCounter < minCount {
// We haven't met the minimum number of matches yet.
// Loop back for another one.
*fp.patIdx() = op.value() + 4 // Loop back.
// Increment time-out counter. (StateSave() does it if count >= minCount)
m.tickCounter--
if m.tickCounter <= 0 {
if err = m.incrementTime(*fp.inputIdx()); err != nil {
return err
} // Re-initializes fTickCounter
}
} else {
// We do have the minimum number of matches.
// If there is no upper bound on the loop iterations, check that the input index
// is progressing, and stop the loop if it is not.
if maxCount == -1 {
lastInputIdx := fp.extra(initOp.value() + 1)
if *fp.inputIdx() == *lastInputIdx {
break
}
*lastInputIdx = *fp.inputIdx()
}
}
// Loop Continuation: we will fall into the pattern following the loop
// (non-greedy, don't execute loop body first), but first do
// a state save to the top of the loop, so that a match failure
// in the following pattern will try another iteration of the loop.
fp, err = m.stateSave(*fp.inputIdx(), op.value()+4)
if err != nil {
return err
}
case urxStoSp:
m.data[op.value()] = m.stack.len()
case urxLdSp:
newStackSize := m.data[op.value()]
newFp := m.stack.offset(newStackSize)
if newFp.equals(fp) {
break
}
copy(newFp, fp)
fp = newFp
m.stack.setSize(newStackSize)
case urxBackref:
groupStartIdx := *fp.extra(op.value())
groupEndIdx := *fp.extra(op.value() + 1)
if groupStartIdx < 0 {
// This capture group has not participated in the match thus far,
fp = m.stack.popFrame() // FAIL, no match.
break
}
success := true
for {
if groupStartIdx >= groupEndIdx {
success = true
break
}
if *fp.inputIdx() >= m.activeLimit {
success = false
m.hitEnd = true
break
}
captureGroupChar := charAt(inputText, groupStartIdx)
inputChar := charAt(inputText, *fp.inputIdx())
groupStartIdx++
*fp.inputIdx()++
if inputChar != captureGroupChar {
success = false
break
}
}
if !success {
fp = m.stack.popFrame()
}
case urxBackrefI:
groupStartIdx := *fp.extra(op.value())
groupEndIdx := *fp.extra(op.value() + 1)
if groupStartIdx < 0 {
// This capture group has not participated in the match thus far,
fp = m.stack.popFrame() // FAIL, no match.
break
}
captureGroupItr := newCaseFoldIterator(m.input, groupStartIdx, groupEndIdx)
inputItr := newCaseFoldIterator(m.input, *fp.inputIdx(), m.activeLimit)
success := true
for {
captureGroupChar := captureGroupItr.next()
if captureGroupChar == -1 {
success = true
break
}
inputChar := inputItr.next()
if inputChar == -1 {
success = false
m.hitEnd = true
break
}
if inputChar != captureGroupChar {
success = false
break
}
}
if success && inputItr.inExpansion() {
// We otained a match by consuming part of a string obtained from
// case-folding a single code point of the input text.
// This does not count as an overall match.
success = false
}
if success {
*fp.inputIdx() = inputItr.index
} else {
fp = m.stack.popFrame()
}
case urxStoInpLoc:
*fp.extra(op.value()) = *fp.inputIdx()
case urxJmpx:
instrOperandLoc := *fp.patIdx()
*fp.patIdx()++
dataLoc := pat[instrOperandLoc].value()
saveInputIdx := *fp.extra(dataLoc)
if saveInputIdx < *fp.inputIdx() {
*fp.patIdx() = op.value() // JMP
} else {
fp = m.stack.popFrame() // FAIL, no progress in loop.
}
case urxLaStart:
m.data[op.value()] = m.stack.len()
m.data[op.value()+1] = *fp.inputIdx()
m.data[op.value()+2] = m.activeStart
m.data[op.value()+3] = m.activeLimit
m.activeStart = m.lookStart // Set the match region change for
m.activeLimit = m.lookLimit // transparent bounds.
case urxLaEnd:
stackSize := m.stack.len()
newStackSize := m.data[op.value()]
if stackSize > newStackSize {
// Copy the current top frame back to the new (cut back) top frame.
// This makes the capture groups from within the look-ahead
// expression available.
newFp := m.stack.offset(newStackSize)
copy(newFp, fp)
fp = newFp
m.stack.setSize(newStackSize)
}
*fp.inputIdx() = m.data[op.value()+1]
m.activeStart = m.data[op.value()+2]
m.activeLimit = m.data[op.value()+3]
case urcOnecharI:
// Case insensitive one char. The char from the pattern is already case folded.
// Input text is not, but case folding the input can not reduce two or more code
// points to one.
if *fp.inputIdx() < m.activeLimit {
c := charAt(inputText, *fp.inputIdx())
if ucase.Fold(c) == op.value32() {
*fp.inputIdx()++
break
}
} else {
m.hitEnd = true
}
fp = m.stack.popFrame()
case urxStringI:
// Case-insensitive test input against a literal string.
// Strings require two slots in the compiled pattern, one for the
// offset to the string text, and one for the length.
// The compiled string has already been case folded.
patternString := litText[op.value():]
var patternStringIdx int
nextOp := pat[*fp.patIdx()]
*fp.patIdx()++
patternStringLen := nextOp.value()
success := true
it := newCaseFoldIterator(inputText, *fp.inputIdx(), m.activeLimit)
for patternStringIdx < patternStringLen {
cText := it.next()
cPattern := patternString[patternStringIdx]
patternStringIdx++
if cText != cPattern {
success = false
if cText == -1 {
m.hitEnd = true
}
break
}
}
if it.inExpansion() {
success = false
}
if success {
*fp.inputIdx() = it.index
} else {
fp = m.stack.popFrame()
}
case urxLbStart:
// Entering a look-behind block.
// Save Stack Ptr, Input Pos and active input region.
// TODO: implement transparent bounds. Ticket #6067
m.data[op.value()] = m.stack.len()
m.data[op.value()+1] = *fp.inputIdx()
// Save input string length, then reset to pin any matches to end at
// the current position.
m.data[op.value()+2] = m.activeStart
m.data[op.value()+3] = m.activeLimit
m.activeStart = m.regionStart
m.activeLimit = *fp.inputIdx()
// Init the variable containing the start index for attempted matches.
m.data[op.value()+4] = -1
case urxLbCont:
// Positive Look-Behind, at top of loop checking for matches of LB expression
// at all possible input starting positions.
// Fetch the min and max possible match lengths. They are the operands
// of this op in the pattern.
minML := pat[*fp.patIdx()]
*fp.patIdx()++
maxML := pat[*fp.patIdx()]
*fp.patIdx()++
lbStartIdx := &m.data[op.value()+4]
if *lbStartIdx < 0 {
// First time through loop.
*lbStartIdx = *fp.inputIdx() - int(minML)
if *lbStartIdx > 0 {
*lbStartIdx = *fp.inputIdx()
}
} else {
// 2nd through nth time through the loop.
// Back up start position for match by one.
*lbStartIdx--
}
if *lbStartIdx < 0 || *lbStartIdx < *fp.inputIdx()-int(maxML) {
// We have tried all potential match starting points without
// getting a match. Backtrack out, and out of the
// Look Behind altogether.
fp = m.stack.popFrame()
m.activeStart = m.data[op.value()+2]
m.activeLimit = m.data[op.value()+3]
break
}
// Save state to this URX_LB_CONT op, so failure to match will repeat the loop.
// (successful match will fall off the end of the loop.)
fp, err = m.stateSave(*fp.inputIdx(), *fp.patIdx()-3)
if err != nil {
return err
}
*fp.inputIdx() = *lbStartIdx
case urxLbEnd:
// End of a look-behind block, after a successful match.
if *fp.inputIdx() != m.activeLimit {
// The look-behind expression matched, but the match did not
// extend all the way to the point that we are looking behind from.
// FAIL out of here, which will take us back to the LB_CONT, which
// will retry the match starting at another position or fail
// the look-behind altogether, whichever is appropriate.
fp = m.stack.popFrame()
break
}
// Look-behind match is good. Restore the orignal input string region,
// which had been truncated to pin the end of the lookbehind match to the
// position being looked-behind.
m.activeStart = m.data[op.value()+2]
m.activeLimit = m.data[op.value()+3]
case urxLbnCount:
// Negative Look-Behind, at top of loop checking for matches of LB expression
// at all possible input starting positions.
// Fetch the extra parameters of this op.
minML := pat[*fp.patIdx()]
*fp.patIdx()++
maxML := pat[*fp.patIdx()]
*fp.patIdx()++
continueLoc := pat[*fp.patIdx()].value()
*fp.patIdx()++
lbStartIdx := &m.data[op.value()+4]
if *lbStartIdx < 0 {
// First time through loop.
*lbStartIdx = *fp.inputIdx() - int(minML)
if *lbStartIdx > 0 {