1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
|
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package source
import (
"context"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/lsp/debug/tag"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/span"
)
type Diagnostic struct {
Range protocol.Range
Message string
Source string
Code string
CodeHref string
Severity protocol.DiagnosticSeverity
Tags []protocol.DiagnosticTag
Related []RelatedInformation
}
type SuggestedFix struct {
Title string
Edits map[span.URI][]protocol.TextEdit
Command *protocol.Command
}
type RelatedInformation struct {
URI span.URI
Range protocol.Range
Message string
}
func GetTypeCheckDiagnostics(ctx context.Context, snapshot Snapshot, pkg Package) TypeCheckDiagnostics {
onlyIgnoredFiles := true
for _, pgf := range pkg.CompiledGoFiles() {
onlyIgnoredFiles = onlyIgnoredFiles && snapshot.IgnoredFile(pgf.URI)
}
if onlyIgnoredFiles {
return TypeCheckDiagnostics{}
}
// Prepare any additional reports for the errors in this package.
for _, e := range pkg.GetErrors() {
// We only need to handle lower-level errors.
if e.Kind != ListError {
continue
}
// If no file is associated with the error, pick an open file from the package.
if e.URI.Filename() == "" {
for _, pgf := range pkg.CompiledGoFiles() {
if snapshot.IsOpen(pgf.URI) {
e.URI = pgf.URI
}
}
}
}
return typeCheckDiagnostics(ctx, snapshot, pkg)
}
func Analyze(ctx context.Context, snapshot Snapshot, pkg Package, typeCheckResult TypeCheckDiagnostics) (map[span.URI][]*Diagnostic, error) {
// Exit early if the context has been canceled. This also protects us
// from a race on Options, see golang/go#36699.
if ctx.Err() != nil {
return nil, ctx.Err()
}
// If we don't have any list or parse errors, run analyses.
analyzers := pickAnalyzers(snapshot, typeCheckResult.HasTypeErrors)
analysisErrors, err := snapshot.Analyze(ctx, pkg.ID(), analyzers...)
if err != nil {
return nil, err
}
reports := emptyDiagnostics(pkg)
// Report diagnostics and errors from root analyzers.
for _, e := range analysisErrors {
// If the diagnostic comes from a "convenience" analyzer, it is not
// meant to provide diagnostics, but rather only suggested fixes.
// Skip these types of errors in diagnostics; we will use their
// suggested fixes when providing code actions.
if isConvenienceAnalyzer(e.Category) {
continue
}
// This is a bit of a hack, but clients > 3.15 will be able to grey out unnecessary code.
// If we are deleting code as part of all of our suggested fixes, assume that this is dead code.
// TODO(golang/go#34508): Return these codes from the diagnostics themselves.
var tags []protocol.DiagnosticTag
if onlyDeletions(e.SuggestedFixes) {
tags = append(tags, protocol.Unnecessary)
}
// Type error analyzers only alter the tags for existing type errors.
if _, ok := snapshot.View().Options().TypeErrorAnalyzers[e.Category]; ok {
existingDiagnostics := typeCheckResult.Diagnostics[e.URI]
for _, d := range existingDiagnostics {
if r := protocol.CompareRange(e.Range, d.Range); r != 0 {
continue
}
if e.Message != d.Message {
continue
}
d.Tags = append(d.Tags, tags...)
}
} else {
reports[e.URI] = append(reports[e.URI], &Diagnostic{
Range: e.Range,
Message: e.Message,
Source: e.Category,
Severity: protocol.SeverityWarning,
Tags: tags,
Related: e.Related,
})
}
}
return reports, nil
}
func pickAnalyzers(snapshot Snapshot, hadTypeErrors bool) []*analysis.Analyzer {
// Always run convenience analyzers.
categories := []map[string]Analyzer{snapshot.View().Options().ConvenienceAnalyzers}
// If we had type errors, only run type error analyzers.
if hadTypeErrors {
categories = append(categories, snapshot.View().Options().TypeErrorAnalyzers)
} else {
categories = append(categories, snapshot.View().Options().DefaultAnalyzers, snapshot.View().Options().StaticcheckAnalyzers)
}
var analyzers []*analysis.Analyzer
for _, m := range categories {
for _, a := range m {
if a.IsEnabled(snapshot.View()) {
analyzers = append(analyzers, a.Analyzer)
}
}
}
return analyzers
}
func FileDiagnostics(ctx context.Context, snapshot Snapshot, uri span.URI) (VersionedFileIdentity, []*Diagnostic, error) {
fh, err := snapshot.GetVersionedFile(ctx, uri)
if err != nil {
return VersionedFileIdentity{}, nil, err
}
pkg, _, err := GetParsedFile(ctx, snapshot, fh, NarrowestPackage)
if err != nil {
return VersionedFileIdentity{}, nil, err
}
typeCheckResults := GetTypeCheckDiagnostics(ctx, snapshot, pkg)
diagnostics := typeCheckResults.Diagnostics[fh.URI()]
if !typeCheckResults.HasParseOrListErrors {
reports, err := Analyze(ctx, snapshot, pkg, typeCheckResults)
if err != nil {
return VersionedFileIdentity{}, nil, err
}
diagnostics = append(diagnostics, reports[fh.URI()]...)
}
return fh.VersionedFileIdentity(), diagnostics, nil
}
type TypeCheckDiagnostics struct {
HasTypeErrors bool
HasParseOrListErrors bool
Diagnostics map[span.URI][]*Diagnostic
}
type diagnosticSet struct {
listErrors, parseErrors, typeErrors []*Diagnostic
}
func typeCheckDiagnostics(ctx context.Context, snapshot Snapshot, pkg Package) TypeCheckDiagnostics {
ctx, done := event.Start(ctx, "source.diagnostics", tag.Package.Of(pkg.ID()))
_ = ctx // circumvent SA4006
defer done()
diagSets := make(map[span.URI]*diagnosticSet)
for _, e := range pkg.GetErrors() {
diag := &Diagnostic{
Message: e.Message,
Range: e.Range,
Severity: protocol.SeverityError,
Related: e.Related,
}
set, ok := diagSets[e.URI]
if !ok {
set = &diagnosticSet{}
diagSets[e.URI] = set
}
switch e.Kind {
case ParseError:
set.parseErrors = append(set.parseErrors, diag)
diag.Source = "syntax"
case TypeError:
set.typeErrors = append(set.typeErrors, diag)
diag.Source = "compiler"
case ListError:
set.listErrors = append(set.listErrors, diag)
diag.Source = "go list"
}
}
typecheck := TypeCheckDiagnostics{
Diagnostics: emptyDiagnostics(pkg),
}
for uri, set := range diagSets {
// Don't report type errors if there are parse errors or list errors.
diags := set.typeErrors
switch {
case len(set.parseErrors) > 0:
typecheck.HasParseOrListErrors = true
diags = set.parseErrors
case len(set.listErrors) > 0:
typecheck.HasParseOrListErrors = true
if len(pkg.MissingDependencies()) > 0 {
diags = set.listErrors
}
case len(set.typeErrors) > 0:
typecheck.HasTypeErrors = true
}
typecheck.Diagnostics[uri] = diags
}
return typecheck
}
func emptyDiagnostics(pkg Package) map[span.URI][]*Diagnostic {
diags := map[span.URI][]*Diagnostic{}
for _, pgf := range pkg.CompiledGoFiles() {
if _, ok := diags[pgf.URI]; !ok {
diags[pgf.URI] = nil
}
}
return diags
}
// onlyDeletions returns true if all of the suggested fixes are deletions.
func onlyDeletions(fixes []SuggestedFix) bool {
for _, fix := range fixes {
for _, edits := range fix.Edits {
for _, edit := range edits {
if edit.NewText != "" {
return false
}
if protocol.ComparePosition(edit.Range.Start, edit.Range.End) == 0 {
return false
}
}
}
}
return len(fixes) > 0
}
func isConvenienceAnalyzer(category string) bool {
for _, a := range DefaultOptions().ConvenienceAnalyzers {
if category == a.Analyzer.Name {
return true
}
}
return false
}
|