1 // Copyright 2018 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.
12 "golang.org/x/tools/go/analysis"
13 "golang.org/x/tools/internal/event"
14 "golang.org/x/tools/internal/lsp/debug/tag"
15 "golang.org/x/tools/internal/lsp/protocol"
16 "golang.org/x/tools/internal/span"
17 errors "golang.org/x/xerrors"
20 type Diagnostic struct {
24 Severity protocol.DiagnosticSeverity
25 Tags []protocol.DiagnosticTag
27 Related []RelatedInformation
30 type SuggestedFix struct {
32 Edits map[span.URI][]protocol.TextEdit
33 Command *protocol.Command
36 type RelatedInformation struct {
42 func Diagnostics(ctx context.Context, snapshot Snapshot, pkg Package, withAnalysis bool) (map[VersionedFileIdentity][]*Diagnostic, bool, error) {
43 onlyIgnoredFiles := true
44 for _, pgf := range pkg.CompiledGoFiles() {
45 onlyIgnoredFiles = onlyIgnoredFiles && snapshot.IgnoredFile(pgf.URI)
48 return nil, false, nil
51 // If we are missing dependencies, it may because the user's workspace is
52 // not correctly configured. Report errors, if possible.
54 if len(pkg.MissingDependencies()) > 0 {
57 // If we have a package with a single file and errors about "undeclared" symbols,
58 // we may have an ad-hoc package with multiple files. Show a warning message.
59 // TODO(golang/go#36416): Remove this when golang.org/cl/202277 is merged.
60 if len(pkg.CompiledGoFiles()) == 1 && hasUndeclaredErrors(pkg) {
63 // Prepare the reports we will send for the files in this package.
64 reports := make(map[VersionedFileIdentity][]*Diagnostic)
65 for _, pgf := range pkg.CompiledGoFiles() {
66 clearReports(snapshot, reports, pgf.URI)
68 // Prepare any additional reports for the errors in this package.
69 for _, e := range pkg.GetErrors() {
70 // We only need to handle lower-level errors.
71 if e.Kind != ListError {
74 // If no file is associated with the error, pick an open file from the package.
75 if e.URI.Filename() == "" {
76 for _, pgf := range pkg.CompiledGoFiles() {
77 if snapshot.IsOpen(pgf.URI) {
82 clearReports(snapshot, reports, e.URI)
84 // Run diagnostics for the package that this URI belongs to.
85 hadDiagnostics, hadTypeErrors, err := diagnostics(ctx, snapshot, reports, pkg, len(pkg.MissingDependencies()) > 0)
89 if hadDiagnostics || !withAnalysis {
90 return reports, warn, nil
92 // Exit early if the context has been canceled. This also protects us
93 // from a race on Options, see golang/go#36699.
95 return nil, warn, ctx.Err()
97 // If we don't have any list or parse errors, run analyses.
98 analyzers := pickAnalyzers(snapshot, hadTypeErrors)
99 if err := analyses(ctx, snapshot, reports, pkg, analyzers); err != nil {
100 event.Error(ctx, "analyses failed", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
101 if ctx.Err() != nil {
102 return nil, warn, ctx.Err()
105 return reports, warn, nil
108 func pickAnalyzers(snapshot Snapshot, hadTypeErrors bool) map[string]Analyzer {
109 analyzers := make(map[string]Analyzer)
111 // Always run convenience analyzers.
112 for k, v := range snapshot.View().Options().ConvenienceAnalyzers {
115 // If we had type errors, only run type error analyzers.
117 for k, v := range snapshot.View().Options().TypeErrorAnalyzers {
122 for k, v := range snapshot.View().Options().DefaultAnalyzers {
125 for k, v := range snapshot.View().Options().StaticcheckAnalyzers {
131 func FileDiagnostics(ctx context.Context, snapshot Snapshot, uri span.URI) (VersionedFileIdentity, []*Diagnostic, error) {
132 fh, err := snapshot.GetVersionedFile(ctx, uri)
134 return VersionedFileIdentity{}, nil, err
136 pkg, _, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage)
138 return VersionedFileIdentity{}, nil, err
140 reports, _, err := Diagnostics(ctx, snapshot, pkg, true)
142 return VersionedFileIdentity{}, nil, err
144 diagnostics, ok := reports[fh.VersionedFileIdentity()]
146 return VersionedFileIdentity{}, nil, errors.Errorf("no diagnostics for %s", uri)
148 return fh.VersionedFileIdentity(), diagnostics, nil
151 type diagnosticSet struct {
152 listErrors, parseErrors, typeErrors []*Diagnostic
155 func diagnostics(ctx context.Context, snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, pkg Package, hasMissingDeps bool) (bool, bool, error) {
156 ctx, done := event.Start(ctx, "source.diagnostics", tag.Package.Of(pkg.ID()))
157 _ = ctx // circumvent SA4006
160 diagSets := make(map[span.URI]*diagnosticSet)
161 for _, e := range pkg.GetErrors() {
165 Severity: protocol.SeverityError,
168 set, ok := diagSets[e.URI]
170 set = &diagnosticSet{}
171 diagSets[e.URI] = set
175 set.parseErrors = append(set.parseErrors, diag)
176 diag.Source = "syntax"
178 set.typeErrors = append(set.typeErrors, diag)
179 diag.Source = "compiler"
181 set.listErrors = append(set.listErrors, diag)
182 diag.Source = "go list"
185 var nonEmptyDiagnostics, hasTypeErrors bool // track if we actually send non-empty diagnostics
186 for uri, set := range diagSets {
187 // Don't report type errors if there are parse errors or list errors.
188 diags := set.typeErrors
189 if len(set.parseErrors) > 0 {
190 diags, nonEmptyDiagnostics = set.parseErrors, true
191 } else if len(set.listErrors) > 0 {
192 // Only show list errors if the package has missing dependencies.
194 diags, nonEmptyDiagnostics = set.listErrors, true
196 } else if len(set.typeErrors) > 0 {
199 if err := addReports(snapshot, reports, uri, diags...); err != nil {
200 return false, false, err
203 return nonEmptyDiagnostics, hasTypeErrors, nil
206 func analyses(ctx context.Context, snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, pkg Package, analyses map[string]Analyzer) error {
207 var analyzers []*analysis.Analyzer
208 for _, a := range analyses {
209 if !a.IsEnabled(snapshot.View()) {
212 analyzers = append(analyzers, a.Analyzer)
214 analysisErrors, err := snapshot.Analyze(ctx, pkg.ID(), analyzers...)
219 // Report diagnostics and errors from root analyzers.
220 for _, e := range analysisErrors {
221 // If the diagnostic comes from a "convenience" analyzer, it is not
222 // meant to provide diagnostics, but rather only suggested fixes.
223 // Skip these types of errors in diagnostics; we will use their
224 // suggested fixes when providing code actions.
225 if isConvenienceAnalyzer(e.Category) {
228 // This is a bit of a hack, but clients > 3.15 will be able to grey out unnecessary code.
229 // If we are deleting code as part of all of our suggested fixes, assume that this is dead code.
230 // TODO(golang/go#34508): Return these codes from the diagnostics themselves.
231 var tags []protocol.DiagnosticTag
232 if onlyDeletions(e.SuggestedFixes) {
233 tags = append(tags, protocol.Unnecessary)
235 if err := addReports(snapshot, reports, e.URI, &Diagnostic{
239 Severity: protocol.SeverityWarning,
249 func clearReports(snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, uri span.URI) {
250 fh := snapshot.FindFile(uri)
254 reports[fh.VersionedFileIdentity()] = []*Diagnostic{}
257 func addReports(snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, uri span.URI, diagnostics ...*Diagnostic) error {
258 fh := snapshot.FindFile(uri)
262 existingDiagnostics, ok := reports[fh.VersionedFileIdentity()]
264 return fmt.Errorf("diagnostics for unexpected file %s", uri)
266 if len(diagnostics) == 1 {
268 if _, ok := snapshot.View().Options().TypeErrorAnalyzers[d1.Source]; ok {
269 for i, d2 := range existingDiagnostics {
270 if r := protocol.CompareRange(d1.Range, d2.Range); r != 0 {
273 if d1.Message != d2.Message {
276 reports[fh.VersionedFileIdentity()][i].Tags = append(reports[fh.VersionedFileIdentity()][i].Tags, d1.Tags...)
281 reports[fh.VersionedFileIdentity()] = append(reports[fh.VersionedFileIdentity()], diagnostics...)
285 // onlyDeletions returns true if all of the suggested fixes are deletions.
286 func onlyDeletions(fixes []SuggestedFix) bool {
287 for _, fix := range fixes {
288 for _, edits := range fix.Edits {
289 for _, edit := range edits {
290 if edit.NewText != "" {
293 if protocol.ComparePosition(edit.Range.Start, edit.Range.End) == 0 {
299 return len(fixes) > 0
302 // hasUndeclaredErrors returns true if a package has a type error
303 // about an undeclared symbol.
304 func hasUndeclaredErrors(pkg Package) bool {
305 for _, err := range pkg.GetErrors() {
306 if err.Kind != TypeError {
309 if strings.Contains(err.Message, "undeclared name:") {
316 func isConvenienceAnalyzer(category string) bool {
317 for _, a := range DefaultOptions().ConvenienceAnalyzers {
318 if category == a.Analyzer.Name {