Debian Codegraph @

gopls/internal/analysis/embeddirective/embeddirective.go

raw symbols SCIP
1 // Copyright 2022 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 embeddirective
6
7 import (
8 _ "embed"
9 "go/ast"
10 "go/token"
11 "go/types"
12 "strings"
13
14 "golang.org/x/tools/go/analysis"
15 "golang.org/x/tools/internal/analysis/analyzerutil"
16 "golang.org/x/tools/internal/refactor"
17 )
18
19 //go:embed doc.go
20 var doc string
21
22 var Analyzer = &analysis.Analyzer{
23 Name: "embed",
24 Doc: analyzerutil.MustExtractDoc(doc, "embed"),
25 Run: run,
26 RunDespiteErrors: true,
27 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/embeddirective",
28 }
29
30 func run(pass *analysis.Pass) (any, error) {
31 for _, f := range pass.Files {
32 comments := embedDirectiveComments(f)
33 if len(comments) == 0 {
34 continue // nothing to check
35 }
36
37 hasEmbedImport := false
38 for _, imp := range f.Imports {
39 if imp.Path.Value == `"embed"` {
40 hasEmbedImport = true
41 break
42 }
43 }
44
45 for _, c := range comments {
46 pos, end := c.Pos(), c.Pos()+token.Pos(len("//go:embed"))
47
48 if !hasEmbedImport {
49 // Add blank import of "embed".
50 _, edits := refactor.AddImport(pass.TypesInfo, f, "_", "embed", "", c.Pos())
51 if len(edits) > 0 {
52 pass.Report(analysis.Diagnostic{
53 Pos: pos,
54 End: end,
55 Message: `must import "embed" when using go:embed directives`,
56 SuggestedFixes: []analysis.SuggestedFix{{
57 Message: `Add missing "embed" import`,
58 TextEdits: edits,
59 }},
60 })
61 }
62 }
63
64 var msg string
65 spec := nextVarSpec(c, f)
66 switch {
67 case spec == nil:
68 msg = `go:embed directives must precede a "var" declaration`
69 case len(spec.Names) != 1:
70 msg = "declarations following go:embed directives must define a single variable"
71 case len(spec.Values) > 0:
72 msg = "declarations following go:embed directives must not specify a value"
73 case !embeddableType(pass.TypesInfo.Defs[spec.Names[0]]):
74 msg = "declarations following go:embed directives must be of type string, []byte or embed.FS"
75 }
76 if msg != "" {
77 pass.Report(analysis.Diagnostic{
78 Pos: pos,
79 End: end,
80 Message: msg,
81 })
82 }
83 }
84 }
85 return nil, nil
86 }
87
88 // embedDirectiveComments returns all comments in f that contains a //go:embed directive.
89 func embedDirectiveComments(f *ast.File) []*ast.Comment {
90 comments := []*ast.Comment{}
91 for _, cg := range f.Comments {
92 for _, c := range cg.List {
93 if strings.HasPrefix(c.Text, "//go:embed ") {
94 comments = append(comments, c)
95 }
96 }
97 }
98 return comments
99 }
100
101 // nextVarSpec returns the ValueSpec for the variable declaration immediately following
102 // the go:embed comment, or nil if the next declaration is not a variable declaration.
103 func nextVarSpec(com *ast.Comment, f *ast.File) *ast.ValueSpec {
104 // Embed directives must be followed by a declaration of one variable with no value.
105 // There may be comments and empty lines between the directive and the declaration.
106 var nextDecl ast.Decl
107 for _, d := range f.Decls {
108 if com.End() < d.End() {
109 nextDecl = d
110 break
111 }
112 }
113 if nextDecl == nil || nextDecl.Pos() == token.NoPos {
114 return nil
115 }
116 decl, ok := nextDecl.(*ast.GenDecl)
117 if !ok {
118 return nil
119 }
120 if decl.Tok != token.VAR {
121 return nil
122 }
123
124 // var declarations can be both freestanding and blocks (with parenthesis).
125 // Only the first variable spec following the directive is interesting.
126 var nextSpec ast.Spec
127 for _, s := range decl.Specs {
128 if com.End() < s.End() {
129 nextSpec = s
130 break
131 }
132 }
133 if nextSpec == nil {
134 return nil
135 }
136 spec, ok := nextSpec.(*ast.ValueSpec)
137 if !ok {
138 // Invalid AST, but keep going.
139 return nil
140 }
141 return spec
142 }
143
144 // embeddableType in go:embed directives are string, []byte or embed.FS.
145 func embeddableType(o types.Object) bool {
146 if o == nil {
147 return false
148 }
149
150 // For embed.FS the underlying type is an implementation detail.
151 // As long as the named type resolves to embed.FS, it is OK.
152 if named, ok := types.Unalias(o.Type()).(*types.Named); ok {
153 obj := named.Obj()
154 if obj.Pkg() != nil && obj.Pkg().Path() == "embed" && obj.Name() == "FS" {
155 return true
156 }
157 }
158
159 switch v := o.Type().Underlying().(type) {
160 case *types.Basic:
161 return types.Identical(v, types.Typ[types.String])
162 case *types.Slice:
163 return types.Identical(v.Elem(), types.Typ[types.Byte])
164 }
165
166 return false
167 }