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