Debian Codegraph @

gopls/internal/fuzzy/symbol_test.go

raw symbols SCIP
1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package fuzzy_test
6
7 import (
8 "go/ast"
9 "go/token"
10 "sort"
11 "testing"
12
13 "golang.org/x/tools/go/packages"
14 . "golang.org/x/tools/gopls/internal/fuzzy"
15 )
16
17 func TestSymbolMatchIndex(t *testing.T) {
18 tests := []struct {
19 pattern, input string
20 want int
21 }{
22 {"test", "foo.TestFoo", 4},
23 {"test", "test", 0},
24 {"test", "Test", 0},
25 {"test", "est", -1},
26 {"t", "shortest", 7},
27 {"", "foo", -1},
28 {"", string([]rune{0}), -1}, // verify that we don't default to an empty pattern.
29 {"anything", "", -1},
30 }
31
32 for _, test := range tests {
33 matcher := NewSymbolMatcher(test.pattern)
34 if got, _ := matcher.Match([]string{test.input}); got != test.want {
35 t.Errorf("NewSymbolMatcher(%q).Match(%q) = %v, _, want %v, _", test.pattern, test.input, got, test.want)
36 }
37 }
38 }
39
40 func TestSymbolRanking(t *testing.T) {
41
42 // query -> symbols to match, in ascending order of score
43 queryRanks := map[string][]string{
44 "test": {
45 "this.is.better.than.most",
46 "test.foo.bar",
47 "thebest",
48 "atest",
49 "test.foo",
50 "testage",
51 "tTest",
52 "foo.test",
53 },
54 "parseside": { // golang/go#60201
55 "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE",
56 "parseContext.parse_sidebyside",
57 },
58 "cvb": {
59 "filecache_test.testIPCValueB",
60 "cover.Boundary",
61 },
62 "dho": {
63 "gocommand.DebugHangingGoCommands",
64 "protocol.DocumentHighlightOptions",
65 },
66 "flg": {
67 "completion.FALLTHROUGH",
68 "main.flagGoCmd",
69 },
70 "fvi": {
71 "godoc.fileIndexVersion",
72 "macho.FlagSubsectionsViaSymbols",
73 },
74 }
75
76 for query, symbols := range queryRanks {
77 t.Run(query, func(t *testing.T) {
78 matcher := NewSymbolMatcher(query)
79 prev := 0.0
80 for _, sym := range symbols {
81 _, score := matcher.Match([]string{sym})
82 t.Logf("Match(%q) = %v", sym, score)
83 if score <= prev {
84 t.Errorf("Match(%q) = _, %v, want > %v", sym, score, prev)
85 }
86 prev = score
87 }
88 })
89 }
90 }
91
92 func TestMatcherSimilarities(t *testing.T) {
93 // This test compares the fuzzy matcher with the symbol matcher on a corpus
94 // of qualified identifiers extracted from x/tools.
95 //
96 // These two matchers are not expected to agree, but inspecting differences
97 // can be useful for finding interesting ranking edge cases.
98 t.Skip("unskip this test to compare matchers")
99
100 idents := collectIdentifiers(t)
101 t.Logf("collected %d unique identifiers", len(idents))
102
103 // We can't use slices.MaxFunc because we want a custom
104 // scoring (not equivalence) function.
105 topMatch := func(score func(string) float64) string {
106 top := ""
107 topScore := 0.0
108 for _, cand := range idents {
109 if s := score(cand); s > topScore {
110 top = cand
111 topScore = s
112 }
113 }
114 return top
115 }
116
117 agreed := 0
118 total := 0
119 bad := 0
120 patterns := generatePatterns()
121 for _, pattern := range patterns {
122 total++
123
124 fm := NewMatcher(pattern)
125 topFuzzy := topMatch(func(input string) float64 {
126 return float64(fm.Score(input))
127 })
128 sm := NewSymbolMatcher(pattern)
129 topSymbol := topMatch(func(input string) float64 {
130 _, score := sm.Match([]string{input})
131 return score
132 })
133 switch {
134 case topFuzzy == "" && topSymbol != "":
135 if false {
136 // The fuzzy matcher has a bug where it misses some matches; for this
137 // test we only care about the symbol matcher.
138 t.Logf("%q matched %q but no fuzzy match", pattern, topSymbol)
139 }
140 total--
141 bad++
142 case topFuzzy != "" && topSymbol == "":
143 t.Fatalf("%q matched %q but no symbol match", pattern, topFuzzy)
144 case topFuzzy == topSymbol:
145 agreed++
146 default:
147 // Enable this log to see mismatches.
148 if false {
149 t.Logf("mismatch for %q: fuzzy: %q, symbol: %q", pattern, topFuzzy, topSymbol)
150 }
151 }
152 }
153 t.Logf("fuzzy matchers agreed on %d out of %d queries (%d bad)", agreed, total, bad)
154 }
155
156 func collectIdentifiers(tb testing.TB) []string {
157 cfg := &packages.Config{
158 Mode: packages.NeedName | packages.NeedSyntax | packages.NeedFiles,
159 Tests: true,
160 }
161 pkgs, err := packages.Load(cfg, "golang.org/x/tools/...")
162 if err != nil {
163 tb.Fatal(err)
164 }
165 uniqueIdents := make(map[string]bool)
166 decls := 0
167 for _, pkg := range pkgs {
168 for _, f := range pkg.Syntax {
169 for _, decl := range f.Decls {
170 decls++
171 switch decl := decl.(type) {
172 case *ast.GenDecl:
173 for _, spec := range decl.Specs {
174 switch decl.Tok {
175 case token.IMPORT:
176 case token.TYPE:
177 name := spec.(*ast.TypeSpec).Name.Name
178 qualified := pkg.Name + "." + name
179 uniqueIdents[qualified] = true
180 case token.CONST, token.VAR:
181 for _, n := range spec.(*ast.ValueSpec).Names {
182 qualified := pkg.Name + "." + n.Name
183 uniqueIdents[qualified] = true
184 }
185 }
186 }
187 }
188 }
189 }
190 }
191 var idents []string
192 for k := range uniqueIdents {
193 idents = append(idents, k)
194 }
195 sort.Strings(idents)
196 return idents
197 }
198
199 func generatePatterns() []string {
200 var patterns []string
201 for x := 'a'; x <= 'z'; x++ {
202 for y := 'a'; y <= 'z'; y++ {
203 for z := 'a'; z <= 'z'; z++ {
204 patterns = append(patterns, string(x)+string(y)+string(z))
205 }
206 }
207 }
208 return patterns
209 }
210
211 // Test that we strongly prefer exact matches.
212 //
213 // In golang/go#60027, we preferred "Runner" for the query "rune" over several
214 // results containing the word "rune" exactly. Following this observation,
215 // scoring was tweaked to more strongly emphasize sequential characters and
216 // exact matches.
217 func TestSymbolRanking_Issue60027(t *testing.T) {
218 matcher := NewSymbolMatcher("rune")
219
220 // symbols to match, in ascending order of ranking.
221 symbols := []string{
222 "Runner",
223 "singleRuneParam",
224 "Config.ifsRune",
225 "Parser.rune",
226 }
227 prev := 0.0
228 for _, sym := range symbols {
229 _, score := matcher.Match([]string{sym})
230 t.Logf("Match(%q) = %v", sym, score)
231 if score < prev {
232 t.Errorf("Match(%q) = _, %v, want > %v", sym, score, prev)
233 }
234 prev = score
235 }
236 }
237
238 func TestChunkedMatch(t *testing.T) {
239 matcher := NewSymbolMatcher("test")
240 _, want := matcher.Match([]string{"test"})
241 chunked := [][]string{
242 {"", "test"},
243 {"test", ""},
244 {"te", "st"},
245 }
246
247 for _, chunks := range chunked {
248 offset, score := matcher.Match(chunks)
249 if offset != 0 || score != want {
250 t.Errorf("Match(%v) = %v, %v, want 0, 1.0", chunks, offset, score)
251 }
252 }
253 }