Debian Codegraph @

gopls/internal/template/parse.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 contains code for dealing with templates
6 package template
7
8 // template files are small enough that the code reprocesses them each time
9 // this may be a bad choice for projects with lots of template files.
10
11 import (
12 "bytes"
13 "fmt"
14 "io"
15 "log"
16 "regexp"
17 "sort"
18 "text/template"
19 "text/template/parse"
20
21 "golang.org/x/tools/gopls/internal/file"
22 "golang.org/x/tools/gopls/internal/protocol"
23 )
24
25 var (
26 lbraces = []byte("{{")
27 rbraces = []byte("}}")
28 )
29
30 type parsed struct {
31 buf []byte // contents
32 mapper *protocol.Mapper
33 elided []int // offsets where lbraces was replaced by blanks
34
35 // tokens are matched lbraces-rbraces pairs, computed before trying to parse
36 tokens []token
37
38 // result of parsing
39 named []*template.Template // the template and embedded templates
40 parseErr error
41 symbols []symbol
42 stack []parse.Node // used while computing symbols
43 }
44
45 // A token is a single {{...}}.
46 type token struct {
47 start, end int // 0-based byte offset from start of template
48 }
49
50 // set contains the Parse of all the template files
51 type set struct {
52 files map[protocol.DocumentURI]*parsed
53 }
54
55 // parseSet returns the set of the snapshot's tmpl files
56 // (maybe cache these, but then avoiding import cycles needs code rearrangements)
57 //
58 // TODO(adonovan): why doesn't parseSet return an error?
59 func parseSet(tmpls map[protocol.DocumentURI]file.Handle) *set {
60 all := make(map[protocol.DocumentURI]*parsed)
61 for uri, fh := range tmpls {
62 buf, err := fh.Content()
63 if err != nil {
64 // TODO(pjw): decide what to do with these errors
65 log.Printf("failed to read %s (%v)", fh.URI().Path(), err)
66 continue
67 }
68 all[uri] = parseBuffer(uri, buf)
69 }
70 return &set{files: all}
71 }
72
73 func parseBuffer(uri protocol.DocumentURI, buf []byte) *parsed {
74 ans := &parsed{
75 buf: buf,
76 mapper: protocol.NewMapper(uri, buf),
77 }
78 if len(buf) == 0 {
79 return ans
80 }
81 ans.setTokens() // ans.buf may be a new []byte
82 t, err := template.New("").Parse(string(ans.buf))
83 if err != nil {
84 funcs := make(template.FuncMap)
85 for t == nil && ans.parseErr == nil {
86 // in 1.17 it may be possible to avoid getting this error
87 // template: :2: function "foo" not defined
88 matches := parseErrR.FindStringSubmatch(err.Error())
89 if len(matches) == 2 {
90 // suppress the error by giving it a function with the right name
91 funcs[matches[1]] = func() any { return nil }
92 t, err = template.New("").Funcs(funcs).Parse(string(ans.buf))
93 continue
94 }
95 ans.parseErr = err // unfixed error
96 return ans
97 }
98 }
99 ans.named = t.Templates()
100 // set the symbols
101 for _, t := range ans.named {
102 ans.stack = append(ans.stack, t.Root)
103 ans.findSymbols()
104 if t.Name() != "" {
105 // defining a template. The pos is just after {{define...}} (or {{block...}}?)
106 at, sz := ans.findLiteralBefore(int(t.Root.Pos))
107 s := symbol{start: at, len: sz, name: t.Name(), kind: protocol.Namespace, vardef: true}
108 ans.symbols = append(ans.symbols, s)
109 }
110 }
111
112 sort.Slice(ans.symbols, func(i, j int) bool {
113 left, right := ans.symbols[i], ans.symbols[j]
114 if left.start != right.start {
115 return left.start < right.start
116 }
117 if left.vardef != right.vardef {
118 return left.vardef
119 }
120 return left.kind < right.kind
121 })
122 return ans
123 }
124
125 // findLiteralBefore locates the first preceding string literal
126 // returning its offset and length in buf or (-1, 0) if there is none.
127 // Assume double-quoted string rather than backquoted string for now.
128 func (p *parsed) findLiteralBefore(pos int) (int, int) {
129 left, right := -1, -1
130 for i := pos - 1; i >= 0; i-- {
131 if p.buf[i] != '"' {
132 continue
133 }
134 if right == -1 {
135 right = i
136 continue
137 }
138 left = i
139 break
140 }
141 if left == -1 {
142 return -1, 0
143 }
144 return left + 1, right - left - 1
145 }
146
147 var (
148 parseErrR = regexp.MustCompile(`template:.*function "([^"]+)" not defined`)
149 )
150
151 func (p *parsed) setTokens() {
152 const (
153 // InRaw and InString only occur inside an action (SeenLeft)
154 Start = iota
155 InRaw
156 InString
157 SeenLeft
158 )
159 state := Start
160 var left, oldState int
161 for n := 0; n < len(p.buf); n++ {
162 c := p.buf[n]
163 switch state {
164 case InRaw:
165 if c == '`' {
166 state = oldState
167 }
168 case InString:
169 if c == '"' && !isEscaped(p.buf[:n]) {
170 state = oldState
171 }
172 case SeenLeft:
173 if c == '`' {
174 oldState = state // it's SeenLeft, but a little clearer this way
175 state = InRaw
176 continue
177 }
178 if c == '"' {
179 oldState = state
180 state = InString
181 continue
182 }
183 if bytes.HasPrefix(p.buf[n:], rbraces) {
184 right := n + len(rbraces)
185 tok := token{start: left, end: right}
186 p.tokens = append(p.tokens, tok)
187 state = Start
188 }
189 // If we see (unquoted) lbraces then the original left is probably the user
190 // typing. Suppress the original left
191 if bytes.HasPrefix(p.buf[n:], lbraces) {
192 p.elideAt(left)
193 left = n
194 n += len(lbraces) - 1 // skip the rest
195 }
196 case Start:
197 if bytes.HasPrefix(p.buf[n:], lbraces) {
198 left = n
199 state = SeenLeft
200 n += len(lbraces) - 1 // skip the rest (avoids {{{ bug)
201 }
202 }
203 }
204 // this error occurs after typing {{ at the end of the file
205 if state != Start {
206 // Unclosed lbraces. remove the lbraces at left
207 p.elideAt(left)
208 }
209 }
210
211 func (p *parsed) elideAt(left int) {
212 if p.elided == nil {
213 // p.buf is the same buffer that v.Read() returns, so copy it.
214 // (otherwise the next time it's parsed, elided information is lost)
215 p.buf = bytes.Clone(p.buf)
216 }
217 for i := range lbraces {
218 p.buf[left+i] = ' '
219 }
220 p.elided = append(p.elided, left)
221 }
222
223 // isEscaped reports whether the byte after buf is escaped
224 func isEscaped(buf []byte) bool {
225 backSlashes := 0
226 for j := len(buf) - 1; j >= 0 && buf[j] == '\\'; j-- {
227 backSlashes++
228 }
229 return backSlashes%2 == 1
230 }
231
232 // lineRange returns the range for the entire specified (1-based) line.
233 func lineRange(m *protocol.Mapper, line int) (protocol.Range, error) {
234 posn := protocol.Position{Line: uint32(line - 1)}
235
236 // start of line
237 start, err := m.PositionOffset(posn)
238 if err != nil {
239 return protocol.Range{}, err
240 }
241
242 // end of line (or file)
243 posn.Line++
244 end := len(m.Content) // EOF
245 if offset, err := m.PositionOffset(posn); err != nil {
246 end = offset - len("\n")
247 }
248
249 return m.OffsetRange(start, end)
250 }
251
252 // -- debugging --
253
254 func (p *parsed) writeNode(w io.Writer, n parse.Node) {
255 wr := wrNode{p: p, w: w}
256 wr.writeNode(n, "")
257 }
258
259 type wrNode struct {
260 p *parsed
261 w io.Writer
262 }
263
264 func (wr wrNode) writeNode(n parse.Node, indent string) {
265 if n == nil {
266 return
267 }
268 at := func(pos parse.Pos) string {
269 offset := int(pos)
270 posn, err := wr.p.mapper.OffsetPosition(offset)
271 if err != nil {
272 return fmt.Sprintf("<bad pos %d: %v>", pos, err)
273 }
274 return fmt.Sprintf("(%d)%v:%v", pos, posn.Line, posn.Character)
275 }
276 switch x := n.(type) {
277 case *parse.ActionNode:
278 fmt.Fprintf(wr.w, "%sActionNode at %s\n", indent, at(x.Pos))
279 wr.writeNode(x.Pipe, indent+". ")
280 case *parse.BoolNode:
281 fmt.Fprintf(wr.w, "%sBoolNode at %s, %v\n", indent, at(x.Pos), x.True)
282 case *parse.BranchNode:
283 fmt.Fprintf(wr.w, "%sBranchNode at %s\n", indent, at(x.Pos))
284 wr.writeNode(x.Pipe, indent+"Pipe. ")
285 wr.writeNode(x.List, indent+"List. ")
286 wr.writeNode(x.ElseList, indent+"Else. ")
287 case *parse.ChainNode:
288 fmt.Fprintf(wr.w, "%sChainNode at %s, %v\n", indent, at(x.Pos), x.Field)
289 case *parse.CommandNode:
290 fmt.Fprintf(wr.w, "%sCommandNode at %s, %d children\n", indent, at(x.Pos), len(x.Args))
291 for _, a := range x.Args {
292 wr.writeNode(a, indent+". ")
293 }
294 //case *parse.CommentNode: // 1.16
295 case *parse.DotNode:
296 fmt.Fprintf(wr.w, "%sDotNode at %s\n", indent, at(x.Pos))
297 case *parse.FieldNode:
298 fmt.Fprintf(wr.w, "%sFieldNode at %s, %v\n", indent, at(x.Pos), x.Ident)
299 case *parse.IdentifierNode:
300 fmt.Fprintf(wr.w, "%sIdentifierNode at %s, %v\n", indent, at(x.Pos), x.Ident)
301 case *parse.IfNode:
302 fmt.Fprintf(wr.w, "%sIfNode at %s\n", indent, at(x.Pos))
303 wr.writeNode(&x.BranchNode, indent+". ")
304 case *parse.ListNode:
305 if x == nil {
306 return // nil BranchNode.ElseList
307 }
308 fmt.Fprintf(wr.w, "%sListNode at %s, %d children\n", indent, at(x.Pos), len(x.Nodes))
309 for _, n := range x.Nodes {
310 wr.writeNode(n, indent+". ")
311 }
312 case *parse.NilNode:
313 fmt.Fprintf(wr.w, "%sNilNode at %s\n", indent, at(x.Pos))
314 case *parse.NumberNode:
315 fmt.Fprintf(wr.w, "%sNumberNode at %s, %s\n", indent, at(x.Pos), x.Text)
316 case *parse.PipeNode:
317 if x == nil {
318 return // {{template "xxx"}}
319 }
320 fmt.Fprintf(wr.w, "%sPipeNode at %s, %d vars, %d cmds, IsAssign:%v\n",
321 indent, at(x.Pos), len(x.Decl), len(x.Cmds), x.IsAssign)
322 for _, d := range x.Decl {
323 wr.writeNode(d, indent+"Decl. ")
324 }
325 for _, c := range x.Cmds {
326 wr.writeNode(c, indent+"Cmd. ")
327 }
328 case *parse.RangeNode:
329 fmt.Fprintf(wr.w, "%sRangeNode at %s\n", indent, at(x.Pos))
330 wr.writeNode(&x.BranchNode, indent+". ")
331 case *parse.StringNode:
332 fmt.Fprintf(wr.w, "%sStringNode at %s, %s\n", indent, at(x.Pos), x.Quoted)
333 case *parse.TemplateNode:
334 fmt.Fprintf(wr.w, "%sTemplateNode at %s, %s\n", indent, at(x.Pos), x.Name)
335 wr.writeNode(x.Pipe, indent+". ")
336 case *parse.TextNode:
337 fmt.Fprintf(wr.w, "%sTextNode at %s, len %d\n", indent, at(x.Pos), len(x.Text))
338 case *parse.VariableNode:
339 fmt.Fprintf(wr.w, "%sVariableNode at %s, %v\n", indent, at(x.Pos), x.Ident)
340 case *parse.WithNode:
341 fmt.Fprintf(wr.w, "%sWithNode at %s\n", indent, at(x.Pos))
342 wr.writeNode(&x.BranchNode, indent+". ")
343 }
344 }