forked from CloudyKit/jet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
1059 lines (952 loc) · 27.6 KB
/
parse.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
// Copyright 2016 José Santos <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jet
import (
"bytes"
"fmt"
"runtime"
"strconv"
"strings"
)
func unquote(text string) (string, error) {
return strconv.Unquote(text)
}
// Template is the representation of a single parsed template.
type Template struct {
Name string // name of the template represented by the tree.
ParseName string // name of the top-level template during parsing, for error messages.
set *Set
extends *Template
imports []*Template
processedBlocks map[string]*BlockNode
passedBlocks map[string]*BlockNode
Root *ListNode // top-level root of the tree.
text string // text parsed to create the template (or its parent)
// Parsing only; cleared after parse.
lex *lexer
token [3]item // three-token lookahead for parser.
peekCount int
}
func (t *Template) String() (template string) {
if t.extends != nil {
if len(t.Root.Nodes) > 0 && len(t.imports) == 0 {
template += fmt.Sprintf("{{extends %q}}", t.extends.ParseName)
} else {
template += fmt.Sprintf("{{extends %q}}", t.extends.ParseName)
}
}
for k, _import := range t.imports {
if t.extends == nil && k == 0 {
template += fmt.Sprintf("{{import %q}}", _import.ParseName)
} else {
template += fmt.Sprintf("\n{{import %q}}", _import.ParseName)
}
}
if t.extends != nil || len(t.imports) > 0 {
if len(t.Root.Nodes) > 0 {
template += "\n" + t.Root.String()
}
} else {
template += t.Root.String()
}
return
}
func (t *Template) addBlocks(blocks map[string]*BlockNode) {
if len(blocks) == 0 {
return
}
if t.processedBlocks == nil {
t.processedBlocks = make(map[string]*BlockNode)
}
for key, value := range blocks {
t.processedBlocks[key] = value
}
}
// next returns the next token.
func (t *Template) next() item {
if t.peekCount > 0 {
t.peekCount--
} else {
t.token[0] = t.lex.nextItem()
}
return t.token[t.peekCount]
}
// backup backs the input stream up one token.
func (t *Template) backup() {
t.peekCount++
}
// backup2 backs the input stream up two tokens.
// The zeroth token is already there.
func (t *Template) backup2(t1 item) {
t.token[1] = t1
t.peekCount = 2
}
// backup3 backs the input stream up three tokens
// The zeroth token is already there.
func (t *Template) backup3(t2, t1 item) {
// Reverse order: we're pushing back.
t.token[1] = t1
t.token[2] = t2
t.peekCount = 3
}
// peek returns but does not consume the next token.
func (t *Template) peek() item {
if t.peekCount > 0 {
return t.token[t.peekCount-1]
}
t.peekCount = 1
t.token[0] = t.lex.nextItem()
return t.token[0]
}
// nextNonSpace returns the next non-space token.
func (t *Template) nextNonSpace() (token item) {
for {
token = t.next()
if token.typ != itemSpace {
break
}
}
return token
}
// peekNonSpace returns but does not consume the next non-space token.
func (t *Template) peekNonSpace() (token item) {
for {
token = t.next()
if token.typ != itemSpace {
break
}
}
t.backup()
return token
}
// errorf formats the error and terminates processing.
func (t *Template) errorf(format string, args ...interface{}) {
t.Root = nil
format = fmt.Sprintf("template: %s:%d: %s", t.ParseName, t.lex.lineNumber(), format)
panic(fmt.Errorf(format, args...))
}
// error terminates processing.
func (t *Template) error(err error) {
t.errorf("%s", err)
}
// expect consumes the next token and guarantees it has the required type.
func (t *Template) expect(expectedType itemType, context, expected string) item {
token := t.nextNonSpace()
if token.typ != expectedType {
t.unexpected(token, context, expected)
}
return token
}
func (t *Template) expectRightDelim(context string) item {
return t.expect(itemRightDelim, context, "closing delimiter")
}
// expectOneOf consumes the next token and guarantees it has one of the required types.
func (t *Template) expectOneOf(expected1, expected2 itemType, context, expectedAs string) item {
token := t.nextNonSpace()
if token.typ != expected1 && token.typ != expected2 {
t.unexpected(token, context, expectedAs)
}
return token
}
// unexpected complains about the token and terminates processing.
func (t *Template) unexpected(token item, context, expected string) {
switch {
case token.typ == itemImport,
token.typ == itemExtends:
t.errorf("parsing %s: unexpected keyword '%s' ('%s' statements must be at the beginning of the template)", context, token.val, token.val)
case token.typ > itemKeyword:
t.errorf("parsing %s: unexpected keyword '%s' (expected %s)", context, token.val, expected)
default:
t.errorf("parsing %s: unexpected token '%s' (expected %s)", context, token.val, expected)
}
}
// recover is the handler that turns panics into returns from the top level of Parse.
func (t *Template) recover(errp *error) {
e := recover()
if e != nil {
if _, ok := e.(runtime.Error); ok {
panic(e)
}
if t != nil {
t.lex.drain()
t.stopParse()
}
*errp = e.(error)
}
return
}
func (s *Set) parse(name, text string, cacheAfterParsing bool) (t *Template, err error) {
t = &Template{
Name: name,
ParseName: name,
text: text,
set: s,
passedBlocks: make(map[string]*BlockNode),
}
defer t.recover(&err)
lexer := lex(name, text, false)
lexer.setDelimiters(s.leftDelim, s.rightDelim)
lexer.run()
t.startParse(lexer)
t.parseTemplate(cacheAfterParsing)
t.stopParse()
if t.extends != nil {
t.addBlocks(t.extends.processedBlocks)
}
for _, _import := range t.imports {
t.addBlocks(_import.processedBlocks)
}
t.addBlocks(t.passedBlocks)
return t, err
}
func (t *Template) expectString(context string) string {
token := t.expectOneOf(itemString, itemRawString, context, "string literal")
s, err := unquote(token.val)
if err != nil {
t.error(err)
}
return s
}
// parse is the top-level parser for a template, essentially the same
// It runs to EOF.
func (t *Template) parseTemplate(cacheAfterParsing bool) (next Node) {
t.Root = t.newList(t.peek().pos)
// {{ extends|import stringLiteral }}
for t.peek().typ != itemEOF {
delim := t.next()
if delim.typ == itemText && strings.TrimSpace(delim.val) == "" {
continue //skips empty text nodes
}
if delim.typ == itemLeftDelim {
token := t.nextNonSpace()
if token.typ == itemExtends || token.typ == itemImport {
s := t.expectString("extends|import")
if token.typ == itemExtends {
if t.extends != nil {
t.errorf("Unexpected extends clause: each template can only extend one template")
} else if len(t.imports) > 0 {
t.errorf("Unexpected extends clause: the 'extends' clause should come before all import clauses")
}
var err error
t.extends, err = t.set.getSiblingTemplate(s, t.Name, cacheAfterParsing)
if err != nil {
t.error(err)
}
} else {
tt, err := t.set.getSiblingTemplate(s, t.Name, cacheAfterParsing)
if err != nil {
t.error(err)
}
t.imports = append(t.imports, tt)
}
t.expect(itemRightDelim, "extends|import", "closing delimiter")
} else {
t.backup2(delim)
break
}
} else {
t.backup()
break
}
}
for t.peek().typ != itemEOF {
switch n := t.textOrAction(); n.Type() {
case nodeEnd, nodeElse, nodeContent:
t.errorf("unexpected %s", n)
default:
t.Root.append(n)
}
}
return nil
}
// startParse initializes the parser, using the lexer.
func (t *Template) startParse(lex *lexer) {
t.Root = nil
t.lex = lex
}
// stopParse terminates parsing.
func (t *Template) stopParse() {
t.lex = nil
}
// IsEmptyTree reports whether this tree (node) is empty of everything but space.
func IsEmptyTree(n Node) bool {
switch n := n.(type) {
case nil:
return true
case *ActionNode:
case *IfNode:
case *ListNode:
for _, node := range n.Nodes {
if !IsEmptyTree(node) {
return false
}
}
return true
case *RangeNode:
case *IncludeNode:
case *TextNode:
return len(bytes.TrimSpace(n.Text)) == 0
case *BlockNode:
case *YieldNode:
default:
panic("unknown node: " + n.String())
}
return false
}
func (t *Template) blockParametersList(isDeclaring bool, context string) *BlockParameterList {
block := &BlockParameterList{}
t.expect(itemLeftParen, context, "opening parenthesis")
for {
var expression Expression
next := t.nextNonSpace()
if next.typ == itemIdentifier {
identifier := next.val
next2 := t.nextNonSpace()
switch next2.typ {
case itemComma, itemRightParen:
block.List = append(block.List, BlockParameter{Identifier: identifier})
next = next2
case itemAssign:
expression, next = t.parseExpression(context)
block.List = append(block.List, BlockParameter{Identifier: identifier, Expression: expression})
default:
if !isDeclaring {
switch next2.typ {
case itemComma, itemRightParen:
default:
t.backup2(next)
expression, next = t.parseExpression(context)
block.List = append(block.List, BlockParameter{Expression: expression})
}
} else {
t.unexpected(next2, context, "comma, assignment, or closing parenthesis")
}
}
} else if !isDeclaring {
switch next.typ {
case itemComma, itemRightParen:
default:
t.backup()
expression, next = t.parseExpression(context)
block.List = append(block.List, BlockParameter{Expression: expression})
}
}
if next.typ != itemComma {
t.backup()
break
}
}
t.expect(itemRightParen, context, "closing parenthesis")
return block
}
func (t *Template) parseBlock() Node {
const context = "block clause"
var pipe Expression
name := t.expect(itemIdentifier, context, "name")
bplist := t.blockParametersList(true, context)
if t.peekNonSpace().typ != itemRightDelim {
pipe = t.expression(context, "context")
}
t.expectRightDelim(context)
list, end := t.itemList(nodeContent, nodeEnd)
var contentList *ListNode
if end.Type() == nodeContent {
contentList, end = t.itemList(nodeEnd)
}
block := t.newBlock(name.pos, t.lex.lineNumber(), name.val, bplist, pipe, list, contentList)
t.passedBlocks[block.Name] = block
return block
}
func (t *Template) parseYield() Node {
const context = "yield clause"
var (
pipe Expression
name item
bplist *BlockParameterList
content *ListNode
)
// parse block name
name = t.nextNonSpace()
if name.typ == itemContent {
// content yield {{yield content}}
if t.peekNonSpace().typ != itemRightDelim {
pipe = t.expression(context, "content context")
}
t.expectRightDelim(context)
return t.newYield(name.pos, t.lex.lineNumber(), "", nil, pipe, nil, true)
} else if name.typ != itemIdentifier {
t.unexpected(name, context, "block name")
}
// parse block parameters
bplist = t.blockParametersList(false, context)
// parse optional context & content
typ := t.peekNonSpace().typ
if typ == itemRightDelim {
t.expectRightDelim(context)
} else {
if typ != itemContent {
// parse context expression
pipe = t.expression("yield", "context")
typ = t.peekNonSpace().typ
}
if typ == itemRightDelim {
t.expectRightDelim(context)
} else if typ == itemContent {
// parse content from following nodes (until {{end}})
t.nextNonSpace()
t.expectRightDelim(context)
content, _ = t.itemList(nodeEnd)
} else {
t.unexpected(t.nextNonSpace(), context, "content keyword or closing delimiter")
}
}
return t.newYield(name.pos, t.lex.lineNumber(), name.val, bplist, pipe, content, false)
}
func (t *Template) parseInclude() Node {
var context Expression
name := t.expression("include", "template name")
if t.peekNonSpace().typ != itemRightDelim {
context = t.expression("include", "context")
}
t.expectRightDelim("include invocation")
return t.newInclude(name.Position(), t.lex.lineNumber(), name, context)
}
func (t *Template) parseReturn() Node {
value := t.expression("return", "value")
t.expectRightDelim("return")
return t.newReturn(value.Position(), t.lex.lineNumber(), value)
}
// itemList:
// textOrAction*
// Terminates at any of the given nodes, returned separately.
func (t *Template) itemList(terminatedBy ...NodeType) (list *ListNode, next Node) {
list = t.newList(t.peekNonSpace().pos)
for t.peekNonSpace().typ != itemEOF {
n := t.textOrAction()
for _, terminatorType := range terminatedBy {
if n.Type() == terminatorType {
return list, n
}
}
list.append(n)
}
t.errorf("unexpected EOF")
return
}
// textOrAction:
// text | action
func (t *Template) textOrAction() Node {
switch token := t.nextNonSpace(); token.typ {
case itemText:
return t.newText(token.pos, token.val)
case itemLeftDelim:
return t.action()
default:
t.unexpected(token, "input", "text or action")
}
return nil
}
func (t *Template) action() (n Node) {
switch token := t.nextNonSpace(); token.typ {
case itemInclude:
return t.parseInclude()
case itemBlock:
return t.parseBlock()
case itemEnd:
return t.endControl()
case itemYield:
return t.parseYield()
case itemContent:
return t.contentControl()
case itemIf:
return t.ifControl()
case itemElse:
return t.elseControl()
case itemRange:
return t.rangeControl()
case itemTry:
return t.parseTry()
case itemCatch:
return t.parseCatch()
case itemReturn:
return t.parseReturn()
}
t.backup()
action := t.newAction(t.peek().pos, t.lex.lineNumber())
expr := t.assignmentOrExpression("command")
if expr.Type() == NodeSet {
action.Set = expr.(*SetNode)
expr = nil
if t.expectOneOf(itemSemicolon, itemRightDelim, "command", "semicolon or right delimiter").typ == itemSemicolon {
expr = t.expression("command", "pipeline base expression")
}
}
if expr != nil {
action.Pipe = t.pipeline("command", expr)
}
return action
}
func (t *Template) logicalExpression(context string) (Expression, item) {
left, endtoken := t.comparativeExpression(context)
for endtoken.typ == itemAnd || endtoken.typ == itemOr {
right, rightendtoken := t.comparativeExpression(context)
left, endtoken = t.newLogicalExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
}
return left, endtoken
}
func (t *Template) parseExpression(context string) (Expression, item) {
expression, endtoken := t.logicalExpression(context)
if endtoken.typ == itemTernary {
var left, right Expression
left, endtoken = t.parseExpression(context)
if endtoken.typ != itemColon {
t.unexpected(endtoken, "ternary expression", "colon in ternary expression")
}
right, endtoken = t.parseExpression(context)
expression = t.newTernaryExpr(expression.Position(), t.lex.lineNumber(), expression, left, right)
}
return expression, endtoken
}
func (t *Template) comparativeExpression(context string) (Expression, item) {
left, endtoken := t.numericComparativeExpression(context)
for endtoken.typ == itemEquals || endtoken.typ == itemNotEquals {
right, rightendtoken := t.numericComparativeExpression(context)
left, endtoken = t.newComparativeExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
}
return left, endtoken
}
func (t *Template) numericComparativeExpression(context string) (Expression, item) {
left, endtoken := t.additiveExpression(context)
for endtoken.typ >= itemGreat && endtoken.typ <= itemLessEquals {
right, rightendtoken := t.additiveExpression(context)
left, endtoken = t.newNumericComparativeExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
}
return left, endtoken
}
func (t *Template) additiveExpression(context string) (Expression, item) {
left, endtoken := t.multiplicativeExpression(context)
for endtoken.typ == itemAdd || endtoken.typ == itemMinus {
right, rightendtoken := t.multiplicativeExpression(context)
left, endtoken = t.newAdditiveExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
}
return left, endtoken
}
func (t *Template) multiplicativeExpression(context string) (left Expression, endtoken item) {
left, endtoken = t.unaryExpression(context)
for endtoken.typ >= itemMul && endtoken.typ <= itemMod {
right, rightendtoken := t.unaryExpression(context)
left, endtoken = t.newMultiplicativeExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
}
return left, endtoken
}
func (t *Template) unaryExpression(context string) (Expression, item) {
next := t.nextNonSpace()
switch next.typ {
case itemNot:
expr, endToken := t.comparativeExpression(context)
return t.newNotExpr(expr.Position(), t.lex.lineNumber(), expr), endToken
case itemMinus, itemAdd:
return t.newAdditiveExpr(next.pos, t.lex.lineNumber(), nil, t.operand("additive expression"), next), t.nextNonSpace()
default:
t.backup()
}
operand := t.operand(context)
return operand, t.nextNonSpace()
}
func (t *Template) assignmentOrExpression(context string) (operand Expression) {
t.peekNonSpace()
line := t.lex.lineNumber()
var right, left []Expression
var isSet bool
var isLet bool
var returned item
operand, returned = t.parseExpression(context)
pos := operand.Position()
if returned.typ == itemComma || returned.typ == itemAssign {
isSet = true
} else {
if operand == nil {
t.unexpected(returned, context, "operand")
}
t.backup()
return operand
}
if isSet {
leftloop:
for {
switch operand.Type() {
case NodeField, NodeChain, NodeIdentifier, NodeUnderscore:
left = append(left, operand)
default:
t.errorf("unexpected node in assign")
}
switch returned.typ {
case itemComma:
operand, returned = t.parseExpression(context)
case itemAssign:
isLet = returned.val == ":="
break leftloop
default:
t.unexpected(returned, "assignment", "comma or assignment")
}
}
if isLet {
for _, operand := range left {
if operand.Type() != NodeIdentifier && operand.Type() != NodeUnderscore {
t.errorf("unexpected node type %s in variable declaration", operand)
}
}
}
for {
operand, returned = t.parseExpression("assignment")
right = append(right, operand)
if returned.typ != itemComma {
t.backup()
break
}
}
var isIndexExprGetLookup bool
if context == "range" {
if len(left) > 2 || len(right) > 1 {
t.errorf("unexpected number of operands in assign on range")
}
} else {
if len(left) != len(right) {
if len(left) == 2 && len(right) == 1 && right[0].Type() == NodeIndexExpr {
isIndexExprGetLookup = true
} else {
t.errorf("unexpected number of operands in assign on range")
}
}
}
operand = t.newSet(pos, line, isLet, isIndexExprGetLookup, left, right)
return
}
return
}
func (t *Template) expression(context, as string) Expression {
expr, tk := t.parseExpression(context)
if expr == nil {
t.unexpected(tk, context, as)
}
t.backup()
return expr
}
func (t *Template) pipeline(context string, baseExprMutate Expression) (pipe *PipeNode) {
pos := t.peekNonSpace().pos
pipe = t.newPipeline(pos, t.lex.lineNumber())
if baseExprMutate == nil {
pipe.errorf("parsing pipeline: first expression cannot be nil")
}
pipe.append(t.command(baseExprMutate))
for {
token := t.expectOneOf(itemPipe, itemRightDelim, "pipeline", "pipe or right delimiter")
if token.typ == itemRightDelim {
break
}
token = t.nextNonSpace()
switch token.typ {
case itemField, itemIdentifier:
t.backup()
pipe.append(t.command(nil))
default:
t.unexpected(token, "pipeline", "field or identifier")
}
}
return
}
func (t *Template) command(baseExpr Expression) *CommandNode {
cmd := t.newCommand(t.peekNonSpace().pos)
if baseExpr == nil {
baseExpr = t.expression("command", "name")
}
if baseExpr.Type() == NodeCallExpr {
call := baseExpr.(*CallExprNode)
cmd.CallExprNode = *call
return cmd
}
cmd.BaseExpr = baseExpr
next := t.nextNonSpace()
switch next.typ {
case itemColon:
cmd.CallArgs = t.parseArguments()
default:
t.backup()
}
if cmd.BaseExpr == nil {
t.errorf("empty command")
}
return cmd
}
// operand:
// term .Field*
// An operand is a space-separated component of a command,
// a term possibly followed by field accesses.
// A nil return means the next item is not an operand.
func (t *Template) operand(context string) Expression {
node := t.term()
if node == nil {
t.unexpected(t.next(), context, "term")
}
RESET:
if t.peek().typ == itemField {
chain := t.newChain(t.peek().pos, node)
for t.peekNonSpace().typ == itemField {
chain.Add(t.next().val)
}
// Compatibility with original API: If the term is of type NodeField
// or NodeVariable, just put more fields on the original.
// Otherwise, keep the Chain node.
// Obvious parsing errors involving literal values are detected here.
// More complex error cases will have to be handled at execution time.
switch node.Type() {
case NodeField:
node = t.newField(chain.Position(), chain.String())
case NodeBool, NodeString, NodeNumber, NodeNil:
t.errorf("unexpected . after term %q", node.String())
default:
node = chain
}
}
nodeTYPE := node.Type()
if nodeTYPE == NodeIdentifier ||
nodeTYPE == NodeCallExpr ||
nodeTYPE == NodeField ||
nodeTYPE == NodeChain ||
nodeTYPE == NodeIndexExpr {
switch t.nextNonSpace().typ {
case itemLeftParen:
callExpr := t.newCallExpr(node.Position(), t.lex.lineNumber(), node)
callExpr.CallArgs = t.parseArguments()
t.expect(itemRightParen, "call expression", "closing parenthesis")
node = callExpr
goto RESET
case itemLeftBrackets:
base := node
var index Expression
var next item
//found colon is slice expression
if t.peekNonSpace().typ != itemColon {
index, next = t.parseExpression("index|slice expression")
} else {
next = t.nextNonSpace()
}
switch next.typ {
case itemColon:
var endIndex Expression
if t.peekNonSpace().typ != itemRightBrackets {
endIndex = t.expression("slice expression", "end indexß")
}
node = t.newSliceExpr(node.Position(), node.line(), base, index, endIndex)
case itemRightBrackets:
node = t.newIndexExpr(node.Position(), node.line(), base, index)
fallthrough
default:
t.backup()
}
t.expect(itemRightBrackets, "index expression", "closing bracket")
goto RESET
default:
t.backup()
}
}
return node
}
func (t *Template) parseArguments() (args CallArgs) {
context := "call expression argument list"
args.Exprs = []Expression{}
loop:
for {
peek := t.peekNonSpace()
if peek.typ == itemRightParen {
break
}
var (
expr Expression
endtoken item
)
expr, endtoken = t.parseExpression(context)
if expr.Type() == NodeUnderscore {
// slot for piped argument
if args.HasPipeSlot {
t.errorf("found two pipe slot markers ('_') for the same function call")
}
args.HasPipeSlot = true
}
args.Exprs = append(args.Exprs, expr)
switch endtoken.typ {
case itemComma:
// continue with closing parens (allowed because of multiline syntax) or next arg
default:
t.backup()
break loop
}
}
return
}
func (t *Template) parseControl(allowElseIf bool, context string) (pos Pos, line int, set *SetNode, expression Expression, list, elseList *ListNode) {
line = t.lex.lineNumber()
expression = t.assignmentOrExpression(context)
pos = expression.Position()
if expression.Type() == NodeSet {
set = expression.(*SetNode)
if context != "range" {
t.expect(itemSemicolon, context, "semicolon between assignment and expression")
expression = t.expression(context, "expression after assignment")
} else {
expression = nil
}
}
t.expectRightDelim(context)
var next Node
list, next = t.itemList(nodeElse, nodeEnd)
if next.Type() == nodeElse {
if allowElseIf && t.peek().typ == itemIf {
// Special case for "else if". If the "else" is followed immediately by an "if",
// the elseControl will have left the "if" token pending. Treat
// {{if a}}_{{else if b}}_{{end}}
// as
// {{if a}}_{{else}}{{if b}}_{{end}}{{end}}.
// To do this, parse the if as usual and stop at it {{end}}; the subsequent{{end}}
// is assumed. This technique works even for long if-else-if chains.
t.next() // Consume the "if" token.
elseList = t.newList(next.Position())
elseList.append(t.ifControl())
// Do not consume the next item - only one {{end}} required.
} else {
elseList, next = t.itemList(nodeEnd)
}
}
return pos, line, set, expression, list, elseList
}
// If:
// {{if expression}} itemList {{end}}
// {{if expression}} itemList {{else}} itemList {{end}}
// If keyword is past.
func (t *Template) ifControl() Node {
return t.newIf(t.parseControl(true, "if"))
}
// Range:
// {{range expression}} itemList {{end}}
// {{range expression}} itemList {{else}} itemList {{end}}
// Range keyword is past.
func (t *Template) rangeControl() Node {
return t.newRange(t.parseControl(false, "range"))
}
// End:
// {{end}}
// End keyword is past.
func (t *Template) endControl() Node {
return t.newEnd(t.expectRightDelim("end").pos)
}
// Content:
// {{content}}
// Content keyword is past.
func (t *Template) contentControl() Node {
return t.newContent(t.expectRightDelim("content").pos)
}
// Else:
// {{else}}
// Else keyword is past.
func (t *Template) elseControl() Node {
// Special case for "else if".
peek := t.peekNonSpace()
if peek.typ == itemIf {
// We see "{{else if ... " but in effect rewrite it to {{else}}{{if ... ".
return t.newElse(peek.pos, t.lex.lineNumber())
}
return t.newElse(t.expectRightDelim("else").pos, t.lex.lineNumber())
}
// Try-catch:
// {{try}}
// itemList
// {{catch <ident>}}
// itemList
// {{end}}
// try keyword is past.
func (t *Template) parseTry() *TryNode {
var recov *catchNode
line := t.lex.lineNumber()
pos := t.expectRightDelim("try").pos
list, next := t.itemList(nodeCatch, nodeEnd)
if next.Type() == nodeCatch {
recov = next.(*catchNode)
}
return t.newTry(pos, line, list, recov)
}
// catch:
// {{catch <ident>}}
// itemList
// {{end}}
// catch keyword is past.
func (t *Template) parseCatch() *catchNode {
line := t.lex.lineNumber()