Debian Codegraph @

gopls/internal/template/completion.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 "bytes"
9 "context"
10 "fmt"
11 "go/scanner"
12 gotoken "go/token"
13 "strings"
14
15 "golang.org/x/tools/gopls/internal/cache"
16 "golang.org/x/tools/gopls/internal/file"
17 "golang.org/x/tools/gopls/internal/protocol"
18 )
19
20 // information needed for completion
21 type completer struct {
22 p *parsed
23 pos protocol.Position
24 offset int // offset of the start of the Token
25 ctx protocol.CompletionContext
26 syms map[string]symbol
27 }
28
29 func Completion(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pos protocol.Position, context protocol.CompletionContext) (*protocol.CompletionList, error) {
30 all := parseSet(snapshot.Templates())
31 var start int // the beginning of the Token (completed or not)
32 syms := make(map[string]symbol)
33 var p *parsed
34 for uri, fc := range all.files {
35 // collect symbols from all template files
36 filterSyms(syms, fc.symbols)
37 if uri.Path() != fh.URI().Path() {
38 continue
39 }
40 offset, err := enclosingTokenStart(fc, pos)
41 if err != nil {
42 return nil, err
43 }
44 start = offset
45 p = fc
46 }
47 if p == nil {
48 // this cannot happen unless the search missed a template file
49 return nil, fmt.Errorf("%s not found", fh.Identity().URI.Path())
50 }
51 c := completer{
52 p: p,
53 pos: pos,
54 offset: start + len(lbraces),
55 ctx: context,
56 syms: syms,
57 }
58 return c.complete()
59 }
60
61 func filterSyms(syms map[string]symbol, ns []symbol) {
62 for _, xsym := range ns {
63 switch xsym.kind {
64 case protocol.Method, protocol.Package, protocol.Boolean, protocol.Namespace,
65 protocol.Function:
66 syms[xsym.name] = xsym // we don't care which symbol we get
67 case protocol.Variable:
68 if xsym.name != "dot" {
69 syms[xsym.name] = xsym
70 }
71 case protocol.Constant:
72 if xsym.name == "nil" {
73 syms[xsym.name] = xsym
74 }
75 }
76 }
77 }
78
79 // enclosingTokenStart returns the start offset of the enclosing token.
80 // A (-1, non-nil) result indicates "no enclosing token".
81 func enclosingTokenStart(fc *parsed, pos protocol.Position) (int, error) {
82 // pos is the pos-th character. if the cursor is at the beginning
83 // of the file, pos is 0. That is, we've only seen characters before pos
84 // 1. pos might be in a Token, return tk.Start
85 // 2. pos might be after an elided but before a Token, return elided
86 // 3. return -1 for false
87 offset, err := fc.mapper.PositionOffset(pos)
88 if err != nil {
89 return 0, err
90 }
91
92 // TODO: opt: this could be a binary search, as the tokens are ordered
93 for _, tk := range fc.tokens {
94 if tk.start+len(lbraces) <= offset && offset+len(rbraces) <= tk.end {
95 return tk.start, nil
96 }
97 }
98
99 for _, x := range fc.elided {
100 if x+len(lbraces) > offset {
101 // fc.elided is sorted, and x is the position where a '{{' was replaced
102 // by ' '. We consider only cases where the replaced {{ is to the left
103 // of the cursor.
104 break
105 }
106 // If the interval [x,offset] does not contain Left or Right
107 // then provide completions. (do we need the test for Right?)
108 if !bytes.Contains(fc.buf[x:offset], lbraces) && !bytes.Contains(fc.buf[x:offset], rbraces) {
109 return x, nil
110 }
111 }
112 return -1, fmt.Errorf("no token enclosing %d", pos)
113 }
114
115 var (
116 keywords = []string{"if", "with", "else", "block", "range", "template", "end}}", "end"}
117 globals = []string{"and", "call", "html", "index", "slice", "js", "len", "not", "or",
118 "urlquery", "printf", "println", "print", "eq", "ne", "le", "lt", "ge", "gt"}
119 )
120
121 // find the completions. start is the offset of either the Token enclosing pos, or where
122 // the incomplete token starts.
123 // The error return is always nil.
124 func (c *completer) complete() (*protocol.CompletionList, error) {
125 ans := &protocol.CompletionList{IsIncomplete: true, Items: []protocol.CompletionItem{}}
126 start, err := c.p.mapper.PositionOffset(c.pos)
127 if err != nil {
128 return ans, err
129 }
130 sofar := c.p.buf[c.offset:start]
131 if len(sofar) == 0 || sofar[len(sofar)-1] == ' ' || sofar[len(sofar)-1] == '\t' {
132 return ans, nil
133 }
134 // sofar could be parsed by either c.analyzer() or scan(). The latter is precise
135 // and slower, but fast enough
136 words := scan(sofar)
137 // 1. if pattern starts $, show variables
138 // 2. if pattern starts ., show methods (and . by itself?)
139 // 3. if len(words) == 1, show firstWords (but if it were a |, show functions and globals)
140 // 4. ...? (parenthetical expressions, arguments, ...) (packages, namespaces, nil?)
141 if len(words) == 0 {
142 return nil, nil // if this happens, why were we called?
143 }
144 pattern := words[len(words)-1]
145 if pattern[0] == '$' {
146 // should we also return a raw "$"?
147 for _, s := range c.syms {
148 if s.kind == protocol.Variable && weakMatch(s.name, pattern) > 0 {
149 ans.Items = append(ans.Items, protocol.CompletionItem{
150 Label: s.name,
151 Kind: protocol.VariableCompletion,
152 Detail: "Variable",
153 })
154 }
155 }
156 return ans, nil
157 }
158 if pattern[0] == '.' {
159 for _, s := range c.syms {
160 if s.kind == protocol.Method && weakMatch("."+s.name, pattern) > 0 {
161 ans.Items = append(ans.Items, protocol.CompletionItem{
162 Label: s.name,
163 Kind: protocol.MethodCompletion,
164 Detail: "Method/member",
165 })
166 }
167 }
168 return ans, nil
169 }
170 // could we get completion attempts in strings or numbers, and if so, do we care?
171 // globals
172 for _, kw := range globals {
173 if weakMatch(kw, pattern) != 0 {
174 ans.Items = append(ans.Items, protocol.CompletionItem{
175 Label: kw,
176 Kind: protocol.KeywordCompletion,
177 Detail: "Function",
178 })
179 }
180 }
181 // and functions
182 for _, s := range c.syms {
183 if s.kind == protocol.Function && weakMatch(s.name, pattern) != 0 {
184 ans.Items = append(ans.Items, protocol.CompletionItem{
185 Label: s.name,
186 Kind: protocol.FunctionCompletion,
187 Detail: "Function",
188 })
189 }
190 }
191 // keywords if we're at the beginning
192 if len(words) <= 1 || len(words[len(words)-2]) == 1 && words[len(words)-2][0] == '|' {
193 for _, kw := range keywords {
194 if weakMatch(kw, pattern) != 0 {
195 ans.Items = append(ans.Items, protocol.CompletionItem{
196 Label: kw,
197 Kind: protocol.KeywordCompletion,
198 Detail: "keyword",
199 })
200 }
201 }
202 }
203 return ans, nil
204 }
205
206 // version of c.analyze that uses go/scanner.
207 func scan(buf []byte) []string {
208 fset := gotoken.NewFileSet()
209 fp := fset.AddFile("", -1, len(buf))
210 var sc scanner.Scanner
211 sc.Init(fp, buf, func(pos gotoken.Position, msg string) {}, scanner.ScanComments)
212 ans := make([]string, 0, 10) // preallocating gives a measurable savings
213 for {
214 _, tok, lit := sc.Scan() // tok is an int
215 if tok == gotoken.EOF {
216 break // done
217 } else if tok == gotoken.SEMICOLON && lit == "\n" {
218 continue // don't care, but probably can't happen
219 } else if tok == gotoken.PERIOD {
220 ans = append(ans, ".") // lit is empty
221 } else if tok == gotoken.IDENT && len(ans) > 0 && ans[len(ans)-1] == "." {
222 ans[len(ans)-1] = "." + lit
223 } else if tok == gotoken.IDENT && len(ans) > 0 && ans[len(ans)-1] == "$" {
224 ans[len(ans)-1] = "$" + lit
225 } else if lit != "" {
226 ans = append(ans, lit)
227 }
228 }
229 return ans
230 }
231
232 // pattern is what the user has typed
233 func weakMatch(choice, pattern string) float64 {
234 lower := strings.ToLower(choice)
235 // for now, use only lower-case everywhere
236 pattern = strings.ToLower(pattern)
237 // The first char has to match
238 if pattern[0] != lower[0] {
239 return 0
240 }
241 // If they start with ., then the second char has to match
242 from := 1
243 if pattern[0] == '.' {
244 if len(pattern) < 2 {
245 return 1 // pattern just a ., so it matches
246 }
247 if pattern[1] != lower[1] {
248 return 0
249 }
250 from = 2
251 }
252 // check that all the characters of pattern occur as a subsequence of choice
253 i, j := from, from
254 for ; i < len(lower) && j < len(pattern); j++ {
255 if pattern[j] == lower[i] {
256 i++
257 if i >= len(lower) {
258 return 0
259 }
260 }
261 }
262 if j < len(pattern) {
263 return 0
264 }
265 return 1
266 }