-
Notifications
You must be signed in to change notification settings - Fork 28
/
gogen_util.go
99 lines (85 loc) · 2.32 KB
/
gogen_util.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
// Copyright 2017 Felix Lange <[email protected]>.
// Use of this source code is governed by the MIT license,
// which can be found in the LICENSE file.
package main
import (
"go/ast"
"go/token"
"go/types"
"strconv"
. "github.com/garslo/gogen"
)
func errCheck(expr Expression) If {
err := Name("err")
return If{
Init: DeclareAndAssign{Lhs: err, Rhs: expr},
Condition: NotEqual{Lhs: err, Rhs: NIL},
Body: []Statement{Return{Values: []Expression{err}}},
}
}
// makeCall creates a call like `make(typ, len(lenfrom))`.
func makeCall(typ types.Type, lenfrom Expression, qf types.Qualifier) Expression {
return CallFunction{Func: Name("make"), Params: []Expression{
Name(types.TypeString(typ, qf)),
CallFunction{Func: Name("len"), Params: []Expression{lenfrom}},
}}
}
// lenCall creates a call like `len(v)`.
func lenCall(v Expression) Expression {
return CallFunction{Func: Name("len"), Params: []Expression{v}}
}
// errorsNewCall creates a call like `errors.New(errmsg)`.
func errorsNewCall(sc *fileScope, errmsg string) Expression {
errors := sc.packageName("errors")
return CallFunction{
Func: Dotted{Receiver: Name(errors), Name: "New"},
Params: []Expression{stringLit{errmsg}},
}
}
// hasSideEffects returns whether an expression may have side effects.
func hasSideEffects(expr Expression) bool {
switch expr := expr.(type) {
case Var:
return false
case Dotted:
return hasSideEffects(expr.Receiver)
case Star:
return hasSideEffects(expr.Value)
case Index:
return hasSideEffects(expr.Index) && hasSideEffects(expr.Value)
default:
return true
}
}
// stringLit is a string literal expression.
type stringLit struct {
V string
}
func (l stringLit) Expression() ast.Expr {
return &ast.BasicLit{Kind: token.STRING, Value: strconv.Quote(l.V)}
}
// declStmt is a declaration statement.
type declStmt struct {
d Declaration
}
func (ds declStmt) Statement() ast.Stmt {
return &ast.DeclStmt{Decl: ds.d.Declaration()}
}
// sliceExpr is a slicing expression Value[Low:High:Cap].
type sliceExpr struct {
Value Expression
Low, High, Cap Expression
}
func (s sliceExpr) Expression() ast.Expr {
sl := &ast.SliceExpr{X: s.Value.Expression()}
if s.Low != nil {
sl.Low = s.Low.Expression()
}
if s.High != nil {
sl.High = s.High.Expression()
}
if s.Cap != nil {
sl.Max = s.Cap.Expression()
}
return sl
}