Debian Codegraph @

gopls/internal/template/implementations.go

raw symbols SCIP
1 // Copyright 2021 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 template
6
7 import (
8 "context"
9 "fmt"
10 "regexp"
11 "strconv"
12 "time"
13
14 "golang.org/x/tools/gopls/internal/cache"
15 "golang.org/x/tools/gopls/internal/file"
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/gopls/internal/protocol/semtok"
18 )
19
20 // line number (1-based) and message
21 var errRe = regexp.MustCompile(`template.*:(\d+): (.*)`)
22
23 // Diagnostics returns parse errors. There is only one per file.
24 // The errors are not always helpful. For instance { {end}}
25 // will likely point to the end of the file.
26 func Diagnostics(snapshot *cache.Snapshot) map[protocol.DocumentURI][]*cache.Diagnostic {
27 diags := make(map[protocol.DocumentURI][]*cache.Diagnostic)
28 for uri, fh := range snapshot.Templates() {
29 diags[uri] = diagnoseOne(fh)
30 }
31 return diags
32 }
33
34 func diagnoseOne(fh file.Handle) []*cache.Diagnostic {
35 // no need for skipTemplate check, as Diagnose is called on the
36 // snapshot's template files
37 buf, err := fh.Content()
38 if err != nil {
39 // TODO: Is a Diagnostic with no Range useful? event.Error also?
40 msg := fmt.Sprintf("failed to read %s (%v)", fh.URI().Path(), err)
41 return []*cache.Diagnostic{{
42 Message: msg,
43 Severity: protocol.SeverityError,
44 URI: fh.URI(),
45 Source: cache.TemplateError,
46 }}
47 }
48 p := parseBuffer(fh.URI(), buf)
49 if p.parseErr == nil {
50 return nil
51 }
52
53 errorf := func(format string, args ...any) []*cache.Diagnostic {
54 msg := fmt.Sprintf("malformed template error %q: %s",
55 p.parseErr.Error(),
56 fmt.Sprintf(format, args...))
57 rng, err := p.mapper.OffsetRange(0, 1) // first UTF-16 code
58 if err != nil {
59 rng = protocol.Range{} // start of file
60 }
61 return []*cache.Diagnostic{{
62 Message: msg,
63 Severity: protocol.SeverityError,
64 Range: rng,
65 URI: fh.URI(),
66 Source: cache.TemplateError,
67 }}
68 }
69
70 // errors look like `template: :40: unexpected "}" in operand`
71 // so the string needs to be parsed
72 matches := errRe.FindStringSubmatch(p.parseErr.Error())
73 if len(matches) != 3 {
74 return errorf("expected 3 matches, got %d (%v)", len(matches), matches)
75 }
76 lineno, err := strconv.Atoi(matches[1])
77 if err != nil {
78 return errorf("couldn't convert %q to int, %v", matches[1], err)
79 }
80 msg := matches[2]
81
82 // Compute the range for the whole (1-based) line.
83 rng, err := lineRange(p.mapper, lineno)
84 if err != nil {
85 return errorf("invalid position: %v", err)
86 }
87
88 return []*cache.Diagnostic{{
89 Message: msg,
90 Severity: protocol.SeverityError,
91 Range: rng,
92 Source: cache.TemplateError,
93 }}
94 }
95
96 // Definition finds the definitions of the symbol at loc. It
97 // does not understand scoping (if any) in templates. This code is
98 // for definitions, type definitions, and implementations.
99 // Results only for variables and templates.
100 func Definition(snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.Location, error) {
101 x, _, err := symAtRange(fh, rng)
102 if err != nil {
103 return nil, err
104 }
105 sym := x.name
106 ans := []protocol.Location{}
107 // PJW: this is probably a pattern to abstract
108 a := parseSet(snapshot.Templates())
109 for _, p := range a.files {
110 for _, s := range p.symbols {
111 if !s.vardef || s.name != sym {
112 continue
113 }
114 loc, err := p.mapper.OffsetLocation(s.offsets())
115 if err != nil {
116 return nil, err
117 }
118 ans = append(ans, loc)
119 }
120 }
121 return ans, nil
122 }
123
124 func Hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) (*protocol.Hover, error) {
125 sym, p, err := symAtRange(fh, rng)
126 if err != nil {
127 return nil, err
128 }
129
130 var value string
131 switch sym.kind {
132 case protocol.Function:
133 value = fmt.Sprintf("function: %s", sym.name)
134 case protocol.Variable:
135 value = fmt.Sprintf("variable: %s", sym.name)
136 case protocol.Constant:
137 value = fmt.Sprintf("constant %s", sym.name)
138 case protocol.Method: // field or method
139 value = fmt.Sprintf("%s: field or method", sym.name)
140 case protocol.Package: // template use, template def (PJW: do we want two?)
141 value = fmt.Sprintf("template %s\n(add definition)", sym.name)
142 case protocol.Namespace:
143 value = fmt.Sprintf("template %s defined", sym.name)
144 case protocol.Number:
145 value = "number"
146 case protocol.String:
147 value = "string"
148 case protocol.Boolean:
149 value = "boolean"
150 default:
151 value = fmt.Sprintf("oops, sym=%#v", sym)
152 }
153
154 symRng, err := p.mapper.OffsetRange(sym.offsets())
155 if err != nil {
156 return nil, err
157 }
158
159 return &protocol.Hover{
160 Range: symRng,
161 Contents: protocol.MarkupContent{
162 Kind: protocol.Markdown,
163 Value: value,
164 },
165 }, nil
166 }
167
168 func References(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, params *protocol.ReferenceParams) ([]protocol.Location, error) {
169 sym, _, err := symAtRange(fh, params.Range)
170 if err != nil {
171 return nil, err
172 }
173 if sym.name == "" {
174 return nil, fmt.Errorf("no symbol at position")
175 }
176 ans := []protocol.Location{}
177
178 a := parseSet(snapshot.Templates())
179 for _, p := range a.files {
180 for _, s := range p.symbols {
181 if s.name != sym.name {
182 continue
183 }
184 if s.vardef && !params.Context.IncludeDeclaration {
185 continue
186 }
187 loc, err := p.mapper.OffsetLocation(s.offsets())
188 if err != nil {
189 return nil, err
190 }
191 ans = append(ans, loc)
192 }
193 }
194 // TODO: do these need to be sorted? (a.files is a map)
195 return ans, nil
196 }
197
198 func SemanticTokens(ctx context.Context, snapshot *cache.Snapshot, spn protocol.DocumentURI) (*protocol.SemanticTokens, error) {
199 fh, err := snapshot.ReadFile(ctx, spn)
200 if err != nil {
201 return nil, err
202 }
203 buf, err := fh.Content()
204 if err != nil {
205 return nil, err
206 }
207 p := parseBuffer(fh.URI(), buf)
208
209 var items []semtok.Token
210 for _, t := range p.tokens {
211 if t.start == t.end {
212 continue // vscode doesn't like 0-length tokens
213 }
214 pos, err := p.mapper.OffsetPosition(t.start)
215 if err != nil {
216 return nil, err
217 }
218 // TODO(adonovan): don't ignore the rng restriction, if any.
219 items = append(items, semtok.Token{
220 Line: pos.Line,
221 Start: pos.Character,
222 Len: uint32(protocol.UTF16Len(p.buf[t.start:t.end])),
223 Type: semtok.TokMacro,
224 })
225 }
226 return &protocol.SemanticTokens{
227 Data: semtok.Encode(items, nil, nil),
228 // for small cache, some day. for now, the LSP client ignores this
229 // (that is, when the LSP client starts returning these, we can cache)
230 ResultID: fmt.Sprintf("%v", time.Now()),
231 }, nil
232 }
233
234 // TODO: still need to do rename, etc
235
236 func symAtRange(fh file.Handle, rng protocol.Range) (*symbol, *parsed, error) {
237 buf, err := fh.Content()
238 if err != nil {
239 return nil, nil, err
240 }
241 p := parseBuffer(fh.URI(), buf)
242 start, end, err := p.mapper.RangeOffsets(rng)
243 if err != nil {
244 return nil, nil, err
245 }
246 var syms []symbol
247 for _, s := range p.symbols {
248 if s.start <= start && end <= s.start+s.len {
249 syms = append(syms, s)
250 }
251 }
252 if len(syms) == 0 {
253 return nil, p, fmt.Errorf("no symbol found")
254 }
255 sym := syms[0]
256 return &sym, p, nil
257 }