forked from goplus/gop
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcompile.go
1571 lines (1438 loc) · 38.3 KB
/
compile.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 (c) 2021 The GoPlus Authors (goplus.org). All rights reserved.
*
* 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 cl compiles Go+ syntax trees (ast).
package cl
import (
"fmt"
"go/types"
"log"
"reflect"
"sort"
"strconv"
"strings"
"github.com/goplus/gop/ast"
"github.com/goplus/gop/ast/fromgo"
"github.com/goplus/gop/token"
"github.com/goplus/gox"
"github.com/goplus/gox/cpackages"
"github.com/goplus/mod/modfile"
"github.com/qiniu/x/errors"
)
type dbgFlags int
const (
DbgFlagLoad dbgFlags = 1 << iota
DbgFlagLookup
FlagNoMarkAutogen
DbgFlagAll = DbgFlagLoad | DbgFlagLookup
)
var (
enableRecover = true
)
var (
debugLoad bool
debugLookup bool
noMarkAutogen bool // add const _ = true
)
func SetDisableRecover(disableRecover bool) {
enableRecover = !disableRecover
}
func SetDebug(flags dbgFlags) {
debugLoad = (flags & DbgFlagLoad) != 0
debugLookup = (flags & DbgFlagLookup) != 0
noMarkAutogen = (flags & FlagNoMarkAutogen) != 0
}
// -----------------------------------------------------------------------------
// Recorder represents a compiling event recorder.
type Recorder interface {
// Type maps expressions to their types, and for constant
// expressions, also their values. Invalid expressions are
// omitted.
//
// For (possibly parenthesized) identifiers denoting built-in
// functions, the recorded signatures are call-site specific:
// if the call result is not a constant, the recorded type is
// an argument-specific signature. Otherwise, the recorded type
// is invalid.
//
// The Types map does not record the type of every identifier,
// only those that appear where an arbitrary expression is
// permitted. For instance, the identifier f in a selector
// expression x.f is found only in the Selections map, the
// identifier z in a variable declaration 'var z int' is found
// only in the Defs map, and identifiers denoting packages in
// qualified identifiers are collected in the Uses map.
Type(ast.Expr, types.TypeAndValue)
// Instantiate maps identifiers denoting generic types or functions to their
// type arguments and instantiated type.
//
// For example, Instantiate will map the identifier for 'T' in the type
// instantiation T[int, string] to the type arguments [int, string] and
// resulting instantiated *Named type. Given a generic function
// func F[A any](A), Instances will map the identifier for 'F' in the call
// expression F(int(1)) to the inferred type arguments [int], and resulting
// instantiated *Signature.
//
// Invariant: Instantiating Uses[id].Type() with Instances[id].TypeArgs
// results in an equivalent of Instances[id].Type.
Instantiate(*ast.Ident, types.Instance)
// Def maps identifiers to the objects they define (including
// package names, dots "." of dot-imports, and blank "_" identifiers).
// For identifiers that do not denote objects (e.g., the package name
// in package clauses, or symbolic variables t in t := x.(type) of
// type switch headers), the corresponding objects are nil.
//
// For an embedded field, Def maps the field *Var it defines.
//
// Invariant: Defs[id] == nil || Defs[id].Pos() == id.Pos()
Def(id *ast.Ident, obj types.Object)
// Use maps identifiers to the objects they denote.
//
// For an embedded field, Use maps the *TypeName it denotes.
//
// Invariant: Uses[id].Pos() != id.Pos()
Use(id *ast.Ident, obj types.Object)
// Implicit maps nodes to their implicitly declared objects, if any.
// The following node and object types may appear:
//
// node declared object
//
// *ast.ImportSpec *PkgName for imports without renames
// *ast.CaseClause type-specific *Var for each type switch case clause (incl. default)
// *ast.Field anonymous parameter *Var (incl. unnamed results)
//
Implicit(node ast.Node, obj types.Object)
// Select maps selector expressions (excluding qualified identifiers)
// to their corresponding selections.
Select(*ast.SelectorExpr, *types.Selection)
// Scope maps ast.Nodes to the scopes they define. Package scopes are not
// associated with a specific node but with all files belonging to a package.
// Thus, the package scope can be found in the type-checked Package object.
// Scopes nest, with the Universe scope being the outermost scope, enclosing
// the package scope, which contains (one or more) files scopes, which enclose
// function scopes which in turn enclose statement and function literal scopes.
// Note that even though package-level functions are declared in the package
// scope, the function scopes are embedded in the file scope of the file
// containing the function declaration.
//
// The following node types may appear in Scopes:
//
// *ast.File
// *ast.FuncType
// *ast.TypeSpec
// *ast.BlockStmt
// *ast.IfStmt
// *ast.SwitchStmt
// *ast.TypeSwitchStmt
// *ast.CaseClause
// *ast.CommClause
// *ast.ForStmt
// *ast.RangeStmt
// *ast.ForPhraseStmt
// *ast.ForPhrase
// *ast.LambdaExpr
// *ast.LambdaExpr2
//
Scope(ast.Node, *types.Scope)
}
// -----------------------------------------------------------------------------
type Project = modfile.Project
type Class = modfile.Class
// Config of loading Go+ packages.
type Config struct {
// Types provides type information for the package (optional).
Types *types.Package
// Fset provides source position information for syntax trees and types (required).
Fset *token.FileSet
// RelativeBase is the root directory of relative path.
RelativeBase string
// C2goBase specifies base of standard c2go packages (optional).
// Default is github.com/goplus/.
C2goBase string
// LookupPub lookups the c2go package pubfile named c2go.a.pub (required).
// See gop/x/c2go.LookupPub.
LookupPub func(pkgPath string) (pubfile string, err error)
// LookupClass lookups a class by specified file extension (required).
// See (*github.com/goplus/mod/gopmod.Module).LookupClass.
LookupClass func(ext string) (c *Project, ok bool)
// An Importer resolves import paths to Packages (optional).
Importer types.Importer
// A Recorder records existing objects including constants, variables and
// types etc (optional).
Recorder Recorder
// NoFileLine = true means not to generate file line comments.
NoFileLine bool
// NoAutoGenMain = true means not to auto generate main func is no entry.
NoAutoGenMain bool
// NoSkipConstant = true means to disable optimization of skipping constants.
NoSkipConstant bool
// Outline = true means to skip compiling function bodies.
Outline bool
}
type nodeInterp struct {
fset *token.FileSet
files map[string]*ast.File
relBaseDir string
}
func (p *nodeInterp) Position(start token.Pos) (pos token.Position) {
pos = p.fset.Position(start)
pos.Filename = relFile(p.relBaseDir, pos.Filename)
return
}
func (p *nodeInterp) Caller(node ast.Node) string {
if expr, ok := node.(*ast.CallExpr); ok {
return p.LoadExpr(expr.Fun)
}
return "the function call"
}
func (p *nodeInterp) LoadExpr(node ast.Node) string {
start := node.Pos()
pos := p.fset.Position(start)
f := p.files[pos.Filename]
n := int(node.End() - start)
return string(f.Code[pos.Offset : pos.Offset+n])
}
type loader interface {
load()
pos() token.Pos
}
type baseLoader struct {
fn func()
start token.Pos
}
func initLoader(ctx *pkgCtx, syms map[string]loader, start token.Pos, name string, fn func(), genBody bool) bool {
if name == "_" {
if genBody {
ctx.inits = append(ctx.inits, fn)
}
return false
}
if old, ok := syms[name]; ok {
oldpos := ctx.Position(old.pos())
ctx.handleErrorf(
start, "%s redeclared in this block\n\tprevious declaration at %v", name, oldpos)
return false
}
syms[name] = &baseLoader{start: start, fn: fn}
return true
}
func (p *baseLoader) load() {
p.fn()
}
func (p *baseLoader) pos() token.Pos {
return p.start
}
type typeLoader struct {
typ, typInit func()
methods []func()
start token.Pos
}
func getTypeLoader(ctx *pkgCtx, syms map[string]loader, start token.Pos, name string) *typeLoader {
t, ok := syms[name]
if ok {
if start != token.NoPos {
ld := t.(*typeLoader)
if ld.start == token.NoPos {
ld.start = start
} else {
ctx.handleErrorf(
start, "%s redeclared in this block\n\tprevious declaration at %v",
name, ctx.Position(ld.pos()))
}
return ld
}
} else {
t = &typeLoader{start: start}
syms[name] = t
}
return t.(*typeLoader)
}
func (p *typeLoader) pos() token.Pos {
return p.start
}
func (p *typeLoader) load() {
doNewType(p)
doInitType(p)
doInitMethods(p)
}
func doNewType(ld *typeLoader) {
if typ := ld.typ; typ != nil {
ld.typ = nil
typ()
}
}
func doInitType(ld *typeLoader) {
if typInit := ld.typInit; typInit != nil {
ld.typInit = nil
typInit()
}
}
func doInitMethods(ld *typeLoader) {
if methods := ld.methods; methods != nil {
ld.methods = nil
for _, method := range methods {
method()
}
}
}
type pkgCtx struct {
*nodeInterp
projs map[string]*gmxProject // .gmx => project
classes map[*ast.File]*gmxClass
fset *token.FileSet
cpkgs *cpackages.Importer
syms map[string]loader
lbinames []any // names that should load before initGopPkg (can be string/func or *ast.Ident/type)
inits []func()
tylds []*typeLoader
errs errors.List
generics map[string]bool // generic type record
idents []*ast.Ident // toType ident recored
inInst int // toType in generic instance
}
type pkgImp struct {
gox.PkgRef
pkgName *types.PkgName
}
type blockCtx struct {
*pkgCtx
proj *gmxProject
pkg *gox.Package
cb *gox.CodeBuilder
imports map[string]pkgImp
autoimps map[string]pkgImp
lookups []gox.PkgRef
clookups []cpackages.PkgRef
tlookup *typeParamLookup
c2goBase string // default is `github.com/goplus/`
relBaseDir string
classRecv *ast.FieldList // available when isClass
baseClass types.Object // available when isClass
fileScope *types.Scope // available when isGopFile
rec *goxRecorder
fileLine bool
isClass bool
isGopFile bool // is Go+ file or not
}
func (p *blockCtx) recorder() *goxRecorder {
if p.isGopFile {
return p.rec
}
return nil
}
func (p *blockCtx) findImport(name string) (pi pkgImp, ok bool) {
pi, ok = p.imports[name]
if !ok && p.autoimps != nil {
pi, ok = p.autoimps[name]
}
return
}
func (p *pkgCtx) newCodeError(pos token.Pos, msg string) error {
return &gox.CodeError{Fset: p.nodeInterp, Pos: pos, Msg: msg}
}
func (p *pkgCtx) newCodeErrorf(pos token.Pos, format string, args ...interface{}) error {
return &gox.CodeError{Fset: p.nodeInterp, Pos: pos, Msg: fmt.Sprintf(format, args...)}
}
func (p *pkgCtx) handleErrorf(pos token.Pos, format string, args ...interface{}) {
p.handleErr(p.newCodeErrorf(pos, format, args...))
}
func (p *pkgCtx) handleErr(err error) {
p.errs = append(p.errs, err)
}
func (p *pkgCtx) loadNamed(at *gox.Package, t *types.Named) {
o := t.Obj()
if o.Pkg() == at.Types {
p.loadType(o.Name())
}
}
func (p *pkgCtx) complete() error {
return p.errs.ToError()
}
func (p *pkgCtx) loadType(name string) {
if sym, ok := p.syms[name]; ok {
if ld, ok := sym.(*typeLoader); ok {
ld.load()
}
}
}
func (p *pkgCtx) loadSymbol(name string) bool {
if enableRecover {
defer func() {
if e := recover(); e != nil {
p.handleRecover(e, nil)
}
}()
}
if f, ok := p.syms[name]; ok {
if ld, ok := f.(*typeLoader); ok {
doNewType(ld) // create this type, but don't init
return true
}
delete(p.syms, name)
f.load()
return true
}
return false
}
func (p *pkgCtx) handleRecover(e interface{}, src ast.Node) {
err := p.recoverErr(e, src)
p.handleErr(err)
}
func (p *pkgCtx) recoverErr(e interface{}, src ast.Node) error {
err, ok := e.(error)
if !ok {
if src != nil {
text := p.LoadExpr(src)
err = p.newCodeErrorf(src.Pos(), "compile `%v`: %v", text, e)
} else {
err = fmt.Errorf("%v", e)
}
}
return err
}
const (
defaultGoFile = ""
skippingGoFile = "_skip"
testingGoFile = "_test"
)
const (
ioxPkgPath = "github.com/goplus/gop/builtin/iox"
)
// NewPackage creates a Go+ package instance.
func NewPackage(pkgPath string, pkg *ast.Package, conf *Config) (p *gox.Package, err error) {
relBaseDir := conf.RelativeBase
fset := conf.Fset
files := pkg.Files
interp := &nodeInterp{
fset: fset, files: files, relBaseDir: relBaseDir,
}
ctx := &pkgCtx{
fset: fset,
nodeInterp: interp,
projs: make(map[string]*gmxProject),
classes: make(map[*ast.File]*gmxClass),
syms: make(map[string]loader),
generics: make(map[string]bool),
}
confGox := &gox.Config{
Types: conf.Types,
Fset: fset,
Importer: conf.Importer,
LoadNamed: ctx.loadNamed,
HandleErr: ctx.handleErr,
NodeInterpreter: interp,
NewBuiltin: newBuiltinDefault,
DefaultGoFile: defaultGoFile,
NoSkipConstant: conf.NoSkipConstant,
PkgPathIox: ioxPkgPath,
DbgPositioner: interp,
}
var rec *goxRecorder
if conf.Recorder != nil {
rec = newRecorder(conf.Recorder)
confGox.Recorder = rec
}
if enableRecover {
defer func() {
if e := recover(); e != nil {
ctx.handleRecover(e, nil)
err = ctx.errs.ToError()
}
}()
}
p = gox.NewPackage(pkgPath, pkg.Name, confGox)
if !noMarkAutogen {
p.CB().NewConstStart(nil, "_").Val(true).EndInit(1)
}
ctx.cpkgs = cpackages.NewImporter(&cpackages.Config{
Pkg: p, LookupPub: conf.LookupPub,
})
// sort files
type File struct {
*ast.File
path string
}
sfiles := make([]*File, 0, len(files))
for fpath, f := range files {
sfiles = append(sfiles, &File{f, fpath})
}
sort.Slice(sfiles, func(i, j int) bool {
return sfiles[i].path < sfiles[j].path
})
for _, f := range sfiles {
gmx := f.File
if gmx.IsClass && !gmx.IsNormalGox {
if debugLoad {
log.Println("==> File", f.path, "normalGox:", gmx.IsNormalGox)
}
loadClass(ctx, p, f.path, gmx, conf)
}
}
for _, f := range sfiles {
fileLine := !conf.NoFileLine
fileScope := types.NewScope(p.Types.Scope(), f.Pos(), f.End(), f.path)
ctx := &blockCtx{
pkg: p, pkgCtx: ctx, cb: p.CB(), relBaseDir: relBaseDir, fileScope: fileScope,
fileLine: fileLine, isClass: f.IsClass, rec: rec,
c2goBase: c2goBase(conf.C2goBase), imports: make(map[string]pkgImp), isGopFile: true,
}
if rec := ctx.rec; rec != nil {
rec.Scope(f.File, fileScope)
}
preloadGopFile(p, ctx, f.path, f.File, conf)
}
gopSyms := make(map[string]bool) // TODO: remove this map
for name := range ctx.syms {
gopSyms[name] = true
}
gofiles := make([]*ast.File, 0, len(pkg.GoFiles))
for _, gof := range pkg.GoFiles {
f := fromgo.ASTFile(gof, 0)
gofiles = append(gofiles, f)
ctx := &blockCtx{
pkg: p, pkgCtx: ctx, cb: p.CB(), relBaseDir: relBaseDir,
imports: make(map[string]pkgImp),
}
preloadFile(p, ctx, f, skippingGoFile, false)
}
initGopPkg(ctx, p, gopSyms)
// genMain = true if it is main package and no main func
var genMain bool
var gen func()
if pkg.Name == "main" {
_, hasMain := ctx.syms["main"]
genMain = !hasMain
}
for _, f := range sfiles {
if f.IsProj {
loadFile(ctx, f.File)
}
}
if genMain { // make classfile main func if need
gen = gmxMainFunc(p, ctx, conf.NoAutoGenMain)
}
for _, f := range sfiles {
if !f.IsProj {
loadFile(ctx, f.File)
}
}
if conf.Outline {
for _, f := range gofiles {
loadFile(ctx, f)
}
}
for _, ld := range ctx.tylds {
ld.load()
}
for _, load := range ctx.inits {
load()
}
err = ctx.complete()
if gen != nil { // generate classfile main func
gen()
} else if genMain && !conf.NoAutoGenMain { // generate empty main func
old, _ := p.SetCurFile(defaultGoFile, false)
p.NewFunc(nil, "main", nil, nil, false).BodyStart(p).End()
p.RestoreCurFile(old)
}
return
}
func isOverloadFunc(name string) bool {
n := len(name)
return n > 3 && name[n-3:n-1] == "__"
}
func initGopPkg(ctx *pkgCtx, pkg *gox.Package, gopSyms map[string]bool) {
for name, f := range ctx.syms {
if gopSyms[name] {
continue
}
if _, ok := f.(*typeLoader); ok {
ctx.loadType(name)
} else if isOverloadFunc(name) {
ctx.loadSymbol(name)
}
}
for _, lbi := range ctx.lbinames {
if name, ok := lbi.(string); ok {
ctx.loadSymbol(name)
} else {
ctx.loadType(lbi.(*ast.Ident).Name)
}
}
gox.InitThisGopPkg(pkg.Types)
}
func inMainPkg(f *ast.File) bool {
return f.Name.Name == "main"
}
func getEntrypoint(f *ast.File) string {
switch {
case f.IsProj:
return "MainEntry"
case f.IsClass:
return "Main"
case inMainPkg(f):
return "main"
default:
return "init"
}
}
func loadFile(ctx *pkgCtx, f *ast.File) {
for _, decl := range f.Decls {
switch d := decl.(type) {
case *ast.GenDecl:
switch d.Tok {
case token.TYPE:
for _, spec := range d.Specs {
ctx.loadType(spec.(*ast.TypeSpec).Name.Name)
}
case token.CONST, token.VAR:
for _, spec := range d.Specs {
for _, name := range spec.(*ast.ValueSpec).Names {
ctx.loadSymbol(name.Name)
}
}
}
case *ast.FuncDecl:
if d.Recv == nil {
name := d.Name.Name
if name != "init" {
ctx.loadSymbol(name)
}
} else {
if name, ok := getRecvTypeName(ctx, d.Recv, false); ok {
getTypeLoader(ctx, ctx.syms, token.NoPos, name).load()
}
}
}
}
}
// gen testingGoFile for:
//
// *_test.gop
// *test.gox
func genGoFile(file string, goxTestFile bool) string {
if goxTestFile || strings.HasSuffix(file, "_test.gop") {
return testingGoFile
}
return defaultGoFile
}
func preloadGopFile(p *gox.Package, ctx *blockCtx, file string, f *ast.File, conf *Config) {
var proj *gmxProject
var c *gmxClass
var classType string
var testType string
var baseTypeName string
var baseType types.Type
var spxClass bool
var goxTestFile bool
var parent = ctx.pkgCtx
if f.IsClass {
if f.IsNormalGox {
classType, _, _ = ClassNameAndExt(file)
if classType == "main" {
classType = "_main"
}
} else {
c = parent.classes[f]
classType = c.tname
proj, ctx.proj = c.proj, c.proj
ctx.autoimps = proj.autoimps
goxTestFile = proj.isTest
if goxTestFile { // test classfile
testType = c.tname
if !f.IsProj {
classType = casePrefix + testNameSuffix(testType)
}
}
if f.IsProj {
o := proj.game
ctx.baseClass = o
baseTypeName, baseType = o.Name(), o.Type()
if proj.gameIsPtr {
baseType = types.NewPointer(baseType)
}
} else {
o := proj.sprite[c.ext]
ctx.baseClass = o
baseTypeName, baseType, spxClass = o.Name(), o.Type(), true
}
}
}
goFile := genGoFile(file, goxTestFile)
if classType != "" {
if debugLoad {
log.Println("==> Preload type", classType)
}
if proj != nil {
ctx.lookups = make([]gox.PkgRef, len(proj.pkgPaths))
for i, pkgPath := range proj.pkgPaths {
ctx.lookups[i] = p.Import(pkgPath)
}
}
syms := parent.syms
pos := f.Pos()
specs := getFields(f)
ld := getTypeLoader(parent, syms, pos, classType)
ld.typ = func() {
if debugLoad {
log.Println("==> Load > NewType", classType)
}
old, _ := p.SetCurFile(goFile, true)
defer p.RestoreCurFile(old)
decl := p.NewTypeDefs().NewType(classType)
ld.typInit = func() { // decycle
if debugLoad {
log.Println("==> Load > InitType", classType)
}
old, _ := p.SetCurFile(goFile, true)
defer p.RestoreCurFile(old)
pkg := p.Types
var flds []*types.Var
var tags []string
chk := newCheckRedecl()
if baseTypeName != "" {
flds = append(flds, types.NewField(pos, pkg, baseTypeName, baseType, true))
tags = append(tags, "")
chk.chkRedecl(ctx, baseTypeName, pos)
}
if spxClass && proj.gameClass != "" {
typ := toType(ctx, &ast.StarExpr{X: &ast.Ident{Name: proj.gameClass}})
name := getTypeName(typ)
if !chk.chkRedecl(ctx, name, pos) {
fld := types.NewField(pos, pkg, name, typ, true)
flds = append(flds, fld)
tags = append(tags, "")
}
}
rec := ctx.recorder()
for _, v := range specs {
spec := v.(*ast.ValueSpec)
typ := toType(ctx, spec.Type)
tag := toFieldTag(spec.Tag)
if len(spec.Names) == 0 {
name := parseTypeEmbedName(spec.Type)
if chk.chkRedecl(ctx, name.Name, spec.Type.Pos()) {
continue
}
fld := types.NewField(spec.Type.Pos(), pkg, name.Name, typ, true)
if rec != nil {
rec.Def(name, fld)
}
flds = append(flds, fld)
tags = append(tags, tag)
} else {
for _, name := range spec.Names {
if chk.chkRedecl(ctx, name.Name, name.Pos()) {
continue
}
fld := types.NewField(name.Pos(), pkg, name.Name, typ, false)
if rec != nil {
rec.Def(name, fld)
}
flds = append(flds, fld)
tags = append(tags, tag)
}
}
}
decl.InitType(p, types.NewStruct(flds, tags))
}
parent.tylds = append(parent.tylds, ld)
}
// bugfix: see TestGopxNoFunc
parent.lbinames = append(parent.lbinames, classType)
ctx.classRecv = &ast.FieldList{List: []*ast.Field{{
Names: []*ast.Ident{
{Name: "this"},
},
Type: &ast.StarExpr{
X: &ast.Ident{Name: classType},
},
}}}
// func Classfname() string
if spxClass {
f.Decls = append(f.Decls, &ast.FuncDecl{
Name: &ast.Ident{
Name: "Classfname",
},
Type: &ast.FuncType{
Params: &ast.FieldList{},
Results: &ast.FieldList{
List: []*ast.Field{
{Type: &ast.Ident{Name: "string"}},
},
},
},
Body: &ast.BlockStmt{
List: []ast.Stmt{
&ast.ReturnStmt{
Results: []ast.Expr{
&ast.BasicLit{Kind: token.STRING, Value: strconv.Quote(c.clsfile)},
},
},
},
},
})
}
}
if d := f.ShadowEntry; d != nil {
d.Name.Name = getEntrypoint(f)
} else if f.IsProj && !conf.NoAutoGenMain && inMainPkg(f) {
var entry = getEntrypoint(f)
var hasEntry bool
for _, decl := range f.Decls {
switch d := decl.(type) {
case *ast.FuncDecl:
if d.Name.Name == entry {
hasEntry = true
}
}
}
if !hasEntry {
f.Decls = append(f.Decls, &ast.FuncDecl{
Name: &ast.Ident{
Name: entry,
},
Type: &ast.FuncType{
Params: &ast.FieldList{},
},
Body: &ast.BlockStmt{},
Shadow: true,
})
}
}
preloadFile(p, ctx, f, goFile, !conf.Outline)
if goxTestFile {
parent.inits = append(parent.inits, func() {
old, _ := p.SetCurFile(testingGoFile, true)
gmxTestFunc(p, testType, f.IsProj)
p.RestoreCurFile(old)
})
}
}
func parseTypeEmbedName(typ ast.Expr) *ast.Ident {
retry:
switch t := typ.(type) {
case *ast.Ident:
return t
case *ast.SelectorExpr:
return t.Sel
case *ast.StarExpr:
typ = t.X
goto retry
}
panic("TODO: parseTypeEmbedName unexpected")
}
func preloadFile(p *gox.Package, ctx *blockCtx, f *ast.File, goFile string, genFnBody bool) {
parent := ctx.pkgCtx
syms := parent.syms
old, _ := p.SetCurFile(goFile, true)
defer p.RestoreCurFile(old)
var skipClassFields bool
if f.IsClass {
skipClassFields = true
}
preloadFuncDecl := func(d *ast.FuncDecl) {
if ctx.classRecv != nil { // in class file (.spx/.gmx)
if d.Recv == nil {
d.Recv = ctx.classRecv
d.IsClass = true
}
}
if d.Recv == nil {
name := d.Name
fn := func() {
old, _ := p.SetCurFile(goFile, true)
defer p.RestoreCurFile(old)
loadFunc(ctx, nil, d, genFnBody)
}
fname := name.Name
if fname == "init" {
if genFnBody {
if debugLoad {
log.Println("==> Preload func init")
}
parent.inits = append(parent.inits, fn)
}
} else {
if debugLoad {
log.Println("==> Preload func", fname)
}
if initLoader(parent, syms, name.Pos(), fname, fn, genFnBody) {
if strings.HasPrefix(fname, "Gopx_") { // Gopx_xxx func
ctx.lbinames = append(ctx.lbinames, fname)
}
}
}
} else {
if name, ok := getRecvTypeName(parent, d.Recv, true); ok {
if debugLoad {
log.Printf("==> Preload method %s.%s\n", name, d.Name.Name)
}
ld := getTypeLoader(parent, syms, token.NoPos, name)
fn := func() {
old, _ := p.SetCurFile(goFile, true)
defer p.RestoreCurFile(old)
doInitType(ld)
recv := toRecv(ctx, d.Recv)
loadFunc(ctx, recv, d, genFnBody)
}
ld.methods = append(ld.methods, fn)
}
}
}
preloadConst := func(d *ast.GenDecl) {
pkg := ctx.pkg
cdecl := pkg.NewConstDefs(pkg.Types.Scope())
for _, spec := range d.Specs {
vSpec := spec.(*ast.ValueSpec)
if debugLoad {
log.Println("==> Preload const", vSpec.Names)
}
setNamesLoader(parent, syms, vSpec.Names, func() {
if c := cdecl; c != nil {