|
| 1 | +package diagnostics |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "sync" |
| 6 | + |
| 7 | + "github.com/creachadair/jrpc2" |
| 8 | + "github.com/hashicorp/hcl/v2" |
| 9 | + "github.com/hashicorp/hcl/v2/hclparse" |
| 10 | + ilsp "github.com/hashicorp/terraform-ls/internal/lsp" |
| 11 | + "github.com/sourcegraph/go-lsp" |
| 12 | +) |
| 13 | + |
| 14 | +type documentContext struct { |
| 15 | + ctx context.Context |
| 16 | + uri lsp.DocumentURI |
| 17 | + text []byte |
| 18 | +} |
| 19 | + |
| 20 | +type Notifier struct { |
| 21 | + sessCtx context.Context |
| 22 | + hclDocs chan<- documentContext |
| 23 | + closeHclDocsOnce sync.Once |
| 24 | +} |
| 25 | + |
| 26 | +func NewNotifier(sessCtx context.Context) *Notifier { |
| 27 | + hclDocs := make(chan documentContext, 10) |
| 28 | + go hclDiags(hclDocs) |
| 29 | + return &Notifier{hclDocs: hclDocs, sessCtx: sessCtx} |
| 30 | +} |
| 31 | + |
| 32 | +func (n *Notifier) DiagnoseHCL(ctx context.Context, uri lsp.DocumentURI, text []byte) { |
| 33 | + select { |
| 34 | + case <-n.sessCtx.Done(): |
| 35 | + n.closeHclDocsOnce.Do(func() { |
| 36 | + close(n.hclDocs) |
| 37 | + }) |
| 38 | + return |
| 39 | + case n.hclDocs <- documentContext{ctx: ctx, uri: uri, text: text}: |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func hclDiags(docs <-chan documentContext) { |
| 44 | + for d := range docs { |
| 45 | + diags := []lsp.Diagnostic{} |
| 46 | + |
| 47 | + _, hclDiags := hclparse.NewParser().ParseHCL(d.text, string(d.uri)) |
| 48 | + for _, hclDiag := range hclDiags { |
| 49 | + if hclDiag.Subject != nil { |
| 50 | + diags = append(diags, lsp.Diagnostic{ |
| 51 | + Range: ilsp.HCLRangeToLSP(*hclDiag.Subject), |
| 52 | + Severity: hclSeverityToLSP(hclDiag.Severity), |
| 53 | + Source: "HCL", |
| 54 | + Message: lspMessage(hclDiag), |
| 55 | + }) |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if err := jrpc2.PushNotify(d.ctx, "textDocument/publishDiagnostics", lsp.PublishDiagnosticsParams{ |
| 60 | + URI: d.uri, |
| 61 | + Diagnostics: diags, |
| 62 | + }); !acceptableError(err) { |
| 63 | + panic(err) |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +func hclSeverityToLSP(severity hcl.DiagnosticSeverity) lsp.DiagnosticSeverity { |
| 69 | + var sev lsp.DiagnosticSeverity |
| 70 | + switch severity { |
| 71 | + case hcl.DiagError: |
| 72 | + sev = lsp.Error |
| 73 | + case hcl.DiagWarning: |
| 74 | + sev = lsp.Warning |
| 75 | + case hcl.DiagInvalid: |
| 76 | + panic("invalid diagnostic") |
| 77 | + } |
| 78 | + return sev |
| 79 | +} |
| 80 | + |
| 81 | +func lspMessage(diag *hcl.Diagnostic) string { |
| 82 | + m := diag.Summary |
| 83 | + if diag.Detail != "" { |
| 84 | + m += ": " + diag.Detail |
| 85 | + } |
| 86 | + return m |
| 87 | +} |
| 88 | + |
| 89 | +func acceptableError(err error) bool { |
| 90 | + return true |
| 91 | +} |
0 commit comments