-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathpackage.go
More file actions
1032 lines (920 loc) · 28.2 KB
/
package.go
File metadata and controls
1032 lines (920 loc) · 28.2 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
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
package convert
import (
"fmt"
"go/token"
"go/types"
"log"
goast "go/ast"
"github.com/goplus/gogen"
"github.com/goplus/llcppg/_xtool/llcppsymg/tool/name"
"github.com/goplus/llcppg/ast"
llcppg "github.com/goplus/llcppg/config"
ctoken "github.com/goplus/llcppg/token"
"github.com/goplus/mod/gopmod"
)
// In Processing Package
type Package struct {
*PkgInfo
p *gogen.Package // package writer
conf *PackageConfig // package config
cvt *TypeConv // package type convert
curFile *HeaderFile // current processing c header file.
files []*HeaderFile // header files.
locMap *ThirdTypeLoc // record third type's location
// incomplete stores type declarations that are not fully defined yet, including:
// - Forward declarations in C/C++
// - Typedef declarations that reference incomplete types
//
// This is crucial for handling cases where:
// 1. A type is referenced before its full definition (forward declaration)
// 2. A typedef refers to a type that hasn't been fully defined yet
//
// These declarations are collected during the parsing phase and will be
// properly initialized after all files have been processed, ensuring that
// all type references can be correctly resolved.
//
// Note: In Go, when creating a new type via "type xxx xxx", the underlying
// type must exist. This differs from C/C++ where incomplete types are allowed.
// Therefore, we need this mechanism to defer type initialization until all
// type definitions are available.
incompleteTypes *IncompleteTypes
symbols *ProcessSymbol // record the processed node
}
type PackageConfig struct {
PkgBase
Name string // current package name
OutputDir string
ConvSym func(name *ast.Object, mangleName string) (goName string, err error)
Symbols *ProcessSymbol
GenConf *gogen.Config
TrimPrefixes []string
LibCommand string // use to gen link command like $(pkg-config --libs xxx)
KeepUnderScore bool
}
// When creating a new package for conversion, a Go file named after the package is generated by default.
// If SetCurFile is not called, all type conversions will be written to this default Go file.
func NewPackage(config *PackageConfig) (*Package, error) {
gogen.GeneratedHeader = ""
if config.GenConf == nil {
config.GenConf = &gogen.Config{
EnableTypesalias: true,
}
}
var symbols *ProcessSymbol
if config.Symbols == nil {
symbols = NewProcessSymbol()
} else {
symbols = config.Symbols
}
p := &Package{
p: gogen.NewPackage(config.PkgPath, config.Name, config.GenConf),
conf: config,
incompleteTypes: NewIncompleteTypes(),
locMap: NewThirdTypeLoc(),
symbols: symbols,
}
// default have load llgo/c
hasC := false
for _, dep := range config.Deps {
if dep == "c" || dep == "github.com/goplus/lib/c" {
hasC = true
break
}
}
if !hasC {
config.Deps = append([]string{"c"}, config.Deps...)
}
mod, err := gopmod.Load(config.OutputDir)
if err != nil {
return nil, fmt.Errorf("failed to load mod: %w", err)
}
p.PkgInfo = NewPkgInfo(config.PkgPath, config.Deps, config.Pubs)
pkgManager := NewPkgDepLoader(mod, p.p)
err = pkgManager.InitDeps(p.PkgInfo)
if err != nil {
return nil, fmt.Errorf("failed to init deps: %w", err)
}
err = p.initLink()
if err != nil {
return nil, fmt.Errorf("failed to init link: %w", err)
}
p.markUseDeps(pkgManager)
p.cvt = NewConv(p)
return p, nil
}
func (p *Package) Config() *PackageConfig {
return p.conf
}
func (p *Package) Pkg() *gogen.Package {
return p.p
}
func (p *Package) markUseDeps(pkgMgr *PkgDepLoader) {
defer p.p.RestoreCurFile(p.p.CurFile())
p.p.SetCurFile(p.autoLinkFile(), true)
pkgs, err := pkgMgr.Imports(p.conf.Deps)
if err != nil {
log.Panicf("failed to import deps: %s", err.Error())
}
for _, pkg := range pkgs {
depPkg := p.p.Import(pkg.PkgPath)
depPkg.MarkForceUsed(p.p)
}
}
func (p *Package) LookupFunc(fn *ast.FuncDecl) (*GoFuncSpec, error) {
goName, err := p.conf.ConvSym(&fn.Object, fn.MangledName)
if err != nil {
return nil, err
}
return NewGoFuncSpec(goName), nil
}
func (p *Package) SetCurFile(hfile *HeaderFile) {
var curFile *HeaderFile
for _, f := range p.files {
if f.File == hfile.File {
curFile = f
break
}
}
if curFile == nil {
curFile = hfile
p.files = append(p.files, curFile)
}
p.curFile = curFile
// for third hfile not register to gogen.Package
if curFile.FileType != llcppg.Third {
fileName := curFile.ToGoFileName(p.conf.Name)
if debugLog {
log.Printf("SetCurFile: %s File in Current Package: %v\n", fileName, curFile.FileType)
}
p.p.SetCurFile(fileName, true)
p.p.Unsafe().MarkForceUsed(p.p)
}
}
// todo(zzy):refine logic
func (p *Package) linkLib(lib string) error {
if lib == "" {
return fmt.Errorf("empty lib name")
}
linkString := fmt.Sprintf("link: %s;", lib)
p.p.CB().NewConstStart(types.Typ[types.String], "LLGoPackage").Val(linkString).EndInit(1)
return nil
}
func (p *Package) newReceiver(typ *ast.FuncType) (*types.Var, error) {
recvField := typ.Params.List[0]
recvType, err := p.ToType(recvField.Type)
if err != nil {
return nil, fmt.Errorf("newReceiver:failed to convert type: %w", err)
}
return p.p.NewParam(token.NoPos, "recv_", recvType), nil
}
func (p *Package) ToSigSignature(recv *types.Var, funcDecl *ast.FuncDecl) (*types.Signature, error) {
var sig *types.Signature
var err error
sig, err = p.cvt.ToSignature(funcDecl.Type, recv)
if err != nil {
return nil, err
}
return sig, nil
}
func (p *Package) bodyStart(decl *gogen.Func, ret ast.Expr) error {
if !Expr(ret).IsVoid() {
retType, err := p.ToType(ret)
if err != nil {
return err
}
if asStruct(retType) {
// use empty named struct type to return,without this solution,we will get a anonymous struct type
// and it will cause a compile error,like following:
// func (recv *Vector3) Vector3Barycenter(p Vector3, a Vector3, b Vector3, c Vector3) Vector3 {
// return struct {
// x c.Int
// y c.Int
// z c.Int
// }{}
// }
// this result will cause the `c` in the return type is use the `c` in the parameter,which is not have the `Int`
decl.BodyStart(p.p).StructLit(retType, 0, true).Return(1).End()
return nil
}
decl.BodyStart(p.p).ZeroLit(retType).Return(1).End()
} else {
decl.BodyStart(p.p).End()
}
return nil
}
func (p *Package) handleFuncDecl(fnSpec *GoFuncSpec, sig *types.Signature, funcDecl *ast.FuncDecl) error {
var decl *gogen.Func
fnPubName := fnSpec.GoSymbName
if fnSpec.IsMethod {
decl = p.p.NewFuncDecl(token.NoPos, fnSpec.FnName, sig)
err := p.bodyStart(decl, funcDecl.Type.Ret)
if err != nil {
return err
}
// we need to use the actual receiver name in link comment
// both for value receiver and pointer receiver
fnPubName = pubMethodName(sig.Recv().Type(), fnSpec)
} else {
decl = p.p.NewFuncDecl(token.NoPos, fnPubName, sig)
}
doc := NewCommentGroupFromC(funcDecl.Doc)
doc.List = append(doc.List, NewFuncDocComment(funcDecl.Name.Name, fnPubName))
decl.SetComments(p.p, doc)
return nil
}
type TypeDefinedError struct {
Name string
OriginName string
}
func (p *TypeDefinedError) Error() string {
return "type " + p.Name + " already defined,original name is " + p.OriginName
}
func NewTypeDefinedError(name, originName string) *TypeDefinedError {
return &TypeDefinedError{
Name: name,
OriginName: originName,
}
}
func getNamedType(recvType types.Type) *types.Named {
switch t := recvType.(type) {
case *types.Named:
return t
case *types.Pointer:
if named, ok := t.Elem().(*types.Named); ok {
return named
}
}
return nil
}
// pubMethodName generates a public method name based on the receiver type and function name.
// It handles both pointer and value receivers.
//
// Parameters:
// - recv: The receiver type from types.Signature
// - fnName: The base function name
//
// Returns:
// - For pointer receiver: "(*TypeName).FuncName"
// - For value receiver: "TypeName.FuncName"
// - For invalid/unknown receiver: just "FuncName"
func pubMethodName(recv types.Type, fnSpec *GoFuncSpec) string {
if !fnSpec.IsMethod {
return fnSpec.FnName
}
named := getNamedType(recv)
if fnSpec.PtrRecv {
return "(*" + named.Obj().Name() + ")." + fnSpec.FnName
}
return named.Obj().Name() + "." + fnSpec.FnName
}
func (p *Package) NewFuncDecl(funcDecl *ast.FuncDecl) error {
isThird, _ := p.handleType(funcDecl.Name, funcDecl.Loc)
if isThird {
if debugLog {
log.Printf("NewFuncDecl: %v is a function of third header file\n", funcDecl.Name)
}
return nil
}
if debugLog {
log.Printf("NewFuncDecl: %v\n", funcDecl.Name)
}
fnSpec, err := p.LookupFunc(funcDecl)
if err != nil {
// not gen the function not in the symbolmap
log.Printf("NewFuncDecl: %s not in the symbolmap: %s", funcDecl.Name.Name, err.Error())
return nil
}
if fnSpec.IsIgnore() {
log.Printf("NewFuncDecl: %v is ignored\n", funcDecl.Name)
return nil
}
recv, exist, err := p.funcIsDefined(fnSpec, funcDecl)
if err != nil {
return fmt.Errorf("NewFuncDecl: %s fail: %w", funcDecl.Name.Name, err)
}
if exist {
if debugLog {
log.Printf("NewFuncDecl: %s is processed\n", funcDecl.Name.Name)
}
return nil
}
sig, err := p.ToSigSignature(recv, funcDecl)
if err != nil {
return fmt.Errorf("NewFuncDecl: fail convert signature %s: %w", funcDecl.Name.Name, err)
}
return p.handleFuncDecl(fnSpec, sig, funcDecl)
}
func (p *Package) funcIsDefined(fnSpec *GoFuncSpec, funcDecl *ast.FuncDecl) (recv *types.Var, exist bool, err error) {
node := Node{
name: funcDecl.Name.Name,
kind: FuncDecl,
}
// if already processed,return
_, exist = p.symbols.Lookup(node)
if exist {
return nil, true, nil
}
if fnSpec.IsMethod &&
funcDecl.Type.Params.List != nil &&
len(funcDecl.Type.Params.List) > 0 {
recv, err = p.newReceiver(funcDecl.Type)
if err != nil {
return nil, false, err
}
var namedType = getNamedType(recv.Type())
methodName := fnSpec.FnName
for i := 0; i < namedType.NumMethods(); i++ {
if namedType.Method(i).Name() == methodName { // unreachable,because if have the same method name,will return in p.symbols.Lookup(node)
return nil, true, fmt.Errorf("NewFuncDecl: %s already defined", fnSpec.GoSymbName)
}
}
} else {
if obj := p.Lookup(fnSpec.FnName); obj != nil {
return nil, true, fmt.Errorf("NewFuncDecl: %s already defined", fnSpec.GoSymbName)
}
}
// register the function
p.symbols.Register(node, fnSpec.FnName)
return
}
func (p *Package) Lookup(name string) types.Object {
return gogen.Lookup(p.p.Types.Scope(), name)
}
func (p *Package) lookupOrigin(name string, pubName string) types.Object {
if obj := p.Lookup(name); obj != nil {
return obj
}
if name != pubName {
return p.Lookup(pubName)
}
return nil
}
func (p *Package) lookupPub(_ string, pubName string) types.Object {
return p.Lookup(pubName)
}
// NewTypeDecl converts C/C++ type declarations to Go.
// Besides regular type declarations, it also supports:
// - Forward declarations: Pre-registers incomplete types for later definition
// - Self-referential types: Handles types that reference themselves (like linked lists)
func (p *Package) NewTypeDecl(typeDecl *ast.TypeDecl) error {
skip, _ := p.handleType(typeDecl.Name, typeDecl.Loc)
if skip {
if debugLog {
log.Printf("NewTypeDecl: %s type of third header\n", typeDecl.Name)
}
return nil
}
if debugLog {
log.Printf("NewTypeDecl: %s\n", typeDecl.Name.Name)
}
cname := typeDecl.Name.Name
isForward := p.cvt.inComplete(typeDecl.Type)
name, changed, exist, err := p.RegisterNode(Node{name: cname, kind: TypeDecl}, p.declName, p.lookupOrigin)
if err != nil {
return fmt.Errorf("NewTypeDecl: %s fail: %w", typeDecl.Name.Name, err)
}
// if the type is already defined,we don't need to process again
// but if the previous processed node is a forward declaration,we need to complete the type
_, isIncom := p.incompleteTypes.Lookup(typeDecl.Name.Name)
if exist && (isForward || !isIncom) {
if debugLog {
log.Printf("NewTypeDecl: %s is processed\n", typeDecl.Name.Name)
}
return nil
}
p.CollectNameMapping(cname, name)
incom := p.handleTypeDecl(name, cname, typeDecl)
if changed {
substObj(p.p.Types, p.p.Types.Scope(), cname, incom.decl.Type().Obj())
}
if !isForward {
if err := p.handleCompleteType(incom, typeDecl.Type, cname); err != nil {
return fmt.Errorf("NewTypeDecl: fail to complete type %s: %w", typeDecl.Name.Name, err)
}
}
return nil
}
// handleTypeDecl creates a new type declaration or retrieves existing one
func (p *Package) handleTypeDecl(pubname string, cname string, typeDecl *ast.TypeDecl) *Incomplete {
if existDecl, exists := p.incompleteTypes.Lookup(cname); exists {
return existDecl
}
decl := p.emptyTypeDecl(pubname, typeDecl.Doc)
inc := &Incomplete{
cname: cname,
file: p.curFile,
decl: decl,
getType: func() (types.Type, error) {
return types.NewStruct(p.cvt.defaultRecordField(), nil), nil
},
}
p.incompleteTypes.Add(inc)
return inc
}
func (p *Package) handleCompleteType(incom *Incomplete, typ *ast.RecordType, name string) error {
// defer delete(p.incomplete, name)
defer p.incompleteTypes.Complete(name)
defer p.SetCurFile(p.curFile)
p.SetCurFile(incom.file)
structType, err := p.cvt.RecordTypeToStruct(typ)
if err != nil {
// For incomplete type's conerter error, we use default struct type
return err
}
incom.decl.InitType(p.p, structType)
return nil
}
// handleImplicitForwardDecl handles type references that cannot be found in the current scope.
// For such declarations, create a empty type decl and store it in the
// incomplete map, but not in the public symbol table.
func (p *Package) handleImplicitForwardDecl(name string) *gogen.TypeDecl {
if decl, ok := p.incompleteTypes.Lookup(name); ok {
return decl.decl
}
// Using TypeDecl as the node kind here because forward declarations in C/C++ typically
// only occur with struct, class, and enum type declarations, not with typedefs or other declarations.
// The TypeDecl node kind ensures these forward declarations are properly tracked and later completed.
pubName, _, _, _ := p.RegisterNode(Node{name: name, kind: TypeDecl}, p.declName, p.lookupOrigin)
decl := p.emptyTypeDecl(pubName, nil)
inc := &Incomplete{
cname: name,
file: p.curFile,
decl: decl,
getType: func() (types.Type, error) {
return types.NewStruct(p.cvt.defaultRecordField(), nil), nil
},
}
p.incompleteTypes.Add(inc)
return decl
}
func (p *Package) emptyTypeDecl(name string, doc *ast.CommentGroup) *gogen.TypeDecl {
typeBlock := p.p.NewTypeDefs()
typeBlock.SetComments(NewCommentGroupFromC(doc))
return typeBlock.NewType(name)
}
func (p *Package) NewTypedefDecl(typedefDecl *ast.TypedefDecl) error {
skip, _ := p.handleType(typedefDecl.Name, typedefDecl.Loc)
if skip {
if debugLog {
log.Printf("NewTypedefDecl: %v is a typedef of third header file\n", typedefDecl.Name)
}
return nil
}
if debugLog {
log.Printf("NewTypedefDecl: %s\n", typedefDecl.Name.Name)
}
node := Node{name: typedefDecl.Name.Name, kind: TypedefDecl}
name, changed, exist, err := p.RegisterNode(node, p.declName, p.lookupOrigin)
if err != nil {
return fmt.Errorf("NewTypedefDecl: %s fail: %w", typedefDecl.Name.Name, err)
}
if exist {
if debugLog {
log.Printf("NewTypedefDecl: %s is processed\n", typedefDecl.Name.Name)
}
return nil
}
p.CollectNameMapping(typedefDecl.Name.Name, name)
genDecl := p.p.NewTypeDefs()
typeSpecdecl := genDecl.NewType(name)
if changed {
substObj(p.p.Types, p.p.Types.Scope(), typedefDecl.Name.Name, typeSpecdecl.Type().Obj())
}
deferInit := p.handleTyperefIncomplete(typedefDecl.Type, typeSpecdecl, typedefDecl.Name.Name)
if deferInit {
if debugLog {
log.Printf("NewTypedefDecl: %s defer init\n", name)
}
return nil
}
typ, err := p.ToType(typedefDecl.Type)
if err != nil {
return fmt.Errorf("NewTypedefDecl:fail to convert type %v: %w", typedefDecl.Name.Name, err)
}
typeSpecdecl.InitType(p.p, typ)
if _, ok := typ.(*types.Signature); ok {
genDecl.SetComments(NewCommentGroup(NewTypecDocComment()))
}
return nil
}
func (p *Package) handleTyperefIncomplete(typeRef ast.Expr, typeSpecdecl *gogen.TypeDecl, namedName string) bool {
var name string
switch expr := typeRef.(type) {
case *ast.TagExpr:
if n, ok := expr.Name.(*ast.Ident); ok {
name = n.Name
} else {
panic("todo:scoping expr not supported")
}
case *ast.Ident:
name = expr.Name
default:
return false
}
_, inc := p.incompleteTypes.Lookup(name)
if !inc {
return false
}
p.incompleteTypes.Add(&Incomplete{
cname: namedName,
file: p.curFile,
decl: typeSpecdecl,
getType: func() (types.Type, error) {
typ, err := p.ToType(typeRef)
return typ, err
},
})
return true
}
// Convert ast.Expr to types.Type
func (p *Package) ToType(expr ast.Expr) (types.Type, error) {
return p.cvt.ToType(expr)
}
func (p *Package) NewTypedefs(name string, typ types.Type) *gogen.TypeDecl {
def := p.p.NewTypeDefs()
t := def.NewType(name)
t.InitType(def.Pkg(), typ)
def.Complete()
return t
}
func (p *Package) NewEnumTypeDecl(enumTypeDecl *ast.EnumTypeDecl) error {
skip, _ := p.handleType(enumTypeDecl.Name, enumTypeDecl.Loc)
if skip {
if debugLog {
log.Printf("NewEnumTypeDecl: %v is a enum type of system header file\n", enumTypeDecl.Name)
}
return nil
}
if debugLog {
log.Printf("NewEnumTypeDecl: %v\n", enumTypeDecl.Name)
}
enumType, exist, err := p.createEnumType(enumTypeDecl.Name)
if err != nil {
return fmt.Errorf("NewEnumTypeDecl: %v fail: %w", enumTypeDecl.Name, err)
}
if exist {
if debugLog {
log.Printf("NewEnumTypeDecl: %v is processed\n", enumTypeDecl.Name)
}
return nil
}
if len(enumTypeDecl.Type.Items) > 0 {
err = p.createEnumItems(enumTypeDecl.Type.Items, enumType)
if err != nil {
return fmt.Errorf("NewEnumTypeDecl: %v fail: %w", enumTypeDecl.Name, err)
}
}
return nil
}
func (p *Package) createEnumType(enumName *ast.Ident) (types.Type, bool, error) {
var name string
var changed bool
var err error
var exist bool
var t *gogen.TypeDecl
if enumName != nil {
node := Node{name: enumName.Name, kind: EnumTypeDecl}
name, changed, exist, err = p.RegisterNode(node, p.declName, p.lookupOrigin)
if err != nil {
return nil, false, err
}
if exist {
return nil, true, nil
}
p.CollectNameMapping(enumName.Name, name)
}
enumType := p.cvt.ToDefaultEnumType()
if name != "" {
t = p.NewTypedefs(name, enumType)
enumType = p.Lookup(name).Type()
}
if changed {
substObj(p.p.Types, p.p.Types.Scope(), enumName.Name, t.Type().Obj())
}
return enumType, false, nil
}
func (p *Package) createEnumItems(items []*ast.EnumItem, enumType types.Type) error {
defs := p.NewConstGroup()
for _, item := range items {
// The 'changed' parameter is intentionally ignored here because enum items are used as constant values, not type identifiers.
// In C/C++ code, there are no type references to enum items, so there's no need to establish a cname->pubName mapping in the scope.
// This is similar to how macro constants (Macro) are handled, as both are value-level symbols rather than type-level.
name, _, exist, err := p.RegisterNode(Node{name: item.Name.Name, kind: EnumItem}, p.constName, p.lookupPub)
if err != nil {
return err
}
if exist {
if debugLog {
log.Printf("NewEnumTypeDecl: %v is processed\n", item.Name.Name)
}
continue
}
val, err := Expr(item.Value).ToInt()
if err != nil {
return fmt.Errorf("createEnumItems:fail to convert %T to int: %w", item.Value, err)
}
defs.New(val, enumType, name)
}
return nil
}
func (p *Package) NewMacro(macro *ast.Macro, goName string) error {
// simple const macro define (#define NAME value)
if len(macro.Tokens) == 2 && macro.Tokens[1].Token == ctoken.LITERAL {
value := macro.Tokens[1].Lit
defs := p.NewConstGroup()
obj := p.lookupPub("", goName)
if obj != nil {
return fmt.Errorf("NewMacro: %s is already defined", macro.Name)
}
// node := Node{name: macro.Name, kind: Macro}
// todo(zzy): remove this,current only to register name to ProcessSymbol,to keep other logic correct
// _, _, exist, err := p.RegisterNode(node, p.constName, p.lookupPub)
// if err != nil {
// return fmt.Errorf("NewMacro: %s fail: %w", macro.Name, err)
// }
// if exist {
// if debugLog {
// log.Printf("NewMacro: %s is processed\n", macro.Name)
// }
// return nil
// }
if debugLog {
log.Printf("NewMacro: %s = %s\n", goName, value)
}
if str, err := litToString(value); err == nil {
defs.New(str, nil, goName)
} else if _, err := litToUint(value); err == nil {
defs.New(&goast.BasicLit{
Kind: token.INT,
Value: value,
}, nil, goName)
} else if _, err := litToFloat(value, 64); err == nil {
defs.New(&goast.BasicLit{
Kind: token.FLOAT,
Value: value,
}, nil, goName)
}
}
return nil
}
func (p *Package) NewConstGroup() *ConstGroup {
return NewConstGroup(p.p, p.p.Types.Scope())
}
func (p *Package) SetGoFile(fileName string) error {
_, err := p.p.SetCurFile(fileName, true)
// todo(zzy):avoid mark every time
p.p.Unsafe().MarkForceUsed(p.p)
return err
}
type ConstGroup struct {
defs *gogen.ConstDefs
}
func NewConstGroup(pkg *gogen.Package, scope *types.Scope) *ConstGroup {
return &ConstGroup{
defs: pkg.NewConstDefs(scope),
}
}
func (p *ConstGroup) New(val any, typ types.Type, name string) {
p.defs.New(func(cb *gogen.CodeBuilder) int {
cb.Val(val)
return 1
}, 0, token.NoPos, typ, name)
}
// Complete completes all incomplete type definitions,
// because some types may be implemented across multiple files.
func (p *Package) Complete() error {
err := p.deferTypeBuild()
if err != nil {
return err
}
return nil
}
func (p *Package) autoLinkFile() string {
return p.conf.Name + "_autogen_link.go"
}
func (p *Package) initLink() error {
fileName := p.autoLinkFile()
_, err := p.p.SetCurFile(fileName, true)
if err != nil {
return fmt.Errorf("failed to set current file: %w", err)
}
err = p.linkLib(p.conf.LibCommand)
if err != nil {
return err
}
return nil
}
func (p *Package) deferTypeBuild() error {
err := p.incompleteTypes.IterateIncomplete(func(inc *Incomplete) error {
p.SetCurFile(inc.file)
typ, err := inc.getType()
if typ != nil {
inc.decl.InitType(p.p, typ)
}
if err != nil {
return err
}
return nil
})
p.incompleteTypes.Clear()
return err
}
type NameMethod func(name string) string
func (p *Package) RegisterNode(node Node, nameMethod NameMethod, lookup func(name string, pubName string) types.Object) (pubName string, changed bool, exist bool, err error) {
pubName, exist = p.symbols.Lookup(node)
if exist {
return pubName, pubName != node.name, exist, nil
}
pubName, changed = p.GetUniqueName(node, nameMethod)
obj := lookup(node.name, pubName)
if obj != nil {
return "", false, exist, NewTypeDefinedError(pubName, node.name)
}
return pubName, changed, exist, nil
}
// GetUniqueName generates a unique public name for a given node using the provided name transformation method.
// It ensures the generated name doesn't conflict with existing names by adding a numeric suffix if needed.
//
// Parameters:
// - node: The node containing the original name to be transformed
// - nameMethod: Function used to transform the original name (e.g., declName, constName)
//
// Returns:
// - pubName: The generated unique public name
// - changed: Whether the generated name differs from the original name
func (p *Package) GetUniqueName(node Node, nameMethod NameMethod) (pubName string, changed bool) {
pubName = nameMethod(node.name)
uniquePubName := p.symbols.Register(node, pubName)
return uniquePubName, uniquePubName != node.name
}
// which is define in llcppg.cfg/typeMap
func (p *Package) definedName(name string) (string, bool) {
definedName, ok := p.Pubs[name]
if ok {
if definedName == "" {
return name, true
}
return definedName, true
}
return name, false
}
// transformName handles identifier name conversion following these rules:
// 1. First checks if the name exists in predefined mapping (in typeMap of llcppg.cfg)
// 2. If not in predefined mapping, applies the transform function
// 3. Before applying the transform function, removes specified prefixes (obtained via trimPrefixes)
//
// Parameters:
// - name: Original C/C++ identifier name
// - transform: Name transformation function (like names.PubName or names.ExportName)
//
// Returns:
// - Transformed identifier name
func (p *Package) transformName(cname string, transform NameMethod) string {
if definedName, ok := p.definedName(cname); ok {
return definedName
}
return transform(name.RemovePrefixedName(cname, p.trimPrefixes()))
}
func (p *Package) declName(cname string) string {
return p.transformName(cname, name.PubName)
}
func (p *Package) constName(cname string) string {
return p.transformName(cname, name.ExportName)
}
func (p *Package) trimPrefixes() []string {
if p.curFile.InCurPkg() {
return p.conf.TrimPrefixes
}
return []string{}
}
// typedecl,enumdecl,funcdecl,funcdecl
// true determine continue execute the type gen
// if this type is in a third header,skip the type gen & collect the type info
func (p *Package) handleType(ident *ast.Ident, loc *ast.Location) (skip bool, anony bool) {
anony = ident == nil
if curPkg := p.curFile.InCurPkg(); curPkg || anony {
return !curPkg, anony
}
if _, ok := p.locMap.Lookup(ident.Name); ok {
// a third ident in multiple location is permit
return true, anony
}
p.locMap.Add(ident, loc)
return true, anony
}
// Collect the name mapping between origin name and pubname
// if in current package, it will be collected in public symbol table
func (p *Package) CollectNameMapping(originName, newName string) {
value := ""
if originName != newName {
value = newName
}
if p.curFile.InCurPkg() {
if !p.conf.KeepUnderScore && rune(originName[0]) == '_' {
return
}
p.Pubs[originName] = value
}
}
type ThirdTypeLoc struct {
locMap map[string]string // type name from third package -> define location
}
func NewThirdTypeLoc() *ThirdTypeLoc {
return &ThirdTypeLoc{
locMap: make(map[string]string),
}
}
func (p *ThirdTypeLoc) Add(ident *ast.Ident, loc *ast.Location) {
p.locMap[ident.Name] = loc.File
}
func (p *ThirdTypeLoc) Lookup(name string) (string, bool) {
loc, ok := p.locMap[name]
return loc, ok
}
type IncompleteTypes struct {
types []*Incomplete // ordered list of incomplete types
typesMap map[string]*Incomplete // quick lookup by C name
}
type Incomplete struct {
cname string // origin name(in c)
file *HeaderFile // the file where the type declaration is located
decl *gogen.TypeDecl // the need to resolved later type declaration
getType func() (types.Type, error) // will be executed after all incomplete types are initialized.
}
func NewIncompleteTypes() *IncompleteTypes {
return &IncompleteTypes{
types: make([]*Incomplete, 0),
typesMap: make(map[string]*Incomplete),
}
}
func (it *IncompleteTypes) Add(inc *Incomplete) {
it.types = append(it.types, inc)
it.typesMap[inc.cname] = inc
}
func (it *IncompleteTypes) Lookup(cname string) (*Incomplete, bool) {
inc, ok := it.typesMap[cname]
return inc, ok
}
func (it *IncompleteTypes) Complete(cname string) {
delete(it.typesMap, cname)
}
func (it *IncompleteTypes) Clear() {
it.types = make([]*Incomplete, 0)
it.typesMap = make(map[string]*Incomplete)
}
func (it *IncompleteTypes) IterateIncomplete(fn func(*Incomplete) error) error {
for _, inc := range it.types {
// skip the type that has been completed
if _, ok := it.typesMap[inc.cname]; !ok {
continue
}
if err := fn(inc); err != nil {
return err
}
}
return nil
}
type NodeKind int
const (
FuncDecl NodeKind = iota + 1
TypeDecl
TypedefDecl
EnumTypeDecl
EnumItem
Macro
)
type Node struct {
name string
kind NodeKind
}
func NewNode(name string, kind NodeKind) Node {
return Node{name: name, kind: kind}
}
func (n Node) Name() string {