/
lazy.go
130 lines (110 loc) · 2.69 KB
/
lazy.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
package parser
import (
"errors"
"strconv"
"strings"
)
const (
lazyTag = "// @Lazy"
lazyName = "@Lazy"
varCommand = "var"
ifCommand = "if"
rangeCommand = "range"
scopeCommand = "scope"
)
func IsLazyCommand(line string) bool {
line = strings.TrimSpace(line)
return strings.HasPrefix(line, lazyTag)
}
type Command struct {
ValCommand []VarCommand
IfCommand []IfCommand
RangeCommand []RangeCommand
}
type VarCommand struct {
Variable string // variable
Target string // replace the content
Scope int // affected scope
}
type IfCommand struct {
Expr string // judgment condition
Scope int // affected scope
}
type RangeCommand struct {
Expr string // judgment condition
Scope int // affected scope
Loop int
TagId int // slot tag id
Counter int
Action [][][]RangeAction
}
type RangeAction struct {
Target string // replace the content
Value string // current slot value
}
func ParseLazyCommand(line string) (command Command, err error) {
var (
scopeLine int
)
if !IsLazyCommand(line) {
return command, errors.New("invalid lazy command")
}
oTagList := strings.Split(line, " ")
for _, oTag := range oTagList {
//parse scope command
if strings.HasPrefix(oTag, scopeCommand) {
vList := strings.Split(oTag, ":")
if len(vList) != 2 {
return command, errors.New("invalid range command, error: " + oTag)
}
scopeLine, err = strconv.Atoi(vList[1])
if err != nil {
return command, err
}
break
}
}
for _, oTag := range oTagList {
if oTag == "//" || oTag == " " || oTag == lazyName {
continue
}
//parse var command
if strings.HasPrefix(oTag, varCommand) {
vList := strings.Split(oTag, ">")
if len(vList) != 2 {
return command, errors.New("invalid var command, error: " + oTag)
}
replaceCommand := VarCommand{}
replaceCommand.Variable = vList[0][len(varCommand)+1:]
replaceCommand.Target = vList[1]
replaceCommand.Scope = scopeLine
command.ValCommand = append(command.ValCommand, replaceCommand)
continue
}
//parse if command
if strings.HasPrefix(oTag, ifCommand) {
vList := strings.Split(oTag, ":")
if len(vList) != 2 {
return command, errors.New("invalid if command, error: " + oTag)
}
command.IfCommand = append(command.IfCommand, IfCommand{
Expr: vList[1],
Scope: scopeLine,
})
continue
}
//parse range command
if strings.HasPrefix(oTag, rangeCommand) {
vList := strings.Split(oTag, ":")
if len(vList) != 2 {
return command, errors.New("invalid range command, error: " + oTag)
}
command.RangeCommand = append(command.RangeCommand, RangeCommand{
Expr: vList[1],
Scope: scopeLine,
})
continue
}
}
return command, nil
}