-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
1237 lines (1036 loc) · 34.9 KB
/
parser.go
File metadata and controls
1237 lines (1036 loc) · 34.9 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
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
package twig
import (
"fmt"
"strconv"
"strings"
)
// Token types
const (
TOKEN_TEXT = iota
TOKEN_VAR_START // {{
TOKEN_VAR_END // }}
TOKEN_BLOCK_START // {%
TOKEN_BLOCK_END // %}
TOKEN_COMMENT_START // {#
TOKEN_COMMENT_END // #}
TOKEN_NAME
TOKEN_NUMBER
TOKEN_STRING
TOKEN_OPERATOR
TOKEN_PUNCTUATION
TOKEN_EOF
// Whitespace control token types
TOKEN_VAR_START_TRIM // {{-
TOKEN_VAR_END_TRIM // -}}
TOKEN_BLOCK_START_TRIM // {%-
TOKEN_BLOCK_END_TRIM // -%}
)
// Parser handles parsing Twig templates into node trees
type Parser struct {
source string
tokens []Token
tokenIndex int
filename string
cursor int
line int
blockHandlers map[string]blockHandlerFunc
}
type blockHandlerFunc func(*Parser) (Node, error)
// Token represents a lexical token
type Token struct {
Type int
Value string
Line int
}
// Parse parses a template source into a node tree
func (p *Parser) Parse(source string) (Node, error) {
p.source = source
p.cursor = 0
p.line = 1
p.tokenIndex = 0
// Initialize default block handlers
p.initBlockHandlers()
// Use the optimized tokenizer for maximum performance and minimal allocations
// This will treat everything outside twig tags as TEXT tokens
var err error
// Use zero allocation tokenizer for optimal performance
tokenizer := GetTokenizer(p.source, 0)
// Use optimized version for larger templates
if len(p.source) > 4096 {
// Use the optimized tag detection for large templates
p.tokens, err = tokenizer.TokenizeOptimized()
} else {
// Use regular tokenization for smaller templates
p.tokens, err = tokenizer.TokenizeHtmlPreserving()
}
// Apply whitespace control to handle whitespace trimming directives
if err == nil {
tokenizer.ApplyWhitespaceControl()
}
// Return the tokenizer to the pool
ReleaseTokenizer(tokenizer)
if err != nil {
return nil, fmt.Errorf("tokenization error: %w", err)
}
// Template tokenization complete
// Whitespace control has already been applied by the tokenizer
// Parse tokens into nodes
nodes, err := p.parseOuterTemplate()
if err != nil {
// Clean up token slice on error
ReleaseTokenSlice(p.tokens)
return nil, fmt.Errorf("parsing error: %w", err)
}
// Clean up token slice after successful parsing
ReleaseTokenSlice(p.tokens)
return NewRootNode(nodes, 1), nil
}
// Initialize block handlers for different tag types
func (p *Parser) initBlockHandlers() {
p.blockHandlers = map[string]blockHandlerFunc{
"if": p.parseIf,
"for": p.parseFor,
"block": p.parseBlock,
"extends": p.parseExtends,
"include": p.parseInclude,
"set": p.parseSet,
"do": p.parseDo,
"macro": p.parseMacro,
"import": p.parseImport,
"from": p.parseFrom,
"spaceless": p.parseSpaceless,
"verbatim": p.parseVerbatim,
"apply": p.parseApply,
// Special closing tags - they will be handled in their corresponding open tag parsers
"endif": p.parseEndTag,
"endfor": p.parseEndTag,
"endmacro": p.parseEndTag,
"endblock": p.parseEndTag,
"endspaceless": p.parseEndTag,
"endapply": p.parseEndTag,
"else": p.parseEndTag,
"elseif": p.parseEndTag,
"endverbatim": p.parseEndTag,
}
}
func isDigit(c byte) bool {
return c >= '0' && c <= '9'
}
func isOperator(c byte) bool {
return strings.ContainsRune("+-*/=<>!&~^%", rune(c))
}
func isPunctuation(c byte) bool {
return strings.ContainsRune("()[]{},.:|?", rune(c))
}
func isWhitespace(c byte) bool {
return c == ' ' || c == '\t' || c == '\n' || c == '\r'
}
// processEscapeSequences handles escape sequences in string literals
func processEscapeSequences(s string) string {
var result strings.Builder
result.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] == '\\' && i+1 < len(s) {
i++
switch s[i] {
case 'n':
result.WriteByte('\n')
case 'r':
result.WriteByte('\r')
case 't':
result.WriteByte('\t')
case '\\':
result.WriteByte('\\')
case '"':
result.WriteByte('"')
case '\'':
result.WriteByte('\'')
case '{':
// Special case for escaping Twig variable/block syntax
result.WriteByte('{')
case '}':
// Special case for escaping Twig variable/block syntax
result.WriteByte('}')
default:
result.WriteByte(s[i])
}
} else {
result.WriteByte(s[i])
}
}
return result.String()
}
// Parse the outer level of a template (text, print tags, blocks)
func (p *Parser) parseOuterTemplate() ([]Node, error) {
var nodes []Node
for p.tokenIndex < len(p.tokens) && p.tokens[p.tokenIndex].Type != TOKEN_EOF {
token := p.tokens[p.tokenIndex]
switch token.Type {
case TOKEN_TEXT:
nodes = append(nodes, NewTextNode(token.Value, token.Line))
p.tokenIndex++
case TOKEN_VAR_START, TOKEN_VAR_START_TRIM:
// Handle both normal and whitespace trimming var start tokens
p.tokenIndex++
expr, err := p.parseExpression()
if err != nil {
return nil, err
}
nodes = append(nodes, NewPrintNode(expr, token.Line))
// Check for either normal or whitespace trimming var end tokens
if p.tokenIndex >= len(p.tokens) || !isVarEndToken(p.tokens[p.tokenIndex].Type) {
return nil, fmt.Errorf("expected }} or -}} at line %d", token.Line)
}
p.tokenIndex++
case TOKEN_BLOCK_START, TOKEN_BLOCK_START_TRIM:
// Handle both normal and whitespace trimming block start tokens
p.tokenIndex++
if p.tokenIndex >= len(p.tokens) || p.tokens[p.tokenIndex].Type != TOKEN_NAME {
return nil, fmt.Errorf("expected block name at line %d", token.Line)
}
blockName := p.tokens[p.tokenIndex].Value
p.tokenIndex++
// Check if this is a control ending tag (endif, endfor, endblock, etc.)
if blockName == "endif" || blockName == "endfor" || blockName == "endblock" ||
blockName == "endmacro" || blockName == "else" || blockName == "elseif" ||
blockName == "endspaceless" || blockName == "endapply" || blockName == "endverbatim" {
// We should return to the parent parser that's handling the parent block
// First move back two steps to the start of the block tag
p.tokenIndex -= 2
return nodes, nil
}
// Check if we have a handler for this block type
handler, ok := p.blockHandlers[blockName]
if !ok {
return nil, fmt.Errorf("unknown block type '%s' at line %d", blockName, token.Line)
}
node, err := handler(p)
if err != nil {
return nil, err
}
nodes = append(nodes, node)
case TOKEN_COMMENT_START:
// Skip comments
p.tokenIndex++
startLine := token.Line
// Find the end of the comment
for p.tokenIndex < len(p.tokens) && p.tokens[p.tokenIndex].Type != TOKEN_COMMENT_END {
p.tokenIndex++
}
if p.tokenIndex >= len(p.tokens) {
return nil, fmt.Errorf("unclosed comment starting at line %d", startLine)
}
p.tokenIndex++
// Add special handling for trim token types
case TOKEN_VAR_END_TRIM, TOKEN_BLOCK_END_TRIM:
// These should have been handled with their corresponding start tokens
return nil, fmt.Errorf("unexpected token %v at line %d", token.Type, token.Line)
// Add special handling for TOKEN_NAME outside of a tag
case TOKEN_NAME, TOKEN_PUNCTUATION, TOKEN_OPERATOR, TOKEN_STRING, TOKEN_NUMBER:
// For raw names, punctuation, operators, and literals not inside tags, convert to text
// In many languages, the text "true" is a literal boolean, but in our parser it's just a name token
// outside of an expression context
// Special handling for text content words - add spaces between consecutive text tokens
// This fixes issues with the spaceless tag's handling of text content
if token.Type == TOKEN_NAME && p.tokenIndex+1 < len(p.tokens) &&
p.tokens[p.tokenIndex+1].Type == TOKEN_NAME &&
p.tokens[p.tokenIndex+1].Line == token.Line {
// Look ahead for consecutive name tokens and join them with spaces
var textContent strings.Builder
textContent.WriteString(token.Value)
currentLine := token.Line
p.tokenIndex++ // Skip the first token as we've already added it
// Collect consecutive name tokens on the same line
for p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_NAME &&
p.tokens[p.tokenIndex].Line == currentLine {
textContent.WriteString(" ") // Add space between words
textContent.WriteString(p.tokens[p.tokenIndex].Value)
p.tokenIndex++
}
nodes = append(nodes, NewTextNode(textContent.String(), token.Line))
} else {
// Regular handling for single text tokens
nodes = append(nodes, NewTextNode(token.Value, token.Line))
p.tokenIndex++
}
default:
return nil, fmt.Errorf("unexpected token %v at line %d", token.Type, token.Line)
}
}
return nodes, nil
}
// Parse an expression
func (p *Parser) parseExpression() (Node, error) {
// Parse the primary expression first
expr, err := p.parseSimpleExpression()
if err != nil {
return nil, err
}
// Check for array access with square brackets
for p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "[" {
// Get the line number for error reporting
line := p.tokens[p.tokenIndex].Line
// Skip the opening bracket
p.tokenIndex++
// Parse the index expression
indexExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
// Expect closing bracket
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != "]" {
return nil, fmt.Errorf("expected closing bracket after array index at line %d", line)
}
p.tokenIndex++ // Skip closing bracket
// Create a GetItemNode
expr = NewGetItemNode(expr, indexExpr, line)
}
// Now check for filter operator (|)
// Process all filters in a loop to handle consecutive filters properly
for p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "|" {
expr, err = p.parseFilters(expr)
if err != nil {
return nil, err
}
}
// Check for binary operators (and, or, ==, !=, <, >, etc.)
// Loop to handle multiple binary operators in sequence, such as 'hello' ~ ' ' ~ 'world'
for p.tokenIndex < len(p.tokens) &&
(p.tokens[p.tokenIndex].Type == TOKEN_OPERATOR ||
(p.tokens[p.tokenIndex].Type == TOKEN_NAME &&
(p.tokens[p.tokenIndex].Value == "and" ||
p.tokens[p.tokenIndex].Value == "or" ||
p.tokens[p.tokenIndex].Value == "in" ||
p.tokens[p.tokenIndex].Value == "not" ||
p.tokens[p.tokenIndex].Value == "is" ||
p.tokens[p.tokenIndex].Value == "matches" ||
p.tokens[p.tokenIndex].Value == "starts" ||
p.tokens[p.tokenIndex].Value == "ends"))) {
expr, err = p.parseBinaryExpression(expr)
if err != nil {
return nil, err
}
}
// Check for ternary operator (? :)
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "?" {
return p.parseConditionalExpression(expr)
}
return expr, nil
}
// Parse ternary conditional expression (condition ? true_expr : false_expr)
func (p *Parser) parseConditionalExpression(condition Node) (Node, error) {
line := p.tokens[p.tokenIndex].Line
// Skip the "?" token
p.tokenIndex++
// Parse the "true" expression
trueExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
// Expect ":" token
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != ":" {
return nil, fmt.Errorf("expected ':' after true expression in conditional at line %d", line)
}
p.tokenIndex++ // Skip ":"
// Parse the "false" expression
falseExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
// Create a conditional node
return &ConditionalNode{
ExpressionNode: ExpressionNode{
exprType: ExprConditional,
line: line,
},
condition: condition,
trueExpr: trueExpr,
falseExpr: falseExpr,
}, nil
}
// Parse a simple expression (literal, variable, function call, array)
func (p *Parser) parseSimpleExpression() (Node, error) {
if p.tokenIndex >= len(p.tokens) {
return nil, fmt.Errorf("unexpected end of template")
}
token := p.tokens[p.tokenIndex]
// Handle unary operators like 'not' and unary minus/plus
if (token.Type == TOKEN_NAME && token.Value == "not") ||
(token.Type == TOKEN_OPERATOR && (token.Value == "-" || token.Value == "+")) {
// Skip the operator token
operator := token.Value
p.tokenIndex++
// Get the line number for the unary node
line := token.Line
// Parse the operand
operand, err := p.parseSimpleExpression()
if err != nil {
return nil, err
}
// Create a unary node
return NewUnaryNode(operator, operand, line), nil
}
switch token.Type {
case TOKEN_STRING:
p.tokenIndex++
// For string literals, process escape sequences
processedValue := processEscapeSequences(token.Value)
return NewLiteralNode(processedValue, token.Line), nil
case TOKEN_NUMBER:
p.tokenIndex++
// Attempt to convert to int or float
if strings.Contains(token.Value, ".") {
// It's a float
val, _ := strconv.ParseFloat(token.Value, 64)
return NewLiteralNode(val, token.Line), nil
} else {
// It's an int
val, _ := strconv.Atoi(token.Value)
return NewLiteralNode(val, token.Line), nil
}
case TOKEN_NAME:
p.tokenIndex++
// Store the variable name for function calls
varName := token.Value
varLine := token.Line
// Special handling for boolean literals and null
if varName == "true" {
return NewLiteralNode(true, varLine), nil
} else if varName == "false" {
return NewLiteralNode(false, varLine), nil
} else if varName == "null" || varName == "nil" {
return NewLiteralNode(nil, varLine), nil
}
// Check if this is a function call (name followed by opening parenthesis)
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "(" {
// This is a function call
p.tokenIndex++ // Skip the opening parenthesis
// Parse arguments list
var args []Node
// If there are arguments (not empty parentheses)
if p.tokenIndex < len(p.tokens) &&
!(p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == ")") {
for {
// Parse each argument expression
argExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
args = append(args, argExpr)
// Check for comma separator between arguments
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "," {
p.tokenIndex++ // Skip comma
continue
}
// No comma, so must be end of argument list
break
}
}
// Expect closing parenthesis
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != ")" {
return nil, fmt.Errorf("expected closing parenthesis after function arguments at line %d", varLine)
}
p.tokenIndex++ // Skip closing parenthesis
// Create and return function node
return NewFunctionNode(varName, args, varLine), nil
}
// If not a function call, it's a regular variable
var result Node = NewVariableNode(varName, varLine)
// Check for attribute access (obj.attr) or method calls (obj.method())
for p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "." {
p.tokenIndex++
if p.tokenIndex >= len(p.tokens) || p.tokens[p.tokenIndex].Type != TOKEN_NAME {
return nil, fmt.Errorf("expected attribute name at line %d", varLine)
}
attrName := p.tokens[p.tokenIndex].Value
attrNode := NewLiteralNode(attrName, p.tokens[p.tokenIndex].Line)
p.tokenIndex++
// Check if this is a method call like (module.method())
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "(" {
if IsDebugEnabled() && debugger.level >= DebugVerbose {
LogVerbose("Detected module.method call: %s.%s(...)", varName, attrName)
}
// This is a method call with the method stored in attrName
// We'll use the moduleExpr field in FunctionNode to store the module expression
// Parse the arguments
p.tokenIndex++ // Skip opening parenthesis
// Parse arguments
var args []Node
// If there are arguments (not empty parentheses)
if p.tokenIndex < len(p.tokens) &&
!(p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == ")") {
for {
// Parse each argument expression
argExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
args = append(args, argExpr)
// Check for comma separator between arguments
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "," {
p.tokenIndex++ // Skip comma
continue
}
// No comma, so must be end of argument list
break
}
}
// Expect closing parenthesis
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != ")" {
return nil, fmt.Errorf("expected closing parenthesis after method arguments at line %d", varLine)
}
p.tokenIndex++ // Skip closing parenthesis
// Create a function call with the module expression and method name
result = &FunctionNode{
ExpressionNode: ExpressionNode{
exprType: ExprFunction,
line: varLine,
},
name: attrName,
args: args,
// Special handling - We'll store the module in the FunctionNode
moduleExpr: result,
}
} else {
// Regular attribute access (not a method call)
result = NewGetAttrNode(result, attrNode, varLine)
}
}
return result, nil
case TOKEN_PUNCTUATION:
// Handle array literals [1, 2, 3]
if token.Value == "[" {
return p.parseArrayExpression()
}
// Handle hash/map literals {'key': value}
if token.Value == "{" {
return p.parseMapExpression()
}
// Handle parenthesized expressions
if token.Value == "(" {
p.tokenIndex++ // Skip "("
// Check for unary operator immediately after opening parenthesis
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_OPERATOR &&
(p.tokens[p.tokenIndex].Value == "-" || p.tokens[p.tokenIndex].Value == "+") {
// Handle unary operation inside parentheses
unaryToken := p.tokens[p.tokenIndex]
operator := unaryToken.Value
line := unaryToken.Line
p.tokenIndex++ // Skip the operator
// Parse the operand
operand, err := p.parseExpression()
if err != nil {
return nil, err
}
// Create a unary node
expr := NewUnaryNode(operator, operand, line)
// Expect closing parenthesis
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != ")" {
return nil, fmt.Errorf("expected closing parenthesis at line %d", token.Line)
}
p.tokenIndex++ // Skip ")"
return expr, nil
}
// Regular parenthesized expression
expr, err := p.parseExpression()
if err != nil {
return nil, err
}
// Expect closing parenthesis
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != ")" {
return nil, fmt.Errorf("expected closing parenthesis at line %d", token.Line)
}
p.tokenIndex++ // Skip ")"
return expr, nil
}
default:
return nil, fmt.Errorf("unexpected token in expression at line %d", token.Line)
}
return nil, fmt.Errorf("unexpected token in expression at line %d", token.Line)
}
// Parse array expression [item1, item2, ...]
func (p *Parser) parseArrayExpression() (Node, error) {
// Save the line number for error reporting
line := p.tokens[p.tokenIndex].Line
// Skip the opening bracket
p.tokenIndex++
// Parse the array items
var items []Node
// Check if there are any items
if p.tokenIndex < len(p.tokens) &&
!(p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "]") {
for {
// Parse each item expression
itemExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
items = append(items, itemExpr)
// Check for comma separator between items
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "," {
p.tokenIndex++ // Skip comma
continue
}
// No comma, so must be end of array
break
}
}
// Expect closing bracket
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != "]" {
return nil, fmt.Errorf("expected closing bracket after array items at line %d", line)
}
p.tokenIndex++ // Skip closing bracket
// Create array node
return &ArrayNode{
ExpressionNode: ExpressionNode{
exprType: ExprArray,
line: line,
},
items: items,
}, nil
}
// parseMapExpression parses a hash/map literal expression, like {'key': value}
func (p *Parser) parseMapExpression() (Node, error) {
// Save the line number for error reporting
line := p.tokens[p.tokenIndex].Line
// Skip the opening brace
p.tokenIndex++
// Parse the map key-value pairs
items := make(map[Node]Node)
// Check if there are any items
if p.tokenIndex < len(p.tokens) &&
!(p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "}") {
for {
// Parse key expression
keyExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
// Expect colon separator
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != ":" {
return nil, fmt.Errorf("expected ':' after map key at line %d", line)
}
p.tokenIndex++ // Skip colon
// Parse value expression
valueExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
// Add key-value pair to map
items[keyExpr] = valueExpr
// Check for comma separator between items
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "," {
p.tokenIndex++ // Skip comma
continue
}
// No comma, so must be end of map
break
}
}
// Expect closing brace
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != "}" {
return nil, fmt.Errorf("expected closing brace after map items at line %d", line)
}
p.tokenIndex++ // Skip closing brace
// Create hash node
return &HashNode{
ExpressionNode: ExpressionNode{
exprType: ExprHash,
line: line,
},
items: items,
}, nil
}
// Parse filter expressions: variable|filter(args)
func (p *Parser) parseFilters(node Node) (Node, error) {
line := p.tokens[p.tokenIndex].Line
// Loop to handle multiple filters (e.g. var|filter1|filter2)
for p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "|" {
p.tokenIndex++ // Skip the | token
// Expect filter name
if p.tokenIndex >= len(p.tokens) || p.tokens[p.tokenIndex].Type != TOKEN_NAME {
return nil, fmt.Errorf("expected filter name at line %d", line)
}
filterName := p.tokens[p.tokenIndex].Value
p.tokenIndex++
// Check for filter arguments
var args []Node
// If there are arguments in parentheses
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "(" {
p.tokenIndex++ // Skip opening parenthesis
// Parse arguments
if p.tokenIndex < len(p.tokens) &&
!(p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == ")") {
for {
// Parse each argument expression
argExpr, err := p.parseExpression()
if err != nil {
return nil, err
}
args = append(args, argExpr)
// Check for comma separator
if p.tokenIndex < len(p.tokens) &&
p.tokens[p.tokenIndex].Type == TOKEN_PUNCTUATION &&
p.tokens[p.tokenIndex].Value == "," {
p.tokenIndex++ // Skip comma
continue
}
// No comma, so end of argument list
break
}
}
// Expect closing parenthesis
if p.tokenIndex >= len(p.tokens) ||
p.tokens[p.tokenIndex].Type != TOKEN_PUNCTUATION ||
p.tokens[p.tokenIndex].Value != ")" {
return nil, fmt.Errorf("expected closing parenthesis after filter arguments at line %d", line)
}
p.tokenIndex++ // Skip closing parenthesis
}
// Create a new FilterNode
node = &FilterNode{
ExpressionNode: ExpressionNode{
exprType: ExprFilter,
line: line,
},
node: node,
filter: filterName,
args: args,
}
}
return node, nil
}
// Operator precedence levels (higher number = higher precedence)
const (
PREC_LOWEST = 0
PREC_OR = 1 // or, ||
PREC_AND = 2 // and, &&
PREC_COMPARE = 3 // ==, !=, <, >, <=, >=, in, not in, matches, starts with, ends with
PREC_SUM = 4 // +, -
PREC_PRODUCT = 5 // *, /, %
PREC_POWER = 6 // ^
PREC_PREFIX = 7 // not, !, +, - (unary)
)
// Get operator precedence
func getOperatorPrecedence(operator string) int {
switch operator {
case "or", "||":
return PREC_OR
case "and", "&&":
return PREC_AND
case "==", "!=", "<", ">", "<=", ">=", "in", "not in", "matches", "starts with", "ends with", "is", "is not":
return PREC_COMPARE
case "+", "-", "~":
return PREC_SUM
case "*", "/", "%":
return PREC_PRODUCT
case "^":
return PREC_POWER
default:
return PREC_LOWEST
}
}
// Parse binary expressions (a + b, a and b, a in b, etc.)
func (p *Parser) parseBinaryExpression(left Node) (Node, error) {
token := p.tokens[p.tokenIndex]
operator := token.Value
line := token.Line
// Special handling for "not defined" pattern
// This is the common pattern used in Twig: {% if variable not defined %}
if operator == "not" && p.tokenIndex+1 < len(p.tokens) &&
p.tokens[p.tokenIndex+1].Type == TOKEN_NAME &&
p.tokens[p.tokenIndex+1].Value == "defined" {
// Next token should be "defined"
p.tokenIndex += 2 // Skip both "not" and "defined"
// Create a TestNode with "defined" test
testNode := &TestNode{
ExpressionNode: ExpressionNode{
exprType: ExprTest,
line: line,
},
node: left,
test: "defined",
args: []Node{},
}
// Then wrap it in a unary "not" node
return &UnaryNode{
ExpressionNode: ExpressionNode{
exprType: ExprUnary,
line: line,
},
operator: "not",
node: testNode,
}, nil
}
// Process multi-word operators
if token.Type == TOKEN_NAME {
// Handle 'not in' operator
if token.Value == "not" && p.tokenIndex+1 < len(p.tokens) &&
p.tokens[p.tokenIndex+1].Type == TOKEN_NAME &&
p.tokens[p.tokenIndex+1].Value == "in" {
operator = "not in"
p.tokenIndex += 2 // Skip both 'not' and 'in'
} else if token.Value == "is" && p.tokenIndex+1 < len(p.tokens) &&
p.tokens[p.tokenIndex+1].Type == TOKEN_NAME &&
p.tokens[p.tokenIndex+1].Value == "not" {
// Handle 'is not' operator
operator = "is not"
p.tokenIndex += 2 // Skip both 'is' and 'not'
} else if token.Value == "starts" && p.tokenIndex+1 < len(p.tokens) &&
p.tokens[p.tokenIndex+1].Type == TOKEN_NAME &&
p.tokens[p.tokenIndex+1].Value == "with" {
// Handle 'starts with' operator
operator = "starts with"