-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
372 lines (335 loc) · 9.19 KB
/
parser.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
package main
import (
"fmt"
"strconv"
"strings"
)
type GorType interface {
string | int | float32 | rune
}
type Node any
type JumptoNode struct {
LabelIdent Token
}
type LabelNode struct {
Name Token
}
type ModuleImportNode struct {
PathIdent Token
}
type AssignableValue interface {
Generate(*map[string]any, *map[string]any) any
}
type IfStatementNode struct {
Expr AssignableValue
Nodes []Node
}
type ElsifStatementNode struct {
Expr AssignableValue
Nodes []Node
}
type ElseStatementNode struct {
Nodes []Node
}
type FunccallNode struct {
Ident Token
args []AssignableValue
}
func (fn FunccallNode) GenerateArgs(vars *map[string]any, funcs *map[string]any) []any {
var out []any
for _, a := range fn.args {
out = append(out, a.Generate(vars, funcs))
}
return out
}
type AssignmentNode struct {
Ident Token
Value AssignableValue
}
func RemoveNewlineTokens(tokens []Token) []Token {
var out []Token
for _, t := range tokens {
if t.Type != NEWLINE {
out = append(out, t)
}
}
return out
}
func CheckTokenType(tokens []Token, index int, _type tokType) bool {
if index < len(tokens) {
return tokens[index].Istype(_type)
}
return false
}
func CollectUntilToken(tokens []Token, _type tokType, oposing_type tokType) ([]Token, bool) {
nest := 0
var out []Token
gotBroken := false
for _, t := range tokens {
if t.Istype(_type) {
if nest > 0 {
nest--
continue
}
gotBroken = true
break
} else if t.Istype(oposing_type) && oposing_type != NULLTOKEN {
nest++
}
out = append(out, t)
}
return out, gotBroken
}
func IndexTokens(tokens []Token, _type tokType) int {
for i, t := range tokens {
if t.Istype(_type) {
return i
}
}
return -1
}
func IndexTokensWithCascadeFailsafe(tokens []Token, types []tokType) int {
i := 0
index := -1
for i < len(types) {
index = IndexTokens(tokens, types[i])
if index == -1 {
i++
continue
}
break
}
return index
}
func GenerateExpressionNodeFromTokens(tokens []Token) (AssignableValue, error) {
tokens = RemoveNewlineTokens(tokens)
if len(tokens) == 0 {
panic("length of tokens is 0")
} else if len(tokens) == 1 {
return ValueNode{Val: tokens[0]}, nil
}
index := IndexTokensWithCascadeFailsafe(tokens, []tokType{AND, OR, EQUALS, NOT_EQUALS, GREATER_THAN, LESSER_THAN, FORWARD_SLASH, PERCENT_SIGN, ASTERISK, HYPHEN, PLUS})
if index == -1 {
return ExpressionNode{}, fmt.Errorf("invalid tokens for expression: %v", tokens)
}
op := tokens[index]
left := tokens[:index]
right := tokens[index+1:]
genLeft, leftErr := GenerateExpressionNodeFromTokens(left)
if leftErr != nil {
return ExpressionNode{}, leftErr
}
genRight, rightErr := GenerateExpressionNodeFromTokens(right)
if rightErr != nil {
return ExpressionNode{}, rightErr
}
return ExpressionNode{Left: genLeft, Operand: op, Right: genRight}, nil
}
type ExpressionNode struct {
Left AssignableValue
Operand Token
Right AssignableValue
}
func (expr ExpressionNode) Generate(vars *map[string]any, funcs *map[string]any) any {
left := expr.Left.Generate(vars, funcs)
_, leftIsString := left.(string)
_, leftIsInt := left.(int)
_, leftIsFloat32 := left.(float32)
_, leftIsError := left.(error)
right := expr.Right.Generate(vars, funcs)
_, rightIsString := right.(string)
_, rightIsInt := right.(int)
_, rightIsFloat32 := right.(float32)
_, rightIsError := right.(error)
if leftIsError {
return left
} else if rightIsError {
return right
}
switch expr.Operand.Type {
case PLUS:
if leftIsString && rightIsString {
return left.(string) + right.(string)
} else if leftIsInt && rightIsInt {
return left.(int) + right.(int)
} else if leftIsFloat32 && rightIsFloat32 {
return left.(float32) + right.(float32)
}
case HYPHEN:
if leftIsInt && rightIsInt {
return left.(int) - right.(int)
} else if leftIsFloat32 && rightIsFloat32 {
return left.(float32) - right.(float32)
}
case ASTERISK:
if leftIsString && rightIsInt {
acc := ""
for range right.(int) {
acc += left.(string)
}
return acc
} else if leftIsInt && rightIsInt {
return left.(int) * right.(int)
} else if leftIsFloat32 && rightIsFloat32 {
return left.(float32) * right.(float32)
}
case FORWARD_SLASH:
if leftIsInt && rightIsInt {
return left.(int) / right.(int)
} else if leftIsFloat32 && rightIsFloat32 {
return left.(float32) / right.(float32)
}
case PERCENT_SIGN:
if leftIsInt && rightIsInt {
return left.(int) % right.(int)
}
case EQUALS:
return left == right
case NOT_EQUALS:
return left != right
case GREATER_THAN:
if leftIsInt && rightIsInt {
return left.(int) > right.(int)
} else if leftIsFloat32 && rightIsFloat32 {
return left.(float32) > right.(float32)
}
case LESSER_THAN:
if leftIsInt && rightIsInt {
return left.(int) < right.(int)
} else if leftIsFloat32 && rightIsFloat32 {
return left.(float32) < right.(float32)
}
}
return nil
}
type ValueNode struct {
Val Token
}
func (v ValueNode) Generate(vars *map[string]any, funcs *map[string]any) any {
switch v.Val.Type {
case STRING:
return v.Val.Lit
case NUMBER:
if strings.Contains(v.Val.Lit, ".") {
res, _ := strconv.ParseFloat(v.Val.Lit, 32)
return float32(res)
}
res, _ := strconv.Atoi(v.Val.Lit)
return res
case IDENT:
if _, ok := (*vars)[v.Val.Lit]; !ok {
return fmt.Errorf("unknown variable '%s'", v.Val.Lit)
}
return (*vars)[v.Val.Lit]
}
return nil
}
func Parse(tokens []Token) ([]Node, error) {
if len(tokens) == 0 {
return []Node{}, nil
}
if tokens[len(tokens)-1].Type == EOF {
tokens = tokens[:len(tokens)-1]
}
var nodes []Node
idx := 0
for idx < len(tokens) {
if tokens[idx].Istype(NEWLINE) {
idx++
} else if tokens[idx].Istype(IDENT) {
ident := tokens[idx]
idx++
if tokens[idx].Istype(ASSIGN) {
idx++
//fmt.Println(tokens)
exprToks, _ := CollectUntilToken(tokens[idx:], SEMICOLON, NULLTOKEN)
if len(exprToks) == 0 {
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("expected expression, but found '%s' instead", string(tokens[idx].Lit)))
}
gen, err := GenerateExpressionNodeFromTokens(exprToks)
if err != nil {
return []Node{}, err
}
nodes = append(nodes, AssignmentNode{Ident: ident, Value: gen})
if !CheckTokenType(tokens, idx+len(exprToks), SEMICOLON) {
return []Node{}, NewGorError(tokens[idx], "expected ';'")
}
idx += len(exprToks) + 1
} else {
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("expected assign glyph, but found '%s' instead", string(tokens[idx].Lit)))
}
} else if tokens[idx].Istype(COLON) {
if idx+1 < len(tokens) {
if idx+2 < len(tokens) {
if !tokens[idx+2].Istype(COLON) {
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("expected colon(':'), but found '%s' instead", string(tokens[idx].Lit)))
}
nodes = append(nodes, LabelNode{Name: tokens[idx+1]})
idx += 3
} else {
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("expected colon(':'), but found '%s' instead", string(tokens[idx].Lit)))
}
} else {
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("expected identifier, but found '%s' instead", string(tokens[idx].Lit)))
}
} else if tokens[idx].Istype(KEYWORD) {
switch tokens[idx].Lit {
case "if", "elsif", "else":
orig := tokens[idx].Lit
idx++
ifExprToks, ok := CollectUntilToken(tokens[idx:], LBRACE, NULLTOKEN)
if !ok {
return []Node{}, NewGorError(tokens[idx-1], "expected '{'")
}
idx += len(ifExprToks) + 1
ifBodyToks, ok := CollectUntilToken(tokens[idx:], RBRACE, LBRACE)
if !ok {
return []Node{}, NewGorError(tokens[idx-1], "expected '}'")
}
//fmt.Println("body", ifBodyToks)
ifBodyNodes, ifParseErr := Parse(ifBodyToks)
if ifParseErr != nil {
return []Node{}, ifParseErr
}
if orig == "elsif" {
gen, err := GenerateExpressionNodeFromTokens(ifExprToks)
if err != nil {
return []Node{}, err
}
nodes = append(nodes, ElsifStatementNode{Expr: gen, Nodes: ifBodyNodes})
} else if orig == "else" {
nodes = append(nodes, ElseStatementNode{Nodes: ifBodyNodes})
} else {
gen, err := GenerateExpressionNodeFromTokens(ifExprToks)
if err != nil {
return []Node{}, err
}
nodes = append(nodes, IfStatementNode{Expr: gen, Nodes: ifBodyNodes})
}
idx += len(ifBodyToks) + 1
case "jumpto":
if CheckTokenType(tokens, idx+1, IDENT) {
if !CheckTokenType(tokens, idx+2, SEMICOLON) {
return []Node{}, NewGorError(tokens[idx+1], "expected ';'")
}
nodes = append(nodes, JumptoNode{tokens[idx+1]})
idx += 3
continue
}
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("expected identifier, but found '%s' instead", string(tokens[idx].Lit)))
case "use":
if CheckTokenType(tokens, idx+1, STRING) {
nodes = append(nodes, ModuleImportNode{tokens[idx+1]})
idx += 2
continue
}
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("expected string, but found '%s' instead", string(tokens[idx].Lit)))
default:
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("unknown keyword '%s'", tokens[idx].Lit))
}
} else {
return []Node{}, NewGorError(tokens[idx], fmt.Sprintf("unexpected '%s'", tokens[idx].Lit))
}
}
return nodes, nil
}