diff --git a/internal/loader/cgo_test.go b/internal/loader/cgo_test.go new file mode 100644 index 0000000..147f858 --- /dev/null +++ b/internal/loader/cgo_test.go @@ -0,0 +1,60 @@ +package loader + +import ( + "context" + "go/token" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "golang.org/x/tools/go/packages" +) + +// TestLocalCgoDiscoveryFallsBackWithoutLosingConstructors reproduces reuse of metadata that omitted native constructor bodies. +func TestLocalCgoDiscoveryFallsBackWithoutLosingConstructors(t *testing.T) { + setting, err := exec.Command("go", "env", "CGO_ENABLED").Output() + if err != nil { + t.Fatal(err) + } + if strings.TrimSpace(string(setting)) != "1" { + t.Skip("native cgo compiler is disabled") + } + root := t.TempDir() + writeTestFile(t, filepath.Join(root, "go.mod"), "module example.com/native\n\ngo 1.25\n") + writeTestFile(t, filepath.Join(root, "native", "types.go"), "package native\n\ntype Value struct { Number int }\n") + bridge := filepath.Join(root, "native", "bridge.go") + writeTestFile(t, bridge, "package native\n\n/* static int value(void) { return 7; } */\nimport \"C\"\n\nfunc New() *Value { return &Value{Number: int(C.value())} }\n") + writeTestFile(t, filepath.Join(root, "app", "app.go"), "package app\n\nimport \"example.com/native/native\"\n\nfunc Init() *native.Value { return native.New() }\n") + discovery, err := New().LoadRootGraph(context.Background(), RootLoadRequest{WD: root, Env: os.Environ(), Patterns: []string{"./app"}, NeedDeps: true}) + if err != nil { + t.Fatal(err) + } + if discovery.Discovery == nil || len(discovery.Discovery.meta["example.com/native/native"].CgoFiles) != 1 { + t.Fatal("discovery lost cgo metadata") + } + result, err := New().LoadPackages(context.Background(), PackageLoadRequest{WD: root, Env: os.Environ(), Patterns: []string{"./app"}, Discovery: discovery.Discovery, Mode: packages.LoadAllSyntax, Fset: token.NewFileSet()}) + if err != nil { + t.Fatal(err) + } + if result.Backend != ModeFallback || result.FallbackReason != FallbackReasonCustomUnsupported { + t.Fatalf("native graph backend = %#v", result) + } + for _, pkg := range collectGraph(result.Packages) { + if len(pkg.Errors) != 0 { + t.Fatalf("native package errors: %v", pkg.Errors) + } + if pkg.PkgPath == "example.com/native/native" && pkg.Types.Scope().Lookup("New") == nil { + t.Fatal("native constructor was lost") + } + } + entry, err := buildDiscoveryCacheEntry(goListRequest{WD: root, Env: os.Environ()}, discovery.Discovery.meta) + if err != nil { + t.Fatal(err) + } + writeTestFile(t, bridge, "package native\n\nimport _ \"strings\"\n\nfunc New() *Value { return &Value{Number: 8} }\n") + if validateDiscoveryCacheEntry(entry) { + t.Fatal("native source edit retained stale discovery") + } +} diff --git a/internal/loader/custom.go b/internal/loader/custom.go index df011c1..6bb8ff0 100644 --- a/internal/loader/custom.go +++ b/internal/loader/custom.go @@ -42,6 +42,7 @@ type unsupportedError struct { func (e unsupportedError) Error() string { return e.reason } +// packageMeta preserves Go's file classification so native sources cannot disappear during cached discovery. type packageMeta struct { ImportPath string Name string @@ -49,6 +50,7 @@ type packageMeta struct { DepOnly bool Export string GoFiles []string + CgoFiles []string CompiledGoFiles []string Imports []string ImportMap map[string]string @@ -265,6 +267,7 @@ func loadPackagesCustom(ctx context.Context, req PackageLoadRequest) (*PackageLo }, nil } +// loadCustomPackagesFromMeta rejects native source before import errors can hide the fallback signal. func loadCustomPackagesFromMeta(ctx context.Context, wd string, env []string, fset *token.FileSet, meta map[string]*packageMeta, targets map[string]struct{}, rootPaths []string, parseFile ParseFileFunc, discoveryDuration time.Duration, mode string) ([]*packages.Package, error) { if len(meta) == 0 { return nil, unsupportedError{reason: "empty go list result"} @@ -272,6 +275,12 @@ func loadCustomPackagesFromMeta(ctx context.Context, wd string, env []string, fs if len(rootPaths) == 0 { return nil, unsupportedError{reason: "no root packages from metadata"} } + workspace := detectModuleRoot(wd) + for _, pkg := range meta { + if pkg != nil && len(pkg.CgoFiles) != 0 && isLocalSourcePackage(workspace, pkg) { + return nil, unsupportedError{reason: "local cgo source requires the native Go package loader"} + } + } if fset == nil { fset = token.NewFileSet() } @@ -1046,6 +1055,7 @@ func normalizeImports(imports []string, importMap map[string]string) []string { return out } +// metaFiles retains native import fingerprints when discovery intentionally skips compiled files. func metaFiles(meta *packageMeta) []string { if meta == nil { return nil @@ -1053,6 +1063,9 @@ func metaFiles(meta *packageMeta) []string { if len(meta.CompiledGoFiles) > 0 { return meta.CompiledGoFiles } + if len(meta.CgoFiles) != 0 { + return append(append([]string(nil), meta.GoFiles...), meta.CgoFiles...) + } return meta.GoFiles } diff --git a/internal/loader/discovery.go b/internal/loader/discovery.go index bccfd93..093e889 100644 --- a/internal/loader/discovery.go +++ b/internal/loader/discovery.go @@ -35,6 +35,7 @@ type goListRequest struct { SkipCompiled bool } +// runGoList preserves source classifications across live and cached package discovery. func runGoList(ctx context.Context, req goListRequest) (map[string]*packageMeta, error) { cacheReadStart := time.Now() if cached, ok := readDiscoveryCache(req); ok { @@ -103,6 +104,11 @@ func runGoList(ctx context.Context, req goListRequest) (map[string]*packageMeta, meta.GoFiles[i] = filepath.Join(meta.Dir, name) } } + for i, name := range meta.CgoFiles { + if !filepath.IsAbs(name) { + meta.CgoFiles[i] = filepath.Join(meta.Dir, name) + } + } for i, name := range meta.CompiledGoFiles { if !filepath.IsAbs(name) { meta.CompiledGoFiles[i] = filepath.Join(meta.Dir, name) diff --git a/internal/loader/discovery_cache.go b/internal/loader/discovery_cache.go index d8d9193..eadbfdf 100644 --- a/internal/loader/discovery_cache.go +++ b/internal/loader/discovery_cache.go @@ -48,7 +48,7 @@ type discoveryFileFingerprint struct { Hash string } -const discoveryCacheVersion = 5 +const discoveryCacheVersion = 6 func readDiscoveryCache(req goListRequest) (map[string]*packageMeta, bool) { entry, err := loadDiscoveryCacheEntry(req)