Debian Codegraph @

tpl/tplimpl/templatetransform.go

raw
1 package tplimpl
2
3 import (
4 "errors"
5 "fmt"
6 "regexp"
7 "slices"
8 "strings"
9
10 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
11
12 htmltemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"
13 texttemplate "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate"
14
15 "github.com/gohugoio/hugo/common/hashing"
16 "github.com/gohugoio/hugo/common/hmaps"
17 "github.com/gohugoio/hugo/tpl"
18 "github.com/mitchellh/mapstructure"
19 )
20
21 type templateTransformContext struct {
22 visited map[string]bool
23 templateNotFound map[string]bool
24 deferNodes map[string]*parse.ListNode
25 lookupFn func(name string, in *TemplInfo) *TemplInfo
26 store *TemplateStore
27
28 // The last error encountered.
29 err error
30
31 // Set when we're done checking for config header.
32 configChecked bool
33
34 t *TemplInfo
35 }
36
37 func (c templateTransformContext) getIfNotVisited(name string) *TemplInfo {
38 if c.visited[name] {
39 return nil
40 }
41 c.visited[name] = true
42 templ := c.lookupFn(name, c.t)
43 if templ == nil {
44 // This may be a inline template defined outside of this file
45 // and not yet parsed. Unusual, but it happens.
46 // Store the name to try again later.
47 c.templateNotFound[name] = true
48 }
49
50 return templ
51 }
52
53 func newTemplateTransformContext(
54 t *TemplInfo,
55 store *TemplateStore,
56 lookupFn func(name string, in *TemplInfo) *TemplInfo,
57 ) *templateTransformContext {
58 return &templateTransformContext{
59 t: t,
60 lookupFn: lookupFn,
61 store: store,
62 visited: make(map[string]bool),
63 templateNotFound: make(map[string]bool),
64 deferNodes: make(map[string]*parse.ListNode),
65 }
66 }
67
68 func applyTemplateTransformers(
69 t *TemplInfo,
70 store *TemplateStore,
71 lookupFn func(name string, in *TemplInfo) *TemplInfo,
72 ) (*templateTransformContext, error) {
73 if t == nil {
74 return nil, errors.New("expected template, but none provided")
75 }
76
77 c := newTemplateTransformContext(t, store, lookupFn)
78 c.t.ParseInfo = defaultParseInfo
79 tree := getParseTree(t.Template)
80 if tree == nil {
81 panic(fmt.Errorf("template %s not parsed", t))
82 }
83
84 if err := c.applyTransformations(tree.Root); err != nil {
85 return c, fmt.Errorf("failed to transform template %q: %w", t.Name(), err)
86 }
87
88 return c, c.err
89 }
90
91 func getParseTree(templ tpl.Template) *parse.Tree {
92 if text, ok := templ.(*texttemplate.Template); ok {
93 return text.Tree
94 }
95 return templ.(*htmltemplate.Template).Tree
96 }
97
98 const (
99 doDeferTempl = `{{ doDefer ("PLACEHOLDER1") ("PLACEHOLDER2") }}`
100
101 // _pushPartialDecorator is always falsy.
102 pushPartialDecoratorTempl = `{{ if or (_pushPartialDecorator ("PLACEHOLDER")) }}{{ end }}`
103 popPartialDecoratorTempl = `{{ if (_popPartialDecorator ("PLACEHOLDER1")) }}{{ . }}{{ else }}("PLACEHOLDER2"){{ end }}`
104
105 // popPartialDecoratorElseTempl is used when partial returns falsy and the with block is skipped.
106 // We still need to pop the decorator ID from the stack.
107 popPartialDecoratorElseTempl = `{{ _popPartialDecorator ("PLACEHOLDER") }}`
108 )
109
110 var (
111 doDefer *parse.ListNode
112 popPartialDecorator *parse.ListNode
113 pushPartialDecorator *parse.ListNode
114 popPartialDecoratorElse *parse.ListNode
115 )
116
117 func init() {
118 templ, err := texttemplate.New("").Funcs(texttemplate.FuncMap{"doDefer": func(string, string) string { return "" }}).Parse(doDeferTempl)
119 if err != nil {
120 panic(err)
121 }
122 doDefer = templ.Tree.Root
123
124 templ, err = texttemplate.New("").Funcs(texttemplate.FuncMap{"_popPartialDecorator": func(string) string { return "" }}).Parse(popPartialDecoratorTempl)
125 if err != nil {
126 panic(err)
127 }
128 popPartialDecorator = templ.Tree.Root
129
130 templ, err = texttemplate.New("").Funcs(texttemplate.FuncMap{"_pushPartialDecorator": func(string) string { return "" }}).Parse(pushPartialDecoratorTempl)
131 if err != nil {
132 panic(err)
133 }
134 pushPartialDecorator = templ.Tree.Root
135
136 templ, err = texttemplate.New("").Funcs(texttemplate.FuncMap{"_popPartialDecorator": func(string) string { return "" }}).Parse(popPartialDecoratorElseTempl)
137 if err != nil {
138 panic(err)
139 }
140 popPartialDecoratorElse = templ.Tree.Root
141 }
142
143 // applyTransformations tracks template (partial) dependencies and some other info.
144 func (c *templateTransformContext) applyTransformations(n parse.Node) error {
145 switch x := n.(type) {
146 case *parse.ListNode:
147 if x != nil {
148 c.applyTransformationsToNodes(x.Nodes...)
149 }
150 case *parse.ActionNode:
151 c.applyTransformationsToNodes(x.Pipe)
152 case *parse.IfNode:
153 c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
154 case *parse.WithNode:
155 c.handleWith(x)
156 c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
157 case *parse.RangeNode:
158 c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
159 case *parse.TemplateNode:
160 subTempl := c.getIfNotVisited(x.Name)
161 if subTempl != nil {
162 c.applyTransformationsToNodes(getParseTree(subTempl.Template).Root)
163 }
164 case *parse.PipeNode:
165 c.collectConfig(x)
166 for i, cmd := range x.Cmds {
167 // A return in any other position would silently discard the rest of the pipeline.
168 if i < len(x.Cmds)-1 && len(cmd.Args) > 0 {
169 if id, ok := cmd.Args[0].(*parse.IdentifierNode); ok && id.Ident == "return" {
170 c.err = errors.New("return must be the last command in a pipeline")
171 return c.err
172 }
173 }
174 c.applyTransformations(cmd)
175 }
176
177 case *parse.CommandNode:
178 if x == nil {
179 return nil
180 }
181 c.collectInnerInShortcode(x)
182 c.collectInnerInPartial(x)
183
184 for _, elem := range x.Args {
185 switch an := elem.(type) {
186 case *parse.PipeNode:
187 c.applyTransformations(an)
188 }
189 }
190 }
191
192 return c.err
193 }
194
195 func (c *templateTransformContext) isWithPartial(args []parse.Node) bool {
196 if len(args) == 0 {
197 return false
198 }
199
200 first := args[0]
201
202 if pn, ok := first.(*parse.PipeNode); ok {
203 if len(pn.Cmds) == 0 || pn.Cmds[0] == nil {
204 return false
205 }
206 return c.isWithPartial(pn.Cmds[0].Args)
207 }
208
209 if id1, ok := first.(*parse.IdentifierNode); ok && (id1.Ident == "partial" || id1.Ident == "partialCached") {
210 return true
211 }
212
213 if chain, ok := first.(*parse.ChainNode); ok {
214 if id2, ok := chain.Node.(*parse.IdentifierNode); !ok || (id2.Ident != "partials") {
215 return false
216 }
217 if len(chain.Field) != 1 {
218 return false
219 }
220 if chain.Field[0] != "Include" && chain.Field[0] != "IncludeCached" {
221 return false
222 }
223 return true
224 }
225 return false
226 }
227
228 func (c *templateTransformContext) isWithDefer(idArg parse.Node) bool {
229 id, ok := idArg.(*parse.ChainNode)
230 if !ok || len(id.Field) != 1 || id.Field[0] != "Defer" {
231 return false
232 }
233 if id2, ok := id.Node.(*parse.IdentifierNode); !ok || id2.Ident != "templates" {
234 return false
235 }
236 return true
237 }
238
239 // PartialDecoratorPrefix is the prefix used for internal partial decorator templates.
240 const PartialDecoratorPrefix = "_internal/decorator_"
241
242 var templatesInnerRe = regexp.MustCompile(`{{\s*(templates\.Inner\b|inner\b)`)
243
244 // hasBreakOrContinueOutsideRange returns true if the given list node contains a break or continue statement without being nested in a range.
245 func (c *templateTransformContext) hasBreakOrContinueOutsideRange(n *parse.ListNode) bool {
246 if n == nil {
247 return false
248 }
249 for _, node := range n.Nodes {
250 switch x := node.(type) {
251 case *parse.ListNode:
252 if c.hasBreakOrContinueOutsideRange(x) {
253 return true
254 }
255 case *parse.RangeNode:
256 // skip
257 case *parse.IfNode:
258 if c.hasBreakOrContinueOutsideRange(x.List) {
259 return true
260 }
261 if c.hasBreakOrContinueOutsideRange(x.ElseList) {
262 return true
263 }
264 case *parse.WithNode:
265 if c.hasBreakOrContinueOutsideRange(x.List) {
266 return true
267 }
268 if c.hasBreakOrContinueOutsideRange(x.ElseList) {
269 return true
270 }
271 case *parse.BreakNode, *parse.ContinueNode:
272 return true
273
274 }
275 }
276 return false
277 }
278
279 func (c *templateTransformContext) handleWithPartial(withNode *parse.WithNode) {
280 withNodeInnerString := withNode.List.String()
281 if templatesInnerRe.MatchString(withNodeInnerString) {
282 c.err = fmt.Errorf("inner cannot be used inside a with block that wraps a partial decorator")
283 return
284 }
285
286 // See #14333. That is a very odd construct, but we need to guard against it.
287 if c.hasBreakOrContinueOutsideRange(withNode.List) {
288 return
289 }
290 innerHash := hashing.XxHashFromStringHexEncoded(c.t.Name() + withNodeInnerString)
291 internalPartialName := fmt.Sprintf("_partials/%s%s", PartialDecoratorPrefix, innerHash)
292
293 if c.lookupFn(internalPartialName, c.t) == nil {
294 innerCopy := withNode.List.CopyList()
295 ti, err := c.store.addTransformedTemplateInsert(internalPartialName, SubCategoryInline)
296 if err != nil {
297 c.err = fmt.Errorf("failed to create internal partial decorator template %q: %w", internalPartialName, err)
298 return
299 }
300 if ti == nil {
301 c.err = fmt.Errorf("failed to find internal partial decorator template %q after insertion", internalPartialName)
302 return
303 }
304 ti.decoratorOwner = c.t
305
306 cc := newTemplateTransformContext(ti, c.store, c.lookupFn)
307
308 tree, err := c.store.addTransformedTemplateSetTree(ti, innerCopy)
309 if err != nil {
310 c.err = fmt.Errorf("failed to add internal partial decorator template %q: %w", internalPartialName, err)
311 return
312 }
313
314 if err := cc.applyTransformations(tree.Root); err != nil {
315 c.err = fmt.Errorf("failed to transform internal partial decorator template %q: %w", internalPartialName, err)
316 return
317 }
318
319 }
320
321 newInner := popPartialDecorator.CopyList()
322 ifNode := newInner.Nodes[0].(*parse.IfNode)
323
324 placeholderPipe := ifNode.Pipe.Cmds[0].Args[0].(*parse.PipeNode)
325
326 // Set PLACEHOLDER1 to the unique ID for this partial decorator.
327 sn1 := placeholderPipe.Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode)
328 sn1.Text = innerHash
329 sn1.Quoted = fmt.Sprintf("%q", sn1.Text)
330
331 ifNode.ElseList = withNode.List.CopyList()
332
333 newPipe := pushPartialDecorator.CopyList()
334 orNode := newPipe.Nodes[0].(*parse.IfNode)
335 setContext := orNode.Pipe.Cmds[0].Args[1]
336 // Replace PLACEHOLDER with the unique ID for this partial decorator.
337 sn2 := setContext.(*parse.PipeNode).Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode)
338 sn2.Text = innerHash
339 sn2.Quoted = fmt.Sprintf("%q", sn2.Text)
340 if pn, ok := withNode.Pipe.Cmds[0].Args[0].(*parse.PipeNode); ok {
341 withNode.Pipe.Cmds[0].Args = pn.Cmds[0].Args
342 }
343 withNode.Pipe.Cmds = append(orNode.Pipe.Cmds, withNode.Pipe.Cmds...)
344
345 withNode.List = newInner
346
347 // When the partial returns a falsy value, the with block is skipped,
348 // but we still need to pop the decorator ID from the stack.
349 // Add a pop call to the else branch.
350 popElse := popPartialDecoratorElse.CopyList()
351 popElseAction := popElse.Nodes[0].(*parse.ActionNode)
352 popElsePipe := popElseAction.Pipe.Cmds[0].Args[1].(*parse.PipeNode)
353 popElseString := popElsePipe.Cmds[0].Args[0].(*parse.StringNode)
354 popElseString.Text = innerHash
355 popElseString.Quoted = fmt.Sprintf("%q", popElseString.Text)
356
357 if withNode.ElseList == nil {
358 withNode.ElseList = popElse
359 } else {
360 // Prepend the pop to the existing else list
361 withNode.ElseList.Nodes = append(popElse.Nodes, withNode.ElseList.Nodes...)
362 }
363 }
364
365 func (c *templateTransformContext) handleWith(withNode *parse.WithNode) {
366 if len(withNode.Pipe.Cmds) != 1 {
367 return
368 }
369
370 if c.isWithPartial(withNode.Pipe.Cmds[0].Args) {
371 c.handleWithPartial(withNode)
372 return
373 }
374
375 cmd := withNode.Pipe.Cmds[0]
376
377 idArg := cmd.Args[0]
378
379 p, ok := idArg.(*parse.PipeNode)
380 if !ok {
381 return
382 }
383
384 if len(p.Cmds) != 1 {
385 return
386 }
387
388 cmd = p.Cmds[0]
389
390 if len(cmd.Args) != 2 {
391 return
392 }
393
394 idArg = cmd.Args[0]
395
396 if !c.isWithDefer(idArg) {
397 return
398 }
399
400 deferArg := cmd.Args[1]
401 cmd.Args = []parse.Node{idArg}
402
403 l := doDefer.CopyList()
404 n := l.Nodes[0].(*parse.ActionNode)
405
406 inner := withNode.List.CopyList()
407 s := inner.String()
408 if strings.Contains(s, "resources.PostProcess") {
409 c.err = errors.New("resources.PostProcess cannot be used in a deferred template")
410 return
411 }
412 // The deferred template is parsed using the owner's escaping mode. Keep
413 // identical bodies shared within that mode, but don't let HTML and plain
414 // text templates register the same deferred template.
415 innerHash := hashing.XxHashFromStringHexEncoded(fmt.Sprintf("%t:%s", c.t.D.IsPlainText, s))
416 deferredID := tpl.HugoDeferredTemplatePrefix + innerHash
417
418 c.deferNodes[deferredID] = inner
419 withNode.List = l
420
421 n.Pipe.Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode).Text = deferredID
422 n.Pipe.Cmds[0].Args[2] = deferArg
423 }
424
425 func (c *templateTransformContext) applyTransformationsToNodes(nodes ...parse.Node) {
426 for _, node := range nodes {
427 c.applyTransformations(node)
428 }
429 }
430
431 func (c *templateTransformContext) hasIdent(idents []string, ident string) bool {
432 return slices.Contains(idents, ident)
433 }
434
435 // collectConfig collects and parses any leading template config variable declaration.
436 // This will be the first PipeNode in the template, and will be a variable declaration
437 // on the form:
438 //
439 // {{ $_hugo_config:= `{ "version": 1 }` }}
440 func (c *templateTransformContext) collectConfig(n *parse.PipeNode) {
441 if c.t.category != CategoryShortcode {
442 return
443 }
444 if c.configChecked {
445 return
446 }
447 c.configChecked = true
448
449 if len(n.Decl) != 1 || len(n.Cmds) != 1 {
450 // This cannot be a config declaration
451 return
452 }
453
454 v := n.Decl[0]
455
456 if len(v.Ident) == 0 || v.Ident[0] != "$_hugo_config" {
457 return
458 }
459
460 cmd := n.Cmds[0]
461
462 if len(cmd.Args) == 0 {
463 return
464 }
465
466 if s, ok := cmd.Args[0].(*parse.StringNode); ok {
467 errMsg := "failed to decode $_hugo_config in template: %w"
468 m, err := hmaps.ToStringMapE(s.Text)
469 if err != nil {
470 c.err = fmt.Errorf(errMsg, err)
471 return
472 }
473 if err := mapstructure.WeakDecode(m, &c.t.ParseInfo.Config); err != nil {
474 c.err = fmt.Errorf(errMsg, err)
475 }
476 }
477 }
478
479 // collectInnerInShortcode determines if the given CommandNode represents a
480 // shortcode call to its .Inner.
481 func (c *templateTransformContext) collectInnerInShortcode(n *parse.CommandNode) {
482 if c.t.category != CategoryShortcode {
483 return
484 }
485 if c.t.ParseInfo.IsInner || len(n.Args) == 0 {
486 return
487 }
488
489 for _, arg := range n.Args {
490 var idents []string
491 switch nt := arg.(type) {
492 case *parse.FieldNode:
493 idents = nt.Ident
494 case *parse.VariableNode:
495 idents = nt.Ident
496 }
497
498 if c.hasIdent(idents, "Inner") || c.hasIdent(idents, "InnerDeindent") {
499 c.t.ParseInfo.IsInner = true
500 break
501 }
502 }
503 }
504
505 func (c *templateTransformContext) collectInnerInPartial(n *parse.CommandNode) {
506 if c.t.category != CategoryPartial {
507 return
508 }
509
510 if c.t.ParseInfo.HasPartialInner || len(n.Args) == 0 {
511 return
512 }
513
514 switch v := n.Args[0].(type) {
515 case *parse.IdentifierNode:
516 if v.Ident == "inner" {
517 c.t.ParseInfo.HasPartialInner = true
518 }
519 case *parse.ChainNode:
520 if v.Field[0] == "Inner" {
521 if id, ok := v.Node.(*parse.IdentifierNode); ok && id.Ident == "templates" {
522 c.t.ParseInfo.HasPartialInner = true
523 }
524 }
525 }
526 }