fork of https://github.com/sourcegraph/zoekt
1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package zoekt
16
17import (
18 "context"
19 "fmt"
20 "log"
21 "math"
22 "regexp/syntax"
23 "sort"
24 "strings"
25
26 enry_data "github.com/go-enry/go-enry/v2/data"
27 "github.com/grafana/regexp"
28
29 "github.com/sourcegraph/zoekt/query"
30)
31
32const maxUInt16 = 0xffff
33
34func (m *FileMatch) addScore(what string, s float64, debugScore bool) {
35 if debugScore {
36 m.Debug += fmt.Sprintf("%s:%.2f, ", what, s)
37 }
38 m.Score += s
39}
40
41// simplifyMultiRepo takes a query and a predicate. It returns Const(true) if all
42// repository names fulfill the predicate, Const(false) if none of them do, and q
43// otherwise.
44func (d *indexData) simplifyMultiRepo(q query.Q, predicate func(*Repository) bool) query.Q {
45 count := 0
46 alive := len(d.repoMetaData)
47 for i := range d.repoMetaData {
48 if d.repoMetaData[i].Tombstone {
49 alive--
50 } else if predicate(&d.repoMetaData[i]) {
51 count++
52 }
53 }
54 if count == alive {
55 return &query.Const{Value: true}
56 }
57 if count > 0 {
58 return q
59 }
60 return &query.Const{Value: false}
61}
62
63func (d *indexData) simplify(in query.Q) query.Q {
64 eval := query.Map(in, func(q query.Q) query.Q {
65 switch r := q.(type) {
66 case *query.Repo:
67 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
68 return r.Regexp.MatchString(repo.Name)
69 })
70 case *query.RepoRegexp:
71 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
72 return r.Regexp.MatchString(repo.Name)
73 })
74 case *query.BranchesRepos:
75 for i := range d.repoMetaData {
76 for _, br := range r.List {
77 if br.Repos.Contains(d.repoMetaData[i].ID) {
78 return q
79 }
80 }
81 }
82 return &query.Const{Value: false}
83 case *query.RepoSet:
84 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
85 return r.Set[repo.Name]
86 })
87 case *query.RepoIDs:
88 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
89 return r.Repos.Contains(repo.ID)
90 })
91 case *query.Language:
92 _, has := d.metaData.LanguageMap[r.Language]
93 if !has && d.metaData.IndexFeatureVersion < 12 {
94 // For index files that haven't been re-indexed by go-enry,
95 // fall back to file-based matching and continue even if this
96 // repo doesn't have the specific language present.
97 extsForLang := enry_data.ExtensionsByLanguage[r.Language]
98 if extsForLang != nil {
99 extFrags := make([]string, 0, len(extsForLang))
100 for _, ext := range extsForLang {
101 extFrags = append(extFrags, regexp.QuoteMeta(ext))
102 }
103 if len(extFrags) > 0 {
104 pattern := fmt.Sprintf("(?i)(%s)$", strings.Join(extFrags, "|"))
105 // inlined copy of query.regexpQuery
106 re, err := syntax.Parse(pattern, syntax.Perl)
107 if err != nil {
108 return &query.Const{Value: false}
109 }
110 if re.Op == syntax.OpLiteral {
111 return &query.Substring{
112 Pattern: string(re.Rune),
113 FileName: true,
114 }
115 }
116 return &query.Regexp{
117 Regexp: re,
118 FileName: true,
119 }
120 }
121 }
122 }
123 if !has {
124 return &query.Const{Value: false}
125 }
126 }
127 return q
128 })
129 return query.Simplify(eval)
130}
131
132func (o *SearchOptions) SetDefaults() {
133 if o.ShardMaxMatchCount == 0 {
134 // We cap the total number of matches, so overly broad
135 // searches don't crash the machine.
136 o.ShardMaxMatchCount = 100000
137 }
138 if o.TotalMaxMatchCount == 0 {
139 o.TotalMaxMatchCount = 10 * o.ShardMaxMatchCount
140 }
141}
142
143func (d *indexData) Search(ctx context.Context, q query.Q, opts *SearchOptions) (sr *SearchResult, err error) {
144 copyOpts := *opts
145 opts = ©Opts
146 opts.SetDefaults()
147
148 var res SearchResult
149 if len(d.fileNameIndex) == 0 {
150 return &res, nil
151 }
152
153 select {
154 case <-ctx.Done():
155 res.Stats.ShardsSkipped++
156 return &res, nil
157 default:
158 }
159
160 q = d.simplify(q)
161 if c, ok := q.(*query.Const); ok && !c.Value {
162 return &res, nil
163 }
164
165 if opts.EstimateDocCount {
166 res.Stats.ShardFilesConsidered = len(d.fileBranchMasks)
167 return &res, nil
168 }
169
170 q = query.Map(q, query.ExpandFileContent)
171
172 mt, err := d.newMatchTree(q, matchTreeOpt{})
173 if err != nil {
174 return nil, err
175 }
176
177 mt, err = pruneMatchTree(mt)
178 if err != nil {
179 return nil, err
180 }
181 if mt == nil {
182 res.Stats.ShardsSkippedFilter++
183 return &res, nil
184 }
185
186 res.Stats.ShardsScanned++
187
188 cp := &contentProvider{
189 id: d,
190 stats: &res.Stats,
191 }
192
193 // Track the number of documents found in a repository for
194 // ShardRepoMaxMatchCount
195 var (
196 lastRepoID uint16
197 repoMatchCount int
198 )
199
200 docCount := uint32(len(d.fileBranchMasks))
201 lastDoc := int(-1)
202
203nextFileMatch:
204 for {
205 canceled := false
206 select {
207 case <-ctx.Done():
208 canceled = true
209 default:
210 }
211
212 nextDoc := mt.nextDoc()
213 if int(nextDoc) <= lastDoc {
214 nextDoc = uint32(lastDoc + 1)
215 }
216
217 for ; nextDoc < docCount; nextDoc++ {
218 repoID := d.repos[nextDoc]
219 repoMetadata := &d.repoMetaData[repoID]
220
221 // Skip tombstoned repositories
222 if repoMetadata.Tombstone {
223 continue
224 }
225
226 // Skip documents that are tombstoned
227 if len(repoMetadata.FileTombstones) > 0 {
228 if _, tombstoned := repoMetadata.FileTombstones[string(d.fileName(nextDoc))]; tombstoned {
229 continue
230 }
231 }
232
233 // Skip documents over ShardRepoMaxMatchCount if specified.
234 if opts.ShardRepoMaxMatchCount > 0 {
235 if repoMatchCount >= opts.ShardRepoMaxMatchCount && repoID == lastRepoID {
236 res.Stats.FilesSkipped++
237 continue
238 }
239 }
240
241 break
242 }
243
244 if nextDoc >= docCount {
245 break
246 }
247
248 lastDoc = int(nextDoc)
249
250 // We track lastRepoID for ShardRepoMaxMatchCount
251 if lastRepoID != d.repos[nextDoc] {
252 lastRepoID = d.repos[nextDoc]
253 repoMatchCount = 0
254 }
255
256 if canceled || (res.Stats.MatchCount >= opts.ShardMaxMatchCount && opts.ShardMaxMatchCount > 0) {
257 res.Stats.FilesSkipped += int(docCount - nextDoc)
258 break
259 }
260
261 res.Stats.FilesConsidered++
262 mt.prepare(nextDoc)
263
264 cp.setDocument(nextDoc)
265
266 known := make(map[matchTree]bool)
267
268 md := d.repoMetaData[d.repos[nextDoc]]
269
270 for cost := costMin; cost <= costMax; cost++ {
271 v, ok := mt.matches(cp, cost, known)
272 if ok && !v {
273 continue nextFileMatch
274 }
275
276 if cost == costMax && !ok {
277 log.Panicf("did not decide. Repo %s, doc %d, known %v",
278 md.Name, nextDoc, known)
279 }
280 }
281
282 fileMatch := FileMatch{
283 Repository: md.Name,
284 RepositoryID: md.ID,
285 RepositoryPriority: md.priority,
286 FileName: string(d.fileName(nextDoc)),
287 Checksum: d.getChecksum(nextDoc),
288 Language: d.languageMap[d.getLanguage(nextDoc)],
289 }
290
291 if s := d.subRepos[nextDoc]; s > 0 {
292 if s >= uint32(len(d.subRepoPaths[d.repos[nextDoc]])) {
293 log.Panicf("corrupt index: subrepo %d beyond %v", s, d.subRepoPaths)
294 }
295 path := d.subRepoPaths[d.repos[nextDoc]][s]
296 fileMatch.SubRepositoryPath = path
297 sr := md.SubRepoMap[path]
298 fileMatch.SubRepositoryName = sr.Name
299 if idx := d.branchIndex(nextDoc); idx >= 0 {
300 fileMatch.Version = sr.Branches[idx].Version
301 }
302 } else {
303 idx := d.branchIndex(nextDoc)
304 if idx >= 0 {
305 fileMatch.Version = md.Branches[idx].Version
306 }
307 }
308
309 atomMatchCount := 0
310 visitMatches(mt, known, func(mt matchTree) {
311 atomMatchCount++
312 })
313 shouldMergeMatches := !opts.ChunkMatches
314 finalCands := gatherMatches(mt, known, shouldMergeMatches)
315
316 if len(finalCands) == 0 {
317 nm := d.fileName(nextDoc)
318 finalCands = append(finalCands,
319 &candidateMatch{
320 caseSensitive: false,
321 fileName: true,
322 substrBytes: nm,
323 substrLowered: nm,
324 file: nextDoc,
325 runeOffset: 0,
326 byteOffset: 0,
327 byteMatchSz: uint32(len(nm)),
328 })
329 }
330
331 if opts.ChunkMatches {
332 fileMatch.ChunkMatches = cp.fillChunkMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore)
333 } else {
334 fileMatch.LineMatches = cp.fillMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore)
335 }
336
337 maxFileScore := 0.0
338 repetitions := 0
339 for i := range fileMatch.LineMatches {
340 if maxFileScore < fileMatch.LineMatches[i].Score {
341 maxFileScore = fileMatch.LineMatches[i].Score
342 repetitions = 0
343 } else if maxFileScore == fileMatch.LineMatches[i].Score {
344 repetitions += 1
345 }
346
347 // Order by ordering in file.
348 fileMatch.LineMatches[i].Score += scoreLineOrderFactor * (1.0 - (float64(i) / float64(len(fileMatch.LineMatches))))
349 }
350
351 for i := range fileMatch.ChunkMatches {
352 if maxFileScore < fileMatch.ChunkMatches[i].Score {
353 maxFileScore = fileMatch.ChunkMatches[i].Score
354 }
355
356 // Order by ordering in file.
357 fileMatch.ChunkMatches[i].Score += scoreLineOrderFactor * (1.0 - (float64(i) / float64(len(fileMatch.ChunkMatches))))
358 }
359
360 // Maintain ordering of input files. This
361 // strictly dominates the in-file ordering of
362 // the matches.
363 fileMatch.addScore("fragment", maxFileScore, opts.DebugScore)
364
365 // Prefer docs with several top-scored matches.
366 fileMatch.addScore("repetition-boost", scoreRepetitionFactor*float64(repetitions), opts.DebugScore)
367
368 // atom-count boosts files with matches from more than 1 atom. The
369 // maximum boost is scoreFactorAtomMatch.
370 if atomMatchCount > 0 {
371 fileMatch.addScore("atom", (1.0-1.0/float64(atomMatchCount))*scoreFactorAtomMatch, opts.DebugScore)
372 }
373
374 if opts.UseDocumentRanks && len(d.ranks) > int(nextDoc) {
375 weight := scoreFileRankFactor
376 if opts.DocumentRanksWeight > 0.0 {
377 weight = opts.DocumentRanksWeight
378 }
379
380 ranks := d.ranks[nextDoc]
381 // The ranks slice always contains one entry representing the file rank (unless it's empty since the
382 // file doesn't have a rank). This is left over from when documents could have multiple rank signals,
383 // and we plan to clean this up.
384 if len(ranks) > 0 {
385 // The file rank represents a log (base 2) count. The log ranks should be bounded at 32, but we
386 // cap it just in case to ensure it falls in the range [0, 1].
387 normalized := math.Min(1.0, ranks[0]/32.0)
388 fileMatch.addScore("file-rank", weight*normalized, opts.DebugScore)
389 }
390 }
391
392 fileMatch.addScore("doc-order", scoreFileOrderFactor*(1.0-float64(nextDoc)/float64(len(d.boundaries))), opts.DebugScore)
393 fileMatch.addScore("repo-rank", scoreRepoRankFactor*float64(md.Rank)/maxUInt16, opts.DebugScore)
394
395 fileMatch.Branches = d.gatherBranches(nextDoc, mt, known)
396 sortMatchesByScore(fileMatch.LineMatches)
397 sortChunkMatchesByScore(fileMatch.ChunkMatches)
398 if opts.Whole {
399 fileMatch.Content = cp.data(false)
400 }
401
402 matchedChunkRanges := 0
403 for _, cm := range fileMatch.ChunkMatches {
404 matchedChunkRanges += len(cm.Ranges)
405 }
406
407 repoMatchCount += len(fileMatch.LineMatches)
408 repoMatchCount += matchedChunkRanges
409
410 if opts.DebugScore {
411 fileMatch.Debug = fmt.Sprintf("score:%.2f <- %s", fileMatch.Score, fileMatch.Debug)
412 }
413
414 res.Files = append(res.Files, fileMatch)
415 res.Stats.MatchCount += len(fileMatch.LineMatches)
416 res.Stats.MatchCount += matchedChunkRanges
417 res.Stats.FileCount++
418 }
419
420 // We do not sort Files here, instead we rely on the shards pkg to do file
421 // ranking. If we sorted now, we would break the assumption that results
422 // from the same repo in a shard appear next to each other.
423
424 for _, md := range d.repoMetaData {
425 r := md
426 addRepo(&res, &r)
427 for _, v := range r.SubRepoMap {
428 addRepo(&res, v)
429 }
430 }
431
432 visitMatchTree(mt, func(mt matchTree) {
433 if atom, ok := mt.(interface{ updateStats(*Stats) }); ok {
434 atom.updateStats(&res.Stats)
435 }
436 })
437
438 // If document ranking is enabled, then we can rank and truncate the files to save memory.
439 if limit := opts.MaxDocDisplayCount; opts.UseDocumentRanks && limit > 0 && limit < len(res.Files) {
440 SortFiles(res.Files)
441 res.Files = res.Files[:limit]
442 }
443
444 return &res, nil
445}
446
447func addRepo(res *SearchResult, repo *Repository) {
448 if res.RepoURLs == nil {
449 res.RepoURLs = map[string]string{}
450 }
451 res.RepoURLs[repo.Name] = repo.FileURLTemplate
452
453 if res.LineFragments == nil {
454 res.LineFragments = map[string]string{}
455 }
456 res.LineFragments[repo.Name] = repo.LineFragmentTemplate
457}
458
459type sortByOffsetSlice []*candidateMatch
460
461func (m sortByOffsetSlice) Len() int { return len(m) }
462func (m sortByOffsetSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
463func (m sortByOffsetSlice) Less(i, j int) bool {
464 return m[i].byteOffset < m[j].byteOffset
465}
466
467// Gather matches from this document. This never returns a mixture of
468// filename/content matches: if there are content matches, all
469// filename matches are trimmed from the result. The matches are
470// returned in document order and are non-overlapping.
471//
472// If `merge` is set, overlapping and adjacent matches will be merged
473// into a single match. Otherwise, overlapping matches will be removed,
474// but adjacent matches will remain.
475func gatherMatches(mt matchTree, known map[matchTree]bool, merge bool) []*candidateMatch {
476 var cands []*candidateMatch
477 visitMatches(mt, known, func(mt matchTree) {
478 if smt, ok := mt.(*substrMatchTree); ok {
479 cands = append(cands, smt.current...)
480 }
481 if rmt, ok := mt.(*regexpMatchTree); ok {
482 cands = append(cands, rmt.found...)
483 }
484 if rmt, ok := mt.(*wordMatchTree); ok {
485 cands = append(cands, rmt.found...)
486 }
487 if smt, ok := mt.(*symbolRegexpMatchTree); ok {
488 cands = append(cands, smt.found...)
489 }
490 })
491
492 foundContentMatch := false
493 for _, c := range cands {
494 if !c.fileName {
495 foundContentMatch = true
496 break
497 }
498 }
499
500 res := cands[:0]
501 for _, c := range cands {
502 if !foundContentMatch || !c.fileName {
503 res = append(res, c)
504 }
505 }
506 cands = res
507
508 if merge {
509 // Merge adjacent candidates. This guarantees that the matches
510 // are non-overlapping.
511 sort.Sort((sortByOffsetSlice)(cands))
512 res = cands[:0]
513 for i, c := range cands {
514 if i == 0 {
515 res = append(res, c)
516 continue
517 }
518 last := res[len(res)-1]
519 lastEnd := last.byteOffset + last.byteMatchSz
520 end := c.byteOffset + c.byteMatchSz
521 if lastEnd >= c.byteOffset {
522 if end > lastEnd {
523 last.byteMatchSz = end - last.byteOffset
524 }
525 continue
526 }
527
528 res = append(res, c)
529 }
530 } else {
531 // Remove overlapping candidates. This guarantees that the matches
532 // are non-overlapping, but also preserves expected match counts.
533 sort.Sort((sortByOffsetSlice)(cands))
534 res = cands[:0]
535 for i, c := range cands {
536 if i == 0 {
537 res = append(res, c)
538 continue
539 }
540 last := res[len(res)-1]
541 lastEnd := last.byteOffset + last.byteMatchSz
542 if lastEnd > c.byteOffset {
543 continue
544 }
545
546 res = append(res, c)
547 }
548 }
549
550 return res
551}
552
553func (d *indexData) branchIndex(docID uint32) int {
554 mask := d.fileBranchMasks[docID]
555 idx := 0
556 for mask != 0 {
557 if mask&0x1 != 0 {
558 return idx
559 }
560 idx++
561 mask >>= 1
562 }
563 return -1
564}
565
566// gatherBranches returns a list of branch names taking into account any branch
567// filters in the query. If the query contains a branch filter, it returns all
568// branches containing the docID and matching the branch filter. Otherwise, it
569// returns all branches containing docID.
570func (d *indexData) gatherBranches(docID uint32, mt matchTree, known map[matchTree]bool) []string {
571 var mask uint64
572 visitMatches(mt, known, func(mt matchTree) {
573 bq, ok := mt.(*branchQueryMatchTree)
574 if !ok {
575 return
576 }
577
578 mask = mask | bq.branchMask()
579 })
580
581 if mask == 0 {
582 mask = d.fileBranchMasks[docID]
583 }
584
585 var branches []string
586 id := uint32(1)
587 branchNames := d.branchNames[d.repos[docID]]
588 for mask != 0 {
589 if mask&0x1 != 0 {
590 branches = append(branches, branchNames[uint(id)])
591 }
592 id <<= 1
593 mask >>= 1
594 }
595
596 return branches
597}
598
599func (d *indexData) List(ctx context.Context, q query.Q, opts *ListOptions) (rl *RepoList, err error) {
600 var include func(rle *RepoListEntry) bool
601
602 q = d.simplify(q)
603 if c, ok := q.(*query.Const); ok {
604 if !c.Value {
605 return &RepoList{}, nil
606 }
607 include = func(rle *RepoListEntry) bool {
608 return true
609 }
610 } else {
611 sr, err := d.Search(ctx, q, &SearchOptions{
612 ShardRepoMaxMatchCount: 1,
613 })
614 if err != nil {
615 return nil, err
616 }
617
618 foundRepos := make(map[string]struct{}, len(sr.Files))
619 for _, file := range sr.Files {
620 foundRepos[file.Repository] = struct{}{}
621 }
622
623 include = func(rle *RepoListEntry) bool {
624 _, ok := foundRepos[rle.Repository.Name]
625 return ok
626 }
627 }
628
629 var l RepoList
630
631 field, err := opts.GetField()
632 if err != nil {
633 return nil, err
634 }
635 switch field {
636 case RepoListFieldRepos:
637 l.Repos = make([]*RepoListEntry, 0, len(d.repoListEntry))
638 case RepoListFieldMinimal:
639 l.Minimal = make(map[uint32]*MinimalRepoListEntry, len(d.repoListEntry))
640 case RepoListFieldReposMap:
641 l.ReposMap = make(ReposMap, len(d.repoListEntry))
642 }
643
644 for i := range d.repoListEntry {
645 if d.repoMetaData[i].Tombstone {
646 continue
647 }
648 rle := &d.repoListEntry[i]
649 if !include(rle) {
650 continue
651 }
652
653 l.Stats.Add(&rle.Stats)
654
655 // Backwards compat for when ID is missing
656 if rle.Repository.ID == 0 {
657 l.Repos = append(l.Repos, rle)
658 continue
659 }
660
661 switch field {
662 case RepoListFieldRepos:
663 l.Repos = append(l.Repos, rle)
664 case RepoListFieldMinimal:
665 l.Minimal[rle.Repository.ID] = &MinimalRepoListEntry{
666 HasSymbols: rle.Repository.HasSymbols,
667 Branches: rle.Repository.Branches,
668 }
669 case RepoListFieldReposMap:
670 l.ReposMap[rle.Repository.ID] = MinimalRepoListEntry{
671 HasSymbols: rle.Repository.HasSymbols,
672 Branches: rle.Repository.Branches,
673 }
674 }
675
676 }
677
678 return &l, nil
679}
680
681// regexpToMatchTreeRecursive converts a regular expression to a matchTree mt. If
682// mt is equivalent to the input r, isEqual = true and the matchTree can be used
683// in place of the regex r. If singleLine = true, then the matchTree and all
684// its children only match terms on the same line. singleLine is used during
685// recursion to decide whether to return an andLineMatchTree (singleLine = true)
686// or a andMatchTree (singleLine = false).
687func (d *indexData) regexpToMatchTreeRecursive(r *syntax.Regexp, minTextSize int, fileName bool, caseSensitive bool) (mt matchTree, isEqual bool, singleLine bool, err error) {
688 // TODO - we could perhaps transform Begin/EndText in '\n'?
689 // TODO - we could perhaps transform CharClass in (OrQuery )
690 // if there are just a few runes, and part of a OpConcat?
691 switch r.Op {
692 case syntax.OpLiteral:
693 s := string(r.Rune)
694 if len(s) >= minTextSize {
695 mt, err := d.newSubstringMatchTree(&query.Substring{Pattern: s, FileName: fileName, CaseSensitive: caseSensitive})
696 return mt, true, !strings.Contains(s, "\n"), err
697 }
698 case syntax.OpCapture:
699 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
700
701 case syntax.OpPlus:
702 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
703
704 case syntax.OpRepeat:
705 if r.Min == 1 {
706 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
707 } else if r.Min > 1 {
708 // (x){2,} can't be expressed precisely by the matchTree
709 mt, _, singleLine, err := d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
710 return mt, false, singleLine, err
711 }
712 case syntax.OpConcat, syntax.OpAlternate:
713 var qs []matchTree
714 isEq := true
715 singleLine = true
716 for _, sr := range r.Sub {
717 if sq, subIsEq, subSingleLine, err := d.regexpToMatchTreeRecursive(sr, minTextSize, fileName, caseSensitive); sq != nil {
718 if err != nil {
719 return nil, false, false, err
720 }
721 isEq = isEq && subIsEq
722 singleLine = singleLine && subSingleLine
723 qs = append(qs, sq)
724 }
725 }
726 if r.Op == syntax.OpConcat {
727 if len(qs) > 1 {
728 isEq = false
729 }
730 newQs := make([]matchTree, 0, len(qs))
731 for _, q := range qs {
732 if _, ok := q.(*bruteForceMatchTree); ok {
733 continue
734 }
735 newQs = append(newQs, q)
736 }
737 if len(newQs) == 1 {
738 return newQs[0], isEq, singleLine, nil
739 }
740 if len(newQs) == 0 {
741 return &bruteForceMatchTree{}, isEq, singleLine, nil
742 }
743 if singleLine {
744 return &andLineMatchTree{andMatchTree{children: newQs}}, isEq, singleLine, nil
745 }
746 return &andMatchTree{newQs}, isEq, singleLine, nil
747 }
748 for _, q := range qs {
749 if _, ok := q.(*bruteForceMatchTree); ok {
750 return q, isEq, false, nil
751 }
752 }
753 if len(qs) == 0 {
754 return &noMatchTree{"const"}, isEq, false, nil
755 }
756 return &orMatchTree{qs}, isEq, false, nil
757 case syntax.OpStar:
758 if r.Sub[0].Op == syntax.OpAnyCharNotNL {
759 return &bruteForceMatchTree{}, false, true, nil
760 }
761 }
762 return &bruteForceMatchTree{}, false, false, nil
763}