-
Notifications
You must be signed in to change notification settings - Fork 85
/
eval.go
763 lines (669 loc) · 20.6 KB
/
eval.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
// Copyright 2016 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 (
"context"
"fmt"
"log"
"regexp/syntax"
"sort"
"strings"
"time"
enry_data "github.com/go-enry/go-enry/v2/data"
"github.com/grafana/regexp"
"github.com/sourcegraph/zoekt/internal/tenant"
"github.com/sourcegraph/zoekt/query"
)
// simplifyMultiRepo takes a query and a predicate. It returns Const(true) if all
// repository names fulfill the predicate, Const(false) if none of them do, and q
// otherwise.
func (d *indexData) simplifyMultiRepo(q query.Q, predicate func(*Repository) bool) query.Q {
count := 0
alive := len(d.repoMetaData)
for i := range d.repoMetaData {
if d.repoMetaData[i].Tombstone {
alive--
} else if predicate(&d.repoMetaData[i]) {
count++
}
}
if count == alive {
return &query.Const{Value: true}
}
if count > 0 {
return q
}
return &query.Const{Value: false}
}
func (d *indexData) simplify(in query.Q) query.Q {
eval := query.Map(in, func(q query.Q) query.Q {
switch r := q.(type) {
case *query.Repo:
return d.simplifyMultiRepo(q, func(repo *Repository) bool {
return r.Regexp.MatchString(repo.Name)
})
case *query.RepoRegexp:
return d.simplifyMultiRepo(q, func(repo *Repository) bool {
return r.Regexp.MatchString(repo.Name)
})
case *query.BranchesRepos:
for i := range d.repoMetaData {
for _, br := range r.List {
if br.Repos.Contains(d.repoMetaData[i].ID) {
return q
}
}
}
return &query.Const{Value: false}
case *query.RepoSet:
return d.simplifyMultiRepo(q, func(repo *Repository) bool {
return r.Set[repo.Name]
})
case query.RawConfig:
return d.simplifyMultiRepo(q, func(repo *Repository) bool { return uint8(r)&encodeRawConfig(repo.RawConfig) == uint8(r) })
case *query.RepoIDs:
return d.simplifyMultiRepo(q, func(repo *Repository) bool {
return r.Repos.Contains(repo.ID)
})
case *query.Language:
_, has := d.metaData.LanguageMap[r.Language]
if !has && d.metaData.IndexFeatureVersion < 12 {
// For index files that haven't been re-indexed by go-enry,
// fall back to file-based matching and continue even if this
// repo doesn't have the specific language present.
extsForLang := enry_data.ExtensionsByLanguage[r.Language]
if extsForLang != nil {
extFrags := make([]string, 0, len(extsForLang))
for _, ext := range extsForLang {
extFrags = append(extFrags, regexp.QuoteMeta(ext))
}
if len(extFrags) > 0 {
pattern := fmt.Sprintf("(?i)(%s)$", strings.Join(extFrags, "|"))
// inlined copy of query.regexpQuery
re, err := syntax.Parse(pattern, syntax.Perl)
if err != nil {
return &query.Const{Value: false}
}
if re.Op == syntax.OpLiteral {
return &query.Substring{
Pattern: string(re.Rune),
FileName: true,
}
}
return &query.Regexp{
Regexp: re,
FileName: true,
}
}
}
}
if !has {
return &query.Const{Value: false}
}
}
return q
})
return query.Simplify(eval)
}
func (o *SearchOptions) SetDefaults() {
if o.ShardMaxMatchCount == 0 {
// We cap the total number of matches, so overly broad
// searches don't crash the machine.
o.ShardMaxMatchCount = 100000
}
if o.TotalMaxMatchCount == 0 {
o.TotalMaxMatchCount = 10 * o.ShardMaxMatchCount
}
}
func (d *indexData) Search(ctx context.Context, q query.Q, opts *SearchOptions) (sr *SearchResult, err error) {
timer := newTimer()
copyOpts := *opts
opts = ©Opts
opts.SetDefaults()
var res SearchResult
if len(d.fileNameIndex) == 0 {
return &res, nil
}
select {
case <-ctx.Done():
res.Stats.ShardsSkipped++
return &res, nil
default:
}
q = d.simplify(q)
if c, ok := q.(*query.Const); ok && !c.Value {
return &res, nil
}
if opts.EstimateDocCount {
res.Stats.ShardFilesConsidered = len(d.fileBranchMasks)
return &res, nil
}
q = query.Map(q, query.ExpandFileContent)
mt, err := d.newMatchTree(q, matchTreeOpt{})
if err != nil {
return nil, err
}
// Capture the costs of construction before pruning
updateMatchTreeStats(mt, &res.Stats)
mt, err = pruneMatchTree(mt)
if err != nil {
return nil, err
}
res.Stats.MatchTreeConstruction = timer.Elapsed()
if mt == nil {
res.Stats.ShardsSkippedFilter++
return &res, nil
}
res.Stats.ShardsScanned++
cp := &contentProvider{
id: d,
stats: &res.Stats,
}
// Track the number of documents found in a repository for
// ShardRepoMaxMatchCount
var (
lastRepoID uint16
repoMatchCount int
)
docCount := uint32(len(d.fileBranchMasks))
lastDoc := int(-1)
// document frequency per term
df := make(termDocumentFrequency)
// term frequency per file match
var tfs []termFrequency
nextFileMatch:
for {
canceled := false
select {
case <-ctx.Done():
canceled = true
default:
}
nextDoc := mt.nextDoc()
if int(nextDoc) <= lastDoc {
nextDoc = uint32(lastDoc + 1)
}
for ; nextDoc < docCount; nextDoc++ {
repoID := d.repos[nextDoc]
repoMetadata := &d.repoMetaData[repoID]
// Skip tombstoned repositories
if repoMetadata.Tombstone {
continue
}
// 🚨 SECURITY: Skip documents that don't belong to the tenant. This check is
// necessary to prevent leaking data across tenants.
if !tenant.HasAccess(ctx, repoMetadata.TenantID) {
continue
}
// Skip documents that are tombstoned
if len(repoMetadata.FileTombstones) > 0 {
if _, tombstoned := repoMetadata.FileTombstones[string(d.fileName(nextDoc))]; tombstoned {
continue
}
}
// Skip documents over ShardRepoMaxMatchCount if specified.
if opts.ShardRepoMaxMatchCount > 0 {
if repoMatchCount >= opts.ShardRepoMaxMatchCount && repoID == lastRepoID {
res.Stats.FilesSkipped++
continue
}
}
break
}
if nextDoc >= docCount {
break
}
lastDoc = int(nextDoc)
// We track lastRepoID for ShardRepoMaxMatchCount
if lastRepoID != d.repos[nextDoc] {
lastRepoID = d.repos[nextDoc]
repoMatchCount = 0
}
if canceled || (res.Stats.MatchCount >= opts.ShardMaxMatchCount && opts.ShardMaxMatchCount > 0) {
res.Stats.FilesSkipped += int(docCount - nextDoc)
break
}
res.Stats.FilesConsidered++
mt.prepare(nextDoc)
cp.setDocument(nextDoc)
known := make(map[matchTree]bool)
md := d.repoMetaData[d.repos[nextDoc]]
for cost := costMin; cost <= costMax; cost++ {
switch evalMatchTree(cp, cost, known, mt) {
case matchesRequiresHigherCost:
if cost == costMax {
log.Panicf("did not decide. Repo %s, doc %d, known %v",
md.Name, nextDoc, known)
}
case matchesFound:
// could short-circuit now, but we want to run higher costs to
// potentially find higher ranked matches.
case matchesNone:
continue nextFileMatch
}
}
fileMatch := FileMatch{
Repository: md.Name,
RepositoryID: md.ID,
RepositoryPriority: md.priority,
FileName: string(d.fileName(nextDoc)),
Checksum: d.getChecksum(nextDoc),
Language: d.languageMap[d.getLanguage(nextDoc)],
}
if s := d.subRepos[nextDoc]; s > 0 {
if s >= uint32(len(d.subRepoPaths[d.repos[nextDoc]])) {
log.Panicf("corrupt index: subrepo %d beyond %v", s, d.subRepoPaths)
}
path := d.subRepoPaths[d.repos[nextDoc]][s]
fileMatch.SubRepositoryPath = path
sr := md.SubRepoMap[path]
fileMatch.SubRepositoryName = sr.Name
if idx := d.branchIndex(nextDoc); idx >= 0 {
fileMatch.Version = sr.Branches[idx].Version
}
} else {
idx := d.branchIndex(nextDoc)
if idx >= 0 {
fileMatch.Version = md.Branches[idx].Version
}
}
// Important invariant for performance: finalCands is sorted by offset and
// non-overlapping. gatherMatches respects this invariant and all later
// transformations respect this.
shouldMergeMatches := !opts.ChunkMatches
finalCands := d.gatherMatches(nextDoc, mt, known, shouldMergeMatches)
if opts.ChunkMatches {
fileMatch.ChunkMatches = cp.fillChunkMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore)
} else {
fileMatch.LineMatches = cp.fillMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore)
}
var tf map[string]int
if opts.UseBM25Scoring {
// For BM25 scoring, the calculation of the score is split in two parts. Here we
// calculate the term frequencies for the current document and update the
// document frequencies. Since we don't store document frequencies in the index,
// we have to defer the calculation of the final BM25 score to after the whole
// shard has been processed.
tf = calculateTermFrequency(finalCands, df)
} else {
// Use the standard, non-experimental scoring method by default
d.scoreFile(&fileMatch, nextDoc, mt, known, opts)
}
fileMatch.Branches = d.gatherBranches(nextDoc, mt, known)
sortMatchesByScore(fileMatch.LineMatches)
sortChunkMatchesByScore(fileMatch.ChunkMatches)
if opts.Whole {
fileMatch.Content = cp.data(false)
}
matchedChunkRanges := 0
for _, cm := range fileMatch.ChunkMatches {
matchedChunkRanges += len(cm.Ranges)
}
repoMatchCount += len(fileMatch.LineMatches)
repoMatchCount += matchedChunkRanges
if opts.UseBM25Scoring {
// Invariant: tfs[i] belongs to res.Files[i]
tfs = append(tfs, termFrequency{
doc: nextDoc,
tf: tf,
})
}
res.Files = append(res.Files, fileMatch)
res.Stats.MatchCount += len(fileMatch.LineMatches)
res.Stats.MatchCount += matchedChunkRanges
res.Stats.FileCount++
}
// Calculate BM25 score for all file matches in the shard. We assume that we
// have seen all documents containing any of the terms in the query so that df
// correctly reflects the document frequencies. This is true, for example, if
// all terms in the query are ORed together.
if opts.UseBM25Scoring {
d.scoreFilesUsingBM25(res.Files, tfs, df, opts)
}
for _, md := range d.repoMetaData {
r := md
addRepo(&res, &r)
for _, v := range r.SubRepoMap {
addRepo(&res, v)
}
}
// Update stats based on work done during document search.
updateMatchTreeStats(mt, &res.Stats)
res.Stats.MatchTreeSearch = timer.Elapsed()
return &res, nil
}
func addRepo(res *SearchResult, repo *Repository) {
if res.RepoURLs == nil {
res.RepoURLs = map[string]string{}
}
res.RepoURLs[repo.Name] = repo.FileURLTemplate
if res.LineFragments == nil {
res.LineFragments = map[string]string{}
}
res.LineFragments[repo.Name] = repo.LineFragmentTemplate
}
// Gather matches from this document. The matches are returned in document
// order and are non-overlapping. All filename and content matches are
// returned, with filename matches first.
//
// If `merge` is set, overlapping and adjacent matches will be merged
// into a single match. Otherwise, overlapping matches will be removed,
// but adjacent matches will remain.
func (d *indexData) gatherMatches(nextDoc uint32, mt matchTree, known map[matchTree]bool, merge bool) []*candidateMatch {
var cands []*candidateMatch
visitMatches(mt, known, 1, func(mt matchTree, scoreWeight float64) {
if smt, ok := mt.(*substrMatchTree); ok {
cands = append(cands, setScoreWeight(scoreWeight, smt.current)...)
}
if rmt, ok := mt.(*regexpMatchTree); ok {
cands = append(cands, setScoreWeight(scoreWeight, rmt.found)...)
}
if rmt, ok := mt.(*wordMatchTree); ok {
cands = append(cands, setScoreWeight(scoreWeight, rmt.found)...)
}
if smt, ok := mt.(*symbolRegexpMatchTree); ok {
cands = append(cands, setScoreWeight(scoreWeight, smt.found)...)
}
})
// If we found no candidate matches at all, assume there must have been a match on filename.
if len(cands) == 0 {
nm := d.fileName(nextDoc)
return []*candidateMatch{{
caseSensitive: false,
fileName: true,
substrBytes: nm,
substrLowered: nm,
file: nextDoc,
runeOffset: 0,
byteOffset: 0,
byteMatchSz: uint32(len(nm)),
}}
}
sort.Sort((sortByOffsetSlice)(cands))
res := cands[:0]
mergeRun := 1
for i, c := range cands {
if i == 0 {
res = append(res, c)
continue
}
last := res[len(res)-1]
// Never compare filename and content matches
if last.fileName != c.fileName {
res = append(res, c)
continue
}
if merge {
// Merge adjacent candidates. This guarantees that the matches
// are non-overlapping.
lastEnd := last.byteOffset + last.byteMatchSz
end := c.byteOffset + c.byteMatchSz
if lastEnd >= c.byteOffset {
mergeRun++
// Average out the score across the merged candidates. Only do it if
// we are boosting to avoid floating point funkiness in the normal
// case.
if !(epsilonEqualsOne(last.scoreWeight) && epsilonEqualsOne(c.scoreWeight)) {
last.scoreWeight = ((last.scoreWeight * float64(mergeRun-1)) + c.scoreWeight) / float64(mergeRun)
}
// latest candidate goes further, update our end
if end > lastEnd {
last.byteMatchSz = end - last.byteOffset
}
continue
} else {
mergeRun = 1
}
} else {
// Remove overlapping candidates. This guarantees that the matches
// are non-overlapping, but also preserves expected match counts.
lastEnd := last.byteOffset + last.byteMatchSz
if lastEnd > c.byteOffset {
continue
}
}
res = append(res, c)
}
return res
}
type sortByOffsetSlice []*candidateMatch
func (m sortByOffsetSlice) Len() int { return len(m) }
func (m sortByOffsetSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m sortByOffsetSlice) Less(i, j int) bool {
// Sort all filename matches to the start
if m[i].fileName != m[j].fileName {
return m[i].fileName
}
if m[i].byteOffset == m[j].byteOffset { // tie break if same offset
// Prefer longer candidates if starting at same position
return m[i].byteMatchSz > m[j].byteMatchSz
}
return m[i].byteOffset < m[j].byteOffset
}
// setScoreWeight is a helper used by gatherMatches to set the weight based on
// the score weight of the matchTree.
func setScoreWeight(scoreWeight float64, cm []*candidateMatch) []*candidateMatch {
for _, m := range cm {
m.scoreWeight = scoreWeight
}
return cm
}
func (d *indexData) branchIndex(docID uint32) int {
mask := d.fileBranchMasks[docID]
idx := 0
for mask != 0 {
if mask&0x1 != 0 {
return idx
}
idx++
mask >>= 1
}
return -1
}
// gatherBranches returns a list of branch names taking into account any branch
// filters in the query. If the query contains a branch filter, it returns all
// branches containing the docID and matching the branch filter. Otherwise, it
// returns all branches containing docID.
func (d *indexData) gatherBranches(docID uint32, mt matchTree, known map[matchTree]bool) []string {
var mask uint64
visitMatchAtoms(mt, known, func(mt matchTree) {
bq, ok := mt.(*branchQueryMatchTree)
if !ok {
return
}
mask = mask | bq.branchMask()
})
if mask == 0 {
mask = d.fileBranchMasks[docID]
}
var branches []string
id := uint32(1)
branchNames := d.branchNames[d.repos[docID]]
for mask != 0 {
if mask&0x1 != 0 {
branches = append(branches, branchNames[uint(id)])
}
id <<= 1
mask >>= 1
}
return branches
}
func (d *indexData) List(ctx context.Context, q query.Q, opts *ListOptions) (rl *RepoList, err error) {
var include func(rle *RepoListEntry) bool
q = d.simplify(q)
if c, ok := q.(*query.Const); ok {
if !c.Value {
return &RepoList{}, nil
}
include = func(rle *RepoListEntry) bool {
return true
}
} else {
sr, err := d.Search(ctx, q, &SearchOptions{
ShardRepoMaxMatchCount: 1,
})
if err != nil {
return nil, err
}
foundRepos := make(map[string]struct{}, len(sr.Files))
for _, file := range sr.Files {
foundRepos[file.Repository] = struct{}{}
}
include = func(rle *RepoListEntry) bool {
_, ok := foundRepos[rle.Repository.Name]
return ok
}
}
var l RepoList
field, err := opts.GetField()
if err != nil {
return nil, err
}
switch field {
case RepoListFieldRepos:
l.Repos = make([]*RepoListEntry, 0, len(d.repoListEntry))
case RepoListFieldReposMap:
l.ReposMap = make(ReposMap, len(d.repoListEntry))
}
for i := range d.repoListEntry {
if d.repoMetaData[i].Tombstone {
continue
}
// 🚨 SECURITY: Skip documents that don't belong to the tenant. This check is
// necessary to prevent leaking data across tenants.
if !tenant.HasAccess(ctx, d.repoMetaData[i].TenantID) {
continue
}
rle := &d.repoListEntry[i]
if !include(rle) {
continue
}
l.Stats.Add(&rle.Stats)
// Backwards compat for when ID is missing
if rle.Repository.ID == 0 {
l.Repos = append(l.Repos, rle)
continue
}
switch field {
case RepoListFieldRepos:
l.Repos = append(l.Repos, rle)
case RepoListFieldReposMap:
l.ReposMap[rle.Repository.ID] = MinimalRepoListEntry{
HasSymbols: rle.Repository.HasSymbols,
Branches: rle.Repository.Branches,
IndexTimeUnix: rle.IndexMetadata.IndexTime.Unix(),
}
}
}
// Only one of these fields is populated and in all cases the size of that
// field is the number of Repos in this shard.
l.Stats.Repos = len(l.Repos) + len(l.ReposMap)
return &l, nil
}
// regexpToMatchTreeRecursive converts a regular expression to a matchTree mt. If
// mt is equivalent to the input r, isEqual = true and the matchTree can be used
// in place of the regex r. If singleLine = true, then the matchTree and all
// its children only match terms on the same line. singleLine is used during
// recursion to decide whether to return an andLineMatchTree (singleLine = true)
// or a andMatchTree (singleLine = false).
func (d *indexData) regexpToMatchTreeRecursive(r *syntax.Regexp, minTextSize int, fileName bool, caseSensitive bool) (mt matchTree, isEqual bool, singleLine bool, err error) {
// TODO - we could perhaps transform Begin/EndText in '\n'?
// TODO - we could perhaps transform CharClass in (OrQuery )
// if there are just a few runes, and part of a OpConcat?
switch r.Op {
case syntax.OpLiteral:
s := string(r.Rune)
if len(s) >= minTextSize {
ignoreCase := syntax.FoldCase == (r.Flags & syntax.FoldCase)
mt, err := d.newSubstringMatchTree(&query.Substring{Pattern: s, FileName: fileName, CaseSensitive: !ignoreCase && caseSensitive})
return mt, true, !strings.Contains(s, "\n"), err
}
case syntax.OpCapture:
return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
case syntax.OpPlus:
return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
case syntax.OpRepeat:
if r.Min == 1 {
return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
} else if r.Min > 1 {
// (x){2,} can't be expressed precisely by the matchTree
mt, _, singleLine, err := d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
return mt, false, singleLine, err
}
case syntax.OpConcat, syntax.OpAlternate:
var qs []matchTree
isEq := true
singleLine = true
for _, sr := range r.Sub {
if sq, subIsEq, subSingleLine, err := d.regexpToMatchTreeRecursive(sr, minTextSize, fileName, caseSensitive); sq != nil {
if err != nil {
return nil, false, false, err
}
isEq = isEq && subIsEq
singleLine = singleLine && subSingleLine
qs = append(qs, sq)
}
}
if r.Op == syntax.OpConcat {
if len(qs) > 1 {
isEq = false
}
newQs := make([]matchTree, 0, len(qs))
for _, q := range qs {
if _, ok := q.(*bruteForceMatchTree); ok {
continue
}
newQs = append(newQs, q)
}
if len(newQs) == 1 {
return newQs[0], isEq, singleLine, nil
}
if len(newQs) == 0 {
return &bruteForceMatchTree{}, isEq, singleLine, nil
}
if singleLine {
return &andLineMatchTree{andMatchTree{children: newQs}}, isEq, singleLine, nil
}
return &andMatchTree{newQs}, isEq, singleLine, nil
}
for _, q := range qs {
if _, ok := q.(*bruteForceMatchTree); ok {
return q, isEq, false, nil
}
}
if len(qs) == 0 {
return &noMatchTree{Why: "const"}, isEq, false, nil
}
return &orMatchTree{qs}, isEq, false, nil
case syntax.OpStar:
if r.Sub[0].Op == syntax.OpAnyCharNotNL {
return &bruteForceMatchTree{}, false, true, nil
}
}
return &bruteForceMatchTree{}, false, false, nil
}
type timer struct {
last time.Time
}
func newTimer() *timer {
return &timer{
last: time.Now(),
}
}
func (t *timer) Elapsed() time.Duration {
now := time.Now()
d := now.Sub(t.last)
t.last = now
return d
}