-
Notifications
You must be signed in to change notification settings - Fork 4
/
fet.go
2264 lines (2195 loc) · 55.3 KB
/
fet.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
package fet
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"sync"
"unicode"
"github.com/fefit/fet/lib/expression"
"github.com/fefit/fet/lib/funcs"
"github.com/fefit/fet/lib/generator"
"github.com/fefit/fet/types"
"github.com/fefit/fet/utils"
)
// Type type
type Type int
// Runes type
type Runes []rune
// MatchTagFn func
type MatchTagFn func(strs *Runes, index int, total int) (int, bool)
// ValidateFn func
type ValidateFn func(node *Node, conf *Config) string
// Mode for parser type
type Mode = types.Mode
// Config for FetConfig
type Config = types.FetConfig
// Params struct
type Params struct {
startTagBeginChar string
endTagBeginChar string
matchStartTag MatchTagFn
matchEndTag MatchTagFn
}
// Prop of Props
type Prop struct {
Raw string
Type string
}
// Props of tag
type Props map[string]*Prop
// Data struct
type Data struct {
Name string
Props Props
}
// Indexs for tags
type Indexs = types.Indexs
// Quote struct
type Quote struct {
Indexs
}
// Position struct
type Position struct {
LineNo int
LineIndex int
}
// CompileOptions struct
type CompileOptions struct {
File string
ParentNS string
LocalNS string
ParentScopes []string
LocalScopes *[]string
Includes *[]string
IncludeChains *Imports
Extends *[]string
Captures *map[string]string
ParseOptions *generator.ParseOptions
}
// Node struct
type Node struct {
IsClosed bool
ContentIndex int
Name string
Content string
Pwd string
GlobalScopes []string
LocalScopes []string
Parent *Node
Pair *Node
Type Type
Props *Props
Features []*Node
Childs []*Node
Current *Node
Quotes []*Quote
Context *Runes
Fet *Fet
Data *map[string][]string
Indexs
*Position
}
// NodeSets for nodelist
type NodeSets map[string][]*Node
// NodeList for
type NodeList struct {
Queues []*Node
Specials NodeSets
}
var (
supportTags = map[string]Type{
"include": SingleType,
"extends": SingleType,
"for": BlockStartType,
"foreach": BlockStartType,
"if": BlockStartType,
"elseif": BlockFeatureType,
"else": BlockFeatureType,
"block": BlockStartType,
"capture": BlockStartType,
}
validateFns = map[string]ValidateFn{
"if": validIfTag,
"else": validElseTag,
"elseif": validElseifTag,
"for": validForTag,
"foreach": validForTag,
"block": validBlockTag,
"include": validIncludeTag,
"extends": validExtendsTag,
"capture": validCaptureTag,
}
)
// ImportNode
// every node will lookup it's prevs
// so nexts are not necessary
type ImportNode struct {
Value string
Prevs []*ImportNode
}
func (importNode *ImportNode) LookupCircle(search *ImportNode, chains []*ImportNode) []string {
prevs := importNode.Prevs
outputCircles := func(result []string, nodes []*ImportNode) []string {
for i := len(nodes) - 1; i >= 0; i-- {
result = append(result, nodes[i].Value)
}
return result
}
if len(prevs) == 0 {
return []string{}
}
// look current node's prevs
for _, node := range prevs {
if node == search {
return outputCircles([]string{
node.Value,
importNode.Value,
}, chains)
}
}
// lookup prevs
curChains := append(chains, importNode)
for _, node := range prevs {
result := node.LookupCircle(search, curChains)
if len(result) > 0 {
return result
}
}
// no circle depends finded
return []string{}
}
type Imports struct {
Nodes map[string]*ImportNode
}
func (imports *Imports) Add(cur string, depend string) []string {
// circle depend itself
if cur == depend {
return []string{cur}
}
// cur node
var curNode *ImportNode
if node, exists := imports.Nodes[cur]; exists {
curNode = node
} else {
node := &ImportNode{
Value: cur,
Prevs: []*ImportNode{},
}
imports.Nodes[cur] = node
curNode = node
}
// next node
var nextNode *ImportNode
if node, exists := imports.Nodes[depend]; exists {
nextNode = node
nextNode.Prevs = append(nextNode.Prevs, curNode)
} else {
node := &ImportNode{
Value: depend,
Prevs: []*ImportNode{
// add cur node to the next node's prevs
curNode,
},
}
imports.Nodes[depend] = node
nextNode = node
}
// judge if the next depend node in prevs chains
return curNode.LookupCircle(nextNode, []*ImportNode{})
}
// UnknownType need parse
const (
UnknownType Type = iota
TextType
CommentType
OutputType
AssignType
SingleType
BlockType
BlockStartType
BlockFeatureType
BlockEndType
)
// AddFeature method for Node
func (node *Node) AddFeature(feature *Node) {
feature.Parent = node
node.Current = feature
node.Features = append(node.Features, feature)
}
const (
isWaitProp Type = iota
isInProp
isWaitEqual
isWaitValue
isInValue
)
// parseProps
func parseProps(node *Node, defField string) (*Props, error) {
content := node.Content
quotes := node.Quotes
baseIndex := node.ContentIndex
rns := []rune(content)
total := len(rns)
qIndex := 0
qTotal := len(quotes)
statu := isWaitProp
isHasDefault := false
prop := ""
value := ""
props := []string{}
values := []string{}
addProp := func() error {
if contains(props, prop) {
return fmt.Errorf("repeated properties: '%s'", prop)
}
if prop == defField {
isHasDefault = true
}
props = append(props, prop)
return nil
}
isQuoteOk := func(i int) (lastIndex int, err error) {
if qIndex < qTotal {
quote := quotes[qIndex]
startIndex := quote.StartIndex - baseIndex
if startIndex == i {
qIndex++
lastIndex = i + quote.EndIndex - quote.StartIndex - 1
return lastIndex, nil
}
}
return i, fmt.Errorf("incorrect quote at index:%d", i)
}
isOperator := func(ch string) bool {
return contains([]string{"!", ">", "<", "="}, ch)
}
lastQuoteIndex := -2
lastValueIndex := -1
prev := ""
for i := 0; i < total; i++ {
s := rns[i]
cur := string(s)
if unicode.IsSpace(s) {
if statu == isInProp {
statu++
if err := addProp(); err != nil {
return nil, err
}
prop = ""
}
} else {
switch statu {
case isWaitProp:
if s == '"' {
if isHasDefault {
return nil, fmt.Errorf("repeated default properties, maybe you need add a property name for one of them")
}
if lastIndex, err := isQuoteOk(i); err == nil {
defValue := string(rns[i : lastIndex+1])
values = append(values, defValue)
i = lastIndex
lastQuoteIndex = lastIndex
statu = isWaitProp
isHasDefault = true
props = append(props, defField)
continue
} else {
return nil, err
}
}
if lastQuoteIndex+1 == i {
return nil, fmt.Errorf("wrong property after quote, must have a space")
}
statu++
prop = cur
case isInProp:
if s == '=' {
if err := addProp(); err != nil {
return nil, err
}
statu = isWaitValue
} else {
prop += cur
}
case isWaitEqual:
if s == '=' {
statu = isWaitValue
} else {
return nil, fmt.Errorf("wrong assign")
}
case isWaitValue:
if s == '"' {
//
if lastIndex, err := isQuoteOk(i); err == nil {
values = append(values, string(rns[i:lastIndex+1]))
i = lastIndex
lastQuoteIndex = lastIndex
statu = isWaitProp
} else {
return nil, err
}
} else {
value = cur
lastValueIndex = i
statu++
}
case isInValue:
if s == '=' {
if i+1 >= total {
return nil, fmt.Errorf("wrong property has no value")
}
next := rns[i+1]
if isOperator(prev) || next == '=' {
value += cur
} else {
all := strings.TrimSpace(string(rns[lastValueIndex:i]))
segs := strings.Fields(all)
if len(segs) < 2 {
return nil, fmt.Errorf("wrong value: %s", all)
}
prop = segs[len(segs)-1]
if err := addProp(); err != nil {
return nil, err
}
curRns := Runes(all)
curValue := strings.TrimSpace(string(curRns[:strings.LastIndex(all, prop)]))
values = append(values, curValue)
value = ""
statu = isWaitValue
}
} else {
value += cur
}
}
}
prev = cur
}
// add last value
if statu == isInValue && value != "" {
values = append(values, value)
}
if !isHasDefault {
return nil, fmt.Errorf("doesn't have default property of '%s'", defField)
}
count := len(props)
if count != len(values) {
return nil, fmt.Errorf("parse error: wrong properties and values counts")
}
result := Props{}
for i := 0; i < count; i++ {
curProp := props[i]
if !utils.IsIdentifier(curProp, types.Gofet) {
return nil, fmt.Errorf("wrong property name:%s", curProp)
}
result[curProp] = &Prop{
Raw: values[i],
}
}
return &result, nil
}
// getDefField
func getStringField(node *Node, defField string) (string, error) {
props := *node.Props
if prop, ok := props[defField]; ok {
content := prop.Raw
// remove side quote
rns := Runes(content)
lastIndex := len(rns) - 1
start, end := rns[0], rns[lastIndex]
if start == '"' || end == '"' {
if start != end {
return "", fmt.Errorf("wrong string property name:'%s'", defField)
}
return string(rns[1:lastIndex]), nil
}
return content, nil
}
return "", fmt.Errorf("don't find the property name:'%s'", defField)
}
// Compile method for Node
func (node *Node) Compile(options *CompileOptions) (result string, err error) {
fet := node.Fet
exp, gen, conf, delimit := fet.exp, fet.gen, fet.Config, fet.wrapCode
includes, extends, captures, includeChains := options.Includes, options.Extends, options.Captures, options.IncludeChains
parseOptions := options.ParseOptions
name, content := node.Name, node.Content
parentScopes, localScopes := options.ParentScopes, options.LocalScopes
parentNS, localNS := options.ParentNS, options.LocalNS
copyScopes := append([]string{}, *localScopes...)
currentScopes := append(copyScopes, node.GlobalScopes...)
addVarPrefix := "$"
isSmartyMode := conf.Mode == types.Smarty
compiledText := ""
noDelimit := false
if isSmartyMode {
addVarPrefix = ""
}
namespace := func(name string) (bool, string) {
if contains(currentScopes, name) {
return true, addVarPrefix + name + localNS
} else if contains(parentScopes, name) {
return true, addVarPrefix + name + parentNS
}
return false, strings.TrimPrefix(name, "$")
}
genOptions := &generator.GenOptions{
NsFn: namespace,
Exp: exp,
}
toError := func(err error) error {
return node.halt(err.Error())
}
switch node.Type {
case CommentType:
// output nothing
case TextType:
// replace all html/template left delimiters to pipeline
result = content
if conf.LeftDelimiter != "{{" {
rule := regexp.MustCompile(`(\{{2,})`)
result = rule.ReplaceAllString(result, `{{"$1"}}`)
}
case AssignType, OutputType:
isAssign := node.Type == AssignType
if isAssign && !utils.IsIdentifier(name, conf.Mode) {
return "", node.halt("wrong identifier '%s', please check the parse mode in fet config", name)
}
ast, expErr := exp.Parse(content)
if expErr != nil {
return "", toError(expErr)
}
if isAssign {
if _, ok := generator.LiteralSymbols[name]; ok {
return "", node.halt("you can't use a literal of '%s' as a variable name", name)
}
symbol := " := "
if contains(currentScopes, name) {
symbol = " = "
}
if compiledText, _, err = gen.Build(ast, genOptions, parseOptions); err != nil {
return "", node.halt("%s", err.Error())
}
result = delimit(addVarPrefix + name + localNS + symbol + compiledText)
} else {
if compiledText, noDelimit, err = gen.Build(ast, genOptions, parseOptions); err != nil {
return "", node.halt("%s", err.Error())
}
if noDelimit {
result = compiledText
} else {
result = delimit(compiledText)
}
}
case SingleType:
isInclude := name == "include"
if isInclude || name == "extends" {
defField := "file"
filename, _ := getStringField(node, defField)
tpl := getRealTplPath(filename, path.Join(node.Pwd, ".."), fet.TemplateDir)
// judge if include chains has circle depends
if len(includeChains.Add(options.File, tpl)) > 0 {
return "", node.halt("the 'include' file '%s' cause a circle depencncy.", tpl)
}
if contains(*extends, tpl) {
return "", node.halt("the 'extends' file '%s' cause a circle depencncy.", tpl)
}
incLocalScopes := []string{}
incCaptures := &map[string]string{}
incOptions := &CompileOptions{
ParentScopes: currentScopes[:],
LocalScopes: &incLocalScopes,
Extends: extends,
Includes: includes,
IncludeChains: includeChains,
File: tpl,
Captures: incCaptures,
ParseOptions: &generator.ParseOptions{
Conf: conf,
Captures: incCaptures,
},
}
if isInclude {
// use relative path, to keep the name
relaTpl, _ := filepath.Rel(fet.TemplateDir, tpl)
ctx := md5.New()
if _, wErr := ctx.Write([]byte(relaTpl)); wErr != nil {
return "", node.halt("include file error:%s", wErr.Error())
}
curNS := hex.EncodeToString(ctx.Sum(nil))
incLocalNS := "_" + curNS
incOptions.ParentNS = localNS
incOptions.LocalNS = incLocalNS
// append include files to depends
*includes = append(*includes, tpl)
// append local property variables
for key, prop := range *node.Props {
if key != defField {
value := prop.Raw
if ast, expErr := exp.Parse(value); expErr == nil {
if compiledText, _, err = gen.Build(ast, genOptions, parseOptions); err != nil {
return "", node.halt("%s", err.Error())
}
incLocalScopes = append(incLocalScopes, "$"+key)
result += "{{ $" + key + incLocalNS + " := " + compiledText + "}}"
} else {
return "", toError(expErr)
}
}
}
}
var incResult string
if incResult, err = fet.compileFileContent(tpl, incOptions); err != nil {
return "", toError(err)
}
if isInclude {
result += incResult
}
// ignore extends, special parse
}
case BlockStartType:
if name == "for" || name == "foreach" {
props := *node.Props
if props["type"].Raw == "foreach" {
target := props["list"].Raw
ast, expErr := exp.Parse(target)
if expErr != nil {
return "", toError(expErr)
}
compiledText, _, err = gen.Build(ast, genOptions, parseOptions)
if err != nil {
return "", node.halt("parse 'foreach' error:%s", err.Error())
}
key := props["key"].Raw
result = "range "
if key != "" {
result += addVarPrefix + key + localNS + ", "
}
result += addVarPrefix + props["value"].Raw + localNS + " := " + compiledText
result = delimit(result)
} else {
data := *node.Data
vars := data["Vars"]
initial := data["Initial"]
res := strings.Builder{}
// add if block for variable context
res.WriteString(delimit("if true"))
for key, name := range vars {
ast, expErr := exp.Parse(initial[key])
if expErr != nil {
return "", toError(expErr)
}
compiledText, _, err = gen.Build(ast, genOptions, parseOptions)
if err != nil {
return "", node.halt("parse 'for' error:%s", err.Error())
}
res.WriteString(delimit(addVarPrefix + name + localNS + ":=" + compiledText))
}
suffixNS := indexString(node.StartIndex) + "_" + indexString(node.EndIndex) + localNS
chanName := "$loop_" + suffixNS
res.WriteString(delimit(chanName + " := (INJECT_MAKE_LOOP_CHAN)"))
res.WriteString(delimit("range " + chanName + ".Chan"))
// Add condition code
conds := data["Conds"][0]
// add initial declares
currentScopes = append(currentScopes, vars...)
ast, expErr := exp.Parse(conds)
if expErr != nil {
return "", toError(expErr)
}
compiledText, _, err = gen.Build(ast, genOptions, parseOptions)
if err != nil {
return "", node.halt("parse 'for' statement error:%s", err.Error())
}
res.WriteString(delimit("if " + compiledText))
res.WriteString(delimit(chanName + ".Next"))
res.WriteString(delimit("else"))
res.WriteString(delimit(chanName + ".Close"))
res.WriteString(delimit("end"))
res.WriteString(delimit("if (gt " + chanName + ".Loop -1)"))
result = res.String()
}
} else if name == "if" {
ast, expErr := exp.Parse(content)
if expErr != nil {
return "", toError(expErr)
}
compiledText, _, err = gen.Build(ast, genOptions, parseOptions)
if err != nil {
return "", node.halt("parse 'if' statement error:%s", err.Error())
}
result = delimit("if " + compiledText)
} else if name == "capture" {
parseOptions.IsInCapture = true
captureName, _ := getStringField(node, "name")
keyName := "$fet.capture." + captureName
if _, ok := (*captures)[keyName]; ok {
// capture name has exists
return "", node.halt("repeated capture name '" + captureName + "'")
}
capVar := "$fet_capture_" + captureName + localNS
result = "{{" + capVar + " := (INJECT_CAPTURE_SCOPE . "
for _, varName := range currentScopes {
varName = strings.TrimPrefix(varName, "$")
result += "\"" + utils.Ucase(varName) + "\" $" + varName
}
result += ")}}"
(*captures)[keyName] = capVar
result += "{{ define \"$capture_" + captureName + "\"}}"
}
case BlockFeatureType:
if name == "elseif" {
ast, expErr := exp.Parse(content)
if expErr != nil {
return "", toError(expErr)
}
compiledText, _, err = gen.Build(ast, genOptions, parseOptions)
if err != nil {
return "", node.halt("parse 'if' statement error:%s", err.Error())
}
result = delimit("else if " + compiledText)
} else if name == "else" {
result = delimit("else")
}
case BlockEndType:
pair := node.Pair
if name == "block" {
blockScopes := pair.LocalScopes
if len(blockScopes) > 0 {
*options.LocalScopes = append(*options.LocalScopes, blockScopes...)
}
} else if name == "for" {
props := *pair.Props
if props["type"].Raw == "for" {
data := *pair.Data
// close index condition
result += delimit("end")
loops := data["Loops"]
for i, total := 0, len(loops); i < total; {
ast, expErr := exp.Parse(loops[i])
if expErr != nil {
return "", toError(expErr)
}
compiledText, _, err = gen.Build(ast, genOptions, parseOptions)
if err != nil {
return "", node.halt("parse 'for' loop error:%s", err.Error())
}
ast, expErr = exp.Parse(loops[i+1])
if expErr != nil {
return "", toError(expErr)
}
var code string
if code, _, err = gen.Build(ast, genOptions, parseOptions); err != nil {
return "", node.halt("parse 'for' loops error:%s", err.Error())
}
compiledText += " = " + code
result += delimit(compiledText)
i += 2
}
// first: close range; last: close if
result += delimit("end") + delimit("end")
} else {
result = delimit("end")
}
} else {
if name == "capture" {
parseOptions.IsInCapture = false
}
result = delimit("end")
}
default:
// types not assign
}
return
}
// halt errors
func (node *Node) halt(format string, args ...interface{}) error {
var errmsg string
if node.Pwd != "" {
errmsg = "[file:'" + node.Pwd + "']"
}
errmsg += "[line:" + indexString(node.LineNo) + ",col:" + indexString(node.StartIndex-node.LineIndex+1) + "][error]" + fmt.Sprintf(format, args...)
return errors.New(errmsg)
}
func getPrevFeature(node *Node) (feature *Node) {
nodes := node.Features
total := len(nodes)
if total > 2 {
feature = nodes[total-2]
}
return
}
/**
* validators
*/
func validIfPrevCondOk(node *Node) (errmsg string) {
prev := getPrevFeature(node.Parent)
if prev == nil {
return
} else if prev.Name != "elseif" {
errmsg = "the prev tag of \"" + node.Name + "\" should not be \"" + prev.Name + "\""
}
return
}
func validIfBlockCorrect(node *Node, blockName string) (errmsg string) {
pname := node.Parent.Name
if pname != blockName {
errmsg = "the \"" + node.Name + "\" tag can not used in block \"" + pname + "\""
}
return
}
func validIfHasProps(node *Node, defField string, only bool) (errmsg string) {
if props, err := parseProps(node, defField); err == nil {
node.Props = props
if only && len(*props) > 1 {
return fmt.Sprintf("the tag '%s' only support property '%s', remove unnessary properties", node.Name, defField)
}
} else {
return err.Error()
}
return errmsg
}
// tag validators
func validIfTag(node *Node, conf *Config) (errmsg string) {
if node.Content == "" {
errmsg = "the \"if\" tag does not have a condition expression"
}
return errmsg
}
func validElseTag(node *Node, conf *Config) (errmsg string) {
if node.Content != "" {
errmsg = "the \"else\" tag should not use a condition expression"
} else if errmsg = validIfPrevCondOk(node); errmsg == "" {
errmsg = validIfBlockCorrect(node, "if")
}
return errmsg
}
func validElseifTag(node *Node, conf *Config) (errmsg string) {
if node.Content == "" {
errmsg = "the \"elseif\" tag does not have a condition expression"
} else if errmsg = validIfPrevCondOk(node); errmsg == "" {
errmsg = validIfBlockCorrect(node, "if")
}
return errmsg
}
func validBlockTag(node *Node, conf *Config) (errmsg string) {
block := node.Parent
if block != nil && block.Parent != nil {
errmsg = "the \"block\" tag should be root tag,can not appears in \"" + block.Parent.Name + "\""
} else {
errmsg = validIfHasProps(node, "name", true)
}
return errmsg
}
func validCaptureTag(node *Node, conf *Config) (errmsg string) {
capture := node.Parent
if capture != nil && capture.Parent != nil {
errmsg = "the \"capture\" tag should be root tag,can not appears in \"" + capture.Parent.Name + "\""
} else {
errmsg = validIfHasProps(node, "name", false)
}
return errmsg
}
func validForTag(node *Node, conf *Config) (errmsg string) {
name := node.Name
content := node.Content
runes := Runes(node.Content)
segs := []string{}
total := 0
maxNum := 2
prevIsSpace := true
hasKey := false
normalErr := "the \"" + content + "\" tag is not correct"
isSmartyMode := conf.Mode == types.Smarty
var (
list, key, value *Prop
)
isForEach := false
if name == "foreach" {
if isSmartyMode {
isForEach = true
count := len(runes)
isArrow, prevIsArrow := false, false
for count > 0 {
count--
s := runes[count]
if unicode.IsSpace(s) {
prevIsSpace = true
if total >= maxNum {
segs = append(segs, string(runes[:count]))
break
}
} else {
if s == '>' && count >= 1 && runes[count-1] == '=' {
hasKey = true
maxNum += 2
isArrow = true
prevIsArrow = true
count--
}
if prevIsSpace || isArrow || prevIsArrow {
if isArrow {
segs = append(segs, "=>")
isArrow = false
} else {
segs = append(segs, string(s))
if prevIsArrow {
prevIsArrow = false
}
}
total++
} else {
segs[total-1] = string(s) + segs[total-1]
}
prevIsSpace = false
}
}
total = len(segs)
if total != maxNum+1 {
errmsg = normalErr
} else {
if (hasKey && segs[1] != "=>") || segs[total-2] != "as" {
return "wrong syntax \"foreach\" block, please check the compile mode"
}
list = &Prop{
Raw: segs[total-1],
}
if !hasKey {
key = &Prop{
Raw: "",
}
} else {
key = &Prop{
Raw: segs[total-3],
}
}
value = &Prop{
Raw: segs[0],
}
}
} else {
return "the Gofet mode does not support 'foreach' block, use 'for' instead"
}
} else {
needTryForIn := true
if isSmartyMode || len(strings.Split(content, ";")) >= 3 {
needTryForIn = false
i := 0
num := len(runes)
colon := ';'
part := []string{}
allParts := [][][]string{}
isInCont := false
isInTranslate := false
isInQuote := false
bLevel := 0
addParts := func(part []string) {
if len(allParts) <= total {
allParts = append(allParts, [][]string{})
}
allParts[total] = append(allParts[total], part)
}
for i < num && total < 3 {
s := runes[i]
ch := string(s)
count := len(part)
i++
if isInQuote || isInTranslate {
// check if is quote or translate
part[count-1] += ch
if isInTranslate {
isInTranslate = false
} else {
if s == '"' {
isInQuote = false
} else if s == '\\' {
isInTranslate = true
}
}
} else {
if unicode.IsSpace(s) {
// empty
if isInCont {
part[count-1] += ch
}
continue
}
if s == '"' {
isInQuote = true
} else if s == '(' {
bLevel++
} else if s == ')' {
bLevel--
} else if bLevel == 0 {
isColon := s == colon
if isColon || s == ',' {
addParts(part)
if isColon {
total++
}
part = []string{}
isInCont = false
continue
} else {
if total == 0 {
if s == '=' {
part = append(part, "=")
isInCont = false
continue
}
} else if total == 2 {
if s == '-' || s == '+' {
if i >= num {
errmsg = "wrong iterator done"
break
} else {
next := runes[i]
if next == '=' || next == s {
part = append(part, ch+string(next))
i++
} else {
errmsg = "wrong iterator done"
break
}