Debian Codegraph @

gopls/internal/util/fingerprint/fingerprint.go

raw symbols SCIP
1 // Copyright 2025 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 fingerprint defines a function to [Encode] types as strings
6 // with the property that identical types have equal string encodings,
7 // in most cases. In the remaining cases (mostly involving generic
8 // types), the encodings can be parsed using [Parse] into [Tree] form
9 // and matched using [Matches].
10 package fingerprint
11
12 import (
13 "fmt"
14 "go/types"
15 "reflect"
16 "strconv"
17 "strings"
18 "text/scanner"
19 )
20
21 // Encode returns an encoding of a [types.Type] such that, in
22 // most cases, Encode(x) == Encode(y) iff [types.Identical](x, y).
23 //
24 // For a minority of types, mostly involving type parameters, identity
25 // cannot be reduced to string comparison; these types are called
26 // "tricky", and are indicated by the boolean result.
27 //
28 // In general, computing identity correctly for tricky types requires
29 // the type checker. However, the fingerprint encoding can be parsed
30 // by [Parse] into a [Tree] form that permits simple matching sufficient
31 // to allow a type parameter to unify with any subtree; see [Match].
32 //
33 // In the standard library, 99.8% of package-level types have a
34 // non-tricky method-set. The most common exceptions are due to type
35 // parameters.
36 //
37 // fingerprint.Encode is defined only for the signature types of functions
38 // and methods. It must not be called for "untyped" basic types, nor
39 // the type of a generic function.
40 func Encode(t types.Type) (_ string, tricky bool) { return fingerprint(t) }
41
42 // A Tree is a parsed form of a fingerprint for use with [Matches].
43 type Tree struct{ tree sexpr }
44
45 // String returns the tree in an unspecified human-readable form.
46 func (tree Tree) String() string {
47 var out strings.Builder
48 writeSexpr(&out, tree.tree)
49 return out.String()
50 }
51
52 // Parse parses a fingerprint into tree form.
53 //
54 // The input must have been produced by [Encode] at the same source
55 // version; parsing is thus infallible.
56 func Parse(fp string) Tree {
57 return Tree{parseFingerprint(fp)}
58 }
59
60 // Matches reports whether two fingerprint trees match, meaning that
61 // under some conditions (for example, particular instantiations of
62 // type parameters) the two types may be identical.
63 func Matches(x, y Tree) bool {
64 return unify(x.tree, y.tree)
65 }
66
67 // Fingerprint syntax
68 //
69 // The lexical syntax is essentially Lisp S-expressions:
70 //
71 // expr = STRING | INTEGER | IDENT | '(' expr... ')'
72 //
73 // where the tokens are as defined by text/scanner.
74 //
75 // The grammar of expression forms is:
76 //
77 // τ = IDENT -- named or basic type
78 // | (qual STRING IDENT) -- qualified named type
79 // | (array INTEGER τ)
80 // | (slice τ)
81 // | (ptr τ)
82 // | (chan IDENT τ)
83 // | (func τ v? τ) -- signature params, results, variadic?
84 // | (map τ τ)
85 // | (struct field*)
86 // | (tuple τ*)
87 // | (interface) -- nonempty interface (lossy)
88 // | (typeparam INTEGER)
89 // | (inst τ τ...) -- instantiation of a named type
90 //
91 // field = IDENT IDENT STRING τ -- name, embedded?, tag, type
92
93 func fingerprint(t types.Type) (string, bool) {
94 var buf strings.Builder
95 tricky := false
96 var print func(t types.Type)
97 print = func(t types.Type) {
98 switch t := t.(type) {
99 case *types.Alias:
100 print(types.Unalias(t))
101
102 case *types.Named:
103 targs := t.TypeArgs()
104 if targs != nil {
105 buf.WriteString("(inst ")
106 }
107 tname := t.Obj()
108 if tname.Pkg() != nil {
109 fmt.Fprintf(&buf, "(qual %q %s)", tname.Pkg().Path(), tname.Name())
110 } else if tname.Name() != "error" && tname.Name() != "comparable" {
111 panic(tname) // error and comparable the only named types with no package
112 } else {
113 buf.WriteString(tname.Name())
114 }
115 if targs != nil {
116 for t0 := range targs.Types() {
117 buf.WriteByte(' ')
118 print(t0)
119 }
120 buf.WriteString(")")
121 }
122
123 case *types.Array:
124 fmt.Fprintf(&buf, "(array %d ", t.Len())
125 print(t.Elem())
126 buf.WriteByte(')')
127
128 case *types.Slice:
129 buf.WriteString("(slice ")
130 print(t.Elem())
131 buf.WriteByte(')')
132
133 case *types.Pointer:
134 buf.WriteString("(ptr ")
135 print(t.Elem())
136 buf.WriteByte(')')
137
138 case *types.Map:
139 buf.WriteString("(map ")
140 print(t.Key())
141 buf.WriteByte(' ')
142 print(t.Elem())
143 buf.WriteByte(')')
144
145 case *types.Chan:
146 fmt.Fprintf(&buf, "(chan %d ", t.Dir())
147 print(t.Elem())
148 buf.WriteByte(')')
149
150 case *types.Tuple:
151 buf.WriteString("(tuple")
152 for v := range t.Variables() {
153 buf.WriteByte(' ')
154 print(v.Type())
155 }
156 buf.WriteByte(')')
157
158 case *types.Basic:
159 // Print byte/uint8 as "byte" instead of calling
160 // BasicType.String, which prints the two distinctly
161 // (even though their Kinds are numerically equal).
162 // Ditto for rune/int32.
163 switch t.Kind() {
164 case types.Byte:
165 buf.WriteString("byte")
166 case types.Rune:
167 buf.WriteString("rune")
168 case types.UnsafePointer:
169 buf.WriteString(`(qual "unsafe" Pointer)`)
170 default:
171 if t.Info()&types.IsUntyped != 0 {
172 panic("fingerprint of untyped type")
173 }
174 buf.WriteString(t.String())
175 }
176
177 case *types.Signature:
178 buf.WriteString("(func ")
179 print(t.Params())
180 if t.Variadic() {
181 buf.WriteString(" v")
182 }
183 buf.WriteByte(' ')
184 print(t.Results())
185 buf.WriteByte(')')
186
187 case *types.Struct:
188 // Non-empty unnamed struct types in method
189 // signatures are vanishingly rare.
190 buf.WriteString("(struct")
191 for i := range t.NumFields() {
192 f := t.Field(i)
193 name := f.Name()
194 if !f.Exported() {
195 name = fmt.Sprintf("(qual %q %s)", f.Pkg().Path(), name)
196 }
197
198 // This isn't quite right for embedded type aliases.
199 // (See types.TypeString(StructType) and #44410 for context.)
200 // But this is vanishingly rare.
201 fmt.Fprintf(&buf, " %s %t %q ", name, f.Embedded(), t.Tag(i))
202 print(f.Type())
203 }
204 buf.WriteByte(')')
205
206 case *types.Interface:
207 if t.NumMethods() == 0 {
208 buf.WriteString("any") // common case
209 } else {
210 // Interface assignability is particularly
211 // tricky due to the possibility of recursion.
212 // However, nontrivial interface type literals
213 // are exceedingly rare in function signatures.
214 //
215 // TODO(adonovan): add disambiguating precision
216 // (e.g. number of methods, their IDs and arities)
217 // as needs arise (i.e. collisions are observed).
218 tricky = true
219 buf.WriteString("(interface)")
220 }
221
222 case *types.TypeParam:
223 // Matching of type parameters will require
224 // parsing fingerprints and unification.
225 tricky = true
226 fmt.Fprintf(&buf, "(%s %d)", symTypeparam, t.Index())
227
228 default: // incl. *types.Union
229 panic(t)
230 }
231 }
232
233 print(t)
234
235 return buf.String(), tricky
236 }
237
238 // sexpr defines the representation of a fingerprint tree.
239 type (
240 sexpr any // = string | int | symbol | *cons | nil
241 symbol string
242 cons struct{ car, cdr sexpr }
243 )
244
245 // parseFingerprint returns the type encoded by fp in tree form.
246 //
247 // The input must have been produced by [fingerprint] at the same
248 // source version; parsing is thus infallible.
249 func parseFingerprint(fp string) sexpr {
250 var scan scanner.Scanner
251 scan.Error = func(scan *scanner.Scanner, msg string) { panic(msg) }
252 scan.Init(strings.NewReader(fp))
253
254 // next scans a token and updates tok.
255 var tok rune
256 next := func() { tok = scan.Scan() }
257
258 next()
259
260 // parse parses a fingerprint and returns its tree.
261 var parse func() sexpr
262 parse = func() sexpr {
263 if tok == '(' {
264 next() // consume '('
265 var head sexpr // empty list
266 tailcdr := &head
267 for tok != ')' {
268 cell := &cons{car: parse()}
269 *tailcdr = cell
270 tailcdr = &cell.cdr
271 }
272 next() // consume ')'
273 return head
274 }
275
276 s := scan.TokenText()
277 switch tok {
278 case scanner.Ident:
279 next() // consume IDENT
280 return symbol(s)
281
282 case scanner.Int:
283 next() // consume INT
284 i, err := strconv.Atoi(s)
285 if err != nil {
286 panic(err)
287 }
288 return i
289
290 case scanner.String:
291 next() // consume STRING
292 s, err := strconv.Unquote(s)
293 if err != nil {
294 panic(err)
295 }
296 return s
297
298 default:
299 panic(tok)
300 }
301 }
302
303 return parse()
304 }
305
306 // writeSexpr formats an S-expression.
307 // It is provided for debugging.
308 func writeSexpr(out *strings.Builder, x sexpr) {
309 switch x := x.(type) {
310 case nil:
311 out.WriteString("()")
312 case string:
313 fmt.Fprintf(out, "%q", x)
314 case int:
315 fmt.Fprintf(out, "%d", x)
316 case symbol:
317 out.WriteString(string(x))
318 case *cons:
319 out.WriteString("(")
320 for {
321 writeSexpr(out, x.car)
322 if x.cdr == nil {
323 break
324 } else if cdr, ok := x.cdr.(*cons); ok {
325 x = cdr
326 out.WriteByte(' ')
327 } else {
328 // Dotted list: should never happen,
329 // but support it for debugging.
330 out.WriteString(" . ")
331 print(x.cdr)
332 break
333 }
334 }
335 out.WriteString(")")
336 default:
337 panic(x)
338 }
339 }
340
341 // unify reports whether x and y match, in the presence of type parameters.
342 // The constraints on type parameters are ignored, but each type parameter must
343 // have a consistent binding.
344 func unify(x, y sexpr) bool {
345
346 // maxTypeParam returns the maximum type parameter index in x.
347 var maxTypeParam func(x sexpr) int
348 maxTypeParam = func(x sexpr) int {
349 if i := typeParamIndex(x); i >= 0 {
350 return i
351 }
352 if c, ok := x.(*cons); ok {
353 return max(maxTypeParam(c.car), maxTypeParam(c.cdr))
354 }
355 return -1
356 }
357
358 // xBindings[i] is the binding for type parameter #i in x, and similarly for y.
359 // Although type parameters are nominally bound to sexprs, each bindings[i]
360 // is a *sexpr, so unbound variables can share a binding.
361 xBindings := make([]*sexpr, maxTypeParam(x)+1)
362 for i := range len(xBindings) {
363 xBindings[i] = new(sexpr)
364 }
365 yBindings := make([]*sexpr, maxTypeParam(y)+1)
366 for i := range len(yBindings) {
367 yBindings[i] = new(sexpr)
368 }
369
370 // bind sets binding b to s from bindings if it does not occur in s.
371 bind := func(b *sexpr, s sexpr, bindings []*sexpr) bool {
372 // occurs reports whether b is present in s.
373 var occurs func(s sexpr) bool
374 occurs = func(s sexpr) bool {
375 if j := typeParamIndex(s); j >= 0 {
376 return b == bindings[j]
377 }
378 if c, ok := s.(*cons); ok {
379 return occurs(c.car) || occurs(c.cdr)
380 }
381 return false
382 }
383
384 if occurs(s) {
385 return false
386 }
387 *b = s
388 return true
389 }
390
391 var uni func(x, y sexpr) bool
392 uni = func(x, y sexpr) bool {
393 var bx, by *sexpr
394 ix := typeParamIndex(x)
395 if ix >= 0 {
396 bx = xBindings[ix]
397 }
398 iy := typeParamIndex(y)
399 if iy >= 0 {
400 by = yBindings[iy]
401 }
402
403 if bx != nil || by != nil {
404 // If both args are type params and neither is bound, have them share a binding.
405 if bx != nil && by != nil && *bx == nil && *by == nil {
406 xBindings[ix] = yBindings[iy]
407 return true
408 }
409 // Treat param bindings like original args in what follows.
410 if bx != nil && *bx != nil {
411 x = *bx
412 }
413 if by != nil && *by != nil {
414 y = *by
415 }
416 // If the x param is unbound, bind it to y.
417 if bx != nil && *bx == nil {
418 return bind(bx, y, yBindings)
419 }
420 // If the y param is unbound, bind it to x.
421 if by != nil && *by == nil {
422 return bind(by, x, xBindings)
423 }
424 // Unify the binding of a bound parameter.
425 return uni(x, y)
426 }
427
428 // Neither arg is a type param.
429 if reflect.TypeOf(x) != reflect.TypeOf(y) {
430 return false // type mismatch
431 }
432 switch x := x.(type) {
433 case nil, string, int, symbol:
434 return x == y
435 case *cons:
436 y := y.(*cons)
437 if !uni(x.car, y.car) {
438 return false
439 }
440 if x.cdr == nil {
441 return y.cdr == nil
442 }
443 if y.cdr == nil {
444 return false
445 }
446 return uni(x.cdr, y.cdr)
447 default:
448 panic(fmt.Sprintf("unify %T %T", x, y))
449 }
450 }
451 // At least one param is bound. Unify its binding with the other.
452 return uni(x, y)
453 }
454
455 // typeParamIndex returns the index of the type parameter,
456 // if x has the form "(typeparam INTEGER)", otherwise -1.
457 func typeParamIndex(x sexpr) int {
458 if x, ok := x.(*cons); ok {
459 if sym, ok := x.car.(symbol); ok && sym == symTypeparam {
460 return x.cdr.(*cons).car.(int)
461 }
462 }
463 return -1
464 }
465
466 const symTypeparam = "typeparam"