Debian Codegraph @

internal/typeparams/genericfeatures/features.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 // The genericfeatures package provides utilities for detecting usage of
6 // generic programming in Go packages.
7 package genericfeatures
8
9 import (
10 "go/ast"
11 "go/types"
12 "strings"
13
14 "golang.org/x/tools/go/ast/inspector"
15 )
16
17 // Features is a set of flags reporting which features of generic Go code a
18 // package uses, or 0.
19 type Features int
20
21 const (
22 // GenericTypeDecls indicates whether the package declares types with type
23 // parameters.
24 GenericTypeDecls Features = 1 << iota
25
26 // GenericFuncDecls indicates whether the package declares functions with
27 // type parameters.
28 GenericFuncDecls
29
30 // EmbeddedTypeSets indicates whether the package declares interfaces that
31 // contain structural type restrictions, i.e. are not fully described by
32 // their method sets.
33 EmbeddedTypeSets
34
35 // TypeInstantiation indicates whether the package instantiates any generic
36 // types.
37 TypeInstantiation
38
39 // FuncInstantiation indicates whether the package instantiates any generic
40 // functions.
41 FuncInstantiation
42 )
43
44 func (f Features) String() string {
45 var feats []string
46 if f&GenericTypeDecls != 0 {
47 feats = append(feats, "typeDecl")
48 }
49 if f&GenericFuncDecls != 0 {
50 feats = append(feats, "funcDecl")
51 }
52 if f&EmbeddedTypeSets != 0 {
53 feats = append(feats, "typeSet")
54 }
55 if f&TypeInstantiation != 0 {
56 feats = append(feats, "typeInstance")
57 }
58 if f&FuncInstantiation != 0 {
59 feats = append(feats, "funcInstance")
60 }
61 return "features{" + strings.Join(feats, ",") + "}"
62 }
63
64 // ForPackage computes which generic features are used directly by the
65 // package being analyzed.
66 func ForPackage(inspect *inspector.Inspector, info *types.Info) Features {
67 nodeFilter := []ast.Node{
68 (*ast.FuncType)(nil),
69 (*ast.InterfaceType)(nil),
70 (*ast.ImportSpec)(nil),
71 (*ast.TypeSpec)(nil),
72 }
73
74 var direct Features
75
76 inspect.Preorder(nodeFilter, func(node ast.Node) {
77 switch n := node.(type) {
78 case *ast.FuncType:
79 if tparams := n.TypeParams; tparams != nil {
80 direct |= GenericFuncDecls
81 }
82 case *ast.InterfaceType:
83 tv := info.Types[n] // may be zero
84 if iface, _ := tv.Type.(*types.Interface); iface != nil && !iface.IsMethodSet() {
85 direct |= EmbeddedTypeSets
86 }
87 case *ast.TypeSpec:
88 if tparams := n.TypeParams; tparams != nil {
89 direct |= GenericTypeDecls
90 }
91 }
92 })
93
94 for _, inst := range info.Instances {
95 switch types.Unalias(inst.Type).(type) {
96 case *types.Named:
97 direct |= TypeInstantiation
98 case *types.Signature:
99 direct |= FuncInstantiation
100 }
101 }
102 return direct
103 }