forked from sourcegraph/zoekt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matchtree.go
1413 lines (1230 loc) · 33.4 KB
/
matchtree.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
// Copyright 2018 Google Inc. All rights reserved.
//
// 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 zoekt
import (
"bytes"
"fmt"
"log"
"regexp/syntax"
"strings"
"unicode/utf8"
"github.com/grafana/regexp"
"github.com/sourcegraph/zoekt/internal/syntaxutil"
"github.com/sourcegraph/zoekt/query"
)
// A docIterator iterates over documents in order.
type docIterator interface {
// provide the next document where we may find something interesting.
//
// This is like a "peek" and shouldn't mutate state. prepare is what should
// change state.
nextDoc() uint32
// clears any per-document state of the docIterator, and
// prepares for evaluating the given doc. The argument is
// strictly increasing over time.
prepare(nextDoc uint32)
}
// costs are passed in increasing order to matchTree.matches until they do not
// return matchesRequiresHigherCost.
const (
costConst = 0
costMemory = 1
costContent = 2
costRegexp = 3
)
const (
costMin = costConst
costMax = costRegexp
)
// matchesState is an enum for the state of a matchTree after a call to
// matchTree.matches.
type matchesState uint8
const (
// matchesRequiresHigherCost is returned when matchTree.matches hasn't done
// a search yet since the cost value is not high enough.
matchesRequiresHigherCost matchesState = iota
// matchesFound is returned when matchTree.matches has done a search and
// found one or more matches.
matchesFound
// matchesNone is returned when matchTree.matches has done a search and
// found nothing.
matchesNone
)
// matchesStatePred is a helper which returns matchesFound if b is true
// otherwise returns matchesNone.
func matchesStatePred(b bool) matchesState {
if b {
return matchesFound
}
return matchesNone
}
// matchesStateForSlice is a helper which returns matchesFound if v is
// non-empty otherwise returns matchesNone.
func matchesStateForSlice[T any](v []T) matchesState {
return matchesStatePred(len(v) > 0)
}
// An expression tree coupled with matches. The matchtree has two
// functions:
//
// * it implements boolean combinations (and, or, not)
//
// * it implements shortcuts, where we skip documents (for example: if
// there are no trigram matches, we can be sure there are no substring
// matches). The matchtree iterates over the documents as they are
// ordered in the shard.
//
// The general process for a given (shard, query) is:
//
// - construct matchTree for the query
//
// - find all different leaf matchTrees (substring, regexp, etc.)
//
// in a loop:
//
// - find next doc to process using nextDoc
//
// - evaluate atoms (leaf expressions that match text)
//
// - evaluate the tree using matches(), storing the result in map.
//
// - if the complete tree returns (matches() != matchesRequiresHigherCost)
// for the document, collect all text matches by looking at leaf
// matchTrees.
type matchTree interface {
docIterator
// matches if cost is high enough. See documentation for matchesState's
// values.
//
// Note: Do not call this directly, rather use evalMatchTree which uses
// known to cache responses once the state transitions away from
// matchesRequiresHigherCost.
matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState
}
// docMatchTree iterates over documents for which predicate(docID) returns true.
type docMatchTree struct {
// the number of documents in a shard.
numDocs uint32
predicate func(docID uint32) bool
// provides additional information about the reason why the docMatchTree was
// created.
reason string
// mutable
firstDone bool
docID uint32
}
type bruteForceMatchTree struct {
// mutable
firstDone bool
docID uint32
}
type andLineMatchTree struct {
andMatchTree
}
type andMatchTree struct {
children []matchTree
}
type orMatchTree struct {
children []matchTree
}
type notMatchTree struct {
child matchTree
}
// Returns only the filename of child matches.
type fileNameMatchTree struct {
child matchTree
}
type boostMatchTree struct {
child matchTree
boost float64
}
// Don't visit this subtree for collecting matches.
type noVisitMatchTree struct {
matchTree
}
type regexpMatchTree struct {
regexp *regexp.Regexp
// origRegexp is the original parsed regexp from the query structure. It
// does not include mutations such as case sensitivity.
origRegexp *syntax.Regexp
fileName bool
// mutable
reEvaluated bool
found []*candidateMatch
// nextDoc, prepare.
bruteForceMatchTree
}
func newRegexpMatchTree(s *query.Regexp) *regexpMatchTree {
prefix := ""
if !s.CaseSensitive {
prefix = "(?i)"
}
return ®expMatchTree{
regexp: regexp.MustCompile(prefix + syntaxutil.RegexpString(s.Regexp)),
origRegexp: s.Regexp,
fileName: s.FileName,
}
}
// \bLITERAL\b
type wordMatchTree struct {
word string
fileName bool
// mutable
evaluated bool
found []*candidateMatch
// nextDoc, prepare.
bruteForceMatchTree
}
type substrMatchTree struct {
matchIterator
query *query.Substring
caseSensitive bool
fileName bool
// mutable
current []*candidateMatch
contEvaluated bool
}
type branchQueryMatchTree struct {
fileMasks []uint64
masks []uint64
repos []uint16
// mutable
firstDone bool
docID uint32
}
func (t *branchQueryMatchTree) branchMask() uint64 {
return t.fileMasks[t.docID] & t.masks[t.repos[t.docID]]
}
type symbolRegexpMatchTree struct {
matchTree
regexp *regexp.Regexp
all bool // skips regex match if .*
reEvaluated bool
found []*candidateMatch
}
func (t *symbolRegexpMatchTree) prepare(doc uint32) {
t.reEvaluated = false
t.found = t.found[:0]
t.matchTree.prepare(doc)
}
func (t *symbolRegexpMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
if t.reEvaluated {
return matchesStateForSlice(t.found)
}
if cost < costRegexp {
return matchesRequiresHigherCost
}
sections := cp.docSections()
content := cp.data(false)
found := t.found[:0]
for i, sec := range sections {
var idx []int
if t.all {
idx = []int{0, int(sec.End - sec.Start)}
} else {
idx = t.regexp.FindIndex(content[sec.Start:sec.End])
if idx == nil {
continue
}
}
cm := &candidateMatch{
byteOffset: sec.Start + uint32(idx[0]),
byteMatchSz: uint32(idx[1] - idx[0]),
symbol: true,
symbolIdx: uint32(i),
}
found = append(found, cm)
}
t.found = found
t.reEvaluated = true
return matchesStateForSlice(t.found)
}
type symbolSubstrMatchTree struct {
*substrMatchTree
patternSize uint32
fileEndRunes []uint32
fileEndSymbol []uint32
doc uint32
sections []DocumentSection
secID uint32
}
func (t *symbolSubstrMatchTree) prepare(doc uint32) {
t.substrMatchTree.prepare(doc)
t.doc = doc
var fileStart uint32
if doc > 0 {
fileStart = t.fileEndRunes[doc-1]
}
var sections []DocumentSection
if len(t.sections) > 0 {
most := t.fileEndSymbol[len(t.fileEndSymbol)-1]
if most == uint32(len(t.sections)) {
sections = t.sections[t.fileEndSymbol[doc]:t.fileEndSymbol[doc+1]]
} else {
for t.secID < uint32(len(t.sections)) && t.sections[t.secID].Start < fileStart {
t.secID++
}
fileEnd, symbolEnd := t.fileEndRunes[doc], t.secID
for symbolEnd < uint32(len(t.sections)) && t.sections[symbolEnd].Start < fileEnd {
symbolEnd++
}
sections = t.sections[t.secID:symbolEnd]
}
}
secIdx := 0
trimmed := t.current[:0]
for len(sections) > secIdx && len(t.current) > 0 {
start := fileStart + t.current[0].runeOffset
end := start + t.patternSize
if start >= sections[secIdx].End {
secIdx++
continue
}
if start < sections[secIdx].Start {
t.current = t.current[1:]
continue
}
if end <= sections[secIdx].End {
t.current[0].symbol = true
t.current[0].symbolIdx = uint32(secIdx)
trimmed = append(trimmed, t.current[0])
}
t.current = t.current[1:]
}
t.current = trimmed
}
// all prepare methods
func (t *bruteForceMatchTree) prepare(doc uint32) {
t.docID = doc
t.firstDone = true
}
func (t *docMatchTree) prepare(doc uint32) {
t.docID = doc
t.firstDone = true
}
func (t *andMatchTree) prepare(doc uint32) {
for _, c := range t.children {
c.prepare(doc)
}
}
func (t *regexpMatchTree) prepare(doc uint32) {
t.found = t.found[:0]
t.reEvaluated = false
t.bruteForceMatchTree.prepare(doc)
}
func (t *wordMatchTree) prepare(doc uint32) {
t.found = t.found[:0]
t.evaluated = false
t.bruteForceMatchTree.prepare(doc)
}
func (t *orMatchTree) prepare(doc uint32) {
for _, c := range t.children {
c.prepare(doc)
}
}
func (t *notMatchTree) prepare(doc uint32) {
t.child.prepare(doc)
}
func (t *fileNameMatchTree) prepare(doc uint32) {
t.child.prepare(doc)
}
func (t *boostMatchTree) prepare(doc uint32) {
t.child.prepare(doc)
}
func (t *substrMatchTree) prepare(nextDoc uint32) {
t.matchIterator.prepare(nextDoc)
t.current = t.matchIterator.candidates()
t.contEvaluated = false
}
func (t *branchQueryMatchTree) prepare(doc uint32) {
t.firstDone = true
t.docID = doc
}
// nextDoc
func (t *docMatchTree) nextDoc() uint32 {
var start uint32
if t.firstDone {
start = t.docID + 1
}
for i := start; i < t.numDocs; i++ {
if t.predicate(i) {
return i
}
}
return maxUInt32
}
func (t *bruteForceMatchTree) nextDoc() uint32 {
if !t.firstDone {
return 0
}
return t.docID + 1
}
func (t *andMatchTree) nextDoc() uint32 {
var max uint32
for _, c := range t.children {
m := c.nextDoc()
if m > max {
max = m
}
}
return max
}
func (t *orMatchTree) nextDoc() uint32 {
min := uint32(maxUInt32)
for _, c := range t.children {
m := c.nextDoc()
if m < min {
min = m
}
}
return min
}
func (t *notMatchTree) nextDoc() uint32 {
return 0
}
func (t *fileNameMatchTree) nextDoc() uint32 {
return t.child.nextDoc()
}
func (t *boostMatchTree) nextDoc() uint32 {
return t.child.nextDoc()
}
func (t *branchQueryMatchTree) nextDoc() uint32 {
var start uint32
if t.firstDone {
start = t.docID + 1
}
for i := start; i < uint32(len(t.fileMasks)); i++ {
if (t.masks[t.repos[i]] & t.fileMasks[i]) != 0 {
return i
}
}
return maxUInt32
}
// all String methods
func (t *bruteForceMatchTree) String() string {
return "all"
}
func (t *docMatchTree) String() string {
return fmt.Sprintf("doc(%s)", t.reason)
}
func (t *andMatchTree) String() string {
return fmt.Sprintf("and%v", t.children)
}
func (t *regexpMatchTree) String() string {
f := ""
if t.fileName {
f = "f"
}
return fmt.Sprintf("%sre(%s)", f, t.regexp)
}
func (t *wordMatchTree) String() string {
f := ""
if t.fileName {
f = "f"
}
return fmt.Sprintf("%sword(%s)", f, t.word)
}
func (t *orMatchTree) String() string {
return fmt.Sprintf("or%v", t.children)
}
func (t *notMatchTree) String() string {
return fmt.Sprintf("not(%v)", t.child)
}
func (t *noVisitMatchTree) String() string {
return fmt.Sprintf("novisit(%v)", t.matchTree)
}
func (t *fileNameMatchTree) String() string {
return fmt.Sprintf("f(%v)", t.child)
}
func (t *boostMatchTree) String() string {
return fmt.Sprintf("boost(%f, %v)", t.boost, t.child)
}
func (t *substrMatchTree) String() string {
f := ""
if t.fileName {
f = "f"
}
return fmt.Sprintf("%ssubstr(%q, %v, %v)", f, t.query.Pattern, t.current, t.matchIterator)
}
func (t *branchQueryMatchTree) String() string {
return fmt.Sprintf("branch(%x)", t.masks)
}
func (t *symbolSubstrMatchTree) String() string {
return fmt.Sprintf("symbol(%v)", t.substrMatchTree)
}
func (t *symbolRegexpMatchTree) String() string {
return fmt.Sprintf("symbol(%v)", t.matchTree)
}
// visitMatches visits all atoms in matchTree. Note: This visits
// noVisitMatchTree. For collecting matches use visitMatches.
func visitMatchTree(t matchTree, f func(matchTree)) {
switch s := t.(type) {
case *andMatchTree:
for _, ch := range s.children {
visitMatchTree(ch, f)
}
case *orMatchTree:
for _, ch := range s.children {
visitMatchTree(ch, f)
}
case *andLineMatchTree:
visitMatchTree(&s.andMatchTree, f)
case *noVisitMatchTree:
visitMatchTree(s.matchTree, f)
case *notMatchTree:
visitMatchTree(s.child, f)
case *fileNameMatchTree:
visitMatchTree(s.child, f)
case *boostMatchTree:
visitMatchTree(s.child, f)
case *symbolSubstrMatchTree:
visitMatchTree(s.substrMatchTree, f)
case *symbolRegexpMatchTree:
visitMatchTree(s.matchTree, f)
default:
f(t)
}
}
// updateMatchTreeStats calls updateStats on all atoms in mt which have that
// function defined.
func updateMatchTreeStats(mt matchTree, stats *Stats) {
visitMatchTree(mt, func(mt matchTree) {
if atom, ok := mt.(interface{ updateStats(*Stats) }); ok {
atom.updateStats(stats)
}
})
}
func visitMatchAtoms(t matchTree, known map[matchTree]bool, f func(matchTree)) {
visitMatches(t, known, 1, func(mt matchTree, _ float64) {
f(mt)
})
}
// visitMatches visits all atoms which can contribute matches. Note: This
// skips noVisitMatchTree.
func visitMatches(t matchTree, known map[matchTree]bool, weight float64, f func(matchTree, float64)) {
switch s := t.(type) {
case *andMatchTree:
for _, ch := range s.children {
if known[ch] {
visitMatches(ch, known, weight, f)
}
}
case *andLineMatchTree:
visitMatches(&s.andMatchTree, known, weight, f)
case *orMatchTree:
for _, ch := range s.children {
if known[ch] {
visitMatches(ch, known, weight, f)
}
}
case *boostMatchTree:
visitMatches(s.child, known, weight*s.boost, f)
case *symbolSubstrMatchTree:
visitMatches(s.substrMatchTree, known, weight, f)
case *notMatchTree:
case *noVisitMatchTree:
// don't collect into negative trees.
case *fileNameMatchTree:
// We will just gather the filename if we do not visit this tree.
default:
f(s, weight)
}
}
// all matches() methods.
func (t *docMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
return matchesStatePred(t.predicate(cp.idx))
}
func (t *bruteForceMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
return matchesFound
}
// andLineMatchTree is a performance optimization of andMatchTree. For content
// searches we don't want to run the regex engine if there is no line that
// contains matches from all terms.
func (t *andLineMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
if state := evalMatchTree(cp, cost, known, &t.andMatchTree); state != matchesFound {
return state
}
// Invariant: all children have matches. If any line contains all of them we
// can return MatchesFound.
// find child with fewest candidates
min := maxUInt32
fewestChildren := 0
for ix, child := range t.children {
v, ok := child.(*substrMatchTree)
// make sure we are running a content search and that all candidates are a
// substrMatchTree
if !ok || v.fileName {
return matchesFound
}
if len(v.current) < min {
min = len(v.current)
fewestChildren = ix
}
}
type lineRange struct {
start int
end int
}
lines := make([]lineRange, 0, len(t.children[fewestChildren].(*substrMatchTree).current))
prev := -1
for _, candidate := range t.children[fewestChildren].(*substrMatchTree).current {
line := cp.newlines().atOffset(candidate.byteOffset)
if line == prev {
continue
}
prev = line
byteStart := int(cp.newlines().lineStart(line))
byteEnd := int(cp.newlines().lineStart(line + 1))
lines = append(lines, lineRange{byteStart, byteEnd})
}
// children keeps track of the children's candidates we have already seen.
children := make([][]*candidateMatch, 0, len(t.children)-1)
for j, child := range t.children {
if j == fewestChildren {
continue
}
children = append(children, child.(*substrMatchTree).current)
}
nextLine:
for i := 0; i < len(lines); i++ {
hits := 1
nextChild:
for j := range children {
nextCandidate:
for len(children[j]) > 0 {
candidate := children[j][0]
bo := int(cp.findOffset(false, candidate.runeOffset))
if bo < lines[i].start {
children[j] = children[j][1:]
continue nextCandidate
}
if bo < lines[i].end {
hits++
continue nextChild
}
// move the `lines` iterator forward until bo < line.end
for i < len(lines) && bo >= lines[i].end {
i++
}
i--
continue nextLine
}
}
// return early once we found any line that contains matches from all children
if hits == len(t.children) {
return matchesFound
}
}
return matchesNone
}
func (t *andMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
// We have found matches unless a child needs to do more work or it hasn't
// found matches.
state := matchesFound
for _, ch := range t.children {
switch evalMatchTree(cp, cost, known, ch) {
case matchesRequiresHigherCost:
// keep evaluating other children incase we come across matchesNone
state = matchesRequiresHigherCost
case matchesFound:
// will return this if every child has this value
case matchesNone:
return matchesNone
}
}
return state
}
func (t *orMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
// we could short-circuit, but we want to use the other possibilities as a
// ranking signal. So we always return the most conservative state.
state := matchesNone
for _, ch := range t.children {
switch evalMatchTree(cp, cost, known, ch) {
case matchesRequiresHigherCost:
state = matchesRequiresHigherCost
case matchesFound:
if state != matchesRequiresHigherCost {
state = matchesFound
}
case matchesNone:
// noop
}
}
return state
}
func (t *branchQueryMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
return matchesStatePred(t.branchMask() != 0)
}
func (t *regexpMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
if t.reEvaluated {
return matchesStateForSlice(t.found)
}
if cost < costRegexp {
return matchesRequiresHigherCost
}
cp.stats.RegexpsConsidered++
idxs := t.regexp.FindAllIndex(cp.data(t.fileName), -1)
found := t.found[:0]
for _, idx := range idxs {
cm := &candidateMatch{
byteOffset: uint32(idx[0]),
byteMatchSz: uint32(idx[1] - idx[0]),
fileName: t.fileName,
}
found = append(found, cm)
}
t.found = found
t.reEvaluated = true
return matchesStateForSlice(t.found)
}
func (t *wordMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
if t.evaluated {
return matchesStateForSlice(t.found)
}
if cost < costRegexp {
return matchesRequiresHigherCost
}
data := cp.data(t.fileName)
offset := 0
found := t.found[:0]
for {
idx := bytes.Index(data[offset:], []byte(t.word))
if idx < 0 {
break
}
relStartOffset := offset + idx
relEndOffset := relStartOffset + len(t.word)
startBoundary := relStartOffset < len(data) && (relStartOffset == 0 || !characterClass(data[relStartOffset-1]))
endBoundary := relEndOffset > 0 && (relEndOffset == len(data) || !characterClass(data[relEndOffset]))
if startBoundary && endBoundary {
found = append(found, &candidateMatch{
byteOffset: uint32(offset + idx),
byteMatchSz: uint32(len(t.word)),
fileName: t.fileName,
})
}
offset += idx + len(t.word)
}
t.found = found
t.evaluated = true
return matchesStateForSlice(t.found)
}
// breakMatchesOnNewlines returns matches resulting from breaking each element
// of cms on newlines within text.
func breakMatchesOnNewlines(cms []*candidateMatch, text []byte) []*candidateMatch {
var lineCMs []*candidateMatch
for _, cm := range cms {
lineCMs = append(lineCMs, breakOnNewlines(cm, text)...)
}
return lineCMs
}
// breakOnNewlines returns matches resulting from breaking cm on newlines
// within text.
func breakOnNewlines(cm *candidateMatch, text []byte) []*candidateMatch {
var cms []*candidateMatch
addMe := &candidateMatch{}
*addMe = *cm
for i := uint32(cm.byteOffset); i < cm.byteOffset+cm.byteMatchSz; i++ {
if text[i] == '\n' {
addMe.byteMatchSz = i - addMe.byteOffset
if addMe.byteMatchSz != 0 {
cms = append(cms, addMe)
}
addMe = &candidateMatch{}
*addMe = *cm
addMe.byteOffset = i + 1
}
}
addMe.byteMatchSz = cm.byteOffset + cm.byteMatchSz - addMe.byteOffset
if addMe.byteMatchSz != 0 {
cms = append(cms, addMe)
}
return cms
}
// evalMatchTree should be called instead of directly calling
// matchTree.matches. It cache known values for future evaluation at higher
// costs.
func evalMatchTree(cp *contentProvider, cost int, known map[matchTree]bool, mt matchTree) matchesState {
if v, ok := known[mt]; ok {
return matchesStatePred(v)
}
ms := mt.matches(cp, cost, known)
if ms != matchesRequiresHigherCost {
known[mt] = ms == matchesFound
}
return ms
}
func (t *notMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
switch evalMatchTree(cp, cost, known, t.child) {
case matchesRequiresHigherCost:
return matchesRequiresHigherCost
case matchesFound:
return matchesNone
case matchesNone:
return matchesFound
default:
panic("unreachable")
}
}
func (t *fileNameMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
return evalMatchTree(cp, cost, known, t.child)
}
func (t *boostMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
return evalMatchTree(cp, cost, known, t.child)
}
func (t *substrMatchTree) matches(cp *contentProvider, cost int, known map[matchTree]bool) matchesState {
if t.contEvaluated {
return matchesStateForSlice(t.current)
}
if len(t.current) == 0 {
return matchesNone
}
if t.fileName && cost < costMemory {
return matchesRequiresHigherCost
}
if !t.fileName && cost < costContent {
return matchesRequiresHigherCost
}
pruned := t.current[:0]
for _, m := range t.current {
if m.byteOffset == 0 && m.runeOffset > 0 {
m.byteOffset = cp.findOffset(m.fileName, m.runeOffset)
}
if m.matchContent(cp.data(m.fileName)) {
pruned = append(pruned, m)
}
}
t.current = pruned
t.contEvaluated = true
return matchesStateForSlice(t.current)
}
type matchTreeOpt struct {
// DisableWordMatchOptimization is used to disable the use of wordMatchTree.
// This was added since we do not support wordMatchTree with symbol search.
DisableWordMatchOptimization bool
}
func (d *indexData) newMatchTree(q query.Q, opt matchTreeOpt) (matchTree, error) {
if q == nil {
return nil, fmt.Errorf("got nil (sub)query")
}
switch s := q.(type) {
case *query.Regexp:
// RegexpToMatchTreeRecursive tries to distill a matchTree that matches a
// superset of the regexp. If the returned matchTree is equivalent to the
// original regexp, it returns true. An equivalent matchTree has the same
// behaviour as the original regexp and can be used instead.
//
subMT, isEq, _, err := d.regexpToMatchTreeRecursive(s.Regexp, ngramSize, s.FileName, s.CaseSensitive)
if err != nil {
return nil, err
}
// if the query can be used in place of the regexp
// return the subtree
if isEq {
return subMT, nil
}
var tr matchTree
if wmt, ok := regexpToWordMatchTree(s, opt); ok {
// A common search we get is "\bLITERAL\b". Avoid the regex engine and
// provide something faster.
tr = wmt
} else {
tr = newRegexpMatchTree(s)
}
return &andMatchTree{
children: []matchTree{
tr, &noVisitMatchTree{subMT},