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
305 cc := newTemplateTransformContext(ti, c.store, c.lookupFn)
306
307 tree, err := c.store.addTransformedTemplateSetTree(ti, innerCopy)
308 if err != nil {
309 c.err = fmt.Errorf("failed to add internal partial decorator template %q: %w", internalPartialName, err)
310 return
311 }
312
313 if err := cc.applyTransformations(tree.Root); err != nil {
314 c.err = fmt.Errorf("failed to transform internal partial decorator template %q: %w", internalPartialName, err)
315 return
316 }
317
318 }
319
320 newInner := popPartialDecorator.CopyList()
321 ifNode := newInner.Nodes[0].(*parse.IfNode)
322
323 placeholderPipe := ifNode.Pipe.Cmds[0].Args[0].(*parse.PipeNode)
324
325 // Set PLACEHOLDER1 to the unique ID for this partial decorator.
326 sn1 := placeholderPipe.Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode)
327 sn1.Text = innerHash
328 sn1.Quoted = fmt.Sprintf("%q", sn1.Text)
329
330 ifNode.ElseList = withNode.List.CopyList()
331
332 newPipe := pushPartialDecorator.CopyList()
333 orNode := newPipe.Nodes[0].(*parse.IfNode)
334 setContext := orNode.Pipe.Cmds[0].Args[1]
335 // Replace PLACEHOLDER with the unique ID for this partial decorator.
336 sn2 := setContext.(*parse.PipeNode).Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode)
337 sn2.Text = innerHash
338 sn2.Quoted = fmt.Sprintf("%q", sn2.Text)
339 if pn, ok := withNode.Pipe.Cmds[0].Args[0].(*parse.PipeNode); ok {
340 withNode.Pipe.Cmds[0].Args = pn.Cmds[0].Args
341 }
342 withNode.Pipe.Cmds = append(orNode.Pipe.Cmds, withNode.Pipe.Cmds...)
343
344 withNode.List = newInner
345
346 // When the partial returns a falsy value, the with block is skipped,
347 // but we still need to pop the decorator ID from the stack.
348 // Add a pop call to the else branch.
349 popElse := popPartialDecoratorElse.CopyList()
350 popElseAction := popElse.Nodes[0].(*parse.ActionNode)
351 popElsePipe := popElseAction.Pipe.Cmds[0].Args[1].(*parse.PipeNode)
352 popElseString := popElsePipe.Cmds[0].Args[0].(*parse.StringNode)
353 popElseString.Text = innerHash
354 popElseString.Quoted = fmt.Sprintf("%q", popElseString.Text)
355
356 if withNode.ElseList == nil {
357 withNode.ElseList = popElse
358 } else {
359 // Prepend the pop to the existing else list
360 withNode.ElseList.Nodes = append(popElse.Nodes, withNode.ElseList.Nodes...)
361 }
362 }
363
364 func (c *templateTransformContext) handleWith(withNode *parse.WithNode) {
365 if len(withNode.Pipe.Cmds) != 1 {
366 return
367 }
368
369 if c.isWithPartial(withNode.Pipe.Cmds[0].Args) {
370 c.handleWithPartial(withNode)
371 return
372 }
373
374 cmd := withNode.Pipe.Cmds[0]
375
376 idArg := cmd.Args[0]
377
378 p, ok := idArg.(*parse.PipeNode)
379 if !ok {
380 return
381 }
382
383 if len(p.Cmds) != 1 {
384 return
385 }
386
387 cmd = p.Cmds[0]
388
389 if len(cmd.Args) != 2 {
390 return
391 }
392
393 idArg = cmd.Args[0]
394
395 if !c.isWithDefer(idArg) {
396 return
397 }
398
399 deferArg := cmd.Args[1]
400 cmd.Args = []parse.Node{idArg}
401
402 l := doDefer.CopyList()
403 n := l.Nodes[0].(*parse.ActionNode)
404
405 inner := withNode.List.CopyList()
406 s := inner.String()
407 if strings.Contains(s, "resources.PostProcess") {
408 c.err = errors.New("resources.PostProcess cannot be used in a deferred template")
409 return
410 }
411 // The deferred template is parsed using the owner's escaping mode. Keep
412 // identical bodies shared within that mode, but don't let HTML and plain
413 // text templates register the same deferred template.
414 innerHash := hashing.XxHashFromStringHexEncoded(fmt.Sprintf("%t:%s", c.t.D.IsPlainText, s))
415 deferredID := tpl.HugoDeferredTemplatePrefix + innerHash
416
417 c.deferNodes[deferredID] = inner
418 withNode.List = l
419
420 n.Pipe.Cmds[0].Args[1].(*parse.PipeNode).Cmds[0].Args[0].(*parse.StringNode).Text = deferredID
421 n.Pipe.Cmds[0].Args[2] = deferArg
422 }
423
424 func (c *templateTransformContext) applyTransformationsToNodes(nodes ...parse.Node) {
425 for _, node := range nodes {
426 c.applyTransformations(node)
427 }
428 }
429
430 func (c *templateTransformContext) hasIdent(idents []string, ident string) bool {
431 return slices.Contains(idents, ident)
432 }
433
434 // collectConfig collects and parses any leading template config variable declaration.
435 // This will be the first PipeNode in the template, and will be a variable declaration
436 // on the form:
437 //
438 // {{ $_hugo_config:= `{ "version": 1 }` }}
439 func (c *templateTransformContext) collectConfig(n *parse.PipeNode) {
440 if c.t.category != CategoryShortcode {
441 return
442 }
443 if c.configChecked {
444 return
445 }
446 c.configChecked = true
447
448 if len(n.Decl) != 1 || len(n.Cmds) != 1 {
449 // This cannot be a config declaration
450 return
451 }
452
453 v := n.Decl[0]
454
455 if len(v.Ident) == 0 || v.Ident[0] != "$_hugo_config" {
456 return
457 }
458
459 cmd := n.Cmds[0]
460
461 if len(cmd.Args) == 0 {
462 return
463 }
464
465 if s, ok := cmd.Args[0].(*parse.StringNode); ok {
466 errMsg := "failed to decode $_hugo_config in template: %w"
467 m, err := hmaps.ToStringMapE(s.Text)
468 if err != nil {
469 c.err = fmt.Errorf(errMsg, err)
470 return
471 }
472 if err := mapstructure.WeakDecode(m, &c.t.ParseInfo.Config); err != nil {
473 c.err = fmt.Errorf(errMsg, err)
474 }
475 }
476 }
477
478 // collectInnerInShortcode determines if the given CommandNode represents a
479 // shortcode call to its .Inner.
480 func (c *templateTransformContext) collectInnerInShortcode(n *parse.CommandNode) {
481 if c.t.category != CategoryShortcode {
482 return
483 }
484 if c.t.ParseInfo.IsInner || len(n.Args) == 0 {
485 return
486 }
487
488 for _, arg := range n.Args {
489 var idents []string
490 switch nt := arg.(type) {
491 case *parse.FieldNode:
492 idents = nt.Ident
493 case *parse.VariableNode:
494 idents = nt.Ident
495 }
496
497 if c.hasIdent(idents, "Inner") || c.hasIdent(idents, "InnerDeindent") {
498 c.t.ParseInfo.IsInner = true
499 break
500 }
501 }
502 }
503
504 func (c *templateTransformContext) collectInnerInPartial(n *parse.CommandNode) {
505 if c.t.category != CategoryPartial {
506 return
507 }
508
509 if c.t.ParseInfo.HasPartialInner || len(n.Args) == 0 {
510 return
511 }
512
513 switch v := n.Args[0].(type) {
514 case *parse.IdentifierNode:
515 if v.Ident == "inner" {
516 c.t.ParseInfo.HasPartialInner = true
517 }
518 case *parse.ChainNode:
519 if v.Field[0] == "Inner" {
520 if id, ok := v.Node.(*parse.IdentifierNode); ok && id.Ident == "templates" {
521 c.t.ParseInfo.HasPartialInner = true
522 }
523 }
524 }
525 }