Repository navigation
Expand file tree
/
Copy pathenvironment.go
More file actions
835 lines (710 loc) · 26.5 KB
/
Copy pathenvironment.go
File metadata and controls
835 lines (710 loc) · 26.5 KB
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
package miya
import (
"fmt"
"hash/fnv"
"runtime/debug"
"sync"
"time"
"github.com/zipreport/miya/branching"
"github.com/zipreport/miya/extensions"
"github.com/zipreport/miya/filters"
"github.com/zipreport/miya/lexer"
"github.com/zipreport/miya/loader"
"github.com/zipreport/miya/macros"
"github.com/zipreport/miya/parser"
"github.com/zipreport/miya/runtime"
)
// Environment is the central configuration object for template compilation and rendering.
// It holds the template loader, filter/test registries, caching, and all rendering options.
// An Environment is safe for concurrent use: templates may be rendered while AddGlobal,
// AddFilter, AddTest and AddExtension are called. Calls to AddTest must not run
// concurrently with each other. SetConfig, SetLoader and changes to a loader's templates
// (such as StringLoader.AddTemplate) must happen before rendering starts.
//
// Create an Environment with NewEnvironment and configure it using EnvironmentOption functions:
//
// env := miya.NewEnvironment(
// miya.WithLoader(loader),
// miya.WithAutoEscape(true),
// miya.WithTrimBlocks(true),
// )
type Environment struct {
loader Loader
filterRegistry *filters.FilterRegistry
macroRegistry *macros.MacroRegistry
testRegistry *branching.TestRegistry
extensionRegistry *extensions.Registry
globals map[string]interface{}
globalsMu sync.RWMutex
tests map[string]TestFunc // deprecated, use testRegistry
cache map[string]*Template // GetTemplate, by name
stringCache map[string]*Template // FromString, by hashString(source)
cacheMutex sync.RWMutex
// New inheritance caching system
inheritanceCache *runtime.InheritanceCache
inheritanceProcessor *runtime.InheritanceProcessor
inheritanceCacheMutex sync.RWMutex
// Performance: Evaluator pooling
evaluatorPool sync.Pool
importSystem *runtime.ImportSystem
autoEscape bool
trimBlocks bool
lstripBlocks bool
keepTrailingNewline bool
undefinedBehavior runtime.UndefinedBehavior
extensionConfig map[string]interface{} // Extension-specific configuration
varStartString string
varEndString string
blockStartString string
blockEndString string
commentStartString string
commentEndString string
}
// EnvironmentOption is a functional option for configuring an Environment.
// Use the With* functions (WithLoader, WithAutoEscape, etc.) to create options.
type EnvironmentOption func(*Environment)
// hashString generates a content-based cache key for template strings
// Uses FNV-1a hash algorithm for fast, uniform distribution
func hashString(s string) string {
h := fnv.New64a()
h.Write([]byte(s))
return fmt.Sprintf("__string__%x", h.Sum64())
}
// NewEnvironment creates a new template Environment with the given options.
// By default, auto-escaping is enabled and undefined variables are handled silently.
func NewEnvironment(opts ...EnvironmentOption) *Environment {
inheritanceCache := runtime.NewInheritanceCache()
env := &Environment{
filterRegistry: filters.NewRegistry(),
macroRegistry: macros.NewMacroRegistry(),
testRegistry: branching.NewTestRegistry(),
extensionRegistry: extensions.NewRegistry(),
globals: make(map[string]interface{}),
tests: make(map[string]TestFunc), // deprecated
cache: make(map[string]*Template),
stringCache: make(map[string]*Template),
inheritanceCache: inheritanceCache,
extensionConfig: make(map[string]interface{}),
autoEscape: true,
undefinedBehavior: runtime.UndefinedSilent, // Default to silent undefined
varStartString: "{{",
varEndString: "}}",
blockStartString: "{%",
blockEndString: "%}",
commentStartString: "{#",
commentEndString: "#}",
}
for _, opt := range opts {
opt(env)
}
env.filterRegistry.SetTestLookup(func(name string) (func(interface{}, ...interface{}) (bool, error), bool) {
t, ok := env.testRegistry.Get(name)
return t, ok
})
// Initialize evaluator pool for performance
env.evaluatorPool = sync.Pool{
New: func() interface{} {
eval := runtime.NewEvaluator()
eval.SetUndefinedBehavior(env.undefinedBehavior)
return eval
},
}
// Initialize shared import system (reused across renders)
templateLoader := runtime.NewSimpleTemplateLoader(env)
env.importSystem = runtime.NewImportSystem(templateLoader, nil)
env.importSystem.SetInheritanceResolver(func(name string, ast *parser.TemplateNode, ctx runtime.Context, eval runtime.Evaluator) (*parser.TemplateNode, error) {
tmpl, err := env.GetTemplate(name)
if err != nil || !tmpl.hasInheritanceDirectives() {
return ast, err
}
return env.getInheritanceProcessor().ResolveInheritanceWith(&templateAdapter{template: tmpl}, ctx, eval)
})
registerBuiltinTests(env)
registerBuiltinGlobals(env)
// Set up extension registry with environment reference
env.extensionRegistry.SetEnvironment(env)
// Note: inheritanceProcessor will be initialized lazily to avoid import cycles
return env
}
// GetTemplate loads and returns a compiled template by name using the configured loader.
// Templates are cached after first compilation; subsequent calls return the cached version.
func (e *Environment) GetTemplate(name string) (*Template, error) {
e.cacheMutex.RLock()
if tmpl, ok := e.cache[name]; ok {
e.cacheMutex.RUnlock()
return tmpl, nil
}
e.cacheMutex.RUnlock()
if e.loader == nil {
return nil, fmt.Errorf("no loader configured for environment")
}
source, err := e.loader.GetSource(name)
if err != nil {
// A template that exists but cannot be read is an error, not "not found"
if loader.IsReadError(err) {
return nil, fmt.Errorf("failed to load template %q: %w", name, err)
}
return nil, &runtime.TemplateNotFoundError{Name: name, Err: err}
}
tmpl, err := e.compile(name, source)
if err != nil {
return nil, err
}
tmpl.cacheKey = name
e.cacheMutex.Lock()
e.cache[name] = tmpl
e.cacheMutex.Unlock()
return tmpl, nil
}
// FromString compiles a template from a string source.
// The compiled template is cached using a content hash as the cache key.
func (e *Environment) FromString(source string) (*Template, error) {
// Generate cache key from content hash (Phase 2 optimization)
cacheKey := hashString(source)
// Check cache first; a hash collision compiles the source uncached
e.cacheMutex.RLock()
tmpl, ok := e.stringCache[cacheKey]
e.cacheMutex.RUnlock()
if ok && tmpl.source == source {
return tmpl, nil
}
collision := ok
// Compile if not cached (use "<string>" as display name)
tmpl, err := e.compile("<string>", source)
if err != nil {
return nil, err
}
if collision {
return tmpl, nil
}
// Store in cache with hash key
tmpl.cacheKey = cacheKey
e.cacheMutex.Lock()
e.stringCache[cacheKey] = tmpl
e.cacheMutex.Unlock()
return tmpl, nil
}
// SetLoader sets the template loader for the environment.
func (e *Environment) SetLoader(loader Loader) {
e.loader = loader
}
func (e *Environment) AddFilterLegacy(name string, filter FilterFunc) error {
return e.filterRegistry.Register(name, filters.FilterFunc(filter))
}
// ApplyFilterKwargs applies a filter with keyword arguments, binding them to
// the filter's declared parameters.
func (e *Environment) ApplyFilterKwargs(name string, value interface{}, args []interface{}, kwargs map[string]interface{}) (interface{}, error) {
return e.filterRegistry.ApplyKwargs(name, value, args, kwargs)
}
// SetFilterParams declares the parameter names of a registered filter so that
// templates can pass them as keyword arguments. Positional calls are unchanged.
func (e *Environment) SetFilterParams(name string, params ...filters.Param) error {
return e.filterRegistry.SetParams(name, params...)
}
// AddFilterWithParams registers a filter and declares its parameter names in
// one step. Keyword arguments are bound to these positions; an unfilled
// position before a bound one receives its Param's Default (nil if unset).
func (e *Environment) AddFilterWithParams(name string, filter FilterFunc, params ...filters.Param) error {
return e.filterRegistry.RegisterWithParams(name, filters.FilterFunc(filter), params...)
}
func (e *Environment) GetFilter(name string) (FilterFunc, bool) {
f, ok := e.filterRegistry.Get(name)
if !ok {
return nil, false
}
return FilterFunc(f), true
}
func (e *Environment) ApplyFilter(name string, value interface{}, args ...interface{}) (interface{}, error) {
return e.filterRegistry.Apply(name, value, args...)
}
// AddGlobal registers a global variable that will be available in all templates rendered by this environment.
func (e *Environment) AddGlobal(name string, value interface{}) {
e.globalsMu.Lock()
defer e.globalsMu.Unlock()
e.globals[name] = value
}
// lookupGlobal reads one global under the lock.
func (e *Environment) lookupGlobal(key string) (interface{}, bool) {
e.globalsMu.RLock()
defer e.globalsMu.RUnlock()
v, ok := e.globals[key]
return v, ok
}
// AddExtension registers an extension with the environment
func (e *Environment) AddExtension(extension extensions.Extension) error {
return e.extensionRegistry.Register(extension)
}
// GetExtensionRegistry returns the extension registry
func (e *Environment) GetExtensionRegistry() *extensions.Registry {
return e.extensionRegistry
}
// IsCustomTag returns true if the tag is handled by an extension
func (e *Environment) IsCustomTag(tagName string) bool {
return e.extensionRegistry.IsCustomTag(tagName)
}
// GetExtensionForTag returns the extension that handles the given tag
func (e *Environment) GetExtensionForTag(tagName string) (extensions.Extension, bool) {
return e.extensionRegistry.GetExtensionForTag(tagName)
}
// ExtensionEnvironment interface implementation
// GetExtension retrieves another extension by name
func (e *Environment) GetExtension(name string) (extensions.Extension, bool) {
return e.extensionRegistry.GetExtension(name)
}
// AddFilter adds a custom filter (for extensions and legacy support)
func (e *Environment) AddFilter(name string, filter interface{}) error {
// Handle legacy FilterFunc type
if filterFunc, ok := filter.(FilterFunc); ok {
return e.filterRegistry.Register(name, filters.FilterFunc(filterFunc))
}
// Handle filters.FilterFunc type
if filterFunc, ok := filter.(filters.FilterFunc); ok {
return e.filterRegistry.Register(name, filterFunc)
}
// For other types, try to convert to filters.FilterFunc
if filterFunc, ok := filter.(func(interface{}, ...interface{}) (interface{}, error)); ok {
return e.filterRegistry.Register(name, filters.FilterFunc(filterFunc))
}
return fmt.Errorf("unsupported filter type: %T", filter)
}
// AddTest adds a custom test (for extensions and legacy support)
func (e *Environment) AddTest(name string, test interface{}) error {
// Handle legacy TestFunc type
if testFunc, ok := test.(TestFunc); ok {
// Legacy TestFunc - wrap it for the new registry
wrappedTest := func(value interface{}, args ...interface{}) (bool, error) {
return testFunc(value, args...)
}
// Register in new registry
if err := e.testRegistry.Register(name, branching.TestFunc(wrappedTest)); err != nil {
return err
}
// Also store in legacy map for backwards compatibility
if _, exists := e.tests[name]; exists {
return fmt.Errorf("test %q already registered", name)
}
e.tests[name] = testFunc
return nil
}
// Handle branching.TestFunc type
if testFunc, ok := test.(branching.TestFunc); ok {
return e.testRegistry.Register(name, testFunc)
}
// For other types, try to convert to branching.TestFunc
if testFunc, ok := test.(func(interface{}, ...interface{}) (bool, error)); ok {
return e.testRegistry.Register(name, branching.TestFunc(testFunc))
}
return fmt.Errorf("unsupported test type: %T", test)
}
// GetConfig gets environment-level configuration for extensions
func (e *Environment) GetConfig(key string) (interface{}, bool) {
value, exists := e.extensionConfig[key]
return value, exists
}
// SetConfig sets environment-level configuration for extensions
func (e *Environment) SetConfig(key string, value interface{}) {
e.extensionConfig[key] = value
}
// GetTest retrieves a test function by name
func (e *Environment) GetTest(name string) (branching.TestFunc, bool) {
return e.testRegistry.Get(name)
}
// ListTests returns all available test names
func (e *Environment) ListTests() []string {
return e.testRegistry.List()
}
// ApplyTest applies a test to a value
func (e *Environment) ApplyTest(name string, value interface{}, args ...interface{}) (bool, error) {
// A test registered under either name wins over the built-in meaning
if _, registered := e.testRegistry.Get(name); registered {
return e.testRegistry.Apply(name, value, args...)
}
switch name {
case "filter":
// x is filter: x names a filter of this environment
filterName, ok := value.(string)
if !ok {
return false, nil
}
_, found := e.filterRegistry.Get(filterName)
return found, nil
case "test":
// x is test: x names a test of this environment
testName, ok := value.(string)
if !ok {
return false, nil
}
_, found := e.testRegistry.Get(testName)
return found || testName == "filter" || testName == "test", nil
}
return e.testRegistry.Apply(name, value, args...)
}
func (e *Environment) SetDelimiters(varStart, varEnd, blockStart, blockEnd string) {
e.varStartString = varStart
e.varEndString = varEnd
e.blockStartString = blockStart
e.blockEndString = blockEnd
}
func (e *Environment) SetCommentDelimiters(start, end string) {
e.commentStartString = start
e.commentEndString = end
}
// GetLoader returns the current template loader
func (e *Environment) GetLoader() Loader {
return e.loader
}
// ListFilters returns all available filter names
func (e *Environment) ListFilters() []string {
return e.filterRegistry.List()
}
// Macro management methods
// GetMacro retrieves a macro by name
//
// Deprecated: the environment-wide macro registry mixes macros from every
// compiled template and binds arguments differently from template calls. It
// will be removed in a later minor release. Call macros from a template
// ({% import %} or {% from %}) instead.
func (e *Environment) GetMacro(name string) (*macros.Macro, bool) {
return e.macroRegistry.Get(name)
}
// ListMacros returns all available macro names
//
// Deprecated: the environment-wide macro registry mixes macros from every
// compiled template and binds arguments differently from template calls. It
// will be removed in a later minor release. Call macros from a template
// ({% import %} or {% from %}) instead.
func (e *Environment) ListMacros() []string {
return e.macroRegistry.List()
}
// CallMacro calls a macro with the given arguments
//
// Deprecated: the environment-wide macro registry mixes macros from every
// compiled template and binds arguments differently from template calls. It
// will be removed in a later minor release. Call macros from a template
// ({% import %} or {% from %}) instead.
func (e *Environment) CallMacro(name string, ctx Context, args []interface{}, kwargs map[string]interface{}) (result interface{}, err error) {
defer func() {
if r := recover(); r != nil {
result = nil
err = &RenderPanicError{Value: r, Stack: debug.Stack()}
}
}()
// Create runtime context adapter
runtimeCtx := &TemplateContextAdapter{ctx: ctx, env: e}
// Create evaluator
evaluator := runtime.NewEvaluator()
// Set up import system for the evaluator
loader := runtime.NewSimpleTemplateLoader(e)
importSystem := runtime.NewImportSystem(loader, evaluator)
evaluator.SetImportSystem(importSystem)
return e.macroRegistry.CallMacro(name, runtimeCtx, evaluator, args, kwargs)
}
// ClearMacros clears all registered macros
//
// Deprecated: the environment-wide macro registry mixes macros from every
// compiled template and binds arguments differently from template calls. It
// will be removed in a later minor release. Call macros from a template
// ({% import %} or {% from %}) instead.
func (e *Environment) ClearMacros() {
e.macroRegistry.Clear()
}
// registerMacrosFromAST walks the AST and registers any macro definitions found
func (e *Environment) registerMacrosFromAST(node parser.Node, templateName string) {
switch n := node.(type) {
case *parser.TemplateNode:
for _, child := range n.Children {
e.registerMacrosFromAST(child, templateName)
}
case *parser.MacroNode:
// Convert defaults from ExpressionNode to interface{}
defaults := make(map[string]interface{})
for key, expr := range n.Defaults {
// For now, we'll store the expression itself
// In a full implementation, we'd evaluate constant expressions
defaults[key] = expr
}
macro := ¯os.Macro{
Name: n.Name,
Parameters: n.Parameters,
Defaults: defaults,
Body: n.Body,
Template: templateName,
}
// Register the macro (ignore errors for now)
e.macroRegistry.Register(n.Name, macro)
case *parser.IfNode:
for _, child := range n.Body {
e.registerMacrosFromAST(child, templateName)
}
for _, elifNode := range n.ElseIfs {
for _, child := range elifNode.Body {
e.registerMacrosFromAST(child, templateName)
}
}
for _, child := range n.Else {
e.registerMacrosFromAST(child, templateName)
}
case *parser.ForNode:
for _, child := range n.Body {
e.registerMacrosFromAST(child, templateName)
}
for _, child := range n.Else {
e.registerMacrosFromAST(child, templateName)
}
case *parser.BlockNode:
for _, child := range n.Body {
e.registerMacrosFromAST(child, templateName)
}
// Other node types don't need special handling for macro registration
}
}
func (e *Environment) compile(name, source string) (*Template, error) {
// Create lexer configuration from environment settings
lexerConfig := &lexer.LexerConfig{
VarStartString: e.varStartString,
VarEndString: e.varEndString,
BlockStartString: e.blockStartString,
BlockEndString: e.blockEndString,
CommentStartString: e.commentStartString,
CommentEndString: e.commentEndString,
TrimBlocks: e.trimBlocks,
LstripBlocks: e.lstripBlocks,
KeepTrailingNewline: e.keepTrailingNewline,
}
// Tokenize the source
l := lexer.NewLexer(source, lexerConfig)
tokens, err := l.Tokenize()
if err != nil {
return nil, fmt.Errorf("lexer error in template %s: %v", name, err)
}
// Parse the tokens into an AST
var ast *parser.TemplateNode
// Use extension-aware parser if we have extensions registered
if len(e.extensionRegistry.GetAllExtensions()) > 0 {
extParser := extensions.NewExtensionAwareParser(tokens, e.extensionRegistry)
var err error
ast, err = extParser.Parse()
if err != nil {
return nil, fmt.Errorf("parser error in template %s: %v", name, err)
}
} else {
// Use standard parser if no extensions
p := parser.NewParser(tokens)
var err error
ast, err = p.Parse()
if err != nil {
return nil, fmt.Errorf("parser error in template %s: %v", name, err)
}
}
// Set the template name in the AST
ast.Name = name
// Register any macros found in the template
e.registerMacrosFromAST(ast, name)
// NOTE: Inheritance resolution moved to render-time to avoid circular dependencies
// Templates are now compiled with their raw AST preserved, allowing proper
// template hierarchy loading without compilation-time circular references
return &Template{
name: name,
source: source,
env: e,
ast: ast,
}, nil
}
// WithLoader returns an EnvironmentOption that sets the template loader.
// The loader is used by GetTemplate to locate and read template sources.
func WithLoader(loader Loader) EnvironmentOption {
return func(e *Environment) {
e.loader = loader
}
}
// WithAutoEscape returns an EnvironmentOption that enables or disables HTML auto-escaping.
// When enabled (the default), template output is automatically HTML-escaped.
func WithAutoEscape(enabled bool) EnvironmentOption {
return func(e *Environment) {
e.autoEscape = enabled
}
}
// WithTrimBlocks returns an EnvironmentOption that enables or disables trimming of
// the first newline after a block tag.
func WithTrimBlocks(enabled bool) EnvironmentOption {
return func(e *Environment) {
e.trimBlocks = enabled
}
}
// WithLstripBlocks returns an EnvironmentOption that enables or disables stripping of
// leading whitespace and tabs from the start of a line to a block tag.
func WithLstripBlocks(enabled bool) EnvironmentOption {
return func(e *Environment) {
e.lstripBlocks = enabled
}
}
// WithKeepTrailingNewline returns an EnvironmentOption that preserves
// the trailing newline at the end of rendered templates.
func WithKeepTrailingNewline(enabled bool) EnvironmentOption {
return func(e *Environment) {
e.keepTrailingNewline = enabled
}
}
// WithTruncateLeeway sets the default leeway of the truncate filter (Jinja2's
// truncate.leeway policy, default 5). Use 0 when truncated text must fit.
func WithTruncateLeeway(n int) EnvironmentOption {
return func(e *Environment) {
e.filterRegistry.Replace("truncate", filters.TruncateFilterWithLeeway(n))
}
}
// WithStrictUndefined enables strict undefined variable handling
func WithStrictUndefined(enabled bool) EnvironmentOption {
return func(e *Environment) {
if enabled {
e.undefinedBehavior = runtime.UndefinedStrict
} else {
e.undefinedBehavior = runtime.UndefinedSilent
}
}
}
// WithDebugUndefined enables debug undefined variable handling
func WithDebugUndefined(enabled bool) EnvironmentOption {
return func(e *Environment) {
if enabled {
e.undefinedBehavior = runtime.UndefinedDebug
} else {
e.undefinedBehavior = runtime.UndefinedSilent
}
}
}
// WithUndefinedBehavior sets the undefined variable behavior
func WithUndefinedBehavior(behavior runtime.UndefinedBehavior) EnvironmentOption {
return func(e *Environment) {
e.undefinedBehavior = behavior
}
}
// Additional Environment methods
// ClearCache clears the template cache
func (e *Environment) ClearCache() {
e.cacheMutex.Lock()
e.cache = make(map[string]*Template)
e.stringCache = make(map[string]*Template)
e.cacheMutex.Unlock()
e.ClearInheritanceCache()
}
// GetCacheSize returns the number of cached templates
func (e *Environment) GetCacheSize() int {
e.cacheMutex.RLock()
defer e.cacheMutex.RUnlock()
return len(e.cache) + len(e.stringCache)
}
// Inheritance cache management methods
// ClearInheritanceCache clears all inheritance-related caches
func (e *Environment) ClearInheritanceCache() {
e.inheritanceCacheMutex.Lock()
defer e.inheritanceCacheMutex.Unlock()
e.inheritanceCache.ClearAll()
}
// InvalidateTemplate removes template from both regular and inheritance caches
func (e *Environment) InvalidateTemplate(templateName string) {
// Remove from regular template cache
e.cacheMutex.Lock()
delete(e.cache, templateName)
e.cacheMutex.Unlock()
// Remove from inheritance cache
e.inheritanceCacheMutex.Lock()
e.inheritanceCache.InvalidateTemplate(templateName)
e.inheritanceCacheMutex.Unlock()
}
// GetInheritanceCacheStats returns inheritance cache performance statistics
func (e *Environment) GetInheritanceCacheStats() runtime.CacheStats {
e.inheritanceCacheMutex.RLock()
defer e.inheritanceCacheMutex.RUnlock()
return e.inheritanceCache.GetStats()
}
// ConfigureInheritanceCache allows tuning of inheritance cache settings.
// resolvedTTL is ignored and deprecated: resolved templates are not cached.
func (e *Environment) ConfigureInheritanceCache(hierarchyTTL, resolvedTTL time.Duration, maxEntries int) {
e.inheritanceCacheMutex.Lock()
defer e.inheritanceCacheMutex.Unlock()
e.inheritanceCache.SetHierarchyTTL(hierarchyTTL)
e.inheritanceCache.SetMaxEntries(maxEntries)
}
// getInheritanceProcessor returns the inheritance processor, initializing it if needed
func (e *Environment) getInheritanceProcessor() *runtime.InheritanceProcessor {
e.inheritanceCacheMutex.Lock()
defer e.inheritanceCacheMutex.Unlock()
if e.inheritanceProcessor == nil {
// Initialize processor with shared cache (lazy initialization to avoid import cycles)
e.inheritanceProcessor = runtime.NewInheritanceProcessorWithCache(&environmentAdapter{env: e}, e.inheritanceCache)
}
return e.inheritanceProcessor
}
// ListTemplates returns all available template names from the loader
func (e *Environment) ListTemplates() ([]string, error) {
if e.loader == nil {
return nil, fmt.Errorf("no loader configured")
}
return e.loader.ListTemplates()
}
// RenderString is a convenience method to compile and render a template from string
func (e *Environment) RenderString(source string, context Context) (string, error) {
template, err := e.FromString(source)
if err != nil {
return "", err
}
return template.Render(context)
}
// RenderTemplate is a convenience method to load and render a template by name
func (e *Environment) RenderTemplate(name string, context Context) (string, error) {
template, err := e.GetTemplate(name)
if err != nil {
return "", err
}
return template.Render(context)
}
func registerBuiltinTests(env *Environment) {
// Will be populated when we implement tests
}
// Global environment instance for convenience functions
var defaultEnv *Environment
// init initializes the default environment
func init() {
defaultEnv = NewEnvironment()
}
// SetDefaultLoader sets the loader for the default environment
func SetDefaultLoader(loader Loader) {
defaultEnv.SetLoader(loader)
}
// FromString is a convenience function that uses the default environment
func FromString(source string) (*Template, error) {
return defaultEnv.FromString(source)
}
// GetTemplate is a convenience function that uses the default environment
func GetTemplate(name string) (*Template, error) {
return defaultEnv.GetTemplate(name)
}
// RenderString is a convenience function using the default environment
func RenderString(source string, context Context) (string, error) {
return defaultEnv.RenderString(source, context)
}
// RenderTemplate is a convenience function using the default environment
func RenderTemplate(name string, context Context) (string, error) {
return defaultEnv.RenderTemplate(name, context)
}
// registerBuiltinGlobals registers all built-in global functions
func registerBuiltinGlobals(env *Environment) {
// namespace() function
env.AddGlobal("namespace", runtime.KeepMarkupFunc(namespaceFunction))
// range() function
env.AddGlobal("range", rangeFunction)
// dict() function
env.AddGlobal("dict", runtime.KeepMarkupFunc(dictFunction))
// cycler() function
env.AddGlobal("cycler", runtime.KeepMarkupFunc(cyclerFunction))
// joiner() function
env.AddGlobal("joiner", runtime.KeepMarkupFunc(joinerFunction))
// lipsum() function
env.AddGlobal("lipsum", lipsumFunction)
// zip() function
env.AddGlobal("zip", zipFunction)
// enumerate() function
env.AddGlobal("enumerate", enumerateFunction)
// url_for() function
env.AddGlobal("url_for", urlForFunction)
}