-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathcodebuild.go
2814 lines (2596 loc) · 69.5 KB
/
codebuild.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
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2021 The GoPlus Authors (goplus.org)
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 (
"errors"
"fmt"
"go/ast"
"go/constant"
"go/token"
"go/types"
"log"
"math/big"
"reflect"
"strconv"
"strings"
"syscall"
"github.com/goplus/gogen/internal"
xtoken "github.com/goplus/gogen/token"
"golang.org/x/tools/go/types/typeutil"
)
func getSrc(node []ast.Node) ast.Node {
if node != nil {
return node[0]
}
return nil
}
func getSrcPos(node ast.Node) token.Pos {
if node != nil {
return node.Pos()
}
return token.NoPos
}
func getPos(src []ast.Node) token.Pos {
if src == nil {
return token.NoPos
}
return getSrcPos(src[0])
}
// ----------------------------------------------------------------------------
type posNode struct {
pos, end token.Pos
}
func NewPosNode(pos token.Pos, end ...token.Pos) ast.Node {
ret := &posNode{pos: pos, end: pos}
if end != nil {
ret.end = end[0]
}
return ret
}
func (p *posNode) Pos() token.Pos { return p.pos }
func (p *posNode) End() token.Pos { return p.end }
// ----------------------------------------------------------------------------
type codeBlock interface {
End(cb *CodeBuilder, src ast.Node)
}
type vblockCtx struct {
codeBlock
scope *types.Scope
}
type codeBlockCtx struct {
codeBlock
scope *types.Scope
base int
stmts []ast.Stmt
label *ast.LabeledStmt
flows int // flow flags
}
const (
flowFlagBreak = 1 << iota
flowFlagContinue
flowFlagReturn
flowFlagGoto
flowFlagWithLabel
)
type Label struct {
types.Label
used bool
}
type funcBodyCtx struct {
codeBlockCtx
fn *Func
labels map[string]*Label
}
func (p *funcBodyCtx) checkLabels(cb *CodeBuilder) {
for name, l := range p.labels {
if !l.used {
cb.handleCodeErrorf(l.Pos(), "label %s defined and not used", name)
}
}
}
type CodeError struct {
Fset dbgPositioner
Pos token.Pos
Msg string
}
func (p *CodeError) Error() string {
pos := p.Fset.Position(p.Pos)
return fmt.Sprintf("%v: %s", pos, p.Msg)
}
// CodeBuilder type
type CodeBuilder struct {
stk internal.Stack
current funcBodyCtx
fset dbgPositioner
comments *ast.CommentGroup
pkg *Package
btiMap *typeutil.Map
valDecl *ValueDecl
ctxt *typesContext
interp NodeInterpreter
rec Recorder
loadNamed LoadNamedFunc
handleErr func(err error)
closureParamInsts
iotav int
commentOnce bool
noSkipConst bool
}
func (p *CodeBuilder) init(pkg *Package) {
conf := pkg.conf
p.pkg = pkg
p.fset = conf.DbgPositioner
if p.fset == nil {
p.fset = conf.Fset
}
p.noSkipConst = conf.NoSkipConstant
p.handleErr = conf.HandleErr
if p.handleErr == nil {
p.handleErr = defaultHandleErr
}
p.rec = conf.Recorder
p.interp = conf.NodeInterpreter
if p.interp == nil {
p.interp = nodeInterp{}
}
p.ctxt = newTypesContext()
p.loadNamed = conf.LoadNamed
if p.loadNamed == nil {
p.loadNamed = defaultLoadNamed
}
p.current.scope = pkg.Types.Scope()
p.stk.Init()
p.closureParamInsts.init()
}
func defaultLoadNamed(at *Package, t *types.Named) {
// no delay-loaded named types
}
func defaultHandleErr(err error) {
panic(err)
}
type nodeInterp struct{}
func (p nodeInterp) LoadExpr(expr ast.Node) string {
return ""
}
func getFunExpr(fn *internal.Elem) (caller string, pos token.Pos) {
if fn == nil {
return "the closure call", token.NoPos
}
caller = types.ExprString(fn.Val)
pos = getSrcPos(fn.Src)
return
}
func getCaller(expr *internal.Elem) string {
if ce, ok := expr.Val.(*ast.CallExpr); ok {
return types.ExprString(ce.Fun)
}
return "the function call"
}
func (p *CodeBuilder) loadExpr(expr ast.Node) (string, token.Pos) {
if expr == nil {
return "", token.NoPos
}
return p.interp.LoadExpr(expr), expr.Pos()
}
func (p *CodeBuilder) newCodeError(pos token.Pos, msg string) *CodeError {
return &CodeError{Msg: msg, Pos: pos, Fset: p.fset}
}
func (p *CodeBuilder) newCodeErrorf(pos token.Pos, format string, args ...interface{}) *CodeError {
return p.newCodeError(pos, fmt.Sprintf(format, args...))
}
func (p *CodeBuilder) handleCodeError(pos token.Pos, msg string) {
p.handleErr(p.newCodeError(pos, msg))
}
func (p *CodeBuilder) handleCodeErrorf(pos token.Pos, format string, args ...interface{}) {
p.handleErr(p.newCodeError(pos, fmt.Sprintf(format, args...)))
}
func (p *CodeBuilder) panicCodeError(pos token.Pos, msg string) {
panic(p.newCodeError(pos, msg))
}
func (p *CodeBuilder) panicCodeErrorf(pos token.Pos, format string, args ...interface{}) {
panic(p.newCodeError(pos, fmt.Sprintf(format, args...)))
}
// Scope returns current scope.
func (p *CodeBuilder) Scope() *types.Scope {
return p.current.scope
}
// Func returns current func (nil means in global scope).
func (p *CodeBuilder) Func() *Func {
return p.current.fn
}
// Pkg returns the package instance.
func (p *CodeBuilder) Pkg() *Package {
return p.pkg
}
func (p *CodeBuilder) startFuncBody(fn *Func, src []ast.Node, old *funcBodyCtx) *CodeBuilder {
p.current.fn, old.fn = fn, p.current.fn
p.current.labels, old.labels = nil, p.current.labels
p.startBlockStmt(fn, src, "func "+fn.Name(), &old.codeBlockCtx)
scope := p.current.scope
sig := fn.Type().(*types.Signature)
insertParams(scope, sig.Params())
insertParams(scope, sig.Results())
if recv := sig.Recv(); recv != nil {
scope.Insert(recv)
}
return p
}
func insertParams(scope *types.Scope, params *types.Tuple) {
for i, n := 0, params.Len(); i < n; i++ {
v := params.At(i)
if name := v.Name(); name != "" && name != "_" {
scope.Insert(v)
}
}
}
func (p *CodeBuilder) endFuncBody(old funcBodyCtx) []ast.Stmt {
p.current.checkLabels(p)
p.current.fn = old.fn
p.current.labels = old.labels
stmts, _ := p.endBlockStmt(&old.codeBlockCtx)
return stmts
}
func (p *CodeBuilder) startBlockStmt(current codeBlock, src []ast.Node, comment string, old *codeBlockCtx) *CodeBuilder {
var start, end token.Pos
if src != nil {
start, end = src[0].Pos(), src[0].End()
}
scope := types.NewScope(p.current.scope, start, end, comment)
p.current.codeBlockCtx, *old = codeBlockCtx{current, scope, p.stk.Len(), nil, nil, 0}, p.current.codeBlockCtx
return p
}
func (p *CodeBuilder) endBlockStmt(old *codeBlockCtx) ([]ast.Stmt, int) {
flows := p.current.flows
if p.current.label != nil {
p.emitStmt(&ast.EmptyStmt{})
}
stmts := p.current.stmts
p.stk.SetLen(p.current.base)
p.current.codeBlockCtx = *old
return stmts, flows
}
func (p *CodeBuilder) clearBlockStmt() []ast.Stmt {
stmts := p.current.stmts
p.current.stmts = nil
return stmts
}
func (p *CodeBuilder) startVBlockStmt(current codeBlock, comment string, old *vblockCtx) *CodeBuilder {
*old = vblockCtx{codeBlock: p.current.codeBlock, scope: p.current.scope}
scope := types.NewScope(p.current.scope, token.NoPos, token.NoPos, comment)
p.current.codeBlock, p.current.scope = current, scope
return p
}
func (p *CodeBuilder) endVBlockStmt(old *vblockCtx) {
p.current.codeBlock, p.current.scope = old.codeBlock, old.scope
}
func (p *CodeBuilder) popStmt() ast.Stmt {
stmts := p.current.stmts
n := len(stmts) - 1
stmt := stmts[n]
p.current.stmts = stmts[:n]
return stmt
}
func (p *CodeBuilder) startStmtAt(stmt ast.Stmt) int {
idx := len(p.current.stmts)
p.emitStmt(stmt)
return idx
}
// Usage:
//
// idx := cb.startStmtAt(stmt)
// ...
// cb.commitStmt(idx)
func (p *CodeBuilder) commitStmt(idx int) {
stmts := p.current.stmts
n := len(stmts) - 1
if n > idx {
stmt := stmts[idx]
copy(stmts[idx:], stmts[idx+1:])
stmts[n] = stmt
}
}
func (p *CodeBuilder) emitStmt(stmt ast.Stmt) {
if p.comments != nil {
p.pkg.setStmtComments(stmt, p.comments)
if p.commentOnce {
p.comments = nil
}
}
if p.current.label != nil {
p.current.label.Stmt = stmt
stmt, p.current.label = p.current.label, nil
}
p.current.stmts = append(p.current.stmts, stmt)
}
func (p *CodeBuilder) startInitExpr(current codeBlock) (old codeBlock) {
p.current.codeBlock, old = current, p.current.codeBlock
return
}
func (p *CodeBuilder) endInitExpr(old codeBlock) {
p.current.codeBlock = old
}
// Comments returns the comments of next statement.
func (p *CodeBuilder) Comments() *ast.CommentGroup {
return p.comments
}
func (p *CodeBuilder) BackupComments() (*ast.CommentGroup, bool) {
return p.comments, p.commentOnce
}
// SetComments sets comments to next statement.
func (p *CodeBuilder) SetComments(comments *ast.CommentGroup, once bool) *CodeBuilder {
if debugComments && comments != nil {
for i, c := range comments.List {
log.Println("SetComments", i, c.Text)
}
}
p.comments, p.commentOnce = comments, once
return p
}
// ReturnErr func
func (p *CodeBuilder) ReturnErr(outer bool) *CodeBuilder {
if debugInstr {
log.Println("ReturnErr", outer)
}
fn := p.current.fn
if outer {
if !fn.isInline() {
panic("only support ReturnOuterErr in an inline call")
}
fn = fn.old.fn
}
results := fn.Type().(*types.Signature).Results()
n := results.Len()
if n > 0 {
last := results.At(n - 1)
if last.Type() == TyError { // last result is error
err := p.stk.Pop()
for i := 0; i < n-1; i++ {
p.doZeroLit(results.At(i).Type(), false)
}
p.stk.Push(err)
p.returnResults(n)
p.current.flows |= flowFlagReturn
return p
}
}
panic("TODO: last result type isn't an error")
}
func (p *CodeBuilder) returnResults(n int) {
var rets []ast.Expr
if n > 0 {
args := p.stk.GetArgs(n)
rets = make([]ast.Expr, n)
for i := 0; i < n; i++ {
rets[i] = args[i].Val
}
p.stk.PopN(n)
}
p.emitStmt(&ast.ReturnStmt{Results: rets})
}
// Return func
func (p *CodeBuilder) Return(n int, src ...ast.Node) *CodeBuilder {
if debugInstr {
log.Println("Return", n)
}
fn := p.current.fn
results := fn.Type().(*types.Signature).Results()
checkFuncResults(p.pkg, p.stk.GetArgs(n), results, getSrc(src))
if fn.isInline() {
for i := n - 1; i >= 0; i-- {
key := closureParamInst{fn, results.At(i)}
elem := p.stk.Pop()
p.doVarRef(p.paramInsts[key], nil, false)
p.stk.Push(elem)
p.doAssignWith(1, 1, nil)
}
p.Goto(p.getEndingLabel(fn))
} else {
p.current.flows |= flowFlagReturn
p.returnResults(n)
}
return p
}
// Call func
func (p *CodeBuilder) Call(n int, ellipsis ...bool) *CodeBuilder {
var flags InstrFlags
if ellipsis != nil && ellipsis[0] {
flags = InstrFlagEllipsis
}
return p.CallWith(n, flags)
}
// CallWith always panics on error, while CallWithEx returns err if match function call failed.
func (p *CodeBuilder) CallWith(n int, flags InstrFlags, src ...ast.Node) *CodeBuilder {
if err := p.CallWithEx(n, flags, src...); err != nil {
panic(err)
}
return p
}
// CallWith always panics on error, while CallWithEx returns err if match function call failed.
// If an error ocurs, CallWithEx pops all function arguments from the CodeBuilder stack.
// In most case, you should call CallWith instead of CallWithEx.
func (p *CodeBuilder) CallWithEx(n int, flags InstrFlags, src ...ast.Node) error {
fn := p.stk.Get(-(n + 1))
if t, ok := fn.Type.(*btiMethodType); ok {
n++
fn.Type = t.Type
fn = p.stk.Get(-(n + 1))
if t.eargs != nil {
for _, arg := range t.eargs {
p.Val(arg)
}
n += len(t.eargs)
}
}
args := p.stk.GetArgs(n)
if debugInstr {
log.Println("Call", n, int(flags), "//", fn.Type)
}
s := getSrc(src)
fn.Src = s
ret, err := matchFuncCall(p.pkg, fn, args, flags)
if err != nil {
p.stk.PopN(n)
return err
}
ret.Src = s
p.stk.Ret(n+1, ret)
return nil
}
type closureParamInst struct {
inst *Func
param *types.Var
}
type closureParamInsts struct {
paramInsts map[closureParamInst]*types.Var
}
func (p *closureParamInsts) init() {
p.paramInsts = make(map[closureParamInst]*types.Var)
}
func (p *CodeBuilder) getEndingLabel(fn *Func) *Label {
key := closureParamInst{fn, nil}
if v, ok := p.paramInsts[key]; ok {
return p.current.labels[v.Name()]
}
ending := p.pkg.autoName()
p.paramInsts[key] = types.NewParam(token.NoPos, nil, ending, nil)
return p.NewLabel(token.NoPos, ending)
}
func (p *CodeBuilder) needEndingLabel(fn *Func) (*Label, bool) {
key := closureParamInst{fn, nil}
if v, ok := p.paramInsts[key]; ok {
return p.current.labels[v.Name()], true
}
return nil, false
}
func (p *Func) inlineClosureEnd(cb *CodeBuilder) {
if ending, ok := cb.needEndingLabel(p); ok {
cb.Label(ending)
}
sig := p.Type().(*types.Signature)
cb.emitStmt(&ast.BlockStmt{List: cb.endFuncBody(p.old)})
cb.stk.PopN(p.getInlineCallArity())
results := sig.Results()
for i, n := 0, results.Len(); i < n; i++ { // return results & clean env
key := closureParamInst{p, results.At(i)}
cb.pushVal(cb.paramInsts[key], nil)
delete(cb.paramInsts, key)
}
for i, n := 0, getParamLen(sig); i < n; i++ { // clean env
key := closureParamInst{p, getParam(sig, i)}
delete(cb.paramInsts, key)
}
}
// CallInlineClosureStart func
func (p *CodeBuilder) CallInlineClosureStart(sig *types.Signature, arity int, ellipsis bool) *CodeBuilder {
if debugInstr {
log.Println("CallInlineClosureStart", arity, ellipsis)
}
pkg := p.pkg
closure := pkg.newInlineClosure(sig, arity)
results := sig.Results()
for i, n := 0, results.Len(); i < n; i++ {
p.emitVar(pkg, closure, results.At(i), false)
}
p.startFuncBody(closure, nil, &closure.old)
args := p.stk.GetArgs(arity)
var flags InstrFlags
if ellipsis {
flags = InstrFlagEllipsis
}
if err := matchFuncType(pkg, args, flags, sig, nil); err != nil {
panic(err)
}
n1 := getParamLen(sig) - 1
if sig.Variadic() && !ellipsis {
p.SliceLit(getParam(sig, n1).Type().(*types.Slice), arity-n1)
}
for i := n1; i >= 0; i-- {
p.emitVar(pkg, closure, getParam(sig, i), true)
}
return p
}
func (p *CodeBuilder) emitVar(pkg *Package, closure *Func, param *types.Var, withInit bool) {
name := pkg.autoName()
if withInit {
p.NewVarStart(param.Type(), name).EndInit(1)
} else {
p.NewVar(param.Type(), name)
}
key := closureParamInst{closure, param}
p.paramInsts[key] = p.current.scope.Lookup(name).(*types.Var)
}
// NewClosure func
func (p *CodeBuilder) NewClosure(params, results *Tuple, variadic bool) *Func {
sig := types.NewSignatureType(nil, nil, nil, params, results, variadic)
return p.NewClosureWith(sig)
}
// NewClosureWith func
func (p *CodeBuilder) NewClosureWith(sig *types.Signature) *Func {
if debugInstr {
t := sig.Params()
for i, n := 0, t.Len(); i < n; i++ {
v := t.At(i)
if _, ok := v.Type().(*unboundType); ok {
panic("can't use unbound type in func parameters")
}
}
}
return p.pkg.newClosure(sig)
}
// NewType func
func (p *CodeBuilder) NewType(name string, src ...ast.Node) *TypeDecl {
return p.NewTypeDefs().NewType(name, src...)
}
// AliasType func
func (p *CodeBuilder) AliasType(name string, typ types.Type, src ...ast.Node) *types.Named {
decl := p.NewTypeDefs().AliasType(name, typ, src...)
return decl.typ
}
// NewConstStart func
func (p *CodeBuilder) NewConstStart(typ types.Type, names ...string) *CodeBuilder {
if debugInstr {
log.Println("NewConstStart", names)
}
defs := p.valueDefs(token.CONST)
return p.pkg.newValueDecl(defs.NewPos(), defs.scope, token.NoPos, token.CONST, typ, names...).InitStart(p.pkg)
}
// NewVar func
func (p *CodeBuilder) NewVar(typ types.Type, names ...string) *CodeBuilder {
if debugInstr {
log.Println("NewVar", names)
}
defs := p.valueDefs(token.VAR)
p.pkg.newValueDecl(defs.NewPos(), defs.scope, token.NoPos, token.VAR, typ, names...)
return p
}
// NewVarStart func
func (p *CodeBuilder) NewVarStart(typ types.Type, names ...string) *CodeBuilder {
if debugInstr {
log.Println("NewVarStart", names)
}
defs := p.valueDefs(token.VAR)
return p.pkg.newValueDecl(defs.NewPos(), defs.scope, token.NoPos, token.VAR, typ, names...).InitStart(p.pkg)
}
// DefineVarStart func
func (p *CodeBuilder) DefineVarStart(pos token.Pos, names ...string) *CodeBuilder {
if debugInstr {
log.Println("DefineVarStart", names)
}
return p.pkg.newValueDecl(
ValueAt{}, p.current.scope, pos, token.DEFINE, nil, names...).InitStart(p.pkg)
}
// NewAutoVar func
func (p *CodeBuilder) NewAutoVar(pos token.Pos, name string, pv **types.Var) *CodeBuilder {
spec := &ast.ValueSpec{Names: []*ast.Ident{ident(name)}}
decl := &ast.GenDecl{Tok: token.VAR, Specs: []ast.Spec{spec}}
stmt := &ast.DeclStmt{
Decl: decl,
}
if debugInstr {
log.Println("NewAutoVar", name)
}
p.emitStmt(stmt)
typ := &unboundType{ptypes: []*ast.Expr{&spec.Type}}
*pv = types.NewVar(pos, p.pkg.Types, name, typ)
if old := p.current.scope.Insert(*pv); old != nil {
oldPos := p.fset.Position(old.Pos())
p.panicCodeErrorf(
pos, "%s redeclared in this block\n\tprevious declaration at %v", name, oldPos)
}
return p
}
// VarRef func: p.VarRef(nil) means underscore (_)
func (p *CodeBuilder) VarRef(ref interface{}, src ...ast.Node) *CodeBuilder {
return p.doVarRef(ref, getSrc(src), true)
}
func (p *CodeBuilder) doVarRef(ref interface{}, src ast.Node, allowDebug bool) *CodeBuilder {
if ref == nil {
if allowDebug && debugInstr {
log.Println("VarRef _")
}
p.stk.Push(&internal.Elem{
Val: underscore, // _
})
} else {
if v, ok := ref.(string); ok {
_, ref = p.Scope().LookupParent(v, token.NoPos)
}
if v, ok := ref.(*types.Var); ok {
if allowDebug && debugInstr {
log.Println("VarRef", v.Name(), v.Type())
}
fn := p.current.fn
if fn != nil && fn.isInline() { // is in an inline call
key := closureParamInst{fn, v}
if arg, ok := p.paramInsts[key]; ok { // replace param with arg
v = arg
}
}
p.stk.Push(&internal.Elem{
Val: toObjectExpr(p.pkg, v), Type: &refType{typ: v.Type()}, Src: src,
})
} else {
code, pos := p.loadExpr(src)
p.panicCodeErrorf(pos, "%s is not a variable", code)
}
}
return p
}
var (
elemNone = &internal.Elem{}
)
// None func
func (p *CodeBuilder) None() *CodeBuilder {
if debugInstr {
log.Println("None")
}
p.stk.Push(elemNone)
return p
}
// ZeroLit func
func (p *CodeBuilder) ZeroLit(typ types.Type) *CodeBuilder {
return p.doZeroLit(typ, true)
}
func (p *CodeBuilder) doZeroLit(typ types.Type, allowDebug bool) *CodeBuilder {
typ0 := typ
if allowDebug && debugInstr {
log.Println("ZeroLit //", typ)
}
retry:
switch t := typ.(type) {
case *types.Basic:
switch kind := t.Kind(); kind {
case types.Bool:
return p.Val(false)
case types.String:
return p.Val("")
case types.UnsafePointer:
return p.Val(nil)
default:
return p.Val(0)
}
case *types.Interface, *types.Map, *types.Slice, *types.Pointer, *types.Signature, *types.Chan:
return p.Val(nil)
case *types.Named:
typ = p.getUnderlying(t)
goto retry
}
ret := &ast.CompositeLit{}
switch t := typ.(type) {
case *unboundType:
if t.tBound == nil {
t.ptypes = append(t.ptypes, &ret.Type)
} else {
typ = t.tBound
typ0 = typ
ret.Type = toType(p.pkg, typ)
}
default:
ret.Type = toType(p.pkg, typ)
}
p.stk.Push(&internal.Elem{Type: typ0, Val: ret})
return p
}
// MapLit func
func (p *CodeBuilder) MapLit(typ types.Type, arity int, src ...ast.Node) *CodeBuilder {
if err := p.MapLitEx(typ, arity, src...); err != nil {
panic(err)
}
return p
}
// MapLit func
func (p *CodeBuilder) MapLitEx(typ types.Type, arity int, src ...ast.Node) error {
if debugInstr {
log.Println("MapLit", typ, arity)
}
var t *types.Map
var typExpr ast.Expr
var pkg = p.pkg
if typ != nil {
var ok bool
switch tt := typ.(type) {
case *types.Named:
typExpr = toNamedType(pkg, tt)
t, ok = p.getUnderlying(tt).(*types.Map)
case *types.Map:
typExpr = toMapType(pkg, tt)
t, ok = tt, true
}
if !ok {
return p.newCodeErrorf(getPos(src), "type %v isn't a map", typ)
}
}
if arity == 0 {
if t == nil {
t = types.NewMap(types.Typ[types.String], TyEmptyInterface)
typ = t
typExpr = toMapType(pkg, t)
}
ret := &ast.CompositeLit{Type: typExpr}
p.stk.Push(&internal.Elem{Type: typ, Val: ret, Src: getSrc(src)})
return nil
}
if (arity & 1) != 0 {
return p.newCodeErrorf(getPos(src), "MapLit: invalid arity, can't be odd - %d", arity)
}
var key, val types.Type
var args = p.stk.GetArgs(arity)
var check = (t != nil)
if check {
key, val = t.Key(), t.Elem()
} else {
key = boundElementType(pkg, args, 0, arity, 2)
val = boundElementType(pkg, args, 1, arity, 2)
t = types.NewMap(Default(pkg, key), Default(pkg, val))
typ = t
typExpr = toMapType(pkg, t)
}
elts := make([]ast.Expr, arity>>1)
for i := 0; i < arity; i += 2 {
elts[i>>1] = &ast.KeyValueExpr{Key: args[i].Val, Value: args[i+1].Val}
if check {
if !AssignableTo(pkg, args[i].Type, key) {
src, pos := p.loadExpr(args[i].Src)
return p.newCodeErrorf(
pos, "cannot use %s (type %v) as type %v in map key", src, args[i].Type, key)
} else if !AssignableTo(pkg, args[i+1].Type, val) {
src, pos := p.loadExpr(args[i+1].Src)
return p.newCodeErrorf(
pos, "cannot use %s (type %v) as type %v in map value", src, args[i+1].Type, val)
}
}
}
p.stk.Ret(arity, &internal.Elem{
Type: typ, Val: &ast.CompositeLit{Type: typExpr, Elts: elts}, Src: getSrc(src),
})
return nil
}
func (p *CodeBuilder) toBoundArrayLen(elts []*internal.Elem, arity, limit int) int {
n := -1
max := -1
for i := 0; i < arity; i += 2 {
if elts[i].Val != nil {
n = p.toIntVal(elts[i], "index which must be non-negative integer constant")
} else {
n++
}
if limit >= 0 && n >= limit { // error message
if elts[i].Src == nil {
pos := getSrcPos(elts[i+1].Src)
p.panicCodeErrorf(pos, "array index %d out of bounds [0:%d]", n, limit)
}
src, pos := p.loadExpr(elts[i].Src)
p.panicCodeErrorf(pos, "array index %s (value %d) out of bounds [0:%d]", src, n, limit)
}
if max < n {
max = n
}
}
return max + 1
}
func (p *CodeBuilder) toIntVal(v *internal.Elem, msg string) int {
if cval := v.CVal; cval != nil && cval.Kind() == constant.Int {
if v, ok := constant.Int64Val(cval); ok {
return int(v)
}
}
code, pos := p.loadExpr(v.Src)
p.panicCodeErrorf(pos, "cannot use %s as %s", code, msg)
return 0
}
func (p *CodeBuilder) indexElemExpr(args []*internal.Elem, i int) ast.Expr {
key := args[i].Val
if key == nil { // none
return args[i+1].Val
}
p.toIntVal(args[i], "index which must be non-negative integer constant")
return &ast.KeyValueExpr{Key: key, Value: args[i+1].Val}
}
// SliceLit func
func (p *CodeBuilder) SliceLit(typ types.Type, arity int, keyVal ...bool) *CodeBuilder {
var keyValMode = (keyVal != nil && keyVal[0])
return p.SliceLitEx(typ, arity, keyValMode)
}
// SliceLitEx func
func (p *CodeBuilder) SliceLitEx(typ types.Type, arity int, keyVal bool, src ...ast.Node) *CodeBuilder {
var elts []ast.Expr
if debugInstr {
log.Println("SliceLit", typ, arity, keyVal)
}
var t *types.Slice
var typExpr ast.Expr
var pkg = p.pkg
if typ != nil {
switch tt := typ.(type) {
case *types.Named:
typExpr = toNamedType(pkg, tt)
t = p.getUnderlying(tt).(*types.Slice)
case *types.Slice:
typExpr = toSliceType(pkg, tt)
t = tt
default:
log.Panicln("SliceLit: typ isn't a slice type -", reflect.TypeOf(typ))
}
}
if keyVal { // in keyVal mode
if (arity & 1) != 0 {
log.Panicln("SliceLit: invalid arity, can't be odd in keyVal mode -", arity)
}
args := p.stk.GetArgs(arity)
val := t.Elem()
n := arity >> 1
elts = make([]ast.Expr, n)
for i := 0; i < arity; i += 2 {
arg := args[i+1]
if !AssignableConv(pkg, arg.Type, val, arg) {
src, pos := p.loadExpr(args[i+1].Src)
p.panicCodeErrorf(
pos, "cannot use %s (type %v) as type %v in slice literal", src, args[i+1].Type, val)
}
elts[i>>1] = p.indexElemExpr(args, i)
}
} else {
if arity == 0 {
if t == nil {
t = types.NewSlice(TyEmptyInterface)
typ = t
typExpr = toSliceType(pkg, t)
}
p.stk.Push(&internal.Elem{
Type: typ, Val: &ast.CompositeLit{Type: typExpr}, Src: getSrc(src),
})
return p
}
var val types.Type
var args = p.stk.GetArgs(arity)
var check = (t != nil)
if check {
val = t.Elem()
} else {
val = boundElementType(pkg, args, 0, arity, 1)
t = types.NewSlice(Default(pkg, val))
typ = t
typExpr = toSliceType(pkg, t)
}
elts = make([]ast.Expr, arity)
for i, arg := range args {
elts[i] = arg.Val
if check {
if !AssignableConv(pkg, arg.Type, val, arg) {
src, pos := p.loadExpr(arg.Src)
p.panicCodeErrorf(
pos, "cannot use %s (type %v) as type %v in slice literal", src, arg.Type, val)
}
}
}
}
p.stk.Ret(arity, &internal.Elem{
Type: typ, Val: &ast.CompositeLit{Type: typExpr, Elts: elts}, Src: getSrc(src),
})
return p
}
// ArrayLit func
func (p *CodeBuilder) ArrayLit(typ types.Type, arity int, keyVal ...bool) *CodeBuilder {
var keyValMode = (keyVal != nil && keyVal[0])
return p.ArrayLitEx(typ, arity, keyValMode)
}
// ArrayLitEx func