-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathfunc.go
More file actions
307 lines (268 loc) · 8.9 KB
/
Copy pathfunc.go
File metadata and controls
307 lines (268 loc) · 8.9 KB
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
/*
Copyright 2021 The XGo Authors (xgo.dev)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gogen
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"github.com/goplus/gogen/internal"
"github.com/goplus/gogen/target"
)
// ----------------------------------------------------------------------------
// NewParam returns a new variable representing a function parameter with optional flag.
func (p *Package) NewParam(pos token.Pos, name string, typ types.Type, optional bool) *types.Var {
param := types.NewParam(pos, p.Types, name, typ)
if optional {
p.setParamOptional(param)
}
return param
}
// ----------------------------------------------------------------------------
// Func type
type Func struct {
*types.Func
decl *funcDecl
cate AutoLambdaCategory
old funcBodyCtx
arity1 int // 0 for normal, (arity+1) for inlineClosure
}
// Obj returns this function object.
func (p *Func) Obj() types.Object {
return p.Func
}
// Comments returns associated documentation.
func (p *Func) Comments() *ast.CommentGroup {
return p.decl.Doc
}
// SetComments sets associated documentation.
func (p *Func) SetComments(pkg *Package, doc *ast.CommentGroup) *Func {
p.decl.Doc = doc
pkg.setDoc(p.Func, doc)
return p
}
// Ancestor returns ancestor of a closure function.
// It returns itself if the specified func is a normal function.
func (p *Func) Ancestor() *Func {
for p.Name() == "" && p.old.fn != nil {
p = p.old.fn
}
return p
}
// BodyStart func
func (p *Func) BodyStart(pkg *Package, src ...ast.Node) *CodeBuilder {
if debugInstr {
var recv string
tag := "NewFunc "
name := p.Name()
sig := p.Type().(*types.Signature)
if v := sig.Recv(); IsMethodRecv(v) {
recv = fmt.Sprintf(" (%v)", v.Type())
}
if name == "" {
tag = "NewClosure"
}
log.Printf("%v%v%v %v\n", tag, name, recv, sig)
}
return pkg.cb.startFuncBody(p, src, &p.old)
}
const (
cantUseFlowsInAutoLambda = "can't use return/continue/break/goto in auto lambda"
)
// End is for internal use.
func (p *Func) End(cb *CodeBuilder, src ast.Node) {
if p.isInline() {
p.inlineClosureEnd(cb)
return
}
pkg := cb.pkg
checker := termChecker{cb.current.panicCalls}
fnBody, flows := cb.endFuncBody(p.old)
cate := p.cate
if cate != AutoLambdaNormal {
if flows != 0 {
cb.handleCodeError(getSrcPos(src), getSrcEnd(src), cantUseFlowsInAutoLambda)
} else {
fnBody = return0IfNeeded(fnBody)
}
}
body := &target.BlockStmt{List: fnBody}
t := p.Type().(*types.Signature)
// Check for missing return at the closing brace position.
// For FuncDecl/FuncLit/BlockStmt, End() returns Rbrace+1, so End()-1 is the Rbrace position.
if cate == AutoLambdaNormal && t.Results().Len() > 0 && !checker.isTerminating(body, "") {
pos, end := token.NoPos, token.NoPos
if src != nil {
end = src.End()
pos = end - 1
}
cb.handleCodeError(pos, end, "missing return")
}
if fn := p.decl; fn == nil { // is closure
expr := newFuncLit(pkg, t, body)
cb.stk.Push(&internal.Elem{Val: expr, Type: t, Src: src})
} else {
fn.Name, fn.Type, fn.Body = &ast.Ident{Name: p.Name()}, toFuncType(pkg, t), body
if recv := t.Recv(); IsMethodRecv(recv) {
fn.Recv = toRecv(pkg, recv)
}
}
}
// NewFuncDecl creates a new function without function body (declaration only).
func (p *Package) NewFuncDecl(pos token.Pos, name string, sig *types.Signature) *Func {
f, err := p.NewFuncWith(pos, name, sig, nil)
if err != nil {
panic(err)
}
fn := f.decl
fn.Name, fn.Type = &ast.Ident{Name: name}, toFuncType(p, sig)
return f
}
// validateParamOrder validates that optional parameters come after positional parameters
// and before any variadic parameter.
// Valid order: positional → optional → variadic
func (p *Package) validateParamOrder(cb *CodeBuilder, pos token.Pos, params *types.Tuple, variadic bool) error {
n := params.Len()
foundOptional := false
for i := 0; i < n; i++ {
param := params.At(i)
isOptional := p.isParamOptional(param)
// If variadic is true, the last parameter is the variadic parameter
isVariadicParam := variadic && i == n-1
if isOptional {
if isVariadicParam {
// Optional parameter cannot also be variadic
return cb.newCodeErrorf(param.Pos(), param.Pos(), "variadic parameter cannot be optional")
}
foundOptional = true
} else if foundOptional && !isVariadicParam {
// Found a positional parameter after an optional one (and it's not the variadic param)
return cb.newCodeErrorf(param.Pos(), param.Pos(), "positional parameter %s must come before optional parameters", param.Name())
}
}
return nil
}
// NewFunc creates a new function (should have a function body).
func (p *Package) NewFunc(recv *types.Var, name string, params, results *types.Tuple, variadic bool) *Func {
sig := types.NewSignatureType(recv, nil, nil, params, results, variadic)
f, err := p.NewFuncWith(token.NoPos, name, sig, nil)
if err != nil {
panic(err)
}
return f
}
func getRecv(recvTypePos func() token.Pos) token.Pos {
if recvTypePos != nil {
return recvTypePos()
}
return token.NoPos
}
func IsMethodRecv(recv *types.Var) bool {
return recv != nil
}
// NewFuncWith creates a new function (should have a function body).
func (p *Package) NewFuncWith(
pos token.Pos, name string, sig *types.Signature, recvTypePos func() token.Pos) (*Func, error) {
if name == "" {
panic("no func name")
}
cb := p.cb
if err := p.validateParamOrder(&cb, pos, sig.Params(), sig.Variadic()); err != nil {
return nil, err
}
fn := &Func{Func: types.NewFunc(pos, p.Types, name, sig)}
if recv := sig.Recv(); IsMethodRecv(recv) { // add method to this type
var t *types.Named
var ok bool
var typ = recv.Type()
switch tt := typ.(type) {
case *types.Named:
t, ok = tt, true
case *types.Pointer:
typ = tt.Elem()
t, ok = typ.(*types.Named)
}
if !ok {
posErr := getRecv(recvTypePos)
return nil, cb.newCodeErrorf(posErr, posErr, "invalid receiver type %v (%v is not a defined type)", typ, typ)
}
switch getUnderlying(p, t.Obj().Type()).(type) {
case *types.Interface:
posErr := getRecv(recvTypePos)
return nil, cb.newCodeErrorf(posErr, posErr, "invalid receiver type %v (%v is an interface type)", typ, typ)
case *types.Pointer:
posErr := getRecv(recvTypePos)
return nil, cb.newCodeErrorf(posErr, posErr, "invalid receiver type %v (%v is a pointer type)", typ, typ)
}
if name != "_" { // skip underscore
if _, obj := lookupStaticMember(t, name); obj != nil {
return nil, cb.newCodeErrorf(pos, pos, "method %s conflicts with existing %s", name, staticMemberKind(obj))
}
t.AddMethod(fn.Func)
}
} else if name == "init" { // init is not a normal func
if sig.Params() != nil || sig.Results() != nil {
return nil, cb.newCodeErrorf(
pos, pos, "func init must have no arguments and no return values")
}
} else if name != "_" { // skip underscore
old := p.Types.Scope().Insert(fn.Obj())
if old != nil {
if !(p.allowRedecl && types.Identical(old.Type(), sig)) { // for c2go
oldPos := cb.fset.Position(old.Pos())
return nil, cb.newCodeErrorf(
pos, pos, "%s redeclared in this block\n\t%v: other declaration of %s", name, oldPos, name)
}
}
p.useName(name)
}
if isXGoFunc(name) {
p.isXGoPkg = true
}
if token.IsExported(name) {
p.expObjTypes = append(p.expObjTypes, sig)
}
fn.decl = &funcDecl{}
p.file.appendFuncDecl(fn.decl, sig)
return fn, nil
}
func (p *Package) newClosure(sig *types.Signature, cate AutoLambdaCategory) *Func {
fn := types.NewFunc(token.NoPos, p.Types, "", sig)
return &Func{Func: fn, cate: cate}
}
func (p *Package) newInlineClosure(sig *types.Signature, arity int) *Func {
fn := types.NewFunc(token.NoPos, p.Types, "", sig)
return &Func{Func: fn, arity1: arity + 1}
}
func (p *Func) isInline() bool {
return p.arity1 != 0
}
func (p *Func) getInlineCallArity() int {
return p.arity1 - 1
}
// ----------------------------------------------------------------------------
type Element = internal.Elem
type InstrFlags token.Pos
const (
InstrFlagEllipsis InstrFlags = 1 << iota
instrFlagApproxType // restricts to all types whose underlying type is T
instrFlagXGoxFunc // call XGox_xxx function
instrFlagXGotFunc // call XGot_xxx function
instrFlagBinaryOp // from cb.BinaryOp
instrFlagUntyped // return type should be mapped to the corresponding untyped kind
)
type Instruction interface {
Call(pkg *Package, args []*Element, lhs int, flags InstrFlags, src ast.Node) (ret *Element, err error)
}
// ----------------------------------------------------------------------------