-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.go
1855 lines (1587 loc) · 46.6 KB
/
render.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Revert to backup file and use the content with our changes
package twig
import (
"errors"
"fmt"
"io"
"math"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// RenderContext holds the state during template rendering
type RenderContext struct {
env *Environment
context map[string]interface{}
blocks map[string][]Node
parentBlocks map[string][]Node // Original block content from parent templates
macros map[string]Node
parent *RenderContext
engine *Engine // Reference to engine for loading templates
extending bool // Whether this template extends another
currentBlock *BlockNode // Current block being rendered (for parent() function)
inParentCall bool // Flag to indicate if we're currently rendering a parent() call
sandboxed bool // Flag indicating if this context is sandboxed
lastLoadedTemplate *Template // The template that created this context (for resolving relative paths)
}
// contextMapPool is a pool for the maps used in RenderContext
var contextMapPool = sync.Pool{
New: func() interface{} {
return make(map[string]interface{}, 16) // Pre-allocate with reasonable size
},
}
// blocksMapPool is a pool for the blocks map used in RenderContext
var blocksMapPool = sync.Pool{
New: func() interface{} {
return make(map[string][]Node, 8) // Pre-allocate with reasonable size
},
}
// macrosMapPool is a pool for the macros map used in RenderContext
var macrosMapPool = sync.Pool{
New: func() interface{} {
return make(map[string]Node, 8) // Pre-allocate with reasonable size
},
}
// renderContextPool is a sync.Pool for RenderContext objects
var renderContextPool = sync.Pool{
New: func() interface{} {
return &RenderContext{
context: contextMapPool.Get().(map[string]interface{}),
blocks: blocksMapPool.Get().(map[string][]Node),
parentBlocks: blocksMapPool.Get().(map[string][]Node),
macros: macrosMapPool.Get().(map[string]Node),
}
},
}
// NewRenderContext gets a RenderContext from the pool and initializes it
func NewRenderContext(env *Environment, context map[string]interface{}, engine *Engine) *RenderContext {
ctx := renderContextPool.Get().(*RenderContext)
// Ensure all maps are initialized (should be from the pool)
if ctx.context == nil {
ctx.context = contextMapPool.Get().(map[string]interface{})
} else {
// Clear any existing data
for k := range ctx.context {
delete(ctx.context, k)
}
}
if ctx.blocks == nil {
ctx.blocks = blocksMapPool.Get().(map[string][]Node)
} else {
// Clear any existing data
for k := range ctx.blocks {
delete(ctx.blocks, k)
}
}
if ctx.parentBlocks == nil {
ctx.parentBlocks = blocksMapPool.Get().(map[string][]Node)
} else {
// Clear any existing data
for k := range ctx.parentBlocks {
delete(ctx.parentBlocks, k)
}
}
if ctx.macros == nil {
ctx.macros = macrosMapPool.Get().(map[string]Node)
} else {
// Clear any existing data
for k := range ctx.macros {
delete(ctx.macros, k)
}
}
// Set basic properties
ctx.env = env
ctx.engine = engine
ctx.extending = false
ctx.currentBlock = nil
ctx.parent = nil
ctx.inParentCall = false
ctx.sandboxed = false
// Copy the context values directly
if context != nil {
for k, v := range context {
ctx.context[k] = v
}
}
return ctx
}
// Release returns the RenderContext to the pool with proper cleanup
func (ctx *RenderContext) Release() {
// Clear references to large objects to prevent memory leaks
ctx.env = nil
ctx.engine = nil
ctx.currentBlock = nil
// Save the maps so we can return them to their respective pools
contextMap := ctx.context
blocksMap := ctx.blocks
parentBlocksMap := ctx.parentBlocks
macrosMap := ctx.macros
// Clear the maps from the context
ctx.context = nil
ctx.blocks = nil
ctx.parentBlocks = nil
ctx.macros = nil
// Don't release parent contexts - they'll be released separately
ctx.parent = nil
// Return to pool
renderContextPool.Put(ctx)
// Clear map contents and return them to their pools
if contextMap != nil {
for k := range contextMap {
delete(contextMap, k)
}
contextMapPool.Put(contextMap)
}
if blocksMap != nil {
for k := range blocksMap {
delete(blocksMap, k)
}
blocksMapPool.Put(blocksMap)
}
if parentBlocksMap != nil {
for k := range parentBlocksMap {
delete(parentBlocksMap, k)
}
blocksMapPool.Put(parentBlocksMap)
}
if macrosMap != nil {
for k := range macrosMap {
delete(macrosMap, k)
}
macrosMapPool.Put(macrosMap)
}
}
// Error types
var (
ErrTemplateNotFound = errors.New("template not found")
ErrUndefinedVar = errors.New("undefined variable")
ErrInvalidAttribute = errors.New("invalid attribute access")
ErrCompilation = errors.New("compilation error")
ErrRender = errors.New("render error")
)
// GetVariable gets a variable from the context
func (ctx *RenderContext) GetVariable(name string) (interface{}, error) {
// Check if this looks like an array literal - this is a hack to handle
// the case where the array literal is parsed as a variable name
if len(name) >= 2 && name[0] == '[' && strings.Contains(name, "]") {
// This looks like an array literal that was parsed as a variable name
// We'll parse it manually here
// Extract the content between [ and ]
content := name[1:strings.LastIndex(name, "]")]
// Split by commas
parts := strings.Split(content, ",")
// Create a result array
result := make([]interface{}, 0, len(parts))
// Process each element
for _, part := range parts {
// Trim whitespace and quotes
element := strings.TrimSpace(part)
// If it's a quoted string, remove the quotes
if len(element) >= 2 && (element[0] == '"' || element[0] == '\'') && element[0] == element[len(element)-1] {
element = element[1 : len(element)-1]
}
result = append(result, element)
}
return result, nil
}
// Fallback ternary expression parser for backward compatibility
// This handles cases where the parser didn't correctly handle ternary expressions
if strings.Contains(name, "?") && strings.Contains(name, ":") {
LogDebug("Parsing inline ternary expression: %s", name)
// Simple ternary expression handler
parts := strings.SplitN(name, "?", 2)
condition := strings.TrimSpace(parts[0])
branches := strings.SplitN(parts[1], ":", 2)
if len(branches) != 2 {
return nil, fmt.Errorf("malformed ternary expression: %s", name)
}
trueExpr := strings.TrimSpace(branches[0])
falseExpr := strings.TrimSpace(branches[1])
// Evaluate condition
var condValue bool
if condition == "true" {
condValue = true
} else if condition == "false" {
condValue = false
} else {
// Try to get variable value
condVar, _ := ctx.GetVariable(condition)
condValue = ctx.toBool(condVar)
}
// Evaluate the appropriate branch
if condValue {
return ctx.GetVariable(trueExpr)
} else {
return ctx.GetVariable(falseExpr)
}
}
// Check local context first
if value, ok := ctx.context[name]; ok {
return value, nil
}
// Check globals
if ctx.env != nil {
if value, ok := ctx.env.globals[name]; ok {
return value, nil
}
}
// Check parent context
if ctx.parent != nil {
return ctx.parent.GetVariable(name)
}
// Return nil with no error for undefined variables
// Twig treats undefined variables as empty strings during rendering
return nil, nil
}
// GetVariableOrNil gets a variable from the context, returning nil silently if not found
func (ctx *RenderContext) GetVariableOrNil(name string) interface{} {
value, _ := ctx.GetVariable(name)
return value
}
// SetVariable sets a variable in the context
func (ctx *RenderContext) SetVariable(name string, value interface{}) {
ctx.context[name] = value
}
// GetEnvironment returns the environment
func (ctx *RenderContext) GetEnvironment() *Environment {
return ctx.env
}
// GetEngine returns the engine
func (ctx *RenderContext) GetEngine() *Engine {
return ctx.engine
}
// SetParent sets the parent context
func (ctx *RenderContext) SetParent(parent *RenderContext) {
ctx.parent = parent
}
// EnableSandbox enables sandbox mode on this context
func (ctx *RenderContext) EnableSandbox() {
ctx.sandboxed = true
}
// IsSandboxed returns whether this context is sandboxed
func (ctx *RenderContext) IsSandboxed() bool {
return ctx.sandboxed
}
// Clone creates a new context as a child of the current context
func (ctx *RenderContext) Clone() *RenderContext {
// Get a new context from the pool with empty maps
newCtx := renderContextPool.Get().(*RenderContext)
// Initialize the context
newCtx.env = ctx.env
newCtx.engine = ctx.engine
newCtx.extending = false
newCtx.currentBlock = nil
newCtx.parent = ctx
newCtx.inParentCall = false
// Inherit sandbox state
newCtx.sandboxed = ctx.sandboxed
// Copy the lastLoadedTemplate reference (crucial for relative path resolution)
newCtx.lastLoadedTemplate = ctx.lastLoadedTemplate
// Ensure maps are initialized (they should be from the pool already)
if newCtx.context == nil {
newCtx.context = contextMapPool.Get().(map[string]interface{})
} else {
// Clear any existing data
for k := range newCtx.context {
delete(newCtx.context, k)
}
}
if newCtx.blocks == nil {
newCtx.blocks = blocksMapPool.Get().(map[string][]Node)
} else {
// Clear any existing data
for k := range newCtx.blocks {
delete(newCtx.blocks, k)
}
}
if newCtx.macros == nil {
newCtx.macros = macrosMapPool.Get().(map[string]Node)
} else {
// Clear any existing data
for k := range newCtx.macros {
delete(newCtx.macros, k)
}
}
if newCtx.parentBlocks == nil {
newCtx.parentBlocks = blocksMapPool.Get().(map[string][]Node)
} else {
// Clear any existing data
for k := range newCtx.parentBlocks {
delete(newCtx.parentBlocks, k)
}
}
// Copy blocks by reference (no need to deep copy)
for name, nodes := range ctx.blocks {
newCtx.blocks[name] = nodes
}
// Copy macros by reference (no need to deep copy)
for name, macro := range ctx.macros {
newCtx.macros[name] = macro
}
return newCtx
}
// GetMacro gets a macro from the context
func (ctx *RenderContext) GetMacro(name string) (interface{}, bool) {
// Check local macros first
if macro, ok := ctx.macros[name]; ok {
return macro, true
}
// Check parent context
if ctx.parent != nil {
return ctx.parent.GetMacro(name)
}
return nil, false
}
// GetMacros returns the macros map
func (ctx *RenderContext) GetMacros() map[string]Node {
return ctx.macros
}
// InitMacros initializes the macros map if it's nil
func (ctx *RenderContext) InitMacros() {
if ctx.macros == nil {
ctx.macros = macrosMapPool.Get().(map[string]Node)
}
}
// SetMacro sets a macro in the context
func (ctx *RenderContext) SetMacro(name string, macro Node) {
if ctx.macros == nil {
ctx.macros = macrosMapPool.Get().(map[string]Node)
}
ctx.macros[name] = macro
}
// CallMacro calls a macro with the given arguments
func (ctx *RenderContext) CallMacro(w io.Writer, name string, args []interface{}) error {
// Find the macro
macro, ok := ctx.GetMacro(name)
if !ok {
return fmt.Errorf("macro '%s' not found", name)
}
// Check if it's a MacroNode
macroNode, ok := macro.(*MacroNode)
if !ok {
return fmt.Errorf("'%s' is not a macro", name)
}
// Call the macro
return macroNode.CallMacro(w, ctx, args...)
}
// CallFunction calls a function with the given arguments
func (ctx *RenderContext) CallFunction(name string, args []interface{}) (interface{}, error) {
// Check if it's a function in the environment
if ctx.env != nil {
if fn, ok := ctx.env.functions[name]; ok {
// Special case for parent() function which needs access to the RenderContext
if name == "parent" {
return fn(args...)
}
// Regular function call
return fn(args...)
}
}
// Check if it's a built-in function
switch name {
case "range":
return ctx.callRangeFunction(args)
case "length", "count":
return ctx.callLengthFunction(args)
case "max":
return ctx.callMaxFunction(args)
case "min":
return ctx.callMinFunction(args)
}
// Check if it's a macro
if macro, ok := ctx.GetMacro(name); ok {
// Return a callable function
return func(w io.Writer) error {
macroNode, ok := macro.(*MacroNode)
if !ok {
return fmt.Errorf("'%s' is not a macro", name)
}
return macroNode.CallMacro(w, ctx, args...)
}, nil
}
return nil, fmt.Errorf("function '%s' not found", name)
}
// callRangeFunction implements the range function
func (ctx *RenderContext) callRangeFunction(args []interface{}) (interface{}, error) {
if len(args) < 2 {
return nil, fmt.Errorf("range function requires at least 2 arguments")
}
// Get the start and end values
start, ok1 := ctx.toNumber(args[0])
end, ok2 := ctx.toNumber(args[1])
if !ok1 || !ok2 {
return nil, fmt.Errorf("range arguments must be numbers")
}
// Get the step value (default is 1)
step := 1.0
if len(args) > 2 {
if s, ok := ctx.toNumber(args[2]); ok {
step = s
}
}
// Create the range
result := make([]interface{}, 0)
if step > 0 {
for i := start; i <= end; i += step {
result = append(result, int(i))
}
} else {
for i := start; i >= end; i += step {
result = append(result, int(i))
}
}
// Always return a non-nil slice for the for loop
if len(result) == 0 {
return []interface{}{}, nil
}
return result, nil
}
// callLengthFunction implements the length/count function
func (ctx *RenderContext) callLengthFunction(args []interface{}) (interface{}, error) {
if len(args) != 1 {
return nil, fmt.Errorf("length/count function requires exactly 1 argument")
}
val := args[0]
v := reflect.ValueOf(val)
switch v.Kind() {
case reflect.String:
return len(v.String()), nil
case reflect.Slice, reflect.Array:
return v.Len(), nil
case reflect.Map:
return v.Len(), nil
default:
return 0, nil
}
}
// callMaxFunction implements the max function
func (ctx *RenderContext) callMaxFunction(args []interface{}) (interface{}, error) {
if len(args) < 1 {
return nil, fmt.Errorf("max function requires at least 1 argument")
}
// If the argument is a slice or array, find the max value in it
if len(args) == 1 {
v := reflect.ValueOf(args[0])
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
if v.Len() == 0 {
return nil, nil
}
max := v.Index(0).Interface()
maxNum, ok := ctx.toNumber(max)
if !ok {
return max, nil
}
for i := 1; i < v.Len(); i++ {
val := v.Index(i).Interface()
if valNum, ok := ctx.toNumber(val); ok {
if valNum > maxNum {
max = val
maxNum = valNum
}
}
}
return max, nil
}
}
// Find the max value in the arguments
max := args[0]
maxNum, ok := ctx.toNumber(max)
if !ok {
return max, nil
}
for i := 1; i < len(args); i++ {
val := args[i]
if valNum, ok := ctx.toNumber(val); ok {
if valNum > maxNum {
max = val
maxNum = valNum
}
}
}
return max, nil
}
// callMinFunction implements the min function
func (ctx *RenderContext) callMinFunction(args []interface{}) (interface{}, error) {
if len(args) < 1 {
return nil, fmt.Errorf("min function requires at least 1 argument")
}
// If the argument is a slice or array, find the min value in it
if len(args) == 1 {
v := reflect.ValueOf(args[0])
if v.Kind() == reflect.Slice || v.Kind() == reflect.Array {
if v.Len() == 0 {
return nil, nil
}
min := v.Index(0).Interface()
minNum, ok := ctx.toNumber(min)
if !ok {
return min, nil
}
for i := 1; i < v.Len(); i++ {
val := v.Index(i).Interface()
if valNum, ok := ctx.toNumber(val); ok {
if valNum < minNum {
min = val
minNum = valNum
}
}
}
return min, nil
}
}
// Find the min value in the arguments
min := args[0]
minNum, ok := ctx.toNumber(min)
if !ok {
return min, nil
}
for i := 1; i < len(args); i++ {
val := args[i]
if valNum, ok := ctx.toNumber(val); ok {
if valNum < minNum {
min = val
minNum = valNum
}
}
}
return min, nil
}
// EvaluateExpression evaluates an expression node
func (ctx *RenderContext) EvaluateExpression(node Node) (interface{}, error) {
if node == nil {
return nil, nil
}
// Check sandbox security if enabled
if ctx.sandboxed && ctx.env.securityPolicy != nil {
switch n := node.(type) {
case *FunctionNode:
if !ctx.env.securityPolicy.IsFunctionAllowed(n.name) {
return nil, NewFunctionViolation(n.name)
}
case *FilterNode:
if !ctx.env.securityPolicy.IsFilterAllowed(n.filter) {
return nil, NewFilterViolation(n.filter)
}
}
}
switch n := node.(type) {
case *LiteralNode:
return n.value, nil
case *VariableNode:
// Check if it's a macro first
if macro, ok := ctx.GetMacro(n.name); ok {
return macro, nil
}
// Otherwise, look up variable
return ctx.GetVariable(n.name)
case *GetAttrNode:
obj, err := ctx.EvaluateExpression(n.node)
if err != nil {
return nil, err
}
attrName, err := ctx.EvaluateExpression(n.attribute)
if err != nil {
return nil, err
}
attrStr, ok := attrName.(string)
if !ok {
return nil, fmt.Errorf("attribute name must be a string")
}
// Check if obj is a map containing macros (from import)
if moduleMap, ok := obj.(map[string]interface{}); ok {
if macro, ok := moduleMap[attrStr]; ok {
return macro, nil
}
}
return ctx.getAttribute(obj, attrStr)
case *GetItemNode:
// Evaluate the container (array, slice, map)
container, err := ctx.EvaluateExpression(n.node)
if err != nil {
return nil, err
}
// Evaluate the item index/key
index, err := ctx.EvaluateExpression(n.item)
if err != nil {
return nil, err
}
return ctx.getItem(container, index)
case *BinaryNode:
// First, evaluate the left side of the expression
left, err := ctx.EvaluateExpression(n.left)
if err != nil {
return nil, err
}
// Implement short-circuit evaluation for logical operators
if n.operator == "and" || n.operator == "&&" {
// For "and" operator, if left side is false, return false without evaluating right side
if !ctx.toBool(left) {
return false, nil
}
} else if n.operator == "or" || n.operator == "||" {
// For "or" operator, if left side is true, return true without evaluating right side
if ctx.toBool(left) {
return true, nil
}
}
// For other operators or if short-circuit condition not met, evaluate right side
right, err := ctx.EvaluateExpression(n.right)
if err != nil {
return nil, err
}
return ctx.evaluateBinaryOp(n.operator, left, right)
case *ConditionalNode:
// Evaluate the condition
condResult, err := ctx.EvaluateExpression(n.condition)
if err != nil {
// Log error if debug is enabled
if IsDebugEnabled() {
LogError(err, "Error evaluating 'if' condition")
}
return nil, err
}
// Log result if debug is enabled
conditionResult := ctx.toBool(condResult)
if IsDebugEnabled() {
LogDebug("Ternary condition result: %v (type: %T, raw value: %v)", conditionResult, condResult, condResult)
LogDebug("Branches: true=%T, false=%T", n.trueExpr, n.falseExpr)
}
// If condition is true, evaluate the true expression, otherwise evaluate the false expression
if ctx.toBool(condResult) {
return ctx.EvaluateExpression(n.trueExpr)
} else {
return ctx.EvaluateExpression(n.falseExpr)
}
case *ArrayNode:
// We need to avoid pooling for arrays that might be directly used by filters like merge
// as those filters return the slice directly to the user
items := make([]interface{}, 0, len(n.items))
for i := 0; i < len(n.items); i++ {
val, err := ctx.EvaluateExpression(n.items[i])
if err != nil {
return nil, err
}
items = append(items, val)
}
// Always return a non-nil slice, even if empty
if len(items) == 0 {
return []interface{}{}, nil
}
return items, nil
case *HashNode:
// Evaluate each key-value pair in the hash using a new map
// We can't use pooling with defer here because the map is returned directly
result := make(map[string]interface{}, len(n.items))
for k, v := range n.items {
// Evaluate the key
keyVal, err := ctx.EvaluateExpression(k)
if err != nil {
return nil, err
}
// Convert key to string
key := ctx.ToString(keyVal)
// Evaluate the value
val, err := ctx.EvaluateExpression(v)
if err != nil {
return nil, err
}
// Store in the map
result[key] = val
}
return result, nil
case *FunctionNode:
// Check if this is a module.function() call (moduleExpr will be non-nil)
if n.moduleExpr != nil {
if IsDebugEnabled() && debugger.level >= DebugVerbose {
LogVerbose("Handling module.function() call with module expression")
}
// Evaluate the module expression first
moduleObj, err := ctx.EvaluateExpression(n.moduleExpr)
if err != nil {
return nil, err
}
// Evaluate all arguments - need direct allocation
args := make([]interface{}, len(n.args))
for i := 0; i < len(n.args); i++ {
val, err := ctx.EvaluateExpression(n.args[i])
if err != nil {
return nil, err
}
args[i] = val
}
// Check if moduleObj is a map that contains macros
if moduleMap, ok := moduleObj.(map[string]interface{}); ok {
if macroObj, ok := moduleMap[n.name]; ok {
if IsDebugEnabled() && debugger.level >= DebugVerbose {
LogVerbose("Found macro '%s' in module map", n.name)
}
// If the macro is a MacroNode, return a callable to render it
if macroNode, ok := macroObj.(*MacroNode); ok {
// Return a callable that can be rendered later
return func(w io.Writer) error {
return macroNode.CallMacro(w, ctx, args...)
}, nil
}
}
}
// Fallback - try calling it like a regular function
if IsDebugEnabled() && debugger.level >= DebugVerbose {
LogVerbose("Fallback - calling '%s' as a regular function", n.name)
}
result, err := ctx.CallFunction(n.name, args)
if err != nil {
return nil, err
}
return result, nil
}
// Check if it's a macro call
if macro, ok := ctx.GetMacro(n.name); ok {
// Evaluate arguments - need direct allocation for macro calls
args := make([]interface{}, len(n.args))
// Evaluate arguments
for i := 0; i < len(n.args); i++ {
val, err := ctx.EvaluateExpression(n.args[i])
if err != nil {
return nil, err
}
args[i] = val
}
// Return a callable that can be rendered later
return func(w io.Writer) error {
macroNode, ok := macro.(*MacroNode)
if !ok {
return fmt.Errorf("'%s' is not a macro", n.name)
}
return macroNode.CallMacro(w, ctx, args...)
}, nil
}
// Otherwise, it's a regular function call
// Evaluate arguments - need direct allocation for function calls
args := make([]interface{}, len(n.args))
// Evaluate arguments
for i := 0; i < len(n.args); i++ {
val, err := ctx.EvaluateExpression(n.args[i])
if err != nil {
return nil, err
}
args[i] = val
}
result, err := ctx.CallFunction(n.name, args)
if err != nil {
return nil, err
}
// Make sure function results that should be iterable actually are
if result == nil && (n.name == "range" || n.name == "length") {
return []interface{}{}, nil
}
return result, nil
case *FilterNode:
// Use the optimized filter chain implementation from render_filter.go
result, err := ctx.evaluateFilterNode(n)
if err != nil {
return nil, err
}
// Ensure filter results are never nil if they're expected to be iterable
if result == nil {
return "", nil
}
return result, nil
case *TestNode:
// Handle special "not defined" test (from parseBinaryExpression)
if n.test == "not defined" {
// Check if it's a variable reference
if varNode, ok := n.node.(*VariableNode); ok {
// Check directly in context
if ctx.context != nil {
_, exists := ctx.context[varNode.name]
if exists {
// If it exists, "not defined" is false
return false, nil
}
}
// Try full variable lookup
val, err := ctx.GetVariable(varNode.name)
// Return true if not defined (err != nil or val is nil)
return err != nil || val == nil, nil
}
// For non-variable nodes, assume defined
return false, nil
}
// Special handling for "is defined" test with attribute access
if n.test == "defined" {
// Check if this is a GetAttrNode
if getAttrNode, ok := n.node.(*GetAttrNode); ok {
// Evaluate the object
obj, err := ctx.EvaluateExpression(getAttrNode.node)
if err != nil {
return false, nil // If can't evaluate the object, it's not defined
}
// If obj is nil, attribute not defined
if obj == nil {
return false, nil
}
// Evaluate the attribute name
attrNameNode, err := ctx.EvaluateExpression(getAttrNode.attribute)
if err != nil {
return false, nil
}
attrName, ok := attrNameNode.(string)
if !ok {
return false, nil
}
// For maps, directly check if the key exists
if objMap, ok := obj.(map[string]interface{}); ok {
_, exists := objMap[attrName]
return exists, nil
}
// For other types, try to get the attribute but catch the error
_, err = ctx.getAttribute(obj, attrName)