Debian Codegraph @

gopls/internal/golang/compileropt.go

raw symbols SCIP
1 // Copyright 2020 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 golang
6
7 import (
8 "bytes"
9 "context"
10 "encoding/json"
11 "fmt"
12 "os"
13 "path/filepath"
14 "strings"
15
16 "golang.org/x/tools/gopls/internal/cache"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/settings"
19 "golang.org/x/tools/internal/event"
20 )
21
22 // CompilerOptDetails invokes the Go compiler with the "-json=0,dir"
23 // flag on the packages and tests in the specified directory, parses
24 // its log of optimization decisions, and returns them as a set of
25 // diagnostics.
26 func CompilerOptDetails(ctx context.Context, snapshot *cache.Snapshot, pkgDir protocol.DocumentURI) (map[protocol.DocumentURI][]*cache.Diagnostic, error) {
27 outDir, err := os.MkdirTemp("", fmt.Sprintf("gopls-%d.details", os.Getpid()))
28 if err != nil {
29 return nil, err
30 }
31 defer func() {
32 if err := os.RemoveAll(outDir); err != nil {
33 event.Error(ctx, "cleaning details dir", err)
34 }
35 }()
36
37 outDirURI := protocol.URIFromPath(outDir)
38 // details doesn't handle Windows URIs in the form of "file:///C:/...",
39 // so rewrite them to "file://C:/...". See golang/go#41614.
40 if !strings.HasPrefix(outDir, "/") {
41 outDirURI = protocol.DocumentURI(strings.Replace(string(outDirURI), "file:///", "file://", 1))
42 }
43
44 // We use "go test -c" not "go build" as it covers all three packages
45 // (p, "p [p.test]", "p_test [p.test]") in the directory, if they exist.
46 // (See also assembly.go.)
47 inv, cleanupInvocation, err := snapshot.GoCommandInvocation(cache.NoNetwork, pkgDir.Path(), "test", []string{
48 "-c",
49 "-vet=off", // weirdly -c doesn't disable vet
50 fmt.Sprintf("-gcflags=-json=0,%s", outDirURI), // JSON schema version 0
51 fmt.Sprintf("-o=%s", os.DevNull),
52 ".",
53 })
54 if err != nil {
55 return nil, err
56 }
57 defer cleanupInvocation()
58 _, err = snapshot.View().GoCommandRunner().Run(ctx, *inv)
59 if err != nil {
60 return nil, err
61 }
62 files, err := findJSONFiles(outDir)
63 if err != nil {
64 return nil, err
65 }
66 reports := make(map[protocol.DocumentURI][]*cache.Diagnostic)
67 var parseError error
68 for _, fn := range files {
69 uri, diagnostics, err := parseDetailsFile(fn, snapshot.Options())
70 if err != nil {
71 // expect errors for all the files, save 1
72 parseError = err
73 }
74 fh, err := snapshot.ReadFile(ctx, uri)
75 if err != nil || fh == nil {
76 continue
77 }
78 if pkgDir != fh.URI().Dir() {
79 // Filter compiler diagnostics to the requested directory.
80 // https://github.com/golang/go/issues/42198
81 // sometimes the detail diagnostics generated for files
82 // outside the package can never be taken back.
83 continue
84 }
85 reports[fh.URI()] = diagnostics
86 }
87 return reports, parseError
88 }
89
90 // parseDetailsFile parses the file written by the Go compiler which contains a JSON-encoded protocol.Diagnostic.
91 func parseDetailsFile(filename string, options *settings.Options) (protocol.DocumentURI, []*cache.Diagnostic, error) {
92 buf, err := os.ReadFile(filename)
93 if err != nil {
94 return "", nil, err
95 }
96 var (
97 uri protocol.DocumentURI
98 i int
99 diagnostics []*cache.Diagnostic
100 )
101 type metadata struct {
102 File string `json:"file,omitempty"`
103 }
104 for dec := json.NewDecoder(bytes.NewReader(buf)); dec.More(); {
105 // The first element always contains metadata.
106 if i == 0 {
107 i++
108 m := new(metadata)
109 if err := dec.Decode(m); err != nil {
110 return "", nil, err
111 }
112 if !strings.HasSuffix(m.File, ".go") {
113 continue // <autogenerated>
114 }
115 uri = protocol.URIFromPath(m.File)
116 continue
117 }
118 d := new(protocol.Diagnostic)
119 if err := dec.Decode(d); err != nil {
120 return "", nil, err
121 }
122 d.Tags = []protocol.DiagnosticTag{} // must be an actual slice
123 msg := d.Code.(string)
124 if msg != "" {
125 msg = fmt.Sprintf("%s(%s)", msg, d.Message)
126 }
127 if !showDiagnostic(msg, d.Source, options) {
128 continue
129 }
130
131 // zeroIndexedRange subtracts 1 from the line and
132 // range, because the compiler output neglects to
133 // convert from 1-based UTF-8 coordinates to 0-based UTF-16.
134 // (See GOROOT/src/cmd/compile/internal/logopt/log_opts.go.)
135 // TODO(rfindley): also translate UTF-8 to UTF-16.
136 zeroIndexedRange := func(rng protocol.Range) protocol.Range {
137 return protocol.Range{
138 Start: protocol.Position{
139 Line: rng.Start.Line - 1,
140 Character: rng.Start.Character - 1,
141 },
142 End: protocol.Position{
143 Line: rng.End.Line - 1,
144 Character: rng.End.Character - 1,
145 },
146 }
147 }
148
149 var related []protocol.DiagnosticRelatedInformation
150 for _, ri := range d.RelatedInformation {
151 related = append(related, protocol.DiagnosticRelatedInformation{
152 Location: ri.Location.URI.Location(zeroIndexedRange(ri.Location.Range)),
153 Message: ri.Message,
154 })
155 }
156 diagnostic := &cache.Diagnostic{
157 URI: uri,
158 Range: zeroIndexedRange(d.Range),
159 Message: msg,
160 Severity: d.Severity,
161 Source: cache.CompilerOptDetailsInfo, // d.Source is always "go compiler" as of 1.16, use our own
162 Tags: d.Tags,
163 Related: related,
164 }
165 diagnostics = append(diagnostics, diagnostic)
166 i++
167 }
168 return uri, diagnostics, nil
169 }
170
171 // showDiagnostic reports whether a given diagnostic should be shown to the end
172 // user, given the current options.
173 func showDiagnostic(msg, source string, o *settings.Options) bool {
174 if source != "go compiler" {
175 return false
176 }
177 if o.Annotations == nil {
178 return true
179 }
180
181 // The strings below were gathered by grepping the source of
182 // cmd/compile for literal arguments in calls to logopt.LogOpt.
183 // (It is not a well defined set.)
184 //
185 // - canInlineFunction
186 // - cannotInlineCall
187 // - cannotInlineFunction
188 // - escape
189 // - escapes
190 // - isInBounds
191 // - isSliceInBounds
192 // - leak
193 // - nilcheck
194 //
195 // Additional ones not handled by logic below:
196 // - copy
197 // - iteration-variable-to-{heap,stack}
198 // - loop-modified-{range,for}
199
200 switch {
201 case strings.HasPrefix(msg, "canInline") ||
202 strings.HasPrefix(msg, "cannotInline") ||
203 strings.HasPrefix(msg, "inlineCall"):
204 return o.Annotations[settings.Inline]
205 case strings.HasPrefix(msg, "escape") || msg == "leak":
206 return o.Annotations[settings.Escape]
207 case strings.HasPrefix(msg, "nilcheck"):
208 return o.Annotations[settings.Nil]
209 case strings.HasPrefix(msg, "isInBounds") ||
210 strings.HasPrefix(msg, "isSliceInBounds"):
211 return o.Annotations[settings.Bounds]
212 }
213 return false
214 }
215
216 func findJSONFiles(dir string) ([]string, error) {
217 ans := []string{}
218 f := func(path string, fi os.FileInfo, _ error) error {
219 if fi.IsDir() {
220 return nil
221 }
222 if strings.HasSuffix(path, ".json") {
223 ans = append(ans, path)
224 }
225 return nil
226 }
227 err := filepath.Walk(dir, f)
228 return ans, err
229 }