-
Notifications
You must be signed in to change notification settings - Fork 6
/
fuzzymatcher.h
1178 lines (1171 loc) · 42.2 KB
/
fuzzymatcher.h
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) 2016, Robert van Engelen, Genivia Inc. All rights reserved. *
* *
* 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. *
* *
* (3) The name of the author may not be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. *
\******************************************************************************/
/**
@file fuzzymatcher.h
@brief RE/flex fuzzy matcher engine
@author Robert van Engelen - [email protected]
@copyright (c) 2016-2020, Robert van Engelen, Genivia Inc. All rights reserved.
@copyright (c) BSD-3 License - see LICENSE.txt
*/
#ifndef REFLEX_FUZZYMATCHER_H
#define REFLEX_FUZZYMATCHER_H
#include <reflex/matcher.h>
#include <reflex/pattern.h>
namespace reflex {
/// RE/flex fuzzy matcher engine class, implements reflex::Matcher fuzzy pattern matching interface with scan, find, split functors and iterators.
/** More info TODO */
class FuzzyMatcher : public Matcher {
public:
/// Optional flags for the max parameter to constrain fuzzy matching, otherwise no constraints
static const uint16_t INS = 0x1000; ///< fuzzy match allows character insertions (default)
static const uint16_t DEL = 0x2000; ///< fuzzy match allows character deletions (default)
static const uint16_t SUB = 0x4000; ///< character substitutions count as one edit, not two (insert+delete) (default)
static const uint16_t BIN = 0x8000; ///< binary matching without UTF-8 multibyte encodings
/// Default constructor.
FuzzyMatcher()
:
Matcher()
{
distance(1);
}
/// Construct matcher engine from a pattern or a string regex, and an input character sequence.
template<typename P> /// @tparam <P> a reflex::Pattern or a string regex
FuzzyMatcher(
const P *pattern, ///< points to a reflex::Pattern or a string regex for this matcher
const Input& input = Input(), ///< input character sequence for this matcher
const char *opt = NULL) ///< option string of the form `(A|N|T(=[[:digit:]])?|;)*`
:
Matcher(pattern, input, opt)
{
distance(1);
}
/// Construct matcher engine from a pattern or a string regex, and an input character sequence.
template<typename P> /// @tparam <P> a reflex::Pattern or a string regex
FuzzyMatcher(
const P *pattern, ///< points to a reflex::Pattern or a string regex for this matcher
uint16_t max, ///< max errors
const Input& input = Input(), ///< input character sequence for this matcher
const char *opt = NULL) ///< option string of the form `(A|N|T(=[[:digit:]])?|;)*`
:
Matcher(pattern, input, opt)
{
distance(max);
}
/// Construct matcher engine from a pattern or a string regex, and an input character sequence.
template<typename P> /// @tparam <P> a reflex::Pattern or a string regex
FuzzyMatcher(
const P& pattern, ///< a reflex::Pattern or a string regex for this matcher
const Input& input = Input(), ///< input character sequence for this matcher
const char *opt = NULL) ///< option string of the form `(A|N|T(=[[:digit:]])?|;)*`
:
Matcher(pattern, input, opt)
{
distance(1);
}
/// Construct matcher engine from a pattern or a string regex, and an input character sequence.
template<typename P> /// @tparam <P> a reflex::Pattern or a string regex
FuzzyMatcher(
const P& pattern, ///< a reflex::Pattern or a string regex for this matcher
uint16_t max, ///< max errors
const Input& input = Input(), ///< input character sequence for this matcher
const char *opt = NULL) ///< option string of the form `(A|N|T(=[[:digit:]])?|;)*`
:
Matcher(pattern, input, opt)
{
distance(max);
}
/// Copy constructor.
FuzzyMatcher(const FuzzyMatcher& matcher) ///< matcher to copy with pattern (pattern may be shared)
:
Matcher(matcher),
max_(matcher.max_),
err_(0),
ins_(matcher.ins_),
del_(matcher.del_),
sub_(matcher.sub_),
bin_(matcher.bin_)
{
DBGLOG("FuzzyMatcher::FuzzyMatcher(matcher)");
bpt_.resize(max_);
}
/// Assign a matcher.
FuzzyMatcher& operator=(const FuzzyMatcher& matcher) ///< matcher to copy
{
Matcher::operator=(matcher);
max_ = matcher.max_;
err_ = 0;
ins_ = matcher.ins_;
del_ = matcher.del_;
sub_ = matcher.sub_;
bin_ = matcher.bin_;
bpt_.resize(max_);
return *this;
}
/// Polymorphic cloning.
virtual FuzzyMatcher *clone()
{
return new FuzzyMatcher(*this);
}
/// Returns the number of edits made for the match, edits() <= max, not guaranteed to be the minimum edit distance.
uint8_t edits()
/// @returns 0 to max edit distance
const
{
return err_;
}
/// Set or update fuzzy distance parameters
void distance(uint16_t max) ///< max errors, INS, DEL, SUB
{
max_ = static_cast<uint8_t>(max);
err_ = 0;
ins_ = ((max & (INS | DEL | SUB)) == 0 || (max & INS));
del_ = ((max & (INS | DEL | SUB)) == 0 || (max & DEL));
sub_ = ((max & (INS | DEL | SUB)) == 0 || (max & SUB));
bin_ = (max & BIN);
bpt_.resize(max_);
}
/// Get the fuzzy distance parameters, the max is stored in the lower byte and INS, DEL, SUB are hi byte bits
uint16_t distance()
{
return max_;
}
protected:
/// Save state to restore fuzzy matcher state after a second pass
struct SaveState {
SaveState(size_t ded)
:
use(false),
loc(0),
cap(0),
txt(0),
cur(0),
pos(0),
ded(ded),
mrk(false),
err(0)
{ }
bool use;
size_t loc;
size_t cap;
size_t txt;
size_t cur;
size_t pos;
size_t ded;
bool mrk;
uint8_t err;
};
/// Backtrack point.
struct BacktrackPoint {
BacktrackPoint()
:
pc0(NULL),
pc1(NULL),
len(0),
err(0),
alt(true),
sub(true)
{ }
const Pattern::Opcode *pc0; ///< start of opcode
const Pattern::Opcode *pc1; ///< pointer to opcode to rerun on backtracking
size_t len; ///< length of string matched so far
uint8_t err; ///< to restore errors
bool alt; ///< true if alternating between pattern char substitution and insertion, otherwise insertion only
bool sub; ///< flag alternates between pattern char substitution (true) and insertion (false)
};
/// Set backtrack point.
void point(BacktrackPoint& bpt, const Pattern::Opcode *pc, size_t len, bool alternate = true, bool eof = false)
{
// advance to a goto opcode
while (!Pattern::is_opcode_goto(*pc))
++pc;
bpt.pc0 = pc;
bpt.pc1 = pc;
bpt.len = len - !eof;
bpt.err = err_;
bpt.alt = sub_ && alternate;
bpt.sub = bpt.alt;
}
/// backtrack on a backtrack point to insert or substitute a pattern char, restoring current text char matched and errors.
const Pattern::Opcode *backtrack(BacktrackPoint& bpt, int& ch)
{
// no more alternatives
if (bpt.pc1 == NULL)
return NULL;
// done when no more goto opcodes on characters remain
if (!Pattern::is_opcode_goto(*bpt.pc1))
return bpt.pc1 = NULL;
Pattern::Index jump = Pattern::index_of(*bpt.pc1);
// last opcode is a HALT?
if (jump == Pattern::Const::HALT)
{
if (bin_ || !Pattern::is_opcode_goto(*bpt.pc0) || (Pattern::lo_of(*bpt.pc0) & 0xC0) != 0xC0 || (Pattern::hi_of(*bpt.pc0) & 0xC0) != 0xC0)
return bpt.pc1 = NULL;
// loop over UTF-8 multibytes, checking linear case only (i.e. one wide char or a short range)
for (int i = 0; i < 3; ++i)
{
jump = Pattern::index_of(*bpt.pc0);
if (jump == Pattern::Const::HALT || pat_->opc_ + jump == bpt.pc0)
return bpt.pc1 = NULL;
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(bpt.pc0[1]);
const Pattern::Opcode *pc0 = pat_->opc_ + jump;
const Pattern::Opcode *pc1 = pc0;
while (!Pattern::is_opcode_goto(*pc1))
++pc1;
if (Pattern::is_meta(Pattern::lo_of(*pc1)) || ((Pattern::lo_of(*pc1) & 0xC0) != 0x80 && (Pattern::hi_of(*pc1) & 0xC0) != 0x80))
break;
bpt.pc0 = pc0;
bpt.pc1 = pc1;
}
jump = Pattern::index_of(*bpt.pc1);
if (jump == Pattern::Const::HALT)
return bpt.pc1 = NULL;
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++bpt.pc1);
bpt.sub = bpt.alt;
DBGLOG("Multibyte jump to %u", jump);
}
else if (jump == Pattern::Const::LONG)
{
jump = Pattern::long_index_of(*++bpt.pc1);
}
// restore errors
err_ = bpt.err;
// restore pos in the input
pos_ = (txt_ - buf_) + bpt.len;
// set ch to previous char before pos
if (pos_ > 0)
ch = static_cast<unsigned char>(buf_[pos_ - 1]);
else
ch = got_;
// substitute or insert a pattern char in the text?
if (bpt.sub)
{
// try substituting a pattern char for a mismatching char in the text
DBGLOG("Substitute: jump to %u at pos %zu char %d (0x%x)", jump, pos_, ch, ch);
int c = get();
if (!bin_ && c != EOF)
{
// skip UTF-8 multibytes
if (c >= 0xC0)
{
int n = (c >= 0xE0) + (c >= 0xF0);
while (n-- >= 0)
if ((c = get()) == EOF)
break;
}
else
{
while ((peek() & 0xC0) == 0x80)
if ((c = get()) == EOF)
break;
}
}
bpt.sub = false;
bpt.pc1 += !bpt.alt;
}
else if (del_)
{
// try inserting a pattern char in the text to match a missing char in the text
DBGLOG("Delete: jump to %u at pos %zu char %d (0x%x)", jump, pos_, ch, ch);
bpt.sub = bpt.alt;
++bpt.pc1;
}
else
{
// no more alternatives
return NULL;
}
return pat_->opc_ + jump;
}
/// Returns true if input fuzzy-matched the pattern using method Const::SCAN, Const::FIND, Const::SPLIT, or Const::MATCH.
virtual size_t match(Method method) ///< Const::SCAN, Const::FIND, Const::SPLIT, or Const::MATCH
/// @returns nonzero if input matched the pattern
{
DBGLOG("BEGIN FuzzyMatcher::match()");
reset_text();
SaveState sst(ded_);
len_ = 0; // split text length starts with 0
anc_ = false; // no word boundary anchor found and applied
scan:
txt_ = buf_ + cur_;
#if !defined(WITH_NO_INDENT)
mrk_ = false;
ind_ = pos_; // ind scans input in buf[] in newline() up to pos - 1
col_ = 0; // count columns for indent matching
#endif
find:
int ch = got_;
bool bol = at_bol(); // at begin of line?
#if !defined(WITH_NO_INDENT)
redo:
#endif
lap_.resize(0);
cap_ = 0;
bool nul = method == Const::MATCH;
if (pat_->opc_ != NULL && (!opt_.W || at_wb()))
{
// skip to next line and keep searching if matching on anchor ^ and not at begin of line
if (method == Const::FIND && pat_->bol_ && !bol)
if (skip('\n'))
goto scan;
err_ = 0;
uint8_t stack = 0;
const Pattern::Opcode *pc = pat_->opc_;
// backtrack point (DFA and relative position in the match)
const Pattern::Opcode *pc0 = pc;
size_t len0 = pos_ - (txt_ - buf_);
while (true)
{
Pattern::Index back = Pattern::Const::IMAX; // where to jump back to
size_t bpos = 0; // backtrack position in the input
while (true)
{
Pattern::Opcode opcode = *pc;
Pattern::Index jump;
DBGLOG("Fetch: code[%zu] = 0x%08X", pc - pat_->opc_, opcode);
if (!Pattern::is_opcode_goto(opcode))
{
// save backtrack point (DFA and relative position in the match)
pc0 = pc;
len0 = pos_ - (txt_ - buf_);
switch (opcode >> 24)
{
case 0xFE: // TAKE
int c;
if (!opt_.W || (c = peek(), at_we(c, pos_)))
{
cap_ = Pattern::long_index_of(opcode);
DBGLOG("Take: cap = %zu", cap_);
cur_ = pos_;
}
++pc;
continue;
case 0xFD: // REDO
cap_ = Const::REDO;
DBGLOG("Redo");
cur_ = pos_;
++pc;
continue;
case 0xFC: // TAIL
{
Pattern::Lookahead la = Pattern::lookahead_of(opcode);
DBGLOG("Tail: %u", la);
if (lap_.size() > la && lap_[la] >= 0)
cur_ = txt_ - buf_ + static_cast<size_t>(lap_[la]); // mind the (new) gap
++pc;
continue;
}
case 0xFB: // HEAD
{
Pattern::Lookahead la = Pattern::lookahead_of(opcode);
DBGLOG("Head: lookahead[%u] = %zu", la, pos_ - (txt_ - buf_));
if (lap_.size() <= la)
lap_.resize(la + 1, -1);
lap_[la] = static_cast<int>(pos_ - (txt_ - buf_)); // mind the gap
++pc;
continue;
}
#if !defined(WITH_NO_INDENT)
case Pattern::META_DED - Pattern::META_MIN:
if (ded_ > 0)
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(pc[1]);
DBGLOG("Dedent ded = %zu", ded_); // unconditional dedent matching \j
nul = true;
pc = pat_->opc_ + jump;
continue;
}
#endif
}
if (ch == EOF)
break;
ch = get();
DBGLOG("Get: ch = %d (0x%x)", ch, ch);
// to jump to longest sequence of matching metas
jump = Pattern::Const::IMAX;
while (true)
{
if (jump == Pattern::Const::IMAX || back == Pattern::Const::IMAX)
{
if (!Pattern::is_opcode_goto(opcode))
{
// we no longer have to pass through all if jump and back are set
switch (opcode >> 24)
{
case 0xFE: // TAKE
if (!opt_.W || at_we(ch, pos_ - 1))
{
cap_ = Pattern::long_index_of(opcode);
DBGLOG("Take: cap = %zu", cap_);
cur_ = pos_;
if (ch != EOF)
--cur_; // must unget one char
}
opcode = *++pc;
continue;
case 0xFD: // REDO
cap_ = Const::REDO;
DBGLOG("Redo");
cur_ = pos_;
if (ch != EOF)
--cur_; // must unget one char
opcode = *++pc;
continue;
case 0xFC: // TAIL
{
Pattern::Lookahead la = Pattern::lookahead_of(opcode);
DBGLOG("Tail: %u", la);
if (lap_.size() > la && lap_[la] >= 0)
cur_ = txt_ - buf_ + static_cast<size_t>(lap_[la]); // mind the (new) gap
opcode = *++pc;
continue;
}
case 0xFB: // HEAD
opcode = *++pc;
continue;
#if !defined(WITH_NO_INDENT)
case Pattern::META_DED - Pattern::META_MIN:
DBGLOG("DED? %d", ch);
if (jump == Pattern::Const::IMAX && back == Pattern::Const::IMAX && bol && dedent())
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_IND - Pattern::META_MIN:
DBGLOG("IND? %d", ch);
if (jump == Pattern::Const::IMAX && back == Pattern::Const::IMAX && bol && indent())
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_UND - Pattern::META_MIN:
DBGLOG("UND");
if (mrk_)
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
mrk_ = false;
ded_ = 0;
opcode = *++pc;
continue;
#endif
case Pattern::META_EOB - Pattern::META_MIN:
DBGLOG("EOB? %d", ch);
if (jump == Pattern::Const::IMAX && ch == EOF)
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_BOB - Pattern::META_MIN:
DBGLOG("BOB? %d", at_bob());
if (jump == Pattern::Const::IMAX && at_bob())
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_EOL - Pattern::META_MIN:
DBGLOG("EOL? %d", ch);
anc_ = true;
if (jump == Pattern::Const::IMAX && (ch == EOF || ch == '\n' || (ch == '\r' && peek() == '\n')))
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_BOL - Pattern::META_MIN:
DBGLOG("BOL? %d", bol);
anc_ = true;
if (jump == Pattern::Const::IMAX && bol)
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_EWE - Pattern::META_MIN:
DBGLOG("EWE? %d", at_ewe(ch));
anc_ = true;
if (jump == Pattern::Const::IMAX && at_ewe(ch))
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_BWE - Pattern::META_MIN:
DBGLOG("BWE? %d", at_bwe(ch));
anc_ = true;
if (jump == Pattern::Const::IMAX && at_bwe(ch))
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_EWB - Pattern::META_MIN:
DBGLOG("EWB? %d", at_ewb());
anc_ = true;
if (jump == Pattern::Const::IMAX && at_ewb())
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_BWB - Pattern::META_MIN:
DBGLOG("BWB? %d", at_bwb());
anc_ = true;
if (jump == Pattern::Const::IMAX && at_bwb())
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_NWE - Pattern::META_MIN:
DBGLOG("NWE? %d", at_nwe(ch));
anc_ = true;
if (jump == Pattern::Const::IMAX && at_nwe(ch))
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_NWB - Pattern::META_MIN:
DBGLOG("NWB? %d", at_nwb());
anc_ = true;
if (jump == Pattern::Const::IMAX && at_nwb())
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_WBE - Pattern::META_MIN:
DBGLOG("WBE? %d", at_wbe(ch));
anc_ = true;
if (jump == Pattern::Const::IMAX && at_wbe(ch))
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case Pattern::META_WBB - Pattern::META_MIN:
DBGLOG("WBB? %d", at_wbb());
anc_ = true;
if (jump == Pattern::Const::IMAX && at_wbb())
{
jump = Pattern::index_of(opcode);
if (jump == Pattern::Const::LONG)
jump = Pattern::long_index_of(*++pc);
}
opcode = *++pc;
continue;
case 0xFF: // LONG
opcode = *++pc;
continue;
}
}
else if (ch != EOF && !Pattern::is_opcode_halt(opcode))
{
if (jump == Pattern::Const::IMAX)
break;
if (back == Pattern::Const::IMAX)
{
back = static_cast<Pattern::Index>(pc - pat_->opc_);
bpos = pos_ - (txt_ - buf_) - 1;
DBGLOG("Backtrack point: back = %u pos = %zu", back, bpos);
}
pc = pat_->opc_ + jump;
opcode = *pc;
}
}
if (jump == Pattern::Const::IMAX)
{
if (back != Pattern::Const::IMAX)
{
pc = pat_->opc_ + back;
opcode = *pc;
back = Pattern::Const::IMAX;
}
break;
}
DBGLOG("Try jump = %u", jump);
if (back == Pattern::Const::IMAX)
{
back = static_cast<Pattern::Index>(pc - pat_->opc_);
bpos = pos_ - (txt_ - buf_) - 1;
DBGLOG("Backtrack point: back = %u pos = %zu", back, bpos);
}
pc = pat_->opc_ + jump;
opcode = *pc;
jump = Pattern::Const::IMAX;
}
if (ch == EOF)
break;
}
else
{
if (ch == EOF)
break;
ch = get();
if (Pattern::is_opcode_halt(opcode))
{
if (back != Pattern::Const::IMAX)
{
pos_ = (txt_ - buf_) + bpos;
pc = pat_->opc_ + back;
DBGLOG("Backtrack: back = %u pos = %zu ch = %d", back, pos_, ch);
back = Pattern::Const::IMAX;
continue;
}
break;
}
DBGLOG("Get: ch = %d (0x%x) at pos %zu", ch, ch, pos_ - 1);
if (bin_ || (ch & 0xC0) != 0x80 || ch == EOF)
{
// save backtrack point (DFA and relative position in the match)
pc0 = pc;
len0 = pos_ - (txt_ - buf_);
}
if (ch == EOF)
break;
}
{
Pattern::Opcode lo = ch << 24;
Pattern::Opcode hi = lo | 0x00FFFFFF;
unrolled:
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
if (hi < opcode || lo > (opcode << 8))
{
opcode = *++pc;
goto unrolled;
}
}
}
}
}
}
}
}
}
jump = Pattern::index_of(opcode);
if (jump == 0)
{
// loop back to start state w/o full match: advance to avoid backtracking
if (cap_ == 0 && method == Const::FIND)
{
if (cur_ + 1 == pos_)
{
// matched one char in a loop, do not backtrack here
++cur_;
}
else
{
// check each char in buf_[cur_+1..pos_-1] if it is a starting char, if not then increase cur_
while (cur_ + 1 < pos_ && !pat_->fst_.test(static_cast<uint8_t>(buf_[cur_ + 1])))
++cur_;
}
}
}
else if (jump >= Pattern::Const::LONG)
{
if (jump == Pattern::Const::HALT)
{
if (back != Pattern::Const::IMAX)
{
pc = pat_->opc_ + back;
pos_ = (txt_ - buf_) + bpos;
DBGLOG("Backtrack: back = %u pos = %zu ch = %d", back, pos_, ch);
back = Pattern::Const::IMAX;
continue;
}
break;
}
jump = Pattern::long_index_of(pc[1]);
}
pc = pat_->opc_ + jump;
}
// exit fuzzy loop if nothing consumed
if (pos_ == static_cast<size_t>(txt_ + len_ - buf_))
break;
// match, i.e. cap_ > 0?
if (method == Const::MATCH)
{
// exit fuzzy loop if fuzzy match succeeds till end of input when insertions are allowed
if (cap_ > 0)
{
if (ch != EOF && ins_)
{
// text insertions are allowed
while (err_ < max_)
{
++err_;
ch = get();
// reached the end?
if (ch == EOF)
break;
// skip one (multibyte) char
if (!bin_ && ch >= 0xC0)
{
int n = (ch >= 0xE0) + (ch >= 0xF0);
while (n-- >= 0)
if ((ch = get()) == EOF)
break;
}
}
}
if (ch == EOF || ins_)
{
// reached the end?
if (at_end())
{
DBGLOG("Match pos = %zu", pos_);
set_current(pos_);
break;
}
}
cap_ = 0;
}
}
else
{
// exit fuzzy loop if match or if first char mismatched
if (cap_ > 0 || pos_ == static_cast<size_t>(txt_ + len_ - buf_ + 1))
break;
}
// no match, use fuzzy matching with max error
if (ch == '\0' || ch == '\n' || ch == EOF)
{
// do not try to fuzzy match NUL, LF, or EOF
if (err_ < max_ && del_)
{
++err_;
// set backtrack point to insert pattern char only, not substitute, if pc0 os a different point than the last
if (stack == 0 || bpt_[stack - 1].pc0 != pc0)
{
point(bpt_[stack++], pc0, len0, false, ch == EOF);
DBGLOG("Point[%u] at %zu pos %zu (\\0|\\nEOF)", stack - 1, pc0 - pat_->opc_, pos_ - 1);
}
}
else
{
// backtrack to try insertion or substitution of pattern char
pc = NULL;
while (stack > 0 && pc == NULL)
{
pc = backtrack(bpt_[stack - 1], ch);
if (pc == NULL)
--stack;
}
// exhausted all backtracking points?
if (pc == NULL)
break;
}
}
else
{
if (err_ < max_)
{
++err_;
if (del_ || sub_)
{
// set backtrack point if pc0 is a different point than the last
if (stack == 0 || bpt_[stack - 1].pc0 != pc0)
{
point(bpt_[stack++], pc0, len0);
DBGLOG("Point[%u] at %zu pos %zu", stack - 1, pc0 - pat_->opc_, pos_ - 1);
}
}
if (ins_)
{
if (!bin_)
{
// try pattern char deletion (text insertion): skip one (multibyte) char then rerun opcode at pc0
if (ch >= 0xC0)
{
int n = (ch >= 0xE0) + (ch >= 0xF0);
while (n-- >= 0)
if ((ch = get()) == EOF)
break;
}
else
{
while ((peek() & 0xC0) == 0x80)
if ((ch = get()) == EOF)
break;
}
}
pc = pc0;
DBGLOG("Insert: %d (0x%x) at pos %zu", ch, ch, pos_ - 1);
}
}
else
{
// backtrack to try insertion or substitution of pattern char
pc = NULL;
while (stack > 0 && pc == NULL)
{
pc = backtrack(bpt_[stack - 1], ch);
if (pc == NULL)
--stack;
}
// exhausted all backtracking points?
if (pc == NULL)
break;
}
}
}
}
// if fuzzy find/split with errors then perform a second pass ahead of this match to check for an exact match
if (cap_ > 0 && err_ > 0 && !sst.use && (method == Const::FIND || method == Const::SPLIT))
{
// this part is based on advance() in matcher.cpp, limited to advancing ahead till the one of the first pattern char(s) match excluding \n
size_t loc = txt_ - buf_ + 1;
const char *s = buf_ + loc;
const char *e = static_cast<const char*>(std::memchr(s, '\n', cur_ - loc));
if (e == NULL)
e = buf_ + cur_;
if (pat_->len_ == 0)
{
if (pat_->min_ > 0)
{
while (s < e && !pat_->fst_.test(static_cast<uint8_t>(*s)))
++s;
if (s < e)
{
loc = s - buf_;
sst.use = true;
sst.loc = loc;
sst.cap = cap_;
sst.txt = txt_ - buf_;
sst.cur = cur_;
sst.pos = pos_;
size_t tmp = ded_;
ded_ = sst.ded;
sst.ded = tmp;
sst.mrk = mrk_;
sst.err = err_;
set_current(loc);
goto scan;
}
}
}
else if (s < e)
{
s = static_cast<const char*>(std::memchr(s, *pat_->chr_, e - s));
if (s != NULL)
{
loc = s - buf_;
sst.use = true;
sst.loc = loc;
sst.cap = cap_;
sst.txt = txt_ - buf_;
sst.cur = cur_;
sst.pos = pos_;
size_t tmp = ded_;
ded_ = sst.ded;
sst.ded = tmp;
sst.mrk = mrk_;
sst.err = err_;
set_current(loc);
goto scan;
}
}
}
else if (sst.use && (cap_ == 0 || err_ >= sst.err))
{
// if the buffer was shifted then cur_, pos_ and txt_ are no longer at the same location in the buffer, we must adjust for this
size_t loc = txt_ - buf_;
size_t shift = sst.loc - loc;
cap_ = sst.cap;
cur_ = sst.cur - shift;
pos_ = sst.pos - shift;
ded_ = sst.ded;
mrk_ = sst.mrk;
err_ = sst.err;
txt_ = buf_ + sst.txt - shift;
}
else if (sst.use && cap_ > 0 && method == Const::SPLIT)
{
size_t loc = txt_ - buf_;
size_t shift = sst.loc - loc;
len_ = loc - sst.txt + shift;
}
#if !defined(WITH_NO_INDENT)
if (mrk_ && cap_ != Const::REDO)
{
if (col_ > 0 && (tab_.empty() || tab_.back() < col_))
{
DBGLOG("Set new stop: tab_[%zu] = %zu", tab_.size(), col_);
tab_.push_back(col_);
}
else if (!tab_.empty() && tab_.back() > col_)
{
size_t n;
for (n = tab_.size() - 1; n > 0; --n)
if (tab_.at(n - 1) <= col_)
break;
ded_ += tab_.size() - n;
DBGLOG("Dedents: ded = %zu tab_ = %zu", ded_, tab_.size());
tab_.resize(n);
// adjust stop when indents are not aligned (Python would give an error)
if (n > 0)
tab_.back() = col_;
}
}
if (ded_ > 0)
{
DBGLOG("Dedents: ded = %zu", ded_);
if (col_ == 0 && bol)
{