forked from awfeequdng/px_golang2cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_switch_stmt.go
89 lines (81 loc) · 2.06 KB
/
parse_switch_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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"go/ast"
"log"
)
// ParseNoConditionCaseClause use 'if' instead of 'case'
func ParseNoConditionCaseClause(caseClause *ast.CaseClause, objectTypeMap *ObjectTypeMap) []string {
var ret []string
var caseList []string
for _, l := range caseClause.List {
caseList = append(caseList, ParseExpr(l))
}
var body []string
var bodyCnt = 0
body = append(body, "{")
for _, b := range caseClause.Body {
body = append(body, ParseStmt(&b, objectTypeMap)...)
bodyCnt++
}
body = append(body, "}")
if len(caseList) == 0 {
// default
ret = append(ret, " ")
} else {
ret = append(ret, " if (")
for id, c := range caseList {
if id == 0 {
ret = append(ret, c)
} else {
ret = append(ret, " || " + c)
}
}
ret = append(ret, ")")
}
ret = append(ret, body...)
return ret
}
func ParseNoConditionSwitchStmt(switchStmt *ast.SwitchStmt, objectTypeMap *ObjectTypeMap) [] string {
var ret []string
if switchStmt.Init != nil {
ret = append(ret, "{")
ret = append(ret, ParseStmt(&switchStmt.Init, objectTypeMap)...)
}
bodyCnt := len(switchStmt.Body.List)
for id, l := range switchStmt.Body.List {
var body []string
if clause, ok := l.(*ast.CaseClause); ok {
body = append(body, ParseNoConditionCaseClause(clause, objectTypeMap)...)
} else {
log.Fatal("invalid case clause")
}
ret = append(ret, body...)
if id != bodyCnt - 1 {
ret = append(ret, " else ")
}
}
if switchStmt.Init != nil {
ret = append(ret, "}")
}
return ret
}
func ParseSwitchStmt(switchStmt *ast.SwitchStmt, objectTypeMap *ObjectTypeMap) []string {
var ret []string
var tag string
if switchStmt.Tag == nil {
return ParseNoConditionSwitchStmt(switchStmt, objectTypeMap)
}
tag = ParseExpr(switchStmt.Tag)
body := ParseBlockStmt(switchStmt.Body, objectTypeMap)
if switchStmt.Init != nil {
ret = append(ret, "{")
ret = append(ret, ParseStmt(&switchStmt.Init, objectTypeMap)...)
}
ret = append(ret, "switch(" + tag + ") {")
ret = append(ret, body...)
ret = append(ret, "}")
if switchStmt.Init != nil {
ret = append(ret, "}")
}
return ret
}