-
Notifications
You must be signed in to change notification settings - Fork 9
/
parse_range_stmt.go
66 lines (58 loc) · 1.56 KB
/
parse_range_stmt.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
package main
import (
"go/ast"
"log"
"strings"
)
func ParseRangeStmt(stmt *ast.RangeStmt, objectTypeMap *ObjectTypeMap) []string {
var ret[]string
var key string = "nil"
var val string = "nil"
tok := stmt.Tok.String()
x := ParseExpr(stmt.X)
objType, err := FindObjectMap(objectTypeMap, x)
if err != nil {
log.Fatal("can not find object type: " + x)
}
if strings.HasPrefix(objType, "unknown") {
log.Fatal("unknown object type: " + x)
}
// whether range object is a map
var isMap = strings.Contains(objType, "map")
if stmt.Key != nil {
key = ParseExpr(stmt.Key)
}
if stmt.Value != nil {
val = ParseExpr(stmt.Value)
}
var keyValType string
if tok == ":=" {
keyValType = "auto "
} else if tok == "=" {
keyValType = ""
} else {
log.Fatal("invalid token type in range for: " + tok)
}
if isMap {
// range for map
ret = append(ret, "for (" + keyValType + " [" + key + ", " + val + "] : " + x + ") {")
} else {
// range for array
if key == "_" {
ret = append(ret, "for (" + keyValType + " " + val + " : " + x + ") {")
} else if val == "nil" {
// only exist key
ret = append(ret, "for (" + keyValType + " " + key + " = 0; " + key + "< " + x + ".size(); " + key + "++ ) {")
} else {
ret = append(ret, "for (" + keyValType + " " + key + " = 0; " + key + "< " + x + ".size(); " + key + "++ ) {")
ret = append(ret, keyValType + val + " = " + x + "[" + key + "];")
}
}
if stmt.Body == nil {
ret = append(ret, "{}")
} else {
ret = append(ret, ParseBlockStmt(stmt.Body, objectTypeMap)...)
}
ret = append(ret, "}")
return ret
}