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