Debian Codegraph @

gopls/internal/template/symbols.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 "text/template/parse"
12
13 "golang.org/x/tools/gopls/internal/cache"
14 "golang.org/x/tools/gopls/internal/file"
15 "golang.org/x/tools/gopls/internal/protocol"
16 "golang.org/x/tools/internal/event"
17 )
18
19 // in local coordinates, to be translated to protocol.DocumentSymbol
20 type symbol struct {
21 start int // 0-based byte offset, for sorting
22 len int // of source, in bytes
23 name string
24 kind protocol.SymbolKind
25 vardef bool // is this a variable definition?
26 // do we care about selection range, or children?
27 // no children yet, and selection range is the same as range
28 }
29
30 func (s symbol) offsets() (start, end int) {
31 return s.start, s.start + s.len
32 }
33
34 func (s symbol) String() string {
35 return fmt.Sprintf("{%d,%d,%s,%s,%v}", s.start, s.len, s.name, s.kind, s.vardef)
36 }
37
38 // for FieldNode or VariableNode (or ChainNode?)
39 func (p *parsed) fields(flds []string, x parse.Node) []symbol {
40 ans := []symbol{}
41 // guessing that there are no embedded blanks allowed. The doc is unclear
42 lookfor := ""
43 switch x.(type) {
44 case *parse.FieldNode:
45 for _, f := range flds {
46 lookfor += "." + f // quadratic, but probably ok
47 }
48 case *parse.VariableNode:
49 lookfor = flds[0]
50 for i := 1; i < len(flds); i++ {
51 lookfor += "." + flds[i]
52 }
53 case *parse.ChainNode: // PJW, what are these?
54 for _, f := range flds {
55 lookfor += "." + f // quadratic, but probably ok
56 }
57 default:
58 // If these happen they will happen even if gopls is restarted
59 // and the users does the same thing, so it is better not to panic.
60 // context.Background() is used because we don't have access
61 // to any other context. [we could, but it would be complicated]
62 event.Log(context.Background(), fmt.Sprintf("%T unexpected in fields()", x))
63 return nil
64 }
65 if len(lookfor) == 0 {
66 event.Log(context.Background(), fmt.Sprintf("no strings in fields() %#v", x))
67 return nil
68 }
69 startsAt := int(x.Position())
70 ix := bytes.Index(p.buf[startsAt:], []byte(lookfor)) // HasPrefix? PJW?
71 if ix < 0 || ix > len(lookfor) { // lookfor expected to be at start (or so)
72 // probably golang.go/#43388, so back up
73 startsAt -= len(flds[0]) + 1
74 ix = bytes.Index(p.buf[startsAt:], []byte(lookfor)) // ix might be 1? PJW
75 if ix < 0 {
76 return ans
77 }
78 }
79 at := ix + startsAt
80 for _, f := range flds {
81 at += 1 // .
82 kind := protocol.Method
83 if f[0] == '$' {
84 kind = protocol.Variable
85 }
86 sym := symbol{name: f, kind: kind, start: at, len: len(f)}
87 if kind == protocol.Variable && len(p.stack) > 1 {
88 if pipe, ok := p.stack[len(p.stack)-2].(*parse.PipeNode); ok {
89 for _, y := range pipe.Decl {
90 if x == y {
91 sym.vardef = true
92 }
93 }
94 }
95 }
96 ans = append(ans, sym)
97 at += len(f)
98 }
99 return ans
100 }
101
102 func (p *parsed) findSymbols() {
103 if len(p.stack) == 0 {
104 return
105 }
106 n := p.stack[len(p.stack)-1]
107 pop := func() {
108 p.stack = p.stack[:len(p.stack)-1]
109 }
110 if n == nil { // allowing nil simplifies the code
111 pop()
112 return
113 }
114 nxt := func(nd parse.Node) {
115 p.stack = append(p.stack, nd)
116 p.findSymbols()
117 }
118 switch x := n.(type) {
119 case *parse.ActionNode:
120 nxt(x.Pipe)
121 case *parse.BoolNode:
122 // need to compute the length from the value
123 msg := fmt.Sprintf("%v", x.True)
124 p.symbols = append(p.symbols, symbol{start: int(x.Pos), len: len(msg), kind: protocol.Boolean})
125 case *parse.BranchNode:
126 nxt(x.Pipe)
127 nxt(x.List)
128 nxt(x.ElseList)
129 case *parse.ChainNode:
130 p.symbols = append(p.symbols, p.fields(x.Field, x)...)
131 nxt(x.Node)
132 case *parse.CommandNode:
133 for _, a := range x.Args {
134 nxt(a)
135 }
136 //case *parse.CommentNode: // go 1.16
137 // log.Printf("implement %d", x.Type())
138 case *parse.DotNode:
139 sym := symbol{name: "dot", kind: protocol.Variable, start: int(x.Pos), len: 1}
140 p.symbols = append(p.symbols, sym)
141 case *parse.FieldNode:
142 p.symbols = append(p.symbols, p.fields(x.Ident, x)...)
143 case *parse.IdentifierNode:
144 sym := symbol{name: x.Ident, kind: protocol.Function, start: int(x.Pos), len: len(x.Ident)}
145 p.symbols = append(p.symbols, sym)
146 case *parse.IfNode:
147 nxt(&x.BranchNode)
148 case *parse.ListNode:
149 if x != nil { // wretched typed nils. Node should have an IfNil
150 for _, nd := range x.Nodes {
151 nxt(nd)
152 }
153 }
154 case *parse.NilNode:
155 sym := symbol{name: "nil", kind: protocol.Constant, start: int(x.Pos), len: 3}
156 p.symbols = append(p.symbols, sym)
157 case *parse.NumberNode:
158 // no name; ascii
159 p.symbols = append(p.symbols, symbol{start: int(x.Pos), len: len(x.Text), kind: protocol.Number})
160 case *parse.PipeNode:
161 if x == nil { // {{template "foo"}}
162 return
163 }
164 for _, d := range x.Decl {
165 nxt(d)
166 }
167 for _, c := range x.Cmds {
168 nxt(c)
169 }
170 case *parse.RangeNode:
171 nxt(&x.BranchNode)
172 case *parse.StringNode:
173 // no name
174 p.symbols = append(p.symbols, symbol{start: int(x.Pos), len: len(x.Quoted), kind: protocol.String})
175 case *parse.TemplateNode:
176 // invoking a template, e.g. {{define "foo"}}
177 // x.Pos is the index of "foo".
178 // The logic below assumes that the literal is trivial.
179 p.symbols = append(p.symbols, symbol{name: x.Name, kind: protocol.Package, start: int(x.Pos) + len(`"`), len: len(x.Name)})
180 nxt(x.Pipe)
181 case *parse.TextNode:
182 if len(x.Text) == 1 && x.Text[0] == '\n' {
183 break
184 }
185 // nothing to report, but build one for hover
186 p.symbols = append(p.symbols, symbol{start: int(x.Pos), len: len(x.Text), kind: protocol.Constant})
187 case *parse.VariableNode:
188 p.symbols = append(p.symbols, p.fields(x.Ident, x)...)
189 case *parse.WithNode:
190 nxt(&x.BranchNode)
191 }
192 pop()
193 }
194
195 // DocumentSymbols returns a hierarchy of the symbols defined in a template file.
196 // (The hierarchy is flat. SymbolInformation might be better.)
197 func DocumentSymbols(snapshot *cache.Snapshot, fh file.Handle) ([]protocol.DocumentSymbol, error) {
198 buf, err := fh.Content()
199 if err != nil {
200 return nil, err
201 }
202 p := parseBuffer(fh.URI(), buf)
203 if p.parseErr != nil {
204 return nil, p.parseErr
205 }
206 var ans []protocol.DocumentSymbol
207 for _, sym := range p.symbols {
208 if sym.kind == protocol.Constant {
209 continue
210 }
211 detail := fmt.Sprint(sym.kind)
212 if detail == "Namespace" {
213 detail = "Template"
214 }
215 if sym.vardef {
216 detail += "(def)"
217 } else {
218 detail += "(use)"
219 }
220 rng, err := p.mapper.OffsetRange(sym.offsets())
221 if err != nil {
222 return nil, err
223 }
224 ans = append(ans, protocol.DocumentSymbol{
225 Name: sym.name,
226 Detail: detail,
227 Kind: sym.kind,
228 Range: rng,
229 SelectionRange: rng, // or should this be the entire {{...}}?
230 })
231 }
232 return ans, nil
233 }