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
35 type RelatedInformation struct {
41 func Diagnostics(ctx context.Context, snapshot Snapshot, pkg Package, withAnalysis bool) (map[VersionedFileIdentity][]*Diagnostic, bool, error) {
42 onlyIgnoredFiles := true
43 for _, pgf := range pkg.CompiledGoFiles() {
44 onlyIgnoredFiles = onlyIgnoredFiles && snapshot.IgnoredFile(pgf.URI)
47 return nil, false, nil
50 // If we are missing dependencies, it may because the user's workspace is
51 // not correctly configured. Report errors, if possible.
53 if len(pkg.MissingDependencies()) > 0 {
56 // If we have a package with a single file and errors about "undeclared" symbols,
57 // we may have an ad-hoc package with multiple files. Show a warning message.
58 // TODO(golang/go#36416): Remove this when golang.org/cl/202277 is merged.
59 if len(pkg.CompiledGoFiles()) == 1 && hasUndeclaredErrors(pkg) {
62 // Prepare the reports we will send for the files in this package.
63 reports := make(map[VersionedFileIdentity][]*Diagnostic)
64 for _, pgf := range pkg.CompiledGoFiles() {
65 clearReports(snapshot, reports, pgf.URI)
67 // Prepare any additional reports for the errors in this package.
68 for _, e := range pkg.GetErrors() {
69 // We only need to handle lower-level errors.
70 if e.Kind != ListError {
73 // If no file is associated with the error, pick an open file from the package.
74 if e.URI.Filename() == "" {
75 for _, pgf := range pkg.CompiledGoFiles() {
76 if snapshot.IsOpen(pgf.URI) {
81 clearReports(snapshot, reports, e.URI)
83 // Run diagnostics for the package that this URI belongs to.
84 hadDiagnostics, hadTypeErrors, err := diagnostics(ctx, snapshot, reports, pkg, len(pkg.MissingDependencies()) > 0)
88 if hadDiagnostics || !withAnalysis {
89 return reports, warn, nil
91 // Exit early if the context has been canceled. This also protects us
92 // from a race on Options, see golang/go#36699.
94 return nil, warn, ctx.Err()
96 // If we don't have any list or parse errors, run analyses.
97 analyzers := pickAnalyzers(snapshot, hadTypeErrors)
98 if err := analyses(ctx, snapshot, reports, pkg, analyzers); err != nil {
99 event.Error(ctx, "analyses failed", err, tag.Snapshot.Of(snapshot.ID()), tag.Package.Of(pkg.ID()))
100 if ctx.Err() != nil {
101 return nil, warn, ctx.Err()
104 return reports, warn, nil
107 func pickAnalyzers(snapshot Snapshot, hadTypeErrors bool) map[string]Analyzer {
108 analyzers := make(map[string]Analyzer)
110 // Always run convenience analyzers.
111 for k, v := range snapshot.View().Options().ConvenienceAnalyzers {
114 // If we had type errors, only run type error analyzers.
116 for k, v := range snapshot.View().Options().TypeErrorAnalyzers {
121 for k, v := range snapshot.View().Options().DefaultAnalyzers {
124 for k, v := range snapshot.View().Options().StaticcheckAnalyzers {
130 func FileDiagnostics(ctx context.Context, snapshot Snapshot, uri span.URI) (VersionedFileIdentity, []*Diagnostic, error) {
131 fh, err := snapshot.GetVersionedFile(ctx, uri)
133 return VersionedFileIdentity{}, nil, err
135 pkg, _, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage)
137 return VersionedFileIdentity{}, nil, err
139 reports, _, err := Diagnostics(ctx, snapshot, pkg, true)
141 return VersionedFileIdentity{}, nil, err
143 diagnostics, ok := reports[fh.VersionedFileIdentity()]
145 return VersionedFileIdentity{}, nil, errors.Errorf("no diagnostics for %s", uri)
147 return fh.VersionedFileIdentity(), diagnostics, nil
150 type diagnosticSet struct {
151 listErrors, parseErrors, typeErrors []*Diagnostic
154 func diagnostics(ctx context.Context, snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, pkg Package, hasMissingDeps bool) (bool, bool, error) {
155 ctx, done := event.Start(ctx, "source.diagnostics", tag.Package.Of(pkg.ID()))
156 _ = ctx // circumvent SA4006
159 diagSets := make(map[span.URI]*diagnosticSet)
160 for _, e := range pkg.GetErrors() {
164 Severity: protocol.SeverityError,
167 set, ok := diagSets[e.URI]
169 set = &diagnosticSet{}
170 diagSets[e.URI] = set
174 set.parseErrors = append(set.parseErrors, diag)
175 diag.Source = "syntax"
177 set.typeErrors = append(set.typeErrors, diag)
178 diag.Source = "compiler"
180 set.listErrors = append(set.listErrors, diag)
181 diag.Source = "go list"
184 var nonEmptyDiagnostics, hasTypeErrors bool // track if we actually send non-empty diagnostics
185 for uri, set := range diagSets {
186 // Don't report type errors if there are parse errors or list errors.
187 diags := set.typeErrors
188 if len(set.parseErrors) > 0 {
189 diags, nonEmptyDiagnostics = set.parseErrors, true
190 } else if len(set.listErrors) > 0 {
191 // Only show list errors if the package has missing dependencies.
193 diags, nonEmptyDiagnostics = set.listErrors, true
195 } else if len(set.typeErrors) > 0 {
198 if err := addReports(snapshot, reports, uri, diags...); err != nil {
199 return false, false, err
202 return nonEmptyDiagnostics, hasTypeErrors, nil
205 func analyses(ctx context.Context, snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, pkg Package, analyses map[string]Analyzer) error {
206 var analyzers []*analysis.Analyzer
207 for _, a := range analyses {
208 if !a.IsEnabled(snapshot.View()) {
211 analyzers = append(analyzers, a.Analyzer)
213 analysisErrors, err := snapshot.Analyze(ctx, pkg.ID(), analyzers...)
218 // Report diagnostics and errors from root analyzers.
219 for _, e := range analysisErrors {
220 // If the diagnostic comes from a "convenience" analyzer, it is not
221 // meant to provide diagnostics, but rather only suggested fixes.
222 // Skip these types of errors in diagnostics; we will use their
223 // suggested fixes when providing code actions.
224 if isConvenienceAnalyzer(e.Category) {
227 // This is a bit of a hack, but clients > 3.15 will be able to grey out unnecessary code.
228 // If we are deleting code as part of all of our suggested fixes, assume that this is dead code.
229 // TODO(golang/go#34508): Return these codes from the diagnostics themselves.
230 var tags []protocol.DiagnosticTag
231 if onlyDeletions(e.SuggestedFixes) {
232 tags = append(tags, protocol.Unnecessary)
234 if err := addReports(snapshot, reports, e.URI, &Diagnostic{
238 Severity: protocol.SeverityWarning,
248 func clearReports(snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, uri span.URI) {
249 fh := snapshot.FindFile(uri)
253 reports[fh.VersionedFileIdentity()] = []*Diagnostic{}
256 func addReports(snapshot Snapshot, reports map[VersionedFileIdentity][]*Diagnostic, uri span.URI, diagnostics ...*Diagnostic) error {
257 fh := snapshot.FindFile(uri)
261 existingDiagnostics, ok := reports[fh.VersionedFileIdentity()]
263 return fmt.Errorf("diagnostics for unexpected file %s", uri)
265 if len(diagnostics) == 1 {
267 if _, ok := snapshot.View().Options().TypeErrorAnalyzers[d1.Source]; ok {
268 for i, d2 := range existingDiagnostics {
269 if r := protocol.CompareRange(d1.Range, d2.Range); r != 0 {
272 if d1.Message != d2.Message {
275 reports[fh.VersionedFileIdentity()][i].Tags = append(reports[fh.VersionedFileIdentity()][i].Tags, d1.Tags...)
280 reports[fh.VersionedFileIdentity()] = append(reports[fh.VersionedFileIdentity()], diagnostics...)
284 // onlyDeletions returns true if all of the suggested fixes are deletions.
285 func onlyDeletions(fixes []SuggestedFix) bool {
286 for _, fix := range fixes {
287 for _, edits := range fix.Edits {
288 for _, edit := range edits {
289 if edit.NewText != "" {
292 if protocol.ComparePosition(edit.Range.Start, edit.Range.End) == 0 {
298 return len(fixes) > 0
301 // hasUndeclaredErrors returns true if a package has a type error
302 // about an undeclared symbol.
303 func hasUndeclaredErrors(pkg Package) bool {
304 for _, err := range pkg.GetErrors() {
305 if err.Kind != TypeError {
308 if strings.Contains(err.Message, "undeclared name:") {
315 func isConvenienceAnalyzer(category string) bool {
316 for _, a := range DefaultOptions().ConvenienceAnalyzers {
317 if category == a.Analyzer.Name {