-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr_of_binary.go
47 lines (44 loc) · 947 Bytes
/
expr_of_binary.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
package gocode
import (
"fmt"
"go/ast"
"reflect"
)
// 表示一個值
type BinaryExpr struct {
Expr *ast.BinaryExpr
}
func NewBinaryExpr(expr *ast.BinaryExpr) *BinaryExpr {
return &BinaryExpr{
Expr: expr,
}
}
func (b *BinaryExpr) String() string {
var (
exprs = []ast.Expr{b.Expr.X, b.Expr.Y}
strs = []string{"", ""}
s string
)
for i, expr := range exprs {
switch t := expr.(type) {
case *ast.Ident:
s = t.Name
case *ast.SelectorExpr:
s = NewSelectorExpr(t).TypeString()
case *ast.BasicLit:
s = t.Value
case *ast.BinaryExpr:
s = NewBinaryExpr(t).String()
case *ast.UnaryExpr:
s = t.Op.String() + NewValueExpr(t.X).String()
case *ast.ParenExpr:
s = `(` + NewValueExpr(t.X).String() + `)`
case *ast.CallExpr:
s = NewCallExpr(t).String()
default:
panic(`unknow x type` + reflect.TypeOf(t).String())
}
strs[i] = s
}
return fmt.Sprintf(`%s %s %s`, strs[0], b.Expr.Op, strs[1])
}