Debian Codegraph @

gopls/internal/cache/diagnostics.go

raw symbols SCIP
1 // Copyright 2023 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 cache
6
7 import (
8 "crypto/sha256"
9 "encoding/json"
10 "fmt"
11 "strings"
12
13 "golang.org/x/tools/gopls/internal/file"
14 "golang.org/x/tools/gopls/internal/protocol"
15 "golang.org/x/tools/gopls/internal/util/bug"
16 )
17
18 // A InitializationError is an error that causes snapshot initialization to fail.
19 // It is either the error returned from go/packages.Load, or an error parsing a
20 // workspace go.work or go.mod file.
21 //
22 // Such an error generally indicates that the View is malformed, and will never
23 // be usable.
24 type InitializationError struct {
25 // MainError is the primary error. Must be non-nil.
26 MainError error
27
28 // Diagnostics contains any supplemental (structured) diagnostics extracted
29 // from the load error.
30 Diagnostics map[protocol.DocumentURI][]*Diagnostic
31 }
32
33 func byURI(d *Diagnostic) protocol.DocumentURI { return d.URI } // For use in maps.Group.
34
35 // A Diagnostic corresponds to an LSP Diagnostic.
36 // https://microsoft.github.io/language-server-protocol/specification#diagnostic
37 //
38 // It is (effectively) gob-serializable; see {encode,decode}Diagnostics.
39 type Diagnostic struct {
40 URI protocol.DocumentURI // of diagnosed file (not diagnostic documentation)
41 Range protocol.Range
42 Severity protocol.DiagnosticSeverity
43 Code string // analysis.Diagnostic.Category (or "default" if empty) or hidden go/types error code
44 CodeHref string
45
46 // Source is a human-readable description of the source of the error.
47 // Diagnostics generated by an analysis.Analyzer set it to Analyzer.Name.
48 Source DiagnosticSource
49
50 Message string
51
52 Tags []protocol.DiagnosticTag
53 Related []protocol.DiagnosticRelatedInformation
54
55 // Fields below are used internally to generate lazy fixes. They aren't
56 // part of the LSP spec and historically didn't leave the server.
57 //
58 // Update(2023-05): version 3.16 of the LSP spec included support for the
59 // Diagnostic.data field, which holds arbitrary data preserved in the
60 // diagnostic for codeAction requests. This field allows bundling additional
61 // information for lazy fixes, and gopls can (and should) use this
62 // information to avoid re-evaluating diagnostics in code-action handlers.
63 //
64 // In order to stage this transition incrementally, the 'BundledFixes' field
65 // may store a 'bundled' (=json-serialized) form of the associated
66 // SuggestedFixes. Not all diagnostics have their fixes bundled.
67 BundledFixes *json.RawMessage
68 SuggestedFixes []SuggestedFix
69 }
70
71 func (d *Diagnostic) String() string {
72 return fmt.Sprintf("%v: %s", d.Range, d.Message)
73 }
74
75 // Hash computes a hash to identify the diagnostic.
76 // The hash is for deduplicating within a file, so does not incorporate d.URI.
77 func (d *Diagnostic) Hash() file.Hash {
78 h := sha256.New()
79 for _, t := range d.Tags {
80 fmt.Fprintf(h, "tag: %s\n", t)
81 }
82 for _, r := range d.Related {
83 fmt.Fprintf(h, "related: %s %s %s\n", r.Location.URI, r.Message, r.Location.Range)
84 }
85 fmt.Fprintf(h, "code: %s\n", d.Code)
86 fmt.Fprintf(h, "codeHref: %s\n", d.CodeHref)
87 fmt.Fprintf(h, "message: %s\n", d.Message)
88 fmt.Fprintf(h, "range: %s\n", d.Range)
89 fmt.Fprintf(h, "severity: %s\n", d.Severity)
90 fmt.Fprintf(h, "source: %s\n", d.Source)
91 if d.BundledFixes != nil {
92 fmt.Fprintf(h, "fixes: %s\n", *d.BundledFixes)
93 }
94 var hash [sha256.Size]byte
95 h.Sum(hash[:0])
96 return hash
97 }
98
99 func ToProtocolDiagnostics(diagnostics ...*Diagnostic) []protocol.Diagnostic {
100 // TODO(rfindley): support bundling edits, and bundle all suggested fixes here.
101 // (see cache.bundleLazyFixes).
102
103 reports := []protocol.Diagnostic{}
104 for _, diag := range diagnostics {
105 pdiag := protocol.Diagnostic{
106 // diag.Message might start with \n or \t
107 Message: strings.TrimSpace(diag.Message),
108 Range: diag.Range,
109 Severity: diag.Severity,
110 Source: string(diag.Source),
111 Tags: protocol.NonNilSlice(diag.Tags),
112 RelatedInformation: diag.Related,
113 Data: diag.BundledFixes,
114 }
115 if diag.Code != "" {
116 pdiag.Code = diag.Code
117 }
118 if diag.CodeHref != "" {
119 pdiag.CodeDescription = &protocol.CodeDescription{Href: diag.CodeHref}
120 }
121 reports = append(reports, pdiag)
122 }
123 return reports
124 }
125
126 // A DiagnosticSource identifies the source of a diagnostic.
127 //
128 // Its value may be one of the distinguished string values below, or
129 // the Name of an [analysis.Analyzer].
130 type DiagnosticSource string
131
132 const (
133 UnknownError DiagnosticSource = "<Unknown source>"
134 ListError DiagnosticSource = "go list"
135 ParseError DiagnosticSource = "syntax"
136 TypeError DiagnosticSource = "compiler"
137 ModTidyError DiagnosticSource = "go mod tidy"
138 CompilerOptDetailsInfo DiagnosticSource = "optimizer details" // cmd/compile -json=0,dir
139 UpgradeNotification DiagnosticSource = "upgrade available"
140 Vulncheck DiagnosticSource = "vulncheck imports"
141 Govulncheck DiagnosticSource = "govulncheck"
142 TemplateError DiagnosticSource = "template"
143 WorkFileError DiagnosticSource = "go.work file"
144 )
145
146 // A SuggestedFix represents a suggested fix (for a diagnostic)
147 // produced by analysis, in protocol form.
148 //
149 // The fixes are reported to the client as a set of code actions in
150 // response to a CodeAction query for a set of diagnostics. Multiple
151 // SuggestedFixes may be produced for the same logical fix, varying
152 // only in ActionKind. For example, a fix may be both a Refactor
153 // (which should appear on the refactoring menu) and a SourceFixAll (a
154 // clear fix that can be safely applied without explicit consent).
155 type SuggestedFix struct {
156 Title string
157 Edits map[protocol.DocumentURI][]protocol.TextEdit
158 Command *protocol.Command
159 ActionKind protocol.CodeActionKind
160 }
161
162 // SuggestedFixFromCommand returns a suggested fix to run the given command.
163 func SuggestedFixFromCommand(cmd *protocol.Command, kind protocol.CodeActionKind) SuggestedFix {
164 return SuggestedFix{
165 Title: cmd.Title,
166 Command: cmd,
167 ActionKind: kind,
168 }
169 }
170
171 // lazyFixesJSON is a JSON-serializable list of code actions (arising
172 // from "lazy" SuggestedFixes with no Edits) to be saved in the
173 // protocol.Diagnostic.Data field. Computation of the edits is thus
174 // deferred until the action's command is invoked.
175 type lazyFixesJSON struct {
176 // TODO(rfindley): pack some sort of identifier here for later
177 // lookup/validation?
178 Actions []protocol.CodeAction
179 }
180
181 // bundleLazyFixes attempts to bundle sd.SuggestedFixes into the
182 // sd.BundledFixes field, so that it can be round-tripped through the client.
183 // It returns false if the fixes cannot be bundled.
184 func bundleLazyFixes(sd *Diagnostic) bool {
185 if len(sd.SuggestedFixes) == 0 {
186 return true
187 }
188 var actions []protocol.CodeAction
189 for _, fix := range sd.SuggestedFixes {
190 if fix.Edits != nil {
191 // For now, we only support bundled code actions that execute commands.
192 //
193 // In order to cleanly support bundled edits, we'd have to guarantee that
194 // the edits were generated on the current snapshot. But this naively
195 // implies that every fix would have to include a snapshot ID, which
196 // would require us to republish all diagnostics on each new snapshot.
197 //
198 // TODO(rfindley): in order to avoid this additional chatter, we'd need
199 // to build some sort of registry or other mechanism on the snapshot to
200 // check whether a diagnostic is still valid.
201 return false
202 }
203 action := protocol.CodeAction{
204 Title: fix.Title,
205 Kind: fix.ActionKind,
206 Command: fix.Command,
207 }
208 actions = append(actions, action)
209 }
210 fixes := lazyFixesJSON{
211 Actions: actions,
212 }
213 data, err := json.Marshal(fixes)
214 if err != nil {
215 bug.Reportf("marshalling lazy fixes: %v", err)
216 return false
217 }
218 msg := json.RawMessage(data)
219 sd.BundledFixes = &msg
220 return true
221 }
222
223 // BundledLazyFixes extracts any bundled codeActions from the
224 // diag.Data field.
225 func BundledLazyFixes(diag protocol.Diagnostic) ([]protocol.CodeAction, error) {
226 var fix lazyFixesJSON
227 if diag.Data != nil {
228 err := protocol.UnmarshalJSON(*diag.Data, &fix)
229 if err != nil {
230 return nil, fmt.Errorf("unmarshalling fix from diagnostic data: %v", err)
231 }
232 }
233
234 var actions []protocol.CodeAction
235 for _, action := range fix.Actions {
236 // See bundleLazyFixes: for now we only support bundling commands.
237 if action.Edit != nil {
238 return nil, fmt.Errorf("bundled fix %q includes workspace edits", action.Title)
239 }
240 // associate the action with the incoming diagnostic
241 // (Note that this does not mutate the fix.Fixes slice).
242 action.Diagnostics = []protocol.Diagnostic{diag}
243 actions = append(actions, action)
244 }
245
246 return actions, nil
247 }