From 927e304327800d7f923125d577779ae3cd61eeec Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 15:48:58 -0500 Subject: [PATCH 1/3] refactor: name the packages without a version: internal/model, internal/schema, emit (#63) The output contract moves from internal/schema/v2 to internal/schema, the analyzer's internal fact model from internal/schema to internal/model, and the emitter from syntactic_analysis/v2emit to syntactic_analysis/emit. Comments, error strings and test names no longer say v1 or v2. The output is unchanged. --- cmd/codeanalyzer/main.go | 22 +- cmd/codeanalyzer/main_test.go | 8 +- internal/analysis/pass.go | 8 +- internal/analysis/registry.go | 4 +- internal/analysis/registry_test.go | 12 +- internal/core/analyzer.go | 54 +- internal/core/analyzer_test.go | 22 +- internal/core/crossfile_method_test.go | 10 +- internal/core/init_collision_test.go | 8 +- internal/core/init_l3_test.go | 8 +- internal/core/multipackage_test.go | 6 +- internal/core/repository_test.go | 14 +- internal/core/testsetup_test.go | 16 +- internal/dataflow/accesspath_test.go | 4 +- internal/dataflow/bodynodes.go | 8 +- internal/dataflow/bodynodes_test.go | 10 +- internal/dataflow/cfg_test.go | 6 +- internal/dataflow/ir.go | 4 +- internal/dataflow/run_test.go | 18 +- internal/frameworks/base.go | 4 +- internal/metamorphic/compare.go | 22 +- internal/metamorphic/run.go | 12 +- internal/metamorphic/transform.go | 4 +- internal/model/model.go | 281 +++++++++ internal/neo4j/artifact_integration_test.go | 16 +- .../neo4j/batched_delete_integration_test.go | 14 +- internal/neo4j/bolt.go | 6 +- internal/neo4j/bolt_integration_test.go | 6 +- internal/neo4j/bolt_session_test.go | 6 +- internal/neo4j/crossfile_lazy_push_test.go | 12 +- internal/neo4j/crossfile_stream_test.go | 8 +- internal/neo4j/crossfile_test.go | 14 +- internal/neo4j/cypher.go | 4 +- internal/neo4j/cypher_test.go | 4 +- internal/neo4j/ddl.go | 4 +- internal/neo4j/emit.go | 2 +- internal/neo4j/large_text_test.go | 8 +- internal/neo4j/project.go | 72 +-- internal/neo4j/project_test.go | 96 +-- internal/neo4j/repository_test.go | 14 +- internal/neo4j/schema.go | 12 +- internal/neo4j/signature_test.go | 24 +- internal/neo4j/source.go | 34 +- internal/neo4j/span_lines_test.go | 20 +- internal/neo4j/stream.go | 6 +- internal/neo4j/stream_test.go | 50 +- internal/options/options.go | 2 +- internal/repository/replace_test.go | 8 +- internal/repository/repository.go | 36 +- internal/repository/repository_test.go | 14 +- internal/schema/{v2 => }/ids.go | 6 +- internal/schema/{v2 => }/ids_external_test.go | 2 +- internal/schema/{v2 => }/ids_member_test.go | 2 +- internal/schema/{v2 => }/ids_test.go | 2 +- internal/schema/{v2 => }/namespace_test.go | 2 +- internal/schema/schema.go | 597 +++++++++++------- .../schema/{v2 => }/testdata/namespaces.json | 0 internal/schema/v2/schema.go | 402 ------------ internal/sdg/footprint.go | 18 +- internal/sdg/footprint_test.go | 4 +- internal/sdg/ir.go | 18 +- internal/sdg/vertices.go | 4 +- internal/sdg/vta.go | 20 +- internal/sdg/vta_test.go | 12 +- internal/semantic_analysis/call_graph.go | 46 +- internal/semantic_analysis/call_graph_test.go | 36 +- .../{v2emit => emit}/artifact_stream_test.go | 18 +- .../{v2emit => emit}/artifacts_stream.go | 16 +- .../determinism_freshbuild_test.go | 8 +- .../{v2emit => emit}/determinism_test.go | 54 +- .../{v2emit => emit}/emit.go | 190 +++--- .../{v2emit => emit}/emit_l3.go | 26 +- .../{v2emit => emit}/emit_l4.go | 50 +- .../{v2emit => emit}/emit_l4_test.go | 12 +- .../{v2emit => emit}/emit_test.go | 20 +- .../{v2emit => emit}/gate_l2_inits_test.go | 10 +- .../{v2emit => emit}/gate_l2_test.go | 90 +-- .../{v2emit => emit}/gate_l3_test.go | 96 +-- .../{v2emit => emit}/gate_l4_done_test.go | 46 +- .../{v2emit => emit}/gate_l4_test.go | 96 +-- .../{v2emit => emit}/gate_l4_wrap_test.go | 22 +- .../{v2emit => emit}/gate_test.go | 108 ++-- .../{v2emit => emit}/offsets.go | 12 +- .../{v2emit => emit}/offsets_test.go | 2 +- .../{v2emit => emit}/repository.go | 20 +- .../{v2emit => emit}/repository_test.go | 6 +- .../{v2emit => emit}/sigindex.go | 26 +- .../{v2emit => emit}/stream.go | 28 +- .../{v2emit => emit}/stream_test.go | 6 +- internal/syntactic_analysis/l3units.go | 14 +- internal/syntactic_analysis/symbol_table.go | 120 ++-- internal/utils/fs_test.go | 4 +- 92 files changed, 1664 insertions(+), 1664 deletions(-) create mode 100644 internal/model/model.go rename internal/schema/{v2 => }/ids.go (98%) rename internal/schema/{v2 => }/ids_external_test.go (99%) rename internal/schema/{v2 => }/ids_member_test.go (99%) rename internal/schema/{v2 => }/ids_test.go (99%) rename internal/schema/{v2 => }/namespace_test.go (99%) rename internal/schema/{v2 => }/testdata/namespaces.json (100%) delete mode 100644 internal/schema/v2/schema.go rename internal/syntactic_analysis/{v2emit => emit}/artifact_stream_test.go (80%) rename internal/syntactic_analysis/{v2emit => emit}/artifacts_stream.go (91%) rename internal/syntactic_analysis/{v2emit => emit}/determinism_freshbuild_test.go (96%) rename internal/syntactic_analysis/{v2emit => emit}/determinism_test.go (77%) rename internal/syntactic_analysis/{v2emit => emit}/emit.go (76%) rename internal/syntactic_analysis/{v2emit => emit}/emit_l3.go (73%) rename internal/syntactic_analysis/{v2emit => emit}/emit_l4.go (85%) rename internal/syntactic_analysis/{v2emit => emit}/emit_l4_test.go (89%) rename internal/syntactic_analysis/{v2emit => emit}/emit_test.go (91%) rename internal/syntactic_analysis/{v2emit => emit}/gate_l2_inits_test.go (90%) rename internal/syntactic_analysis/{v2emit => emit}/gate_l2_test.go (87%) rename internal/syntactic_analysis/{v2emit => emit}/gate_l3_test.go (85%) rename internal/syntactic_analysis/{v2emit => emit}/gate_l4_done_test.go (89%) rename internal/syntactic_analysis/{v2emit => emit}/gate_l4_test.go (90%) rename internal/syntactic_analysis/{v2emit => emit}/gate_l4_wrap_test.go (83%) rename internal/syntactic_analysis/{v2emit => emit}/gate_test.go (86%) rename internal/syntactic_analysis/{v2emit => emit}/offsets.go (87%) rename internal/syntactic_analysis/{v2emit => emit}/offsets_test.go (99%) rename internal/syntactic_analysis/{v2emit => emit}/repository.go (72%) rename internal/syntactic_analysis/{v2emit => emit}/repository_test.go (83%) rename internal/syntactic_analysis/{v2emit => emit}/sigindex.go (86%) rename internal/syntactic_analysis/{v2emit => emit}/stream.go (66%) rename internal/syntactic_analysis/{v2emit => emit}/stream_test.go (94%) diff --git a/cmd/codeanalyzer/main.go b/cmd/codeanalyzer/main.go index bb33a28..9079abe 100644 --- a/cmd/codeanalyzer/main.go +++ b/cmd/codeanalyzer/main.go @@ -6,7 +6,7 @@ package main import ( "fmt" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "os" "path/filepath" "runtime" @@ -17,7 +17,7 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/core" "github.com/codellm-devkit/codeanalyzer-go/internal/neo4j" "github.com/codellm-devkit/codeanalyzer-go/internal/options" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -38,7 +38,7 @@ func rootCmd() *cobra.Command { inputPath string outputDir string format string - emit string + projection string appName string namespace string level int @@ -80,7 +80,7 @@ via CLDK(language="go").analysis(project_path=...).`, // analysis path below but is ALWAYS full-depth, so an explicit // -a/--analysis-level alongside it is a flag error (the level gate // applies to the JSON path only). - emitTarget := options.EmitTarget(emit) + emitTarget := options.EmitTarget(projection) switch emitTarget { case options.EmitJSON: if err := validateAnalysisLevel(level); err != nil { @@ -104,7 +104,7 @@ via CLDK(language="go").analysis(project_path=...).`, } // Force full depth: the graph carries every implemented // level's facts in both projections. (Output is always the - // canonical v2 tree.) L4 is whole-program, so a targeted run + // canonical tree.) L4 is whole-program, so a targeted run // projects at L3 and says so. level = int(options.LevelSDG) if len(targetFiles) > 0 { @@ -123,7 +123,7 @@ via CLDK(language="go").analysis(project_path=...).`, cmd.Println("wrote " + path) return nil default: - return fmt.Errorf("unsupported --emit target %q; supported: json, neo4j, schema", emit) + return fmt.Errorf("unsupported --emit target %q; supported: json, neo4j, schema", projection) } if inputPath == "" { @@ -165,7 +165,7 @@ via CLDK(language="go").analysis(project_path=...).`, if cmd.Flags().Changed("namespace") { ns = &namespace } - identity, err := v2.ResolveIdentity(appName, ns) + identity, err := schema.ResolveIdentity(appName, ns) if err != nil { return err } @@ -173,7 +173,7 @@ via CLDK(language="go").analysis(project_path=...).`, InputPath: inputPath, OutputDir: outputDir, Format: format, - Emit: options.EmitTarget(emit), + Emit: options.EmitTarget(projection), AppName: appName, Namespace: ns, Level: options.AnalysisLevel(level), Strict: strict, @@ -200,12 +200,12 @@ via CLDK(language="go").analysis(project_path=...).`, } utils.LogMemory("analysis") - // Neo4j projection: stream the canonical v2 payload (the SAME modules + // Neo4j projection: stream the canonical payload (the SAME modules // the JSON path emits) one module at a time into the projection, so // the full tree is never held (#59). --neo4j-uri set → live Bolt push; // absent → a graph.cypher snapshot in the output dir. if emitTarget == options.EmitNeo4j { - src := v2emit.Open(app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, core.KLimit(opts), analyzer.L3(), analyzer.L4()) + src := emit.Open(app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, core.KLimit(opts), analyzer.L3(), analyzer.L4()) boltCfg := neo4j.BoltConfig{ URI: opts.Neo4jURI, User: opts.Neo4jUser, @@ -239,7 +239,7 @@ via CLDK(language="go").analysis(project_path=...).`, f.StringVarP(&inputPath, "input", "i", "", "Project root to analyze (required)") f.StringVarP(&outputDir, "output", "o", "", "Output directory for analysis.json (default: stdout)") f.StringVarP(&format, "format", "f", "json", "Output format: json|msgpack") - f.StringVar(&emit, "emit", "json", "Output projection: json|neo4j|schema") + f.StringVar(&projection, "emit", "json", "Output projection: json|neo4j|schema") f.StringVar(&namespace, "namespace", "", "Identity namespace (default: application name)") f.StringVar(&appName, "app-name", "", "Application anchor name for can:// ids and Neo4j :Application (default: input dir name)") diff --git a/cmd/codeanalyzer/main_test.go b/cmd/codeanalyzer/main_test.go index d233e3b..52839ce 100644 --- a/cmd/codeanalyzer/main_test.go +++ b/cmd/codeanalyzer/main_test.go @@ -213,7 +213,6 @@ func TestRootCmd_Level1ProducesNoCallGraph(t *testing.T) { t.Fatalf("command failed: %v", err) } - // The default is now the v2 shape, where call_graph lives under application (not top-level). var result struct { Application struct { CallGraph []interface{} `json:"call_graph"` @@ -239,7 +238,6 @@ func TestRootCmd_Level2ProducesCallGraph(t *testing.T) { t.Fatalf("command failed: %v", err) } - // The default is now the v2 shape, where call_graph lives under application (not top-level). var result struct { Application struct { CallGraph []interface{} `json:"call_graph"` @@ -253,11 +251,11 @@ func TestRootCmd_Level2ProducesCallGraph(t *testing.T) { } } -// ── schema output (always canonical v2) ───────────────────────────────────────── +// ── schema output (always canonical) ──────────────────────────────────────────── -// The analyzer emits only the canonical v2 containment tree. This asserts the +// The analyzer emits only the canonical containment tree. This asserts the // envelope shape and identity anchor on the default (and only) output path. -func TestRootCmd_EmitsCanonicalV2(t *testing.T) { +func TestRootCmd_EmitsCanonical(t *testing.T) { td := cliTestdataDir() out, _, err := runCmd("--input", filepath.Join(td, "greeter"), "--cache-dir", t.TempDir()) if err != nil { diff --git a/internal/analysis/pass.go b/internal/analysis/pass.go index 3142774..096c5be 100644 --- a/internal/analysis/pass.go +++ b/internal/analysis/pass.go @@ -8,7 +8,7 @@ // codeanalyzer-extension-builder can register out-of-tree passes. package analysis -import "github.com/codellm-devkit/codeanalyzer-go/internal/schema" +import "github.com/codellm-devkit/codeanalyzer-go/internal/model" // AnalysisContext carries the shared context available to every pass. type AnalysisContext struct { @@ -19,9 +19,9 @@ type AnalysisContext struct { // AnalysisResult holds the output of a single pass run. type AnalysisResult struct { // Entrypoints discovered by this pass, keyed by framework name. - Entrypoints map[string][]schema.GoEntrypoint + Entrypoints map[string][]model.GoEntrypoint // SyntheticEdges are additional call-graph edges contributed by this pass. - SyntheticEdges []schema.GoCallEdge + SyntheticEdges []model.GoCallEdge } // AnalysisPass is the interface every built-in and out-of-tree pass implements. @@ -34,5 +34,5 @@ type AnalysisPass interface { // this pass runs. The registry hard-errors on unsatisfied dependencies. Requires() []string // Run performs the analysis and returns its contributions. - Run(app *schema.GoApplication, ctx AnalysisContext) (AnalysisResult, error) + Run(app *model.GoApplication, ctx AnalysisContext) (AnalysisResult, error) } diff --git a/internal/analysis/registry.go b/internal/analysis/registry.go index 2503578..1a18d7f 100644 --- a/internal/analysis/registry.go +++ b/internal/analysis/registry.go @@ -4,7 +4,7 @@ package analysis import ( "fmt" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -63,7 +63,7 @@ func orderPasses(passes []AnalysisPass) ([]AnalysisPass, error) { // RunPipeline runs all registered passes over app in dependency order, // merging each result into the running application before the next pass. // Pass output is deliberately not cached — out-of-tree enrichment must not go stale. -func RunPipeline(app *schema.GoApplication, ctx AnalysisContext) error { +func RunPipeline(app *model.GoApplication, ctx AnalysisContext) error { ordered, err := orderPasses(registeredPasses) if err != nil { return err diff --git a/internal/analysis/registry_test.go b/internal/analysis/registry_test.go index 68bd55d..0f428ad 100644 --- a/internal/analysis/registry_test.go +++ b/internal/analysis/registry_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) // stubPass is a minimal AnalysisPass for testing orderPasses. @@ -19,10 +19,10 @@ type stubPass struct { requires []string } -func (s *stubPass) Name() string { return s.name } +func (s *stubPass) Name() string { return s.name } func (s *stubPass) Provides() []string { return s.provides } func (s *stubPass) Requires() []string { return s.requires } -func (s *stubPass) Run(_ *schema.GoApplication, _ AnalysisContext) (AnalysisResult, error) { +func (s *stubPass) Run(_ *model.GoApplication, _ AnalysisContext) (AnalysisResult, error) { return AnalysisResult{}, nil } @@ -117,9 +117,9 @@ func TestRunPipeline_EmptyRegistry(t *testing.T) { registeredPasses = nil defer func() { registeredPasses = old }() - app := &schema.GoApplication{ - Entrypoints: map[string][]schema.GoEntrypoint{}, - CallGraph: []schema.GoCallEdge{}, + app := &model.GoApplication{ + Entrypoints: map[string][]model.GoEntrypoint{}, + CallGraph: []model.GoCallEdge{}, } if err := RunPipeline(app, AnalysisContext{}); err != nil { t.Fatalf("RunPipeline with empty registry: %v", err) diff --git a/internal/core/analyzer.go b/internal/core/analyzer.go index c6c704a..1a95eff 100644 --- a/internal/core/analyzer.go +++ b/internal/core/analyzer.go @@ -19,7 +19,7 @@ import ( "encoding/json" "errors" "fmt" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "io" "io/fs" "math/rand/v2" @@ -31,13 +31,13 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/options" "github.com/codellm-devkit/codeanalyzer-go/internal/repository" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -49,17 +49,17 @@ type Analyzer struct { // of it, so no application's cache is recorded as a project artifact. cacheRoot string // l3 is the Phase 5 side table (nil below L3). It stays off - // schema.GoApplication: schema must not depend on dataflow, and the - // cached v1 model has no L3 facts. + // model.GoApplication: the model must not depend on dataflow, and the + // cached model has no L3 facts. l3 map[dataflow.L3Key]dataflow.Result // l4 is the Phase 6 result (nil below L4). Pass it to RenderJSON / - // WriteOutput / v2emit.Emit with L3(). + // WriteOutput / emit.Emit with L3(). l4 *sdg.Result } // L3 returns the dataflow side table of the last Analyze run: one result per // callable with a body, keyed by (declaring file, signature). Nil below -// level 3. Pass it to RenderJSON / WriteOutput / v2emit.Emit. +// level 3. Pass it to RenderJSON / WriteOutput / emit.Emit. func (a *Analyzer) L3() map[dataflow.L3Key]dataflow.Result { return a.l3 } // L4 returns the SDG result of the last Analyze run. Nil below level 4. @@ -75,16 +75,16 @@ func KLimit(opts options.AnalysisOptions) int { } // resolveIdentity preserves the default input basename for programmatic callers. -func resolveIdentity(opts options.AnalysisOptions) (v2.Identity, error) { +func resolveIdentity(opts options.AnalysisOptions) (schema.Identity, error) { name := opts.AppName if name == "" { root, err := filepath.Abs(opts.InputPath) if err != nil { - return v2.Identity{}, err + return schema.Identity{}, err } name = filepath.Base(filepath.Clean(root)) } - return v2.ResolveIdentity(name, opts.Namespace) + return schema.ResolveIdentity(name, opts.Namespace) } // New creates an Analyzer with a cache isolated by canonical application identity. @@ -100,7 +100,7 @@ func New(opts options.AnalysisOptions) *Analyzer { } // Analyze runs the full analysis pipeline and returns a GoApplication. -func (a *Analyzer) Analyze() (*schema.GoApplication, error) { +func (a *Analyzer) Analyze() (*model.GoApplication, error) { app, err := a.analyze() if err != nil { return nil, err @@ -137,7 +137,7 @@ func (a *Analyzer) Analyze() (*schema.GoApplication, error) { return app, nil } -func (a *Analyzer) analyze() (*schema.GoApplication, error) { +func (a *Analyzer) analyze() (*model.GoApplication, error) { if _, err := resolveIdentity(a.opts); err != nil { return nil, err } @@ -170,10 +170,10 @@ func (a *Analyzer) analyze() (*schema.GoApplication, error) { } utils.Info("symbol table: %d files", len(symbolTable)) - app := &schema.GoApplication{ + app := &model.GoApplication{ SymbolTable: symbolTable, - CallGraph: []schema.GoCallEdge{}, - Entrypoints: map[string][]schema.GoEntrypoint{}, + CallGraph: []model.GoCallEdge{}, + Entrypoints: map[string][]model.GoEntrypoint{}, } if a.opts.Level < options.LevelCallGraph { @@ -312,7 +312,7 @@ func (a *Analyzer) materialize() error { } // finalizeAndCache caches the application and returns it. -func (a *Analyzer) finalizeAndCache(app *schema.GoApplication) (*schema.GoApplication, error) { +func (a *Analyzer) finalizeAndCache(app *model.GoApplication) (*model.GoApplication, error) { if a.opts.CacheDir != "" { _ = a.saveCache(app) } @@ -320,9 +320,9 @@ func (a *Analyzer) finalizeAndCache(app *schema.GoApplication) (*schema.GoApplic } // saveCache persists the application to cache as analysis_cache.json, in the -// internal v1 shape. Nothing reads it back: it is a debugging aid, not an -// input, so a v1 shape change (e.g. closures gaining path) affects nothing. -func (a *Analyzer) saveCache(app *schema.GoApplication) error { +// internal model's shape. Nothing reads it back: it is a debugging aid, not an +// input, so a model shape change (e.g. closures gaining path) affects nothing. +func (a *Analyzer) saveCache(app *model.GoApplication) error { if err := utils.EnsureDir(a.opts.CacheDir); err != nil { return err } @@ -347,15 +347,15 @@ func checkFormat(opts options.AnalysisOptions) error { } } -// RenderJSON serializes the analysis to JSON as the canonical v2 containment -// tree via the v2emit emitter, as one []byte. It is the reference the +// RenderJSON serializes the analysis to JSON as the canonical containment +// tree via the emitter, as one []byte. It is the reference the // streaming StreamJSON / WriteOutput paths are byte-identical to; the CLI // streams instead, so the document never exists in memory at once. // // l3 is the Analyzer's L3() side table (nil below level 3) and l4 its L4() // result (nil below level 4). At level 3 the envelope carries k_limit = // KLimit(opts) whether or not l3 is set. -func RenderJSON(app *schema.GoApplication, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result, opts options.AnalysisOptions) ([]byte, error) { +func RenderJSON(app *model.GoApplication, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result, opts options.AnalysisOptions) ([]byte, error) { if err := checkFormat(opts); err != nil { return nil, err } @@ -363,13 +363,13 @@ func RenderJSON(app *schema.GoApplication, l3 map[dataflow.L3Key]dataflow.Result if err != nil { return nil, err } - payload := v2emit.Emit(app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, KLimit(opts), l3, l4) + payload := emit.Emit(app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, KLimit(opts), l3, l4) return json.Marshal(payload) } // StreamJSON writes the bytes RenderJSON returns to w, emitting and encoding -// one module at a time (v2emit.EmitTo) through a buffered writer. -func StreamJSON(w io.Writer, app *schema.GoApplication, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result, opts options.AnalysisOptions) error { +// one module at a time (emit.EmitTo) through a buffered writer. +func StreamJSON(w io.Writer, app *model.GoApplication, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result, opts options.AnalysisOptions) error { if err := checkFormat(opts); err != nil { return err } @@ -378,7 +378,7 @@ func StreamJSON(w io.Writer, app *schema.GoApplication, l3 map[dataflow.L3Key]da return err } bw := bufio.NewWriterSize(w, 1<<20) - if err := v2emit.EmitTo(bw, app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, KLimit(opts), l3, l4); err != nil { + if err := emit.EmitTo(bw, app, identity, opts.InputPath, int(opts.Level), opts.AnalyzerVersion, KLimit(opts), l3, l4); err != nil { return err } return bw.Flush() @@ -387,7 +387,7 @@ func StreamJSON(w io.Writer, app *schema.GoApplication, l3 map[dataflow.L3Key]da // WriteOutput streams the analysis to outputDir/analysis.json, or to stdout // when outputDir is empty. The file is written beside its destination and // renamed into place, so a failed run never leaves a truncated analysis.json. -func WriteOutput(app *schema.GoApplication, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result, opts options.AnalysisOptions) error { +func WriteOutput(app *model.GoApplication, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result, opts options.AnalysisOptions) error { if _, err := resolveIdentity(opts); err != nil { return err } diff --git a/internal/core/analyzer_test.go b/internal/core/analyzer_test.go index 8df7513..bb240a8 100644 --- a/internal/core/analyzer_test.go +++ b/internal/core/analyzer_test.go @@ -10,9 +10,9 @@ import ( "time" "github.com/codellm-devkit/codeanalyzer-go/internal/core" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/options" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" ) // greeterDir returns the absolute path to testdata/greeter. @@ -76,7 +76,7 @@ func TestSymbolTable_StructFields(t *testing.T) { func TestSymbolTable_CallSitesRecorded(t *testing.T) { f := sharedGreeterL1.SymbolTable["main.go"] - var mainFn *schema.GoCallable + var mainFn *model.GoCallable for _, c := range f.Functions { c := c if c.Name == "main" { @@ -148,13 +148,13 @@ func TestWriteOutput_ValidJSON(t *testing.T) { if err != nil { t.Fatalf("reading analysis.json: %v", err) } - // Output is the canonical v2 containment tree; round-trip into it. - var round v2.Analysis + // Output is the canonical containment tree; round-trip into it. + var round schema.Analysis if err := json.Unmarshal(data, &round); err != nil { t.Fatalf("JSON round-trip failed: %v", err) } - if round.SchemaVersion != v2.SchemaVersion { - t.Errorf("schema_version = %q, want %q", round.SchemaVersion, v2.SchemaVersion) + if round.SchemaVersion != schema.SchemaVersion { + t.Errorf("schema_version = %q, want %q", round.SchemaVersion, schema.SchemaVersion) } if len(round.Application.SymbolTable) == 0 { t.Error("round-tripped symbol table is empty") @@ -310,7 +310,7 @@ func TestCaching_CacheContentsRoundTrip(t *testing.T) { if err != nil { t.Fatalf("reading analysis_cache.json: %v", err) } - var cached schema.GoApplication + var cached model.GoApplication if err := json.Unmarshal(data, &cached); err != nil { t.Fatalf("cache JSON round-trip failed: %v", err) } @@ -361,10 +361,10 @@ func TestCaching_EagerForcesRebuild(t *testing.T) { // allSignatures collects every callable signature, closures included (a closure // is a call-graph edge source). -func allSignatures(app *schema.GoApplication) map[string]bool { +func allSignatures(app *model.GoApplication) map[string]bool { sigs := map[string]bool{} - var add func(sig string, c schema.GoCallable) - add = func(sig string, c schema.GoCallable) { + var add func(sig string, c model.GoCallable) + add = func(sig string, c model.GoCallable) { sigs[sig] = true for _, ic := range c.InnerCallables { add(ic.Signature, ic) @@ -441,7 +441,7 @@ func TestWriteOutputInvalidIdentityPreservesFilesystem(t *testing.T) { } ns := "" opts := options.AnalysisOptions{InputPath: greeterDir(t), AppName: "greeter", Namespace: &ns, OutputDir: dst} - if err := core.WriteOutput(&schema.GoApplication{}, nil, nil, opts); err == nil { + if err := core.WriteOutput(&model.GoApplication{}, nil, nil, opts); err == nil { t.Fatal("accepted invalid identity") } if !existing { diff --git a/internal/core/crossfile_method_test.go b/internal/core/crossfile_method_test.go index aa3060a..9294581 100644 --- a/internal/core/crossfile_method_test.go +++ b/internal/core/crossfile_method_test.go @@ -9,8 +9,8 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/core" "github.com/codellm-devkit/codeanalyzer-go/internal/options" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // crossFileProject: T is declared in a.go, its method M in b.go, a package-level @@ -33,7 +33,7 @@ func crossFileProject(t *testing.T) string { } // analyzeL2 runs the real pipeline at -a 2 and returns the analysis.json tree as -// generic maps (the v2 Go structs are not needed for these checks). +// generic maps (the schema's Go structs are not needed for these checks). func analyzeL2(t *testing.T, dir string) map[string]any { t.Helper() opts := options.AnalysisOptions{ @@ -44,11 +44,11 @@ func analyzeL2(t *testing.T, dir string) map[string]any { if err != nil { t.Fatal(err) } - identity, err := v2.ResolveIdentity("xf", nil) + identity, err := schema.ResolveIdentity("xf", nil) if err != nil { t.Fatal(err) } - payload := v2emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil) + payload := emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil) raw, err := json.Marshal(payload) if err != nil { t.Fatal(err) diff --git a/internal/core/init_collision_test.go b/internal/core/init_collision_test.go index 7cdaf8d..74fba30 100644 --- a/internal/core/init_collision_test.go +++ b/internal/core/init_collision_test.go @@ -9,8 +9,8 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/core" "github.com/codellm-devkit/codeanalyzer-go/internal/options" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // initProject declares two func init() in one file (Go allows any number per @@ -46,11 +46,11 @@ func emitCallGraphJSON(t *testing.T, dir string) []byte { if err != nil { t.Fatal(err) } - identity, err := v2.ResolveIdentity("repoapp", nil) + identity, err := schema.ResolveIdentity("repoapp", nil) if err != nil { t.Fatal(err) } - out, err := json.Marshal(v2emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil)) + out, err := json.Marshal(emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil)) if err != nil { t.Fatal(err) } diff --git a/internal/core/init_l3_test.go b/internal/core/init_l3_test.go index 139ae46..7b524ec 100644 --- a/internal/core/init_l3_test.go +++ b/internal/core/init_l3_test.go @@ -9,8 +9,8 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/core" "github.com/codellm-devkit/codeanalyzer-go/internal/options" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // repeatedFuncProject declares two func init() and two func _() in one file, @@ -50,11 +50,11 @@ func TestRepeatedFunc_ClosuresAndL3AreTheirOwn(t *testing.T) { if err != nil { t.Fatal(err) } - identity, err := v2.ResolveIdentity("rep", nil) + identity, err := schema.ResolveIdentity("rep", nil) if err != nil { t.Fatal(err) } - out, err := json.Marshal(v2emit.Emit(app, identity, dir, int(opts.Level), "test", core.KLimit(opts), an.L3(), an.L4())) + out, err := json.Marshal(emit.Emit(app, identity, dir, int(opts.Level), "test", core.KLimit(opts), an.L3(), an.L4())) if err != nil { t.Fatal(err) } diff --git a/internal/core/multipackage_test.go b/internal/core/multipackage_test.go index b1070bc..430d28b 100644 --- a/internal/core/multipackage_test.go +++ b/internal/core/multipackage_test.go @@ -8,11 +8,11 @@ import ( "strings" "testing" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) // findCallableByName searches all functions and methods in a GoFile by short name. -func findCallableByName(f schema.GoFile, name string) *schema.GoCallable { +func findCallableByName(f model.GoFile, name string) *model.GoCallable { for _, c := range f.Functions { if c.Name == name { c := c @@ -292,7 +292,7 @@ func TestRealistic_LocalVariablesHaveType(t *testing.T) { // ── Helpers ─────────────────────────────────────────────────────────────────── -func edgeTargets(app *schema.GoApplication) []string { +func edgeTargets(app *model.GoApplication) []string { out := make([]string, 0, len(app.CallGraph)) for _, e := range app.CallGraph { out = append(out, e.Target) diff --git a/internal/core/repository_test.go b/internal/core/repository_test.go index 1f72580..178ba89 100644 --- a/internal/core/repository_test.go +++ b/internal/core/repository_test.go @@ -8,8 +8,8 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/core" "github.com/codellm-devkit/codeanalyzer-go/internal/options" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // repoProject is a Go module with no requires (so no network materialization), @@ -31,7 +31,7 @@ func repoProject(t *testing.T) string { return dir } -// emitJSON runs Analyze at level 1 and returns the v2 analysis.json bytes. +// emitJSON runs Analyze at level 1 and returns the analysis.json bytes. func emitJSON(t *testing.T, dir string, artifactText bool) []byte { t.Helper() opts := options.AnalysisOptions{ @@ -42,11 +42,11 @@ func emitJSON(t *testing.T, dir string, artifactText bool) []byte { if err != nil { t.Fatal(err) } - identity, err := v2.ResolveIdentity("repoapp", nil) + identity, err := schema.ResolveIdentity("repoapp", nil) if err != nil { t.Fatal(err) } - payload := v2emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil) + payload := emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil) out, err := json.Marshal(payload) if err != nil { t.Fatal(err) @@ -58,7 +58,7 @@ func TestAnalyze_ArtifactsDefaultMetadataOnly(t *testing.T) { dir := repoProject(t) var doc struct { Application struct { - Artifacts map[string]v2.Artifact `json:"artifacts"` + Artifacts map[string]schema.Artifact `json:"artifacts"` } `json:"application"` } if err := json.Unmarshal(emitJSON(t, dir, false), &doc); err != nil { @@ -83,7 +83,7 @@ func TestAnalyze_ArtifactTextCapturesSource(t *testing.T) { dir := repoProject(t) var doc struct { Application struct { - Artifacts map[string]v2.Artifact `json:"artifacts"` + Artifacts map[string]schema.Artifact `json:"artifacts"` } `json:"application"` } if err := json.Unmarshal(emitJSON(t, dir, true), &doc); err != nil { diff --git a/internal/core/testsetup_test.go b/internal/core/testsetup_test.go index f68d89b..13d8151 100644 --- a/internal/core/testsetup_test.go +++ b/internal/core/testsetup_test.go @@ -8,19 +8,19 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/core" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/options" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // Shared analysis results, populated once in TestMain and reused across all tests. // Caching tests are excluded: they must exercise the caching machinery themselves. var ( - sharedGreeterL1 *schema.GoApplication // greeter, symbol-table only - sharedGreeterL2 *schema.GoApplication // greeter, full call-graph - sharedMultipackageL1 *schema.GoApplication // multipackage, symbol-table only - sharedMultipackageL2 *schema.GoApplication // multipackage, full call-graph - sharedGenericsL1 *schema.GoApplication // generics, symbol-table only - sharedChiL2 *schema.GoApplication // chi (external dep), full call-graph + sharedGreeterL1 *model.GoApplication // greeter, symbol-table only + sharedGreeterL2 *model.GoApplication // greeter, full call-graph + sharedMultipackageL1 *model.GoApplication // multipackage, symbol-table only + sharedMultipackageL2 *model.GoApplication // multipackage, full call-graph + sharedGenericsL1 *model.GoApplication // generics, symbol-table only + sharedChiL2 *model.GoApplication // chi (external dep), full call-graph ) func TestMain(m *testing.M) { @@ -42,7 +42,7 @@ func runTestMain(m *testing.M) int { name string path string level options.AnalysisLevel - dst **schema.GoApplication + dst **model.GoApplication } for _, f := range []fixture{ diff --git a/internal/dataflow/accesspath_test.go b/internal/dataflow/accesspath_test.go index 8efee74..1314cca 100644 --- a/internal/dataflow/accesspath_test.go +++ b/internal/dataflow/accesspath_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // ---- a hermetic two-package source for access-path and def/use tests ---- @@ -274,7 +274,7 @@ func (fx *duFixture) keyAt(t *testing.T, sub string, delta int) string { t.Fatalf("no %q in duSrc", sub) } p := fx.fset.Position(fx.fset.File(fx.file.Pos()).Pos(off + delta)) - return v2.LocalID(p.Line, p.Column) + return schema.LocalID(p.Line, p.Column) } func TestPathOf_KLimit(t *testing.T) { diff --git a/internal/dataflow/bodynodes.go b/internal/dataflow/bodynodes.go index 89f36d2..a35c566 100644 --- a/internal/dataflow/bodynodes.go +++ b/internal/dataflow/bodynodes.go @@ -7,7 +7,7 @@ import ( "strconv" "github.com/codellm-devkit/codeanalyzer-go/internal/astwalk" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // BuildNodes maps a callable body onto its L3 body nodes (spec §4.2) and @@ -35,7 +35,7 @@ import ( // statement gets one only as a label target. Function literal bodies are // skipped: closures are their own callables. // -// calls holds the L1 call nodes: each call-node key (v2.CallBodyKeys over the +// calls holds the L1 call nodes: each call-node key (schema.CallBodyKeys over the // callable's call sites) with the raw CallExpr.Lparen of its site. They are // paired with the body's call expressions by Lparen — never by index or by // line:col — so their order is irrelevant. A call no entry names gets no call @@ -43,7 +43,7 @@ import ( // with an unpaired call rather than build it. // // Keys: call nodes take their L1 key. Statement nodes take -// v2.LocalID(line, col) of their anchor; a statement starting with a call +// schema.LocalID(line, col) of their anchor; a statement starting with a call // (`f().x = v`) would collide with the L1 call key, so it takes the next free // "/n" suffix instead and the L1 key is never moved. // @@ -290,7 +290,7 @@ func (b *builder) folded(k string, s ast.Stmt) { // earlier node) already holds it. func (b *builder) add(kind NodeKind, n ast.Node, pos, end token.Pos) string { p := b.fset.PositionFor(pos, false) - key := NextFreeKey(v2.LocalID(p.Line, p.Column), b.taken) + key := NextFreeKey(schema.LocalID(p.Line, p.Column), b.taken) b.nodes = append(b.nodes, Node{Key: key, Kind: kind, Pos: pos, End: end, Stmt: n}) b.keyOf[n] = key return key diff --git a/internal/dataflow/bodynodes_test.go b/internal/dataflow/bodynodes_test.go index fe6cf44..d2fd5a4 100644 --- a/internal/dataflow/bodynodes_test.go +++ b/internal/dataflow/bodynodes_test.go @@ -12,8 +12,8 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) @@ -23,7 +23,7 @@ type flowFixture struct { fset *token.FileSet info *types.Info decls map[string]*ast.FuncDecl - sites map[string][]schema.GoCallsite + sites map[string][]model.GoCallsite } var ( @@ -43,7 +43,7 @@ func loadFlow(t *testing.T) *flowFixture { fixtureErr = err return } - fx := &flowFixture{fset: b.Fset(), decls: map[string]*ast.FuncDecl{}, sites: map[string][]schema.GoCallsite{}} + fx := &flowFixture{fset: b.Fset(), decls: map[string]*ast.FuncDecl{}, sites: map[string][]model.GoCallsite{}} for _, fn := range st[filepath.Join("flow", "flow.go")].Functions { fx.sites[fn.Name] = fn.CallSites } @@ -65,7 +65,7 @@ func loadFlow(t *testing.T) *flowFixture { } // callKeys builds the L1 call-node keys exactly as the driver does: keys from -// v2.CallBodyKeys over the call sites' [line, col], in recording order, each +// schema.CallBodyKeys over the call sites' [line, col], in recording order, each // with its site's Lparen. BuildNodes pairs them with the AST calls by Lparen. func (fx *flowFixture) callKeys(t *testing.T, fn string) []dataflow.UnitCall { t.Helper() @@ -74,7 +74,7 @@ func (fx *flowFixture) callKeys(t *testing.T, fn string) []dataflow.UnitCall { for i, cs := range sites { pos[i] = [2]int{cs.StartLine, cs.StartColumn} } - keys := v2.CallBodyKeys(pos) + keys := schema.CallBodyKeys(pos) out := make([]dataflow.UnitCall, len(sites)) for i, cs := range sites { out[i] = dataflow.UnitCall{Key: keys[i], Lparen: cs.Lparen} diff --git a/internal/dataflow/cfg_test.go b/internal/dataflow/cfg_test.go index f575e2c..6265cb1 100644 --- a/internal/dataflow/cfg_test.go +++ b/internal/dataflow/cfg_test.go @@ -18,7 +18,7 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/astwalk" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // Statement keys in testdata/dataflow/flow/flow.go (line:col of each node's @@ -771,7 +771,7 @@ func gateOne(t *testing.T, name string, nodes []dataflow.Node, es []dataflow.Cfg } // gateCallKeys lists the L1 call node of every call in body in the L1 -// recording order (astwalk.Calls), each keyed as v2.CallBodyKeys assigns it +// recording order (astwalk.Calls), each keyed as schema.CallBodyKeys assigns it // from the call's real (not //line-adjusted) position and carrying its // Lparen. func gateCallKeys(fset *token.FileSet, body *ast.BlockStmt) []dataflow.UnitCall { @@ -781,7 +781,7 @@ func gateCallKeys(fset *token.FileSet, body *ast.BlockStmt) []dataflow.UnitCall p := fset.PositionFor(c.Expr.Pos(), false) pos[i] = [2]int{p.Line, p.Column} } - keys := v2.CallBodyKeys(pos) + keys := schema.CallBodyKeys(pos) out := make([]dataflow.UnitCall, len(calls)) for i, c := range calls { out[i] = dataflow.UnitCall{Key: keys[i], Lparen: c.Expr.Lparen} diff --git a/internal/dataflow/ir.go b/internal/dataflow/ir.go index b0895ff..a549021 100644 --- a/internal/dataflow/ir.go +++ b/internal/dataflow/ir.go @@ -3,8 +3,8 @@ // emitter writes ("l:c", "l:c/2", "@entry", "@exit"), so the L3 overlay joins // the L1 call nodes on one string and never recomposes ids. // -// The package must not import the v1 schema (internal/schema) or the v2 emitter -// (internal/syntactic_analysis/v2emit): the emitter imports this package. +// The package must not import the model (internal/model) or the emitter +// (internal/syntactic_analysis/emit): the emitter imports this package. package dataflow import ( diff --git a/internal/dataflow/run_test.go b/internal/dataflow/run_test.go index 6576041..0f5a2c5 100644 --- a/internal/dataflow/run_test.go +++ b/internal/dataflow/run_test.go @@ -3,7 +3,7 @@ package dataflow_test import ( "bytes" "encoding/json" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "go/ast" "go/importer" "go/parser" @@ -18,10 +18,10 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -40,7 +40,7 @@ func TestRun_JobsDeterminism(t *testing.T) { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} units := b.L3Units(st) if len(units) < 100 { t.Fatalf("chi yields only %d L3 units", len(units)) @@ -51,8 +51,8 @@ func TestRun_JobsDeterminism(t *testing.T) { if len(l3) != len(units) { t.Errorf("-j %d: %d results for %d units", jobs, len(l3), len(units)) } - data, err := json.Marshal(v2emit.Emit(app, func() v2.Identity { - i, e := v2.ResolveIdentity("chi", nil) + data, err := json.Marshal(emit.Emit(app, func() schema.Identity { + i, e := schema.ResolveIdentity("chi", nil) if e != nil { panic(e) } @@ -413,11 +413,11 @@ func TestResult_ReleaseDropsASTs(t *testing.T) { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} out := dataflow.Run(b.Fset(), b.L3Units(st), 3, 4) emit := func() []byte { - data, err := json.Marshal(v2emit.Emit(app, func() v2.Identity { - i, e := v2.ResolveIdentity("dataflow", nil) + data, err := json.Marshal(emit.Emit(app, func() schema.Identity { + i, e := schema.ResolveIdentity("dataflow", nil) if e != nil { panic(e) } diff --git a/internal/frameworks/base.go b/internal/frameworks/base.go index 9d17251..1172de7 100644 --- a/internal/frameworks/base.go +++ b/internal/frameworks/base.go @@ -8,7 +8,7 @@ package frameworks import ( "github.com/codellm-devkit/codeanalyzer-go/internal/analysis" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) // BaseEntrypointFinder is the abstract base for framework-specific entrypoint finders. @@ -33,6 +33,6 @@ func (b BaseEntrypointFinder) Provides() []string { return []string{b.framework func (b BaseEntrypointFinder) Requires() []string { return nil } // Run implements analysis.AnalysisPass — delegates to FindEntrypoints. -func (b BaseEntrypointFinder) Run(app *schema.GoApplication, ctx analysis.AnalysisContext) (analysis.AnalysisResult, error) { +func (b BaseEntrypointFinder) Run(app *model.GoApplication, ctx analysis.AnalysisContext) (analysis.AnalysisResult, error) { return analysis.AnalysisResult{}, nil } diff --git a/internal/metamorphic/compare.go b/internal/metamorphic/compare.go index d4e930e..c11db02 100644 --- a/internal/metamorphic/compare.go +++ b/internal/metamorphic/compare.go @@ -36,7 +36,7 @@ import ( "strings" "sync" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // View is the normalized analysis. @@ -147,7 +147,7 @@ func Collect(r io.Reader) (*View, error) { if err != nil { return nil, err } - var m v2.Module + var m schema.Module if err := dec.Decode(&m); err != nil { return nil, err } @@ -157,7 +157,7 @@ func Collect(r io.Reader) (*View, error) { return nil, err } case "call_graph": - var es []v2.Edge + var es []schema.Edge if err := dec.Decode(&es); err != nil { return nil, err } @@ -165,7 +165,7 @@ func Collect(r io.Reader) (*View, error) { v.App["cg|"+resolveID(ids, e.Src)+"|"+resolveID(ids, e.Dst)+"|"+strings.Join(e.Prov, ",")] = true } case "external_symbols": - var ext map[string]v2.ExternalSymbol + var ext map[string]schema.ExternalSymbol if err := dec.Decode(&ext); err != nil { return nil, err } @@ -186,7 +186,7 @@ func Collect(r io.Reader) (*View, error) { return nil, err } for dec.More() { - var e v2.ParamEdge + var e schema.ParamEdge if err := dec.Decode(&e); err != nil { return nil, err } @@ -223,7 +223,7 @@ func resolveID(ids map[string]string, id string) string { return "?" + id } -// globalNode is the Node of a global body-node id (v2.GlobalOrdinal). +// globalNode is the Node of a global body-node id (schema.GlobalOrdinal). func globalNode(ids map[string]string, gid string) string { i := strings.LastIndexByte(gid, '@') if i < 0 { @@ -236,9 +236,9 @@ func globalNode(ids map[string]string, gid string) string { return Node(resolveID(ids, owner), local) } -func (v *View) addModule(rel string, m *v2.Module, ids map[string]string, callee map[*CV]map[string]string) { - var walk func(c *v2.Callable, file string, topInit bool) - walk = func(c *v2.Callable, file string, topInit bool) { +func (v *View) addModule(rel string, m *schema.Module, ids map[string]string, callee map[*CV]map[string]string) { + var walk func(c *schema.Callable, file string, topInit bool) + walk = func(c *schema.Callable, file string, topInit bool) { if c.SourceFile != "" { file = c.SourceFile } @@ -435,7 +435,7 @@ func (m *mapper) key(file, k string) (string, string, bool) { if !ok { return k, file, false } - return v2.LocalID(p.Line, p.Col) + g[3], p.File, true + return schema.LocalID(p.Line, p.Col) + g[3], p.File, true } func (m *mapper) must(ident, file, k string) string { @@ -682,7 +682,7 @@ func (r Ref) resolve(m *mapper, file string, marks map[string]Pos) (string, erro if !ok { return "", fmt.Errorf("no mark %s", r.Mark) } - return v2.LocalID(p.Line, p.Col), nil + return schema.LocalID(p.Line, p.Col), nil } k, _, ok := m.key(file, r.Pre) if !ok { diff --git a/internal/metamorphic/run.go b/internal/metamorphic/run.go index cb4208b..eecfae0 100644 --- a/internal/metamorphic/run.go +++ b/internal/metamorphic/run.go @@ -8,18 +8,18 @@ package metamorphic import ( "fmt" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "io" "path/filepath" "sort" "github.com/codellm-devkit/codeanalyzer-go/internal/analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // AppName is the --app-name every run uses, so both sides of a relation @@ -36,7 +36,7 @@ type Run struct { // Analyze runs the analyzer pipeline over dir at level (3 or 4) the way // core.Analyzer.Analyze does — symbol table, call graph, pass pipeline, // dataflow, and at level 4 sdg.Run with its call-graph additions — minus -// `go mod download` (the inputs are already materialized), and emits the v2 +// `go mod download` (the inputs are already materialized), and emits the // payload. targets is --target-files (absolute paths); nil is a full run. // Test files are skipped (the CLI default). func Analyze(dir string, level int, targets []string) (*Run, error) { @@ -53,7 +53,7 @@ func Analyze(dir string, level int, targets []string) (*Run, error) { } sort.Strings(errs) cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) - app := &schema.GoApplication{SymbolTable: st, CallGraph: cg.Build(st), Externals: cg.Externals(), Entrypoints: map[string][]schema.GoEntrypoint{}} + app := &model.GoApplication{SymbolTable: st, CallGraph: cg.Build(st), Externals: cg.Externals(), Entrypoints: map[string][]model.GoEntrypoint{}} app.Externals = cg.Externals() if err := analysis.RunPipeline(app, analysis.AnalysisContext{ProjectDir: dir}); err != nil { return nil, err @@ -79,7 +79,7 @@ func Analyze(dir string, level int, targets []string) (*Run, error) { // so a large app's tree never exists in memory at once. pr, pw := io.Pipe() go func() { - pw.CloseWithError(v2emit.EmitTo(pw, app, func() v2.Identity { i, _ := v2.ResolveIdentity(AppName, nil); return i }(), dir, level, "metamorphic", k, res, l4)) + pw.CloseWithError(emit.EmitTo(pw, app, func() schema.Identity { i, _ := schema.ResolveIdentity(AppName, nil); return i }(), dir, level, "metamorphic", k, res, l4)) }() v, err := Collect(pr) pr.CloseWithError(err) diff --git a/internal/metamorphic/transform.go b/internal/metamorphic/transform.go index 30ab5be..c9a4ccc 100644 --- a/internal/metamorphic/transform.go +++ b/internal/metamorphic/transform.go @@ -31,7 +31,7 @@ import ( "golang.org/x/tools/go/packages" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -46,7 +46,7 @@ type Pos struct { } // Key is p's body key, "line:col". -func (p Pos) Key() string { return v2.LocalID(p.Line, p.Col) } +func (p Pos) Key() string { return schema.LocalID(p.Line, p.Col) } // lineTable holds the offset of each line start of a file. type lineTable []int diff --git a/internal/model/model.go b/internal/model/model.go new file mode 100644 index 0000000..4f84c33 --- /dev/null +++ b/internal/model/model.go @@ -0,0 +1,281 @@ +// Package model is the analyzer's internal fact model. The parser, the +// resolver and the call-graph builder fill it, and the emitter +// (internal/syntactic_analysis/emit) converts it to the canonical schema +// (internal/schema). It is serialized only to the debugging file +// analysis_cache.json, which nothing reads back. +// +// The root object is GoApplication{symbol_table, call_graph}. +package model + +import "go/token" + +// ─── Leaf models ───────────────────────────────────────────────────────────── + +// GoImport represents a single import declaration in a Go source file. +type GoImport struct { + Module string `json:"module"` + Alias string `json:"alias,omitempty"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` +} + +// GoComment represents a comment (line, block, or doc comment). +type GoComment struct { + Content string `json:"content"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + StartColumn int `json:"start_column"` + EndColumn int `json:"end_column"` + IsDocComment bool `json:"is_doc_comment"` +} + +// GoParameter represents a single parameter of a callable. +type GoParameter struct { + Name string `json:"name"` + Type string `json:"type"` + IsVariadic bool `json:"is_variadic"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` +} + +// GoVariableDeclaration represents a variable declaration (var/short-assign). +type GoVariableDeclaration struct { + Name string `json:"name"` + Type string `json:"type,omitempty"` + Initializer string `json:"initializer,omitempty"` + Scope string `json:"scope"` // "package" | "function" + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + StartColumn int `json:"start_column"` + EndColumn int `json:"end_column"` +} + +// GoField represents a struct field, including its struct tags. +type GoField struct { + Name string `json:"name"` + Type string `json:"type"` + Comments []GoComment `json:"comments"` + Tags map[string]string `json:"tags"` // parsed struct tags, e.g. {"json": "name,omitempty"} + IsExported bool `json:"is_exported"` + IsEmbedded bool `json:"is_embedded"` // anonymous/embedded field + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` +} + +// GoSymbol represents a symbol accessed inside a callable. +type GoSymbol struct { + Name string `json:"name"` + Scope string `json:"scope"` // "local" | "package" | "external" + Kind string `json:"kind"` // "variable" | "function" | "type" | "constant" + Type string `json:"type,omitempty"` + QualifiedName string `json:"qualified_name,omitempty"` + IsBuiltin bool `json:"is_builtin"` + Lineno int `json:"lineno"` + ColOffset int `json:"col_offset"` +} + +// ─── Call site ──────────────────────────────────────────────────────────────── + +// GoCallsite represents a single call expression inside a callable. +// callee_signature is null when first recorded; the resolver backfills it +// during call-graph construction (never during symbol-table build). +type GoCallsite struct { + MethodName string `json:"method_name"` + ReceiverExpr string `json:"receiver_expr,omitempty"` + ReceiverType string `json:"receiver_type,omitempty"` + ArgumentTypes []string `json:"argument_types"` + ReturnType string `json:"return_type,omitempty"` + CalleeSignature *string `json:"callee_signature"` // null until resolved + // CalleeImportPath is the callee's package import path, set only when the + // resolved callee is an external (library) function; see GoApplication.Externals. + CalleeImportPath string `json:"callee_import_path,omitempty"` + IsConstructorCall bool `json:"is_constructor_call"` + IsGoroutine bool `json:"is_goroutine"` // true when preceded by `go` keyword + IsDeferred bool `json:"is_deferred,omitempty"` // true when preceded by `defer` keyword + StartLine int `json:"start_line"` + StartColumn int `json:"start_column"` + EndLine int `json:"end_line"` + EndColumn int `json:"end_column"` + // Lparen is the call's raw CallExpr.Lparen in the builder's FileSet: the + // in-memory join key from an L1 site to its *ast.CallExpr (L3 body nodes, + // and go/ssa CallCommon.Pos() at L4). Never serialized; meaningless once + // the FileSet is gone. + Lparen token.Pos `json:"-"` +} + +// ─── Callable ───────────────────────────────────────────────────────────────── + +// GoCallable represents a function, method, or function literal in Go. +// receiver_type / receiver_name are non-empty for methods; empty for functions. +type GoCallable struct { + Name string `json:"name"` + // Path is the declaring file (a symbol_table key). A closure carries its + // enclosing callable's declaring file, so the model's inner_callables have a path. + Path string `json:"path"` + Signature string `json:"signature"` // signatureOf() output — edge id + Comments []GoComment `json:"comments"` + Parameters []GoParameter `json:"parameters"` + ReturnType string `json:"return_type"` // joined, e.g. "(int, error)" + ReturnTypes []string `json:"return_types"` // Go extension: individual return types + Code string `json:"code,omitempty"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + CodeStartLine int `json:"code_start_line"` + AccessedSymbols []GoSymbol `json:"accessed_symbols"` + CallSites []GoCallsite `json:"call_sites"` + InnerCallables map[string]GoCallable `json:"inner_callables"` + LocalVariables []GoVariableDeclaration `json:"local_variables"` + CyclomaticComplexity int `json:"cyclomatic_complexity"` + IsEntrypoint bool `json:"is_entrypoint"` + EntrypointFramework string `json:"entrypoint_framework,omitempty"` + ReceiverType string `json:"receiver_type,omitempty"` // e.g. "*MyStruct" + ReceiverName string `json:"receiver_name,omitempty"` // e.g. "r" + IsExported bool `json:"is_exported"` +} + +// ─── Type (struct or interface) ─────────────────────────────────────────────── + +// GoType represents a named Go type — either a struct (is_interface=false) or +// an interface (is_interface=true). This unified model mirrors Go's native type +// system where both are types.Named with different Underlying() values. +// +// base_types carries: embedded struct types (for structs) and the method-set +// signatures of satisfied interfaces (for both) — the Go analog of base_classes. +type GoType struct { + Name string `json:"name"` + Signature string `json:"signature"` // signatureOf() output + Comments []GoComment `json:"comments"` + Code string `json:"code,omitempty"` + IsInterface bool `json:"is_interface"` + TypeKind string `json:"type_kind,omitempty"` // struct | interface | alias | defined + IsExported bool `json:"is_exported"` + Fields []GoField `json:"fields"` // empty for interfaces + Methods map[string]GoCallable `json:"methods"` // sig → callable + BaseTypes []string `json:"base_types"` // embedded types + satisfied interface sigs + InnerTypes map[string]GoType `json:"inner_types"` // Go doesn't nest, but preserves spine + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` +} + +// ─── File (Module analog) ───────────────────────────────────────────────────── + +// GoFile is the Module analog for Go: one compilation unit (source file). +// symbol_table is keyed by file path relative to the project root. +type GoFile struct { + FilePath string `json:"file_path"` + PackageName string `json:"module_name"` // JSON key = module_name for spine compat + Imports []GoImport `json:"imports"` + Comments []GoComment `json:"comments"` + Types map[string]GoType `json:"classes"` // JSON key = classes for spine compat + Functions map[string]GoCallable `json:"functions"` + Variables []GoVariableDeclaration `json:"variables"` + // Caching metadata + ContentHash *string `json:"content_hash"` + LastModified *float64 `json:"last_modified"` + FileSize *int64 `json:"file_size"` +} + +// ─── Call graph edge ────────────────────────────────────────────────────────── + +// GoCallEdge is an identity-only call-graph edge. source and target are +// GoCallable.signature strings that must exist in the symbol table. +type GoCallEdge struct { + Source string `json:"source"` + Target string `json:"target"` + Type string `json:"type"` // always "CALL_DEP" + Weight int `json:"weight"` // accumulated when merging backends + Provenance []string `json:"provenance"` // e.g. ["go/types"] + Tags map[string]string `json:"tags"` + + // SourcePath is the relative file in which the source callable is declared. + // A signature is not globally unique for package-level init functions: Go + // permits many `func init()` per package (one per file), all sharing the + // signature ".init". Those are distinct callables with distinct + // can:// ids (the id embeds the declaring file via its module), so the output + // emitter needs this to resolve the edge's source to the SPECIFIC init that + // owns the call site rather than to an arbitrary one. Empty for callables + // whose signature is already unique (the common case). Internal-only; not + // part of the output schema. + SourcePath string `json:"-"` + + // TargetPath is the relative file declaring the target callable, set only + // when the signature alone may not name it: a VTA target can be a closure + // of a package-level init (".init.closure_1" repeats once per file + // with an init). Empty for L2 edges (a static call never targets an init + // or a closure) and for an external target. Internal-only, like SourcePath. + TargetPath string `json:"-"` +} + +// ─── Root object ────────────────────────────────────────────────────────────── + +// GoApplication is the root of analysis.json. The SDK facade deserializes this. +type GoApplication struct { + SymbolTable map[string]GoFile `json:"symbol_table"` // file_path → GoFile + CallGraph []GoCallEdge `json:"call_graph"` // identity-only edges + Entrypoints map[string][]GoEntrypoint `json:"entrypoints"` // optional, default {} + // Externals holds the library (out-of-project) functions the resolver saw + // called, keyed by the full callee signature (".[Type.]Name"). + Externals map[string]GoExternalCallee `json:"externals,omitempty"` + // Repository holds the repository-artifact facts (non-.go project files and + // go.mod/go.sum dependencies), set by the analyzer after symbol-table + // construction. Never cached or serialized in the model: it is recomputed + // on every run, since it reads files outside the analyzed Go source. + Repository *RepositoryFacts `json:"-"` +} + +// RepositoryFacts is the repository-artifact layer (spec artifacts): every +// non-.go project file as an artifact, and the go.mod requires as dependencies. +type RepositoryFacts struct { + // Artifacts is keyed by repo-relative POSIX path. + Artifacts map[string]GoArtifact + // Dependencies is sorted by module path. + Dependencies []GoDependency +} + +// GoArtifact is one non-.go project file. +type GoArtifact struct { + Path string + Format string + Roles []string + SizeBytes int64 + SHA256 string + Source string // whole file text, only when --artifact-text is on + Extraction string // none | full +} + +// GoDependency is one go.mod require, evidence-tagged by go.sum. +type GoDependency struct { + Name string + Ecosystem string + Spec string + Kind string + Direct bool + LockedVersion string // go.sum version of Spec, when both its h1 and /go.mod lines exist + LockedIn string // path of the go.sum artifact that gave LockedVersion + ReplacedBy string // go.mod replace target: "@", or a local directory + DeclaredIn string // path of the go.mod artifact + ProvidesImports []string // project import paths that resolve to this module + Prov []string // declared | lockfile +} + +// GoExternalCallee describes a library function or method called from the +// project. Params exclude the receiver; unnamed parameters are named "_". +type GoExternalCallee struct { + ImportPath string `json:"import_path"` + Sig string `json:"signature"` // callee signature without the "." prefix + Name string `json:"name"` + Params []GoParameter `json:"parameters"` + ReturnType string `json:"return_type,omitempty"` + // Receiver is the method receiver (nil for a plain function): named by the + // receiver variable, or "_recv" when unnamed or "_"; typed by the origin's + // receiver type string. + Receiver *GoParameter `json:"receiver,omitempty"` +} + +// GoEntrypoint marks a callable as a framework entry point. +type GoEntrypoint struct { + Signature string `json:"signature"` + Framework string `json:"framework"` + DetectionSource string `json:"detection_source"` + Tags map[string]string `json:"tags"` +} diff --git a/internal/neo4j/artifact_integration_test.go b/internal/neo4j/artifact_integration_test.go index 132b38f..c9d4994 100644 --- a/internal/neo4j/artifact_integration_test.go +++ b/internal/neo4j/artifact_integration_test.go @@ -8,7 +8,7 @@ import ( "github.com/neo4j/neo4j-go-driver/v5/neo4j" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // Live tests for the artifact reconcile (#70, Q4–Q6). Each builds a real @@ -17,17 +17,17 @@ import ( // withRepo returns a with the artifacts named by paths (go.mod and go.sum are // always there) and the dependencies named by deps, each declared in go.mod // and locked in go.sum. -func withRepo(t *testing.T, paths []string, deps []string) *v2.Analysis { +func withRepo(t *testing.T, paths []string, deps []string) *schema.Analysis { t.Helper() a := buildMultipackageL2(t) app := a.Application.ID - a.Application.Artifacts = map[string]v2.Artifact{} + a.Application.Artifacts = map[string]schema.Artifact{} for _, p := range append([]string{"go.mod", "go.sum"}, paths...) { - a.Application.Artifacts[p] = v2.Artifact{ID: app + "/artifact/" + p, Kind: "artifact", Path: p, Format: "text", Extraction: "none"} + a.Application.Artifacts[p] = schema.Artifact{ID: app + "/artifact/" + p, Kind: "artifact", Path: p, Format: "text", Extraction: "none"} } a.Application.Dependencies = nil for _, d := range deps { - a.Application.Dependencies = append(a.Application.Dependencies, v2.Dependency{ + a.Application.Dependencies = append(a.Application.Dependencies, schema.Dependency{ Name: d, Ecosystem: "golang", Spec: "v1.0.0", Kind: "runtime", Direct: true, LockedVersion: "v1.0.0", LockedIn: app + "/artifact/go.sum", DeclaredIn: app + "/artifact/go.mod", Prov: []string{"declared", "lockfile"}, @@ -36,7 +36,7 @@ func withRepo(t *testing.T, paths []string, deps []string) *v2.Analysis { return a } -func pushIT(t *testing.T, ctx context.Context, a *v2.Analysis, cfg BoltConfig) { +func pushIT(t *testing.T, ctx context.Context, a *schema.Analysis, cfg BoltConfig) { t.Helper() if _, _, err := PushBolt(ctx, treeSource(a), cfg); err != nil { t.Fatalf("push: %v", err) @@ -61,7 +61,7 @@ func countIT(t *testing.T, ctx context.Context, cfg BoltConfig, q string, params // the DECLARES_DEPENDENCY and LOCKS edges to golang.org/x/text. func repoState(t *testing.T, ctx context.Context, cfg BoltConfig, app string) (config, declares, locks int) { t.Helper() - p := map[string]any{"cfg": app + "/artifact/config.yaml", "pkg": v2.PackageID("golang", "golang.org/x/text")} + p := map[string]any{"cfg": app + "/artifact/config.yaml", "pkg": schema.PackageID("golang", "golang.org/x/text")} config = countIT(t, ctx, cfg, "MATCH (n:Artifact {id: $cfg}) RETURN count(n)", p) declares = countIT(t, ctx, cfg, "MATCH (:Artifact)-[r:DECLARES_DEPENDENCY]->(:Package {id: $pkg}) RETURN count(r)", p) locks = countIT(t, ctx, cfg, "MATCH (:Artifact)-[r:LOCKS]->(:Package {id: $pkg}) RETURN count(r)", p) @@ -83,7 +83,7 @@ func seed(t *testing.T, ctx context.Context, cfg BoltConfig) string { } // after is the "after" state: config.yaml deleted, golang.org/x/text removed. -func after(t *testing.T) *v2.Analysis { +func after(t *testing.T) *schema.Analysis { return withRepo(t, nil, []string{"github.com/gorilla/mux"}) } diff --git a/internal/neo4j/batched_delete_integration_test.go b/internal/neo4j/batched_delete_integration_test.go index a59a54d..e98a2c4 100644 --- a/internal/neo4j/batched_delete_integration_test.go +++ b/internal/neo4j/batched_delete_integration_test.go @@ -8,7 +8,7 @@ import ( "slices" "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // Live tests for the batched deletes (#61). They need a database with a small @@ -41,19 +41,19 @@ func requireTxLimit(t *testing.T, ctx context.Context, cfg BoltConfig) { } // withBigModule grows a's first module and sets its content_hash to hash. -func withBigModule(a *v2.Analysis, hash string) { +func withBigModule(a *schema.Analysis, hash string) { k := firstModuleFile(a) m := a.Application.SymbolTable[k] if m.Functions == nil { - m.Functions = map[string]v2.Callable{} + m.Functions = map[string]schema.Callable{} } for i := range bigModuleFunctions { name := fmt.Sprintf("generated%d", i) - fn := v2.Callable{ID: m.ID + "/" + name, Kind: "function", Signature: m.Package + "." + name, - Callables: map[string]v2.Callable{}} + fn := schema.Callable{ID: m.ID + "/" + name, Kind: "function", Signature: m.Package + "." + name, + Callables: map[string]schema.Callable{}} for j := 1; j <= bigModuleClosures; j++ { c := fmt.Sprintf("closure_%d", j) - fn.Callables[c] = v2.Callable{ID: fn.ID + "/" + c, Kind: "lambda", Signature: fn.Signature + "." + c} + fn.Callables[c] = schema.Callable{ID: fn.ID + "/" + c, Kind: "lambda", Signature: fn.Signature + "." + c} } m.Functions[name] = fn } @@ -99,7 +99,7 @@ func TestIntegration_EagerPartialPushPurgesLargeModuleInBatches(t *testing.T) { } // firstModuleFile is the first symbol_table key, the module withBigModule grows. -func firstModuleFile(a *v2.Analysis) string { +func firstModuleFile(a *schema.Analysis) string { keys := make([]string, 0, len(a.Application.SymbolTable)) for k := range a.Application.SymbolTable { keys = append(keys, k) diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index bb956f7..b6d5f8c 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -8,7 +8,7 @@ import ( "sort" "strconv" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/neo4j/neo4j-go-driver/v5/neo4j" ) @@ -390,7 +390,7 @@ func (w *boltWriter) storedAppStale() (bool, error) { namespaceValue, _ := res.Record().Get("ns") name, nameOK := nameValue.(string) namespace, namespaceOK := namespaceValue.(string) - identity, identityErr := v2.ResolveIdentity(name, &namespace) + identity, identityErr := schema.ResolveIdentity(name, &namespace) if !nameOK || !namespaceOK || identityErr != nil || identity.ApplicationID != w.appID { return fmt.Errorf("incompatible stored application identity metadata") } @@ -453,7 +453,7 @@ func eagerPurgeQuery(root string) (string, map[string]any) { } // artifactPrefix is the id prefix of an application's artifacts: -// /artifact/ (spec v2-artifacts). +// /artifact/ (spec artifacts). func artifactPrefix(root string) string { return descendantPrefix(root) + "artifact/" } diff --git a/internal/neo4j/bolt_integration_test.go b/internal/neo4j/bolt_integration_test.go index fea22b3..78c7ac0 100644 --- a/internal/neo4j/bolt_integration_test.go +++ b/internal/neo4j/bolt_integration_test.go @@ -24,7 +24,7 @@ import ( "github.com/neo4j/neo4j-go-driver/v5/neo4j" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) func itConfig(t *testing.T) BoltConfig { @@ -232,7 +232,7 @@ func TestIntegration_LazyL4PushOverLowerLevelGraph(t *testing.T) { wantN, wantE := countSubgraph(t, ctx, cfg, id) want := l4Counts(t, ctx, cfg, id) - for _, seed := range []*v2.Analysis{buildDataflowAt(t, 2), buildDataflowL3(t)} { + for _, seed := range []*schema.Analysis{buildDataflowAt(t, 2), buildDataflowL3(t)} { if seed.Application.ID != id { t.Fatalf("app ids differ: %s, %s", seed.Application.ID, id) } @@ -328,7 +328,7 @@ func TestIntegration_EagerFullPushRemovesVanishedModule(t *testing.T) { // The run no longer has the file, so it has none of its calls either. b := buildMultipackageL2(t) delete(b.Application.SymbolTable, gone) - b.Application.CallGraph = slices.DeleteFunc(b.Application.CallGraph, func(e v2.Edge) bool { + b.Application.CallGraph = slices.DeleteFunc(b.Application.CallGraph, func(e schema.Edge) bool { return strings.HasPrefix(e.Src, id+"/") || strings.HasPrefix(e.Dst, id+"/") }) if err := WriteBolt(ctx, Project(b), b.Application.ID, cfg); err != nil { diff --git a/internal/neo4j/bolt_session_test.go b/internal/neo4j/bolt_session_test.go index d46b88d..158d4ae 100644 --- a/internal/neo4j/bolt_session_test.go +++ b/internal/neo4j/bolt_session_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/neo4j/neo4j-go-driver/v5/neo4j" ) @@ -220,7 +220,7 @@ func pushRows(t *testing.T, db *fakeDB, rows GraphRows, appID string, cfg BoltCo // pushPaths runs body once, in a "replay" subtest, with a replay of // Project(a) and once, in a "stream" subtest, with a streamGraph push of a's // tree. -func pushPaths(t *testing.T, a *v2.Analysis, body func(t *testing.T, push func(*fakeDB, BoltConfig))) { +func pushPaths(t *testing.T, a *schema.Analysis, body func(t *testing.T, push func(*fakeDB, BoltConfig))) { t.Helper() rows := Project(a) t.Run("replay", func(t *testing.T) { @@ -616,7 +616,7 @@ func TestBolt_StreamPushOrder(t *testing.T) { t.Run("lazy", func(t *testing.T) { streamPushOrder(t, a, BoltConfig{}) }) } -func streamPushOrder(t *testing.T, a *v2.Analysis, cfg BoltConfig) { +func streamPushOrder(t *testing.T, a *schema.Analysis, cfg BoltConfig) { db := &fakeDB{} w := newBoltWriter(context.Background(), db, a.Application.ID, cfg) if _, _, err := streamGraph(treeSource(a), w); err != nil { diff --git a/internal/neo4j/crossfile_lazy_push_test.go b/internal/neo4j/crossfile_lazy_push_test.go index 1f25de5..fc6bba2 100644 --- a/internal/neo4j/crossfile_lazy_push_test.go +++ b/internal/neo4j/crossfile_lazy_push_test.go @@ -6,10 +6,10 @@ import ( "strings" "testing" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // The lazy push upserts a module's rows only when that module's content_hash @@ -20,7 +20,7 @@ import ( // symbol-table builder and emitter, and project each version with Project. // analyzeXF writes the files to a fresh project and returns its L1 analysis. -func analyzeXF(t *testing.T, files map[string]string) *v2.Analysis { +func analyzeXF(t *testing.T, files map[string]string) *schema.Analysis { t.Helper() dir := t.TempDir() for rel, content := range files { @@ -33,12 +33,12 @@ func analyzeXF(t *testing.T, files map[string]string) *v2.Analysis { if err != nil { t.Fatalf("symbol table build: %v", err) } - app := &schema.GoApplication{SymbolTable: st} - id, err := v2.ResolveIdentity("xf", nil) + app := &model.GoApplication{SymbolTable: st} + id, err := schema.ResolveIdentity("xf", nil) if err != nil { t.Fatal(err) } - return v2emit.Emit(app, id, dir, 1, "lazy-push-test", 0, nil, nil) + return emit.Emit(app, id, dir, 1, "lazy-push-test", 0, nil, nil) } // lazyUpsertIDs is the set of node ids a lazy (non-eager) push would upsert when diff --git a/internal/neo4j/crossfile_stream_test.go b/internal/neo4j/crossfile_stream_test.go index 7329116..3beb9ed 100644 --- a/internal/neo4j/crossfile_stream_test.go +++ b/internal/neo4j/crossfile_stream_test.go @@ -3,7 +3,7 @@ package neo4j import ( "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // The streaming push stages a row with the module that owns it. A cross-file @@ -22,7 +22,7 @@ var xfLayouts = []struct { {"declaring file before receiver", "z.go"}, } -func xfAnalysis(t *testing.T, typeFile, method string) *v2.Analysis { +func xfAnalysis(t *testing.T, typeFile, method string) *schema.Analysis { t.Helper() return analyzeXF(t, map[string]string{ "go.mod": xfMod, @@ -55,7 +55,7 @@ func TestStreamPush_LazyFollowsDeclaringFile(t *testing.T) { for m, ns := range byModule { stored[m] = moduleHash(ns) } - push := func(t *testing.T, a *v2.Analysis) map[string]bool { + push := func(t *testing.T, a *schema.Analysis) map[string]bool { t.Helper() hashes := map[string]string{} for m, h := range stored { @@ -87,7 +87,7 @@ func TestStreamPush_LazyFollowsDeclaringFile(t *testing.T) { } } -func pushStream(t *testing.T, db *fakeDB, a *v2.Analysis, cfg BoltConfig) { +func pushStream(t *testing.T, db *fakeDB, a *schema.Analysis, cfg BoltConfig) { t.Helper() if _, _, err := streamGraph(treeSource(a), newBoltWriter(t.Context(), db, a.Application.ID, cfg)); err != nil { t.Fatal(err) diff --git a/internal/neo4j/crossfile_test.go b/internal/neo4j/crossfile_test.go index 1c7132d..bab4209 100644 --- a/internal/neo4j/crossfile_test.go +++ b/internal/neo4j/crossfile_test.go @@ -3,7 +3,7 @@ package neo4j import ( "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // A method declared in b.go but whose receiver type lives in a.go: GO_HAS_METHOD @@ -16,14 +16,14 @@ func TestProject_CrossFileMethodDeclaredByItsModule(t *testing.T) { typeID = typeMod + "/T" methodID = declMod + "/T/M" ) - a := &v2.Analysis{ - IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, - Application: v2.Application{ + a := &schema.Analysis{ + IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 1, + Application: schema.Application{ IdentityVersion: 2, ID: app, Kind: "application", - SymbolTable: map[string]v2.Module{ - "a.go": {ID: typeMod, Kind: "module", Types: map[string]v2.Type{ + SymbolTable: map[string]schema.Module{ + "a.go": {ID: typeMod, Kind: "module", Types: map[string]schema.Type{ "T": {ID: typeID, Kind: "struct", Signature: "example.com/xf.T", - Callables: map[string]v2.Callable{ + Callables: map[string]schema.Callable{ "example.com/xf.T.M": {ID: methodID, Kind: "method", Signature: "example.com/xf.T.M", SourceFile: "b.go"}, }}, }}, diff --git a/internal/neo4j/cypher.go b/internal/neo4j/cypher.go index d0c637f..99248db 100644 --- a/internal/neo4j/cypher.go +++ b/internal/neo4j/cypher.go @@ -9,7 +9,7 @@ import ( "sort" "strings" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // Milestone M4: the snapshot writer. RenderCypher turns a GraphRows bag into a @@ -69,7 +69,7 @@ func validateIdentity(rows GraphRows, appID string) error { if !ok { return fmt.Errorf("missing identity_namespace") } - identity, err := v2.ResolveIdentity(name, &ns) + identity, err := schema.ResolveIdentity(name, &ns) if err != nil { return err } diff --git a/internal/neo4j/cypher_test.go b/internal/neo4j/cypher_test.go index a765c9a..f5178ad 100644 --- a/internal/neo4j/cypher_test.go +++ b/internal/neo4j/cypher_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // M4 gate: the snapshot writer. The DDL + scoped wipe + batched node/edge MERGE @@ -235,7 +235,7 @@ func TestWriteCypher_FailureLeavesOutput(t *testing.T) { // TestWriteCypher_Deterministic: writing the snapshot twice for the same input // gives byte-identical files (module key order plus each builder's sort). func TestWriteCypher_Deterministic(t *testing.T) { - for name, a := range map[string]*v2.Analysis{ + for name, a := range map[string]*schema.Analysis{ "multipackage L2": buildMultipackageL2(t), "dataflow L4": buildDataflowL4(t), "chi L4": buildFixtureL4(t, "chi"), diff --git a/internal/neo4j/ddl.go b/internal/neo4j/ddl.go index b35632a..77e65ff 100644 --- a/internal/neo4j/ddl.go +++ b/internal/neo4j/ddl.go @@ -4,7 +4,7 @@ import ( "fmt" "sort" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // Derived DDL + the --emit schema document. Constraints are DERIVED from the @@ -131,7 +131,7 @@ func BuildSchemaDocument() SchemaDocument { return SchemaDocument{ RelationshipFactProperty: RelationshipFactProperty, SchemaVersion: SchemaVersion, - Language: v2.Language, + Language: schema.Language, NodePrefix: NodePrefix, RelPrefix: RelPrefix, MarkerLabel: MarkerLabel, diff --git a/internal/neo4j/emit.go b/internal/neo4j/emit.go index 9d79da4..db078a5 100644 --- a/internal/neo4j/emit.go +++ b/internal/neo4j/emit.go @@ -9,7 +9,7 @@ import ( ) // Facade between the CLI and the Neo4j backend: EmitSchema (static contract, -// needs no project) and EmitNeo4j (stream the v2 payload into a graph.cypher +// needs no project) and EmitNeo4j (stream the payload into a graph.cypher // snapshot when no URI is set, or into a live Bolt push when one is). // GraphFileName is the snapshot script written when no --neo4j-uri is given. diff --git a/internal/neo4j/large_text_test.go b/internal/neo4j/large_text_test.go index f965d86..5aba3da 100644 --- a/internal/neo4j/large_text_test.go +++ b/internal/neo4j/large_text_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // TestCypherValueWriters_MatchStrings: the streaming value writers write the @@ -32,14 +32,14 @@ func TestCypherValueWriters_MatchStrings(t *testing.T) { } } -func largeTextAnalysis(t *testing.T, sources ...string) *v2.Analysis { +func largeTextAnalysis(t *testing.T, sources ...string) *schema.Analysis { t.Helper() a := buildMultipackageL2(t) app := a.Application.ID - a.Application.Artifacts = map[string]v2.Artifact{} + a.Application.Artifacts = map[string]schema.Artifact{} for i, src := range sources { p := string(rune('a'+i)) + ".csv" - a.Application.Artifacts[p] = v2.Artifact{ID: app + "/artifact/" + p, Kind: "artifact", Path: p, + a.Application.Artifacts[p] = schema.Artifact{ID: app + "/artifact/" + p, Kind: "artifact", Path: p, Format: "text", SizeBytes: int64(len(src)), Source: src, Extraction: "full"} } return a diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 6365893..e47214c 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -6,15 +6,15 @@ import ( "sort" "strings" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) -// Milestone M3: the pure projector. Project walks the canonical v2 Analysis +// Milestone M3: the pure projector. Project walks the canonical Analysis // tree and emits a GraphRows bag — one graph node per tree/body node, keyed on // its can:// id, with containment and every typed overlay as relationships. No // I/O, no driver; both writers consume the result identically. // -// The projector NEVER invents ids: it reads them off the stamped v2 tree, so +// The projector NEVER invents ids: it reads them off the stamped tree, so // the graph and analysis.json join on one string (two-projection agreement). // Node ids are can:// ids; the application segment is the outermost prefix of // every id the app owns, which is what makes prefix scoping exact. @@ -26,7 +26,7 @@ import ( // Project is the pure (tree) → GraphRows function. appID is analysis.Application.ID // (the can:/// root); it is read from the envelope, never recomposed. -func Project(a *v2.Analysis) GraphRows { +func Project(a *schema.Analysis) GraphRows { src := treeSource(a) p := &projector{ b: NewRowBuilder(), @@ -49,15 +49,15 @@ func Project(a *v2.Analysis) GraphRows { type projector struct { b *RowBuilder - analysis *v2.Analysis // the envelope: id, externals, call graph, repository - modules map[string]bool // symbol_table keys, for the in-project import check - declared map[string]bool // declared type and callable ids - calleeIDs map[string]bool // pass 1 only: @external body callees, which get a ghost later + analysis *schema.Analysis // the envelope: id, externals, call graph, repository + modules map[string]bool // symbol_table keys, for the in-project import check + declared map[string]bool // declared type and callable ids + calleeIDs map[string]bool // pass 1 only: @external body callees, which get a ghost later } // ─── application ───────────────────────────────────────────────────────────── -func (p *projector) projectApplication(degraded []v2.Degraded) { +func (p *projector) projectApplication(degraded []schema.Degraded) { a := p.analysis p.b.Node( []string{LabelApplication, MarkerLabel}, @@ -76,7 +76,7 @@ func (p *projector) projectApplication(degraded []v2.Degraded) { // degradedJSON is the envelope's degraded[] (spec §4.15) as a JSON string, // nil (pruned) when nothing degraded. -func degradedJSON(d []v2.Degraded) Value { +func degradedJSON(d []schema.Degraded) Value { if len(d) == 0 { return nil } @@ -91,7 +91,7 @@ func (p *projector) appRef() NodeRef { return NodeRef{Label: LabelApplication, KeyProp: "id", Value: p.analysis.Application.ID} } -// ─── repository layer (spec v2-artifacts) ──────────────────────────────────── +// ─── repository layer (spec artifacts) ──────────────────────────────────── // projectRepository writes the artifact and dependency rows. An artifact is an // app-scoped node (its id is a can:// id) hung off the application; a dependency @@ -124,7 +124,7 @@ func (p *projector) projectRepository() { for _, dep := range p.analysis.Application.Dependencies { pkgRef := p.b.Node( []string{LabelPackage}, - "id", v2.PackageID(dep.Ecosystem, dep.Name), + "id", schema.PackageID(dep.Ecosystem, dep.Name), Props{"ecosystem": dep.Ecosystem, "name": dep.Name}, "", ) @@ -141,7 +141,7 @@ func (p *projector) projectRepository() { // ─── module ────────────────────────────────────────────────────────────────── -func (p *projector) projectModule(m v2.Module) { +func (p *projector) projectModule(m schema.Module) { modRef := p.b.Node( []string{LabelModule, MarkerLabel}, "id", m.ID, @@ -168,7 +168,7 @@ func (p *projector) projectModule(m v2.Module) { // ─── type ───────────────────────────────────────────────────────────────────── -func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { +func (p *projector) projectType(modRef NodeRef, module string, t schema.Type) { tRef := p.b.Node( []string{SymbolLabel, LabelType, MarkerLabel}, "id", t.ID, @@ -213,12 +213,12 @@ func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { // upserted. The node id is unchanged; only the row's owner moves. owner := module if m.SourceFile != "" { - owner = v2.ModuleID(p.analysis.Application.ID, m.SourceFile) + owner = schema.ModuleID(p.analysis.Application.ID, m.SourceFile) } mRef := p.projectCallable(tRef, owner, m) p.b.Edge(RelHasMethod, tRef, mRef, nil, "") // A method declared in another file is also declared by that file's module, - // so "which file declares this method" is one query (spec v2-go-ids § Amendment). + // so "which file declares this method" is one query (spec go-ids § Amendment). if m.SourceFile != "" { declaring := NodeRef{Label: LabelModule, KeyProp: "id", Value: owner} p.b.Edge(RelDeclares, declaring, mRef, nil, "") @@ -231,7 +231,7 @@ func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { // projectCallable emits a callable node (+ its body call nodes and nested // closures) and returns its ref. The containment edge from the parent (DECLARES // or HAS_METHOD) is the caller's responsibility, since it differs by parent kind. -func (p *projector) projectCallable(parentRef NodeRef, module string, c v2.Callable) NodeRef { +func (p *projector) projectCallable(parentRef NodeRef, module string, c schema.Callable) NodeRef { cRef := p.b.Node( []string{SymbolLabel, LabelCallable, MarkerLabel}, "id", c.ID, @@ -266,10 +266,10 @@ func (p *projector) projectCallable(parentRef NodeRef, module string, c v2.Calla // projectBodyNode emits one body node of the callable (or, for a stand-in, // the :GoExternal) at callableRef and its GO_HAS_BODY_NODE. module is the // owning module, "" for a stand-in's vertices (shared, like the ghost). -func (p *projector) projectBodyNode(callableRef NodeRef, module, callableID, local string, bn v2.BodyNode) { +func (p *projector) projectBodyNode(callableRef NodeRef, module, callableID, local string, bn schema.BodyNode) { // GlobalOrdinal, not callableID+"@"+local: synthetic keys ("@entry") already // carry the "@", and the JSON body node id uses the same rule. - id := v2.GlobalOrdinal(callableID, local) + id := schema.GlobalOrdinal(callableID, local) // call_node is the parent statement's LOCAL key (JSON `parent` verbatim), // resolved against the owning callable — Python parity: codeanalyzer-python // projects node.parent unchanged and python-sdk's reconstruct maps call_node @@ -317,11 +317,11 @@ func (p *projector) projectBodyNode(callableRef NodeRef, module, callableID, loc // projectFlow emits a callable's intra-callable overlay: L3's cfg / cdg / ddg // and L4's port ddg edges (prov reaching-defs / points-to) and summary. JSON // edge endpoints are LOCAL body keys; the graph addresses :GoBodyNode by its -// global id, so each endpoint goes through v2.GlobalOrdinal. Parallel edges +// global id, so each endpoint goes through schema.GlobalOrdinal. Parallel edges // survive via _k: GO_CFG_NEXT per kind, GO_DDG per (var, prov). -func (p *projector) projectFlow(c v2.Callable) { +func (p *projector) projectFlow(c schema.Callable) { ref := func(local string) NodeRef { - return NodeRef{Label: LabelBodyNode, KeyProp: "id", Value: v2.GlobalOrdinal(c.ID, local)} + return NodeRef{Label: LabelBodyNode, KeyProp: "id", Value: schema.GlobalOrdinal(c.ID, local)} } for _, e := range c.Cfg { p.b.Edge(RelCFGNext, ref(e.Src), ref(e.Dst), Props{"kind": e.Kind}, e.Kind) @@ -361,7 +361,7 @@ func (p *projector) projectStandIns() { // projectParamEdges emits GO_PARAM_IN / GO_PARAM_OUT {var}, one row per JSON // param_in / param_out edge. -func (p *projector) projectParamEdges(in, out iter.Seq[v2.ParamEdge]) { +func (p *projector) projectParamEdges(in, out iter.Seq[schema.ParamEdge]) { for e := range in { r := paramEdgeRow(RelParamIn, e) p.b.Edge(r.Type, r.From, r.To, r.Props, r.Key) @@ -374,7 +374,7 @@ func (p *projector) projectParamEdges(in, out iter.Seq[v2.ParamEdge]) { // paramEdgeRow is the row of one param edge. Endpoints are body node ids // already (the emitter minted them), addressed as :GoBodyNode. -func paramEdgeRow(rel string, e v2.ParamEdge) EdgeRow { +func paramEdgeRow(rel string, e schema.ParamEdge) EdgeRow { ref := func(id string) NodeRef { return NodeRef{Label: LabelBodyNode, KeyProp: "id", Value: id} } return EdgeRow{Type: rel, From: ref(e.Src), To: ref(e.Dst), Props: Props{"var": e.Var}} } @@ -385,13 +385,13 @@ func paramEdgeRow(rel string, e v2.ParamEdge) EdgeRow { // resolved target. An import whose path names an in-tree module resolves to that // :GoModule; otherwise it resolves to an id-keyed :GoExternal ghost (stdlib / // third-party), which never dangles. -func (p *projector) projectImports(modRef NodeRef, m v2.Module) { +func (p *projector) projectImports(modRef NodeRef, m schema.Module) { appID := p.analysis.Application.ID for _, imp := range m.Imports { // Is the import path an in-project module? (symbol_table is keyed by // relative file path; Go imports name a package path, not a file — so an // in-project hit is rare and handled conservatively via the id space.) - targetModuleID := v2.ModuleID(appID, imp.Path) + targetModuleID := schema.ModuleID(appID, imp.Path) if p.modules[imp.Path] { p.b.Edge(RelImports, modRef, NodeRef{Label: LabelModule, KeyProp: "id", Value: targetModuleID}, @@ -399,7 +399,7 @@ func (p *projector) projectImports(modRef NodeRef, m v2.Module) { continue } // External/stdlib → :GoExternal ghost keyed by import path. - ghostID := v2.ExternalID(appID, imp.Path, "") + ghostID := schema.ExternalID(appID, imp.Path, "") ghostRef := p.b.Node( []string{SymbolLabel, LabelExternal, MarkerLabel}, "id", ghostID, @@ -413,7 +413,7 @@ func (p *projector) projectImports(modRef NodeRef, m v2.Module) { // ─── call graph ───────────────────────────────────────────────────────────── // projectCallGraph emits the aggregated GO_CALLS edges. Endpoints are already -// can:// callable ids in the v2 edge; a declared id resolves to its callable +// can:// callable ids in the edge; a declared id resolves to its callable // node, anything else to an id-keyed external ghost — so no GO_CALLS endpoint // ever dangles. func (p *projector) projectCallGraph() { @@ -452,7 +452,7 @@ func (p *projector) callEndpoint(id string) NodeRef { // collectDeclaredIDs walks the tree once to gather every declared type and // callable id, so endpoint resolution can distinguish a declared target from an // external one without emitting it twice. -func collectDeclaredIDs(a *v2.Analysis) map[string]bool { +func collectDeclaredIDs(a *schema.Analysis) map[string]bool { ids := make(map[string]bool) for _, m := range a.Application.SymbolTable { moduleDeclared(m, ids) @@ -461,9 +461,9 @@ func collectDeclaredIDs(a *v2.Analysis) map[string]bool { } // moduleDeclared adds the type and callable ids that module m declares to into. -func moduleDeclared(m v2.Module, into map[string]bool) { - var walkCallable func(c v2.Callable) - walkCallable = func(c v2.Callable) { +func moduleDeclared(m schema.Module, into map[string]bool) { + var walkCallable func(c schema.Callable) + walkCallable = func(c schema.Callable) { into[c.ID] = true for _, inner := range c.Callables { walkCallable(inner) @@ -484,7 +484,7 @@ func moduleDeclared(m v2.Module, into map[string]bool) { // spanLine is a span's start or end line as a node property, nil (pruned) for the // span-less synthetic nodes. Lines are 1-based, so a zero span is the absent one. -func spanLine(s v2.Span, start bool) Value { +func spanLine(s schema.Span, start bool) Value { if s.Start[0] == 0 && s.End[0] == 0 { return nil } @@ -497,7 +497,7 @@ func spanLine(s v2.Span, start bool) Value { // spanJSON flattens a span to a compact JSON string property. (A span is a // nested map, which Neo4j cannot store as a property, so it rides as *_json — // the same approach the siblings use for variant-shaped fields.) -func spanJSON(s v2.Span) Value { +func spanJSON(s schema.Span) Value { data, err := json.Marshal(s) if err != nil { return nil @@ -562,8 +562,8 @@ func lastSegment(id string) string { // bodySpanJSON is spanJSON for a body node, nil for the span-less synthetic // @entry / @exit (L3), whose JSON node has no span either. -func bodySpanJSON(s v2.Span) Value { - if s == (v2.Span{}) { +func bodySpanJSON(s schema.Span) Value { + if s == (schema.Span{}) { return nil } return spanJSON(s) diff --git a/internal/neo4j/project_test.go b/internal/neo4j/project_test.go index ff3af9a..f1fff0d 100644 --- a/internal/neo4j/project_test.go +++ b/internal/neo4j/project_test.go @@ -9,12 +9,12 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // M3 gate: the pure projector. These project the multipackage fixture at L2 @@ -23,8 +23,8 @@ import ( // and the Go-specific shapes. // buildMultipackageL2 builds the fixture through the real symbol-table builder -// and resolver and emits the v2 L2 analysis — the input to Project. -func buildMultipackageL2(t *testing.T) *v2.Analysis { +// and resolver and emits the L2 analysis — the input to Project. +func buildMultipackageL2(t *testing.T) *schema.Analysis { t.Helper() _, thisFile, _, _ := runtime.Caller(0) dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "testdata", "multipackage")) @@ -38,9 +38,9 @@ func buildMultipackageL2(t *testing.T) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} - return v2emit.Emit(app, func() v2.Identity { - i, e := v2.ResolveIdentity("multipackage", nil) + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + return emit.Emit(app, func() schema.Identity { + i, e := schema.ResolveIdentity("multipackage", nil) if e != nil { panic(e) } @@ -51,7 +51,7 @@ func buildMultipackageL2(t *testing.T) *v2.Analysis { func TestProject_NoDanglingEndpoints(t *testing.T) { for _, c := range []struct { name string - a func(*testing.T) *v2.Analysis + a func(*testing.T) *schema.Analysis }{ {"multipackage L2", buildMultipackageL2}, {"dataflow L4", buildDataflowL4}, @@ -189,7 +189,7 @@ func hasLabel(n NodeRow, label string) bool { func TestProject_ExternalGhostCarriesSignature(t *testing.T) { a := buildMultipackageL2(t) rows := Project(a) - ext := v2.ExternalID(a.Application.ID, "fmt", "Println") + ext := schema.ExternalID(a.Application.ID, "fmt", "Println") var ghost *NodeRow for i, n := range rows.Nodes { @@ -223,14 +223,14 @@ func TestProject_ExternalGhostCarriesSignature(t *testing.T) { // ─── L3 overlay ────────────────────────────────────────────────────────────── // buildDataflowL3 builds testdata/dataflow through the real -a 3 wiring (symbol -// table, resolver, dataflow driver) and emits the v2 L3 analysis. -func buildDataflowL3(t *testing.T) *v2.Analysis { +// table, resolver, dataflow driver) and emits the L3 analysis. +func buildDataflowL3(t *testing.T) *schema.Analysis { t.Helper() return buildDataflowAt(t, 3) } // buildDataflowAt is buildDataflowL3 at level 2 or 3 (no dataflow below 3). -func buildDataflowAt(t *testing.T, level int) *v2.Analysis { +func buildDataflowAt(t *testing.T, level int) *schema.Analysis { t.Helper() _, thisFile, _, _ := runtime.Caller(0) dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "testdata", "dataflow")) @@ -244,10 +244,10 @@ func buildDataflowAt(t *testing.T, level int) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} if level < 3 { - return v2emit.Emit(app, func() v2.Identity { - i, e := v2.ResolveIdentity("dataflow", nil) + return emit.Emit(app, func() schema.Identity { + i, e := schema.ResolveIdentity("dataflow", nil) if e != nil { panic(e) } @@ -255,8 +255,8 @@ func buildDataflowAt(t *testing.T, level int) *v2.Analysis { }(), dir, level, "neo4j-gate", 3, nil, nil) } res := dataflow.Run(b.Fset(), b.L3Units(st), 3, 4) - return v2emit.Emit(app, func() v2.Identity { - i, e := v2.ResolveIdentity("dataflow", nil) + return emit.Emit(app, func() schema.Identity { + i, e := schema.ResolveIdentity("dataflow", nil) if e != nil { panic(e) } @@ -265,9 +265,9 @@ func buildDataflowAt(t *testing.T, level int) *v2.Analysis { } // walkCallables visits every callable (methods and nested closures included). -func walkCallables(a *v2.Analysis, visit func(c v2.Callable)) { - var walk func(c v2.Callable) - walk = func(c v2.Callable) { +func walkCallables(a *schema.Analysis, visit func(c schema.Callable)) { + var walk func(c schema.Callable) + walk = func(c schema.Callable) { visit(c) for _, in := range c.Callables { walk(in) @@ -302,7 +302,7 @@ func TestProject_L3CountsMatchJSON(t *testing.T) { rows := Project(a) var cfg, cdg, ddg, body int - walkCallables(a, func(c v2.Callable) { + walkCallables(a, func(c schema.Callable) { cfg += len(c.Cfg) cdg += len(c.Cdg) ddg += len(c.Ddg) @@ -378,7 +378,7 @@ func TestProject_SyntheticBodyNodes(t *testing.T) { } } checked := 0 - walkCallables(a, func(c v2.Callable) { + walkCallables(a, func(c schema.Callable) { for _, tag := range []string{"@entry", "@exit"} { if _, ok := c.Body[tag]; !ok { continue @@ -406,30 +406,30 @@ func TestProject_SyntheticBodyNodes(t *testing.T) { } } -func overlayFixture() *v2.Analysis { +func overlayFixture() *schema.Analysis { const app = "can://go/x" const mod = app + "/a.go" const fn = mod + "/f()" - return &v2.Analysis{ - SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 3, - Application: v2.Application{ + return &schema.Analysis{ + SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 3, + Application: schema.Application{ ID: app, - SymbolTable: map[string]v2.Module{"a.go": { + SymbolTable: map[string]schema.Module{"a.go": { ID: mod, - Functions: map[string]v2.Callable{"f()": { + Functions: map[string]schema.Callable{"f()": { ID: fn, - Body: map[string]v2.BodyNode{ + Body: map[string]schema.BodyNode{ "@entry": {Kind: "entry", ID: fn + "@entry"}, - "3:2": {Kind: "branch", ID: fn + "@3:2", Span: v2.Span{Start: [2]int{3, 2}, End: [2]int{3, 9}, Bytes: [2]int{10, 17}}}, - "4:3": {Kind: "call", ID: fn + "@4:3", Parent: "3:2", Span: v2.Span{Start: [2]int{4, 3}, End: [2]int{4, 9}, Bytes: [2]int{20, 26}}}, + "3:2": {Kind: "branch", ID: fn + "@3:2", Span: schema.Span{Start: [2]int{3, 2}, End: [2]int{3, 9}, Bytes: [2]int{10, 17}}}, + "4:3": {Kind: "call", ID: fn + "@4:3", Parent: "3:2", Span: schema.Span{Start: [2]int{4, 3}, End: [2]int{4, 9}, Bytes: [2]int{20, 26}}}, "@exit": {Kind: "exit", ID: fn + "@exit"}, }, - Cfg: []v2.CfgEdge{ + Cfg: []schema.CfgEdge{ {Src: "3:2", Dst: "4:3", Kind: "true"}, {Src: "3:2", Dst: "4:3", Kind: "exception"}, }, - Cdg: []v2.CdgEdge{{Src: "3:2", Dst: "4:3"}}, - Ddg: []v2.DdgEdge{ + Cdg: []schema.CdgEdge{{Src: "3:2", Dst: "4:3"}}, + Ddg: []schema.DdgEdge{ {Src: "@entry", Dst: "4:3", Var: "x", Prov: []string{"ssa"}}, {Src: "@entry", Dst: "4:3", Var: "x", Prov: []string{"ssa", "points-to"}}, {Src: "@entry", Dst: "4:3", Var: "y", Prov: []string{"ssa"}}, @@ -509,7 +509,7 @@ func TestProject_BodyNodeCallNodeAndVar(t *testing.T) { // TestProject_CallNodeResolvesWithinOwner (I6): on the real -a 3 fixture every // call_node is a local key that, resolved against the owning callable (the -// GO_HAS_BODY_NODE source) with v2.GlobalOrdinal, names a projected body node +// GO_HAS_BODY_NODE source) with schema.GlobalOrdinal, names a projected body node // of that same callable — no dangling call_node. func TestProject_CallNodeResolvesWithinOwner(t *testing.T) { rows := Project(buildDataflowL3(t)) @@ -533,7 +533,7 @@ func TestProject_CallNodeResolvesWithinOwner(t *testing.T) { t.Errorf("%s: call_node %v is not a local key", n.Value, cn) continue } - parent := v2.GlobalOrdinal(owner[n.Value], local) + parent := schema.GlobalOrdinal(owner[n.Value], local) if owner[parent] != owner[n.Value] || owner[n.Value] == "" { t.Errorf("%s: call_node %q resolves to %s, not a body node of %s", n.Value, local, parent, owner[n.Value]) } @@ -546,10 +546,10 @@ func TestProject_CallNodeResolvesWithinOwner(t *testing.T) { // ─── L4 overlay ────────────────────────────────────────────────────────────── -// l4Inputs are the arguments v2emit.Emit and v2emit.Open take for a fixture at -a 4. +// l4Inputs are the arguments emit.Emit and emit.Open take for a fixture at -a 4. type l4Inputs struct { - app *schema.GoApplication - identity v2.Identity + app *model.GoApplication + identity schema.Identity dir string l3 map[dataflow.L3Key]dataflow.Result l4 *sdg.Result @@ -558,7 +558,7 @@ type l4Inputs struct { var ( l4Mu sync.Mutex l4InCache = map[string]*l4Inputs{} - l4OutCache = map[string]*v2.Analysis{} + l4OutCache = map[string]*schema.Analysis{} ) // buildL4Inputs builds testdata/ through the real -a 4 wiring (symbol @@ -583,7 +583,7 @@ func buildL4Inputs(t *testing.T, name string) *l4Inputs { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} units := b.L3Units(st) res := dataflow.RunWithSideTables(b.Fset(), units, 3, 4) l4 := sdg.Run(sdg.Input{ @@ -591,7 +591,7 @@ func buildL4Inputs(t *testing.T, name string) *l4Inputs { Externals: app.Externals, CallGraph: app.CallGraph, Units: units, L3: res, K: 3, Jobs: 4, }) l4.ApplyTo(app) - identity, err := v2.ResolveIdentity(name, nil) + identity, err := schema.ResolveIdentity(name, nil) if err != nil { t.Fatalf("%s: identity: %v", name, err) } @@ -602,7 +602,7 @@ func buildL4Inputs(t *testing.T, name string) *l4Inputs { // buildFixtureL4 emits testdata/ at -a 4. Built once per name: the // projection never mutates it. -func buildFixtureL4(t *testing.T, name string) *v2.Analysis { +func buildFixtureL4(t *testing.T, name string) *schema.Analysis { t.Helper() in := buildL4Inputs(t, name) l4Mu.Lock() @@ -610,13 +610,13 @@ func buildFixtureL4(t *testing.T, name string) *v2.Analysis { if a, ok := l4OutCache[name]; ok { return a } - a := v2emit.Emit(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4) + a := emit.Emit(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4) l4OutCache[name] = a return a } // buildDataflowL4 is buildFixtureL4 over testdata/dataflow. -func buildDataflowL4(t *testing.T) *v2.Analysis { +func buildDataflowL4(t *testing.T) *schema.Analysis { t.Helper() return buildFixtureL4(t, "dataflow") } @@ -638,7 +638,7 @@ func TestProject_L4CountsMatchJSON(t *testing.T) { a := buildDataflowL4(t) rows := Project(a) var ddg, port, summary, body, vertices int - walkCallables(a, func(c v2.Callable) { + walkCallables(a, func(c schema.Callable) { ddg += len(c.Ddg) for _, e := range c.Ddg { if strings.Join(e.Prov, ",") != "ssa" { @@ -711,7 +711,7 @@ func TestProject_L4VertexProps(t *testing.T) { for _, n := range rows.Nodes { byID[n.Labels[0]+"\x00"+n.Value] = n } - walkCallables(a, func(c v2.Callable) { + walkCallables(a, func(c schema.Callable) { for _, n := range c.Body { if !isVertex(n.Kind) { continue @@ -772,7 +772,7 @@ func TestProject_L4VertexProps(t *testing.T) { func TestProject_DegradedJSONOnApplication(t *testing.T) { a := overlayFixture() a.MaxLevel = 4 - a.Degraded = []v2.Degraded{ + a.Degraded = []schema.Degraded{ {Code: "no_vta", Detail: "panic: x"}, {Code: "range_func", Packages: []string{"example.com/p"}, Callables: []string{"can://go/x/a.go/f()"}}, } diff --git a/internal/neo4j/repository_test.go b/internal/neo4j/repository_test.go index cb548b2..e55de42 100644 --- a/internal/neo4j/repository_test.go +++ b/internal/neo4j/repository_test.go @@ -4,30 +4,30 @@ import ( "reflect" "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // repoAnalysis is a minimal L1 analysis carrying only the repository layer: // go.mod and go.sum artifacts, two dependencies (one locked, one not), and a // nested tools/go.mod whose dependency its own tools/go.sum locks. -func repoAnalysis() *v2.Analysis { +func repoAnalysis() *schema.Analysis { const app = "can://frontend/frontend" goMod := app + "/artifact/go.mod" goSum := app + "/artifact/go.sum" toolsMod := app + "/artifact/tools/go.mod" toolsSum := app + "/artifact/tools/go.sum" - return &v2.Analysis{ - IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, - Application: v2.Application{ + return &schema.Analysis{ + IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 1, + Application: schema.Application{ IdentityVersion: 2, ID: app, Kind: "application", - Artifacts: map[string]v2.Artifact{ + Artifacts: map[string]schema.Artifact{ "go.mod": {ID: goMod, Kind: "artifact", Path: "go.mod", Format: "gomod", Roles: []string{"dependency-manifest"}, SizeBytes: 42, SHA256: "abc123", Source: "module frontend\n", Extraction: "full"}, "go.sum": {ID: goSum, Kind: "artifact", Path: "go.sum", Format: "gosum", Roles: []string{"lockfile"}, Extraction: "none"}, "tools/go.mod": {ID: toolsMod, Kind: "artifact", Path: "tools/go.mod", Format: "gomod", Extraction: "none"}, "tools/go.sum": {ID: toolsSum, Kind: "artifact", Path: "tools/go.sum", Format: "gosum", Extraction: "none"}, }, - Dependencies: []v2.Dependency{ + Dependencies: []schema.Dependency{ {Name: "github.com/gorilla/mux", Ecosystem: "golang", Spec: "v1.8.0", Kind: "runtime", Direct: true, LockedVersion: "v1.8.0", LockedIn: goSum, DeclaredIn: goMod, Prov: []string{"declared", "lockfile"}}, {Name: "golang.org/x/text", Ecosystem: "golang", Spec: "v0.14.0", Kind: "runtime", Direct: false, diff --git a/internal/neo4j/schema.go b/internal/neo4j/schema.go index 1c5ab48..08bc9a1 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -1,4 +1,4 @@ -// Package neo4j is the Neo4j projection of the canonical schema-v2 CPG envelope: +// Package neo4j is the Neo4j projection of the canonical CPG envelope: // a pure, identity-preserving second projection of the SAME tree the JSON path // emits to analysis.json, keyed on the SAME can:// ids. JSON and graph are // interchangeable and can never diverge. @@ -9,7 +9,7 @@ // schema.go this file — the declarative contract (labels, relationships, // derived DDL, SCHEMA_VERSION, --emit schema serialization) // rows.go output-agnostic row IR + RowBuilder (M2) -// project.go pure projector: v2.Analysis tree -> GraphRows (M3) +// project.go pure projector: schema.Analysis tree -> GraphRows (M3) // cypher.go snapshot writer -> graph.cypher (M4) // bolt.go incremental Bolt writer (M5) // emit.go facade: EmitSchema / EmitNeo4j (M6) @@ -28,11 +28,11 @@ // targets, never a renamed shared name. package neo4j -import v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +import "github.com/codellm-devkit/codeanalyzer-go/internal/schema" // SchemaVersion is the graph contract version, stamped onto the :GoApplication // node so a consumer can detect a producer/consumer mismatch at runtime. It -// moves in lockstep with the JSON schema major (v2.SchemaVersion). The +// moves in lockstep with the JSON schema major (schema.SchemaVersion). The // additive-MINOR rule is suspended for the 2.0.0 line (parity with the sibling // ruling); consumers gate on the analyzer-version floor instead. // RelationshipFactProperty is the private SHA-256 discriminator every writer @@ -40,7 +40,7 @@ import v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" // It hashes the canonical JSON of the existing pruned fact properties. const RelationshipFactProperty = "_fact" -const SchemaVersion = v2.SchemaVersion // "2.0.0" +const SchemaVersion = schema.SchemaVersion // "2.0.0" // ─── namespacing (parity: Python PY_/Py, TS TS_/TS) ───────────────────────── @@ -228,7 +228,7 @@ var Nodes = []NodeSpec{ }, // Repository layer. An artifact id is can:////artifact/ - // (spec v2-artifacts, Python parity), so it is app-scoped: it carries the + // (spec artifacts, Python parity), so it is app-scoped: it carries the // :GoCanNode marker and falls under the prefix scope on wipe. { Label: LabelArtifact, MergeLabel: LabelArtifact, Key: "id", CanNode: true, diff --git a/internal/neo4j/signature_test.go b/internal/neo4j/signature_test.go index 1df9ffc..d6087ae 100644 --- a/internal/neo4j/signature_test.go +++ b/internal/neo4j/signature_test.go @@ -3,7 +3,7 @@ package neo4j import ( "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // The :GoCallable signature property is the JSON signature field, the full @@ -14,17 +14,17 @@ func TestProject_CallableSignatureFromJSONField(t *testing.T) { sig = "github.com/acme/app/worker.Worker.Run" mod = "can://ns/app/go/worker.go" ) - a := &v2.Analysis{ - IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, - Application: v2.Application{ + a := &schema.Analysis{ + IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 1, + Application: schema.Application{ IdentityVersion: 2, ID: "can://ns/app", Kind: "application", - SymbolTable: map[string]v2.Module{ + SymbolTable: map[string]schema.Module{ "worker.go": { ID: mod, Kind: "module", - Types: map[string]v2.Type{ + Types: map[string]schema.Type{ "Worker": { ID: mod + "/Worker", Kind: "struct", Signature: "github.com/acme/app/worker.Worker", - Callables: map[string]v2.Callable{ + Callables: map[string]schema.Callable{ "Run": {ID: mod + "/Worker/Run", Kind: "method", Signature: sig}, }, }, @@ -52,12 +52,12 @@ func TestProject_TypeSignatureFromJSONField(t *testing.T) { sig = "github.com/acme/app/worker.Worker" mod = "can://ns/app/go/worker.go" ) - a := &v2.Analysis{ - IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, - Application: v2.Application{ + a := &schema.Analysis{ + IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 1, + Application: schema.Application{ IdentityVersion: 2, ID: "can://ns/app", Kind: "application", - SymbolTable: map[string]v2.Module{ - "worker.go": {ID: mod, Kind: "module", Types: map[string]v2.Type{ + SymbolTable: map[string]schema.Module{ + "worker.go": {ID: mod, Kind: "module", Types: map[string]schema.Type{ "Worker": {ID: mod + "/Worker", Kind: "struct", Signature: sig}, }}, }, diff --git a/internal/neo4j/source.go b/internal/neo4j/source.go index efcdfe5..b8675b0 100644 --- a/internal/neo4j/source.go +++ b/internal/neo4j/source.go @@ -5,29 +5,29 @@ import ( "maps" "slices" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) -// Source is the v2 payload as a module stream. *v2emit.Stream satisfies it. +// Source is the payload as a module stream. *emit.Stream satisfies it. // ParamIn, ParamOut and Degraded are valid only after one complete Modules walk. type Source interface { - Envelope() *v2.Analysis + Envelope() *schema.Analysis ModuleKeys() []string - Modules() iter.Seq2[string, v2.Module] - ParamIn() iter.Seq[v2.ParamEdge] - ParamOut() iter.Seq[v2.ParamEdge] - Degraded() []v2.Degraded + Modules() iter.Seq2[string, schema.Module] + ParamIn() iter.Seq[schema.ParamEdge] + ParamOut() iter.Seq[schema.ParamEdge] + Degraded() []schema.Degraded } // TreeSource adapts an in-memory tree to a Source. Tests and Project use it. -func TreeSource(a *v2.Analysis) Source { return treeSource(a) } +func TreeSource(a *schema.Analysis) Source { return treeSource(a) } type tree struct { - a *v2.Analysis - env *v2.Analysis + a *schema.Analysis + env *schema.Analysis } -func treeSource(a *v2.Analysis) *tree { +func treeSource(a *schema.Analysis) *tree { env := *a env.Application.SymbolTable = nil env.Application.ParamIn = nil @@ -36,14 +36,14 @@ func treeSource(a *v2.Analysis) *tree { return &tree{a: a, env: &env} } -func (t *tree) Envelope() *v2.Analysis { return t.env } +func (t *tree) Envelope() *schema.Analysis { return t.env } func (t *tree) ModuleKeys() []string { return slices.Sorted(maps.Keys(t.a.Application.SymbolTable)) } -func (t *tree) Modules() iter.Seq2[string, v2.Module] { - return func(yield func(string, v2.Module) bool) { +func (t *tree) Modules() iter.Seq2[string, schema.Module] { + return func(yield func(string, schema.Module) bool) { for _, k := range t.ModuleKeys() { if !yield(k, t.a.Application.SymbolTable[k]) { return @@ -52,6 +52,6 @@ func (t *tree) Modules() iter.Seq2[string, v2.Module] { } } -func (t *tree) ParamIn() iter.Seq[v2.ParamEdge] { return slices.Values(t.a.Application.ParamIn) } -func (t *tree) ParamOut() iter.Seq[v2.ParamEdge] { return slices.Values(t.a.Application.ParamOut) } -func (t *tree) Degraded() []v2.Degraded { return t.a.Degraded } +func (t *tree) ParamIn() iter.Seq[schema.ParamEdge] { return slices.Values(t.a.Application.ParamIn) } +func (t *tree) ParamOut() iter.Seq[schema.ParamEdge] { return slices.Values(t.a.Application.ParamOut) } +func (t *tree) Degraded() []schema.Degraded { return t.a.Degraded } diff --git a/internal/neo4j/span_lines_test.go b/internal/neo4j/span_lines_test.go index 2bd3af5..d8dd61e 100644 --- a/internal/neo4j/span_lines_test.go +++ b/internal/neo4j/span_lines_test.go @@ -3,7 +3,7 @@ package neo4j import ( "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // The projector writes start_line and end_line beside span_json on every span-bearing @@ -18,18 +18,18 @@ func TestProject_SpanLineProperties(t *testing.T) { bod = fn + "@12:3" syn = fn + "@entry" ) - span := func(sl, el int) v2.Span { return v2.Span{Start: [2]int{sl, 1}, End: [2]int{el, 2}} } - a := &v2.Analysis{ - IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, - Application: v2.Application{ + span := func(sl, el int) schema.Span { return schema.Span{Start: [2]int{sl, 1}, End: [2]int{el, 2}} } + a := &schema.Analysis{ + IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 1, + Application: schema.Application{ IdentityVersion: 2, ID: app, Kind: "application", - SymbolTable: map[string]v2.Module{ - "a.go": {ID: mod, Kind: "module", Span: span(1, 20), Types: map[string]v2.Type{ + SymbolTable: map[string]schema.Module{ + "a.go": {ID: mod, Kind: "module", Span: span(1, 20), Types: map[string]schema.Type{ "T": {ID: typ, Kind: "struct", Span: span(5, 9), StartLine: 5, EndLine: 9, - Fields: map[string]v2.Field{"n": {ID: fld, Kind: "field", Span: span(6, 6), StartLine: 6, EndLine: 6}}, - Callables: map[string]v2.Callable{ + Fields: map[string]schema.Field{"n": {ID: fld, Kind: "field", Span: span(6, 6), StartLine: 6, EndLine: 6}}, + Callables: map[string]schema.Callable{ "M": {ID: fn, Kind: "method", Signature: "example.com/a.T.M", Span: span(11, 14), StartLine: 11, EndLine: 14, - Body: map[string]v2.BodyNode{ + Body: map[string]schema.BodyNode{ "12:3": {ID: bod, Kind: "call", Span: span(12, 12), StartLine: 12, EndLine: 12}, "@entry": {ID: syn, Kind: "entry"}, }}, diff --git a/internal/neo4j/stream.go b/internal/neo4j/stream.go index add4ecf..ede8da7 100644 --- a/internal/neo4j/stream.go +++ b/internal/neo4j/stream.go @@ -5,7 +5,7 @@ import ( "maps" "slices" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -177,7 +177,7 @@ func streamParamEdges(src Source, st stager) (int, error) { } for _, s := range []struct { rel string - edges iter.Seq[v2.ParamEdge] + edges iter.Seq[schema.ParamEdge] }{{RelParamIn, src.ParamIn()}, {RelParamOut, src.ParamOut()}} { for e := range s.edges { chunk = append(chunk, paramEdgeRow(s.rel, e)) @@ -239,7 +239,7 @@ func replayRows(rows GraphRows, st stager) (nodes, edges int, err error) { // appRow is the application row projectApplication makes, without // degraded_json, which is known only after the module walk. -func appRow(env *v2.Analysis) NodeRow { +func appRow(env *schema.Analysis) NodeRow { p := &projector{b: NewRowBuilder(), analysis: env} p.projectApplication(nil) return p.b.Finish().Nodes[0] diff --git a/internal/neo4j/stream_test.go b/internal/neo4j/stream_test.go index bbebe48..96806d6 100644 --- a/internal/neo4j/stream_test.go +++ b/internal/neo4j/stream_test.go @@ -7,8 +7,8 @@ import ( "strings" "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" - "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/emit" ) // collectStager records the stages in order. @@ -62,9 +62,9 @@ func (c *collectStager) end() error { } // parityFixtures are the trees the parity gate projects both ways. -func parityFixtures(t *testing.T) map[string]*v2.Analysis { +func parityFixtures(t *testing.T) map[string]*schema.Analysis { t.Helper() - fx := map[string]*v2.Analysis{ + fx := map[string]*schema.Analysis{ "multipackage L2": buildMultipackageL2(t), "dataflow L1": buildDataflowAt(t, 1), "dataflow L3": buildDataflowL3(t), @@ -81,38 +81,38 @@ func parityFixtures(t *testing.T) map[string]*v2.Analysis { // crossModuleAnalysis is a hand-built tree whose facts cross modules the way // pass 1 cannot see: a.go's body callee and embedded type live in b.go, a.go's // type embeds a call-graph ghost, and one external is reached by a body callee only. -func crossModuleAnalysis() *v2.Analysis { +func crossModuleAnalysis() *schema.Analysis { const app = "can://x/x" - a, b := v2.ModuleID(app, "a.go"), v2.ModuleID(app, "b.go") - typeB, iface := v2.TypeID(b, "B"), v2.TypeID(b, "I") - f, g := v2.CallableID(a, "F()"), v2.CallableID(b, "G()") - ghost := v2.ExternalID(app, "lib", "Q") // call graph only - bodyOnly := v2.ExternalID(app, "lib", "E") // body callee only - return &v2.Analysis{ - IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 2, - Application: v2.Application{ + a, b := schema.ModuleID(app, "a.go"), schema.ModuleID(app, "b.go") + typeB, iface := schema.TypeID(b, "B"), schema.TypeID(b, "I") + f, g := schema.CallableID(a, "F()"), schema.CallableID(b, "G()") + ghost := schema.ExternalID(app, "lib", "Q") // call graph only + bodyOnly := schema.ExternalID(app, "lib", "E") // body callee only + return &schema.Analysis{ + IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 2, + Application: schema.Application{ IdentityVersion: 2, ID: app, Kind: "application", - SymbolTable: map[string]v2.Module{ + SymbolTable: map[string]schema.Module{ "a.go": {ID: a, Kind: "module", Package: "x", - Imports: []v2.Import{{Name: "b", Path: "b.go"}, {Name: "fmt", Path: "fmt"}}, - Types: map[string]v2.Type{"A": {ID: v2.TypeID(a, "A"), Kind: "struct", + Imports: []schema.Import{{Name: "b", Path: "b.go"}, {Name: "fmt", Path: "fmt"}}, + Types: map[string]schema.Type{"A": {ID: schema.TypeID(a, "A"), Kind: "struct", BaseTypes: []string{typeB, ghost, "raw.Unresolved"}, Interfaces: []string{iface}}}, - Functions: map[string]v2.Callable{"F()": {ID: f, Kind: "function", Signature: "F()", - Body: map[string]v2.BodyNode{ + Functions: map[string]schema.Callable{"F()": {ID: f, Kind: "function", Signature: "F()", + Body: map[string]schema.BodyNode{ "0": {Kind: "call", Callee: &g}, "1": {Kind: "call", Callee: new(bodyOnly)}, }}}, }, "b.go": {ID: b, Kind: "module", Package: "x", - Types: map[string]v2.Type{ + Types: map[string]schema.Type{ "B": {ID: typeB, Kind: "struct"}, "I": {ID: iface, Kind: "interface"}, }, - Functions: map[string]v2.Callable{"G()": {ID: g, Kind: "function", Signature: "G()"}}, + Functions: map[string]schema.Callable{"G()": {ID: g, Kind: "function", Signature: "G()"}}, }, }, - CallGraph: []v2.Edge{{Src: f, Dst: g, Weight: 1}, {Src: f, Dst: ghost, Weight: 1}}, - ExternalSymbols: map[string]v2.ExternalSymbol{ + CallGraph: []schema.Edge{{Src: f, Dst: g, Weight: 1}, {Src: f, Dst: ghost, Weight: 1}}, + ExternalSymbols: map[string]schema.ExternalSymbol{ bodyOnly: {ID: bodyOnly, Kind: "external", Name: "E", Module: "lib", Signature: "E"}, }, }, @@ -198,13 +198,13 @@ func TestStream_ParityWithProject(t *testing.T) { } } -// TestStream_ParityThroughEmitterStream: streamGraph over v2emit.Open equals Project(v2emit.Emit(...)). +// TestStream_ParityThroughEmitterStream: streamGraph over emit.Open equals Project(emit.Emit(...)). func TestStream_ParityThroughEmitterStream(t *testing.T) { for _, name := range []string{"dataflow", "chi", "generics", "storedlit", "rangefunc"} { in := buildL4Inputs(t, name) - want := Project(v2emit.Emit(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4)) + want := Project(emit.Emit(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4)) c := &collectStager{} - src := v2emit.Open(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4) + src := emit.Open(in.app, in.identity, in.dir, 4, "neo4j-gate", 3, in.l3, in.l4) if _, _, err := streamGraph(src, c); err != nil { t.Fatalf("%s: %v", name, err) } diff --git a/internal/options/options.go b/internal/options/options.go index 46e59f3..babe9b6 100644 --- a/internal/options/options.go +++ b/internal/options/options.go @@ -50,7 +50,7 @@ type AnalysisOptions struct { // LibraryModels is the --library-models JSON file overriding library // stand-in summaries at L4 (sdg.LoadModels). Empty = the defaults. LibraryModels string - // AnalyzerVersion is the analyzer's own version, recorded in the v2 + // AnalyzerVersion is the analyzer's own version, recorded in the // manifest's analyzer{} tag. Set by the CLI from its build-stamped value. AnalyzerVersion string // TargetFiles restricts analysis to specific files (incremental mode). diff --git a/internal/repository/replace_test.go b/internal/repository/replace_test.go index e7991e2..1642e94 100644 --- a/internal/repository/replace_test.go +++ b/internal/repository/replace_test.go @@ -4,12 +4,12 @@ import ( "reflect" "testing" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) // replaceFacts runs Facts on a project with the given go.mod and go.sum, whose // code imports the given paths. -func replaceFacts(t *testing.T, mod, sum string, imports ...string) map[string]schema.GoDependency { +func replaceFacts(t *testing.T, mod, sum string, imports ...string) map[string]model.GoDependency { t.Helper() root := t.TempDir() writeTree(t, root, map[string]string{"go.mod": mod, "go.sum": sum, "main.go": "package main\n"}) @@ -17,7 +17,7 @@ func replaceFacts(t *testing.T, mod, sum string, imports ...string) map[string]s if err != nil { t.Fatal(err) } - out := map[string]schema.GoDependency{} + out := map[string]model.GoDependency{} for _, d := range facts.Dependencies { out[d.Name] = d } @@ -37,7 +37,7 @@ require example.com/x v1.0.0 replace example.com/x => example.com/y v1.2.0 `, "example.com/y v1.2.0 h1:AAA=\nexample.com/y v1.2.0/go.mod h1:BBB=\n", "example.com/x/sub") - want := schema.GoDependency{ + want := model.GoDependency{ Name: "example.com/x", Ecosystem: "golang", Spec: "v1.0.0", Kind: "runtime", Direct: true, LockedVersion: "v1.2.0", LockedIn: "go.sum", ReplacedBy: "example.com/y@v1.2.0", DeclaredIn: "go.mod", ProvidesImports: []string{"example.com/x/sub"}, Prov: []string{"declared", "lockfile"}, diff --git a/internal/repository/repository.go b/internal/repository/repository.go index e65e901..4454fa9 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -1,5 +1,5 @@ // Package repository collects the repository-artifact layer (spec -// docs/design/specs/v2-artifacts.md): every non-.go project file as an artifact, +// docs/design/specs/artifacts.md): every non-.go project file as an artifact, // and the go.mod requires as dependencies, with go.sum supplying locked versions. // // It reads files outside the Go source the symbol table sees, so it runs on every @@ -22,7 +22,7 @@ import ( "strings" "sync" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" "golang.org/x/mod/modfile" "golang.org/x/mod/module" @@ -68,7 +68,7 @@ var outputFileNames = map[string]bool{"analysis.json": true, "graph.cypher": tru // recorded under the link's path (a symlinked go.mod, #73). Any other symlink, // including one to a directory, is skipped, so discovery never leaves the // project root. -func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { +func Discover(root string, opts Options) (map[string]model.GoArtifact, error) { absRoot, err := resolveDir(root) if err != nil { return nil, fmt.Errorf("resolving project root: %w", err) @@ -96,7 +96,7 @@ func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { } skipDirs[d] = true } - out := map[string]schema.GoArtifact{} + out := map[string]model.GoArtifact{} err = filepath.WalkDir(absRoot, func(p string, d fs.DirEntry, werr error) error { rel, err := filepath.Rel(absRoot, p) if err != nil { @@ -247,28 +247,28 @@ func resolveDir(p string) (string, error) { // info is the walk's view of the entry. The opened file must be that same file, // so a path swapped for a symlink or a device between the walk and the open is // refused rather than read. -func readArtifact(abs string, info fs.FileInfo, rel string, captureText bool) (schema.GoArtifact, error) { +func readArtifact(abs string, info fs.FileInfo, rel string, captureText bool) (model.GoArtifact, error) { f, err := os.Open(abs) if err != nil { - return schema.GoArtifact{}, err + return model.GoArtifact{}, err } defer f.Close() st, err := f.Stat() if err != nil { - return schema.GoArtifact{}, err + return model.GoArtifact{}, err } if !st.Mode().IsRegular() || !os.SameFile(info, st) { - return schema.GoArtifact{}, fmt.Errorf("replaced during analysis; not the file the walk saw") + return model.GoArtifact{}, fmt.Errorf("replaced during analysis; not the file the walk saw") } buf := copyBufs.Get().(*[]byte) defer copyBufs.Put(buf) s := newSniff() if _, err := io.CopyBuffer(s, onlyReader{f}, *buf); err != nil { - return schema.GoArtifact{}, err + return model.GoArtifact{}, err } s.finish() - art := schema.GoArtifact{ + art := model.GoArtifact{ Path: rel, Format: formatOf(rel, s.binary()), SizeBytes: s.size, @@ -287,11 +287,11 @@ func readArtifact(abs string, info fs.FileInfo, rel string, captureText bool) (s // Second read, for the text only. if _, err := f.Seek(0, io.SeekStart); err != nil { - return schema.GoArtifact{}, err + return model.GoArtifact{}, err } text, err := readText(f, s.size, s.sum(), *buf) if err != nil { - return schema.GoArtifact{}, err + return model.GoArtifact{}, err } art.Source = text art.Extraction = "full" @@ -367,12 +367,12 @@ func formatOf(rel string, binary bool) string { // Facts builds the repository layer for a project: its artifacts, and the // dependencies declared by the root go.mod. imports are the project's import // paths (from the symbol table), used to fill provides_imports. -func Facts(root string, app *schema.GoApplication, opts Options) (*schema.RepositoryFacts, error) { +func Facts(root string, app *model.GoApplication, opts Options) (*model.RepositoryFacts, error) { artifacts, err := Discover(root, opts) if err != nil { return nil, err } - facts := &schema.RepositoryFacts{Artifacts: artifacts} + facts := &model.RepositoryFacts{Artifacts: artifacts} modPath := filepath.Join(root, "go.mod") modData, err := os.ReadFile(modPath) if err != nil { @@ -395,9 +395,9 @@ func Facts(root string, app *schema.GoApplication, opts Options) (*schema.Reposi } replaces := replaceIndex(f.Replace) - deps := make([]schema.GoDependency, 0, len(f.Require)) + deps := make([]model.GoDependency, 0, len(f.Require)) for _, r := range f.Require { - dep := schema.GoDependency{ + dep := model.GoDependency{ Name: r.Mod.Path, Ecosystem: Ecosystem, Spec: r.Mod.Version, @@ -532,7 +532,7 @@ func LoadImports(root string, tests bool) ([]string, error) { return slices.Sorted(maps.Keys(seen)), nil } -func projectImports(app *schema.GoApplication) []string { +func projectImports(app *model.GoApplication) []string { seen := map[string]bool{} for _, f := range app.SymbolTable { for _, imp := range f.Imports { @@ -550,7 +550,7 @@ func projectImports(app *schema.GoApplication) []string { // assignImports gives each import to the dependency whose module path is its // longest prefix (the path itself, or a path under it followed by "/"). An // import matching no requirement is not recorded. -func assignImports(deps []schema.GoDependency, imports []string) { +func assignImports(deps []model.GoDependency, imports []string) { for _, imp := range imports { best := -1 bestLen := -1 diff --git a/internal/repository/repository_test.go b/internal/repository/repository_test.go index 80426ca..75d1d56 100644 --- a/internal/repository/repository_test.go +++ b/internal/repository/repository_test.go @@ -6,7 +6,7 @@ import ( "reflect" "testing" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) // writeTree creates the files under root (path → content). A NUL in content @@ -25,12 +25,12 @@ func writeTree(t *testing.T, root string, files map[string]string) { } // appWithImports is a symbol-table stub carrying the given import paths in one file. -func appWithImports(paths ...string) *schema.GoApplication { - imps := make([]schema.GoImport, 0, len(paths)) +func appWithImports(paths ...string) *model.GoApplication { + imps := make([]model.GoImport, 0, len(paths)) for _, p := range paths { - imps = append(imps, schema.GoImport{Module: p}) + imps = append(imps, model.GoImport{Module: p}) } - return &schema.GoApplication{SymbolTable: map[string]schema.GoFile{"main.go": {Imports: imps}}} + return &model.GoApplication{SymbolTable: map[string]model.GoFile{"main.go": {Imports: imps}}} } const goMod = `module example.com/app @@ -69,7 +69,7 @@ func TestFacts_DependenciesLocksAndImports(t *testing.T) { t.Fatal(err) } - want := []schema.GoDependency{ + want := []model.GoDependency{ {Name: "cloud.google.com/go", Ecosystem: "golang", Spec: "v0.1.0", Kind: "runtime", Direct: true, DeclaredIn: "go.mod", ProvidesImports: []string{"cloud.google.com/go/storage"}, Prov: []string{"declared"}}, {Name: "cloud.google.com/go/auth", Ecosystem: "golang", Spec: "v0.2.0", Kind: "runtime", Direct: true, @@ -105,7 +105,7 @@ func TestFacts_ArtifactsClassifiedAndSkipped(t *testing.T) { if err != nil { t.Fatal(err) } - got := map[string]schema.GoArtifact{} + got := map[string]model.GoArtifact{} for p, a := range facts.Artifacts { got[p] = a } diff --git a/internal/schema/v2/ids.go b/internal/schema/ids.go similarity index 98% rename from internal/schema/v2/ids.go rename to internal/schema/ids.go index 817f3dd..55add2e 100644 --- a/internal/schema/v2/ids.go +++ b/internal/schema/ids.go @@ -1,4 +1,4 @@ -package v2 +package schema import ( "crypto/sha256" @@ -101,7 +101,7 @@ func ModuleID(appID, relPath string) string { } // PackageID builds the id of a :Package node: the version-less purl -// pkg:/ (spec v2-artifacts). The sibling analyzers use the same +// pkg:/ (spec artifacts). The sibling analyzers use the same // form (pkg:pypi/, pkg:npm/), so every analyzer of one repository // converges on one package node. It is the one place a package id is built. func PackageID(ecosystem, name string) string { @@ -234,7 +234,7 @@ func NewSpan(startLine, startCol, endLine, endCol, fromByte, toByte int) Span { } // Slice returns the node's source text: module source sliced by the span's byte -// offsets. It is the O(1) replacement for the v1 per-node `code` field. Out-of- +// offsets. It is the O(1) way to recover a node's text. Out-of- // range or inverted offsets yield "" rather than panicking, so a malformed span // degrades gracefully. func (s Span) Slice(source string) string { diff --git a/internal/schema/v2/ids_external_test.go b/internal/schema/ids_external_test.go similarity index 99% rename from internal/schema/v2/ids_external_test.go rename to internal/schema/ids_external_test.go index 10426e4..ea12c46 100644 --- a/internal/schema/v2/ids_external_test.go +++ b/internal/schema/ids_external_test.go @@ -1,4 +1,4 @@ -package v2 +package schema import "testing" diff --git a/internal/schema/v2/ids_member_test.go b/internal/schema/ids_member_test.go similarity index 99% rename from internal/schema/v2/ids_member_test.go rename to internal/schema/ids_member_test.go index 4cb931a..af715d9 100644 --- a/internal/schema/v2/ids_member_test.go +++ b/internal/schema/ids_member_test.go @@ -1,4 +1,4 @@ -package v2 +package schema import "testing" diff --git a/internal/schema/v2/ids_test.go b/internal/schema/ids_test.go similarity index 99% rename from internal/schema/v2/ids_test.go rename to internal/schema/ids_test.go index 8ad5a74..ecdd68c 100644 --- a/internal/schema/v2/ids_test.go +++ b/internal/schema/ids_test.go @@ -1,4 +1,4 @@ -package v2 +package schema import "testing" diff --git a/internal/schema/v2/namespace_test.go b/internal/schema/namespace_test.go similarity index 99% rename from internal/schema/v2/namespace_test.go rename to internal/schema/namespace_test.go index bfcfa7b..325fa87 100644 --- a/internal/schema/v2/namespace_test.go +++ b/internal/schema/namespace_test.go @@ -1,4 +1,4 @@ -package v2 +package schema import ( "encoding/json" diff --git a/internal/schema/schema.go b/internal/schema/schema.go index f03fea5..d9e725a 100644 --- a/internal/schema/schema.go +++ b/internal/schema/schema.go @@ -1,279 +1,402 @@ -// Package schema defines the canonical data contract for codeanalyzer-go output. +// Package schema defines the canonical CLDK schema types that codeanalyzer-go +// emits. It is a faithful transcript of the keystone +// (designing-cldk-changes/references/canonical-schema.md) and the Go-specific +// leaf additions recorded in the repo-root CLAUDE.md § Schema decisions. // -// The root object is GoApplication{symbol_table, call_graph}. Every field uses -// snake_case JSON keys so the Python SDK's Pydantic models parse it without -// transformation. Design decisions are recorded in .claude/SCHEMA_DECISIONS.md. +// The model is ONE additive containment tree +// (application → module → type → callable → body) with typed edge overlays +// laid over it (a Code Property Graph). This package declares the L1 tree, the +// L2 refinement/edge slots, the L3 body completion (statement nodes, body +// node id/parent, the callable's cfg/cdg/ddg) and the L4 fields (the envelope's +// degraded marker, body node `of`, a callable's summary, the application's +// param_in/param_out, an external symbol's receiver and body). The L4 fields +// are all omitempty and absent below -a 4; they reuse the L1-L3 ids/spans +// unchanged. +// +// Conventions from the keystone, held here: +// - snake_case JSON keys everywhere, so one set of SDK models parses every +// analyzer. +// - a fact is present or absent; there is no null, EXCEPT the one sanctioned +// `callee: null` refinement slot on a call node (null at L1, backfilled at +// L2). Absence is the "no fact" encoding — `omitempty` on optional fields. +// - open-vocabulary fields (prov, tags) are plain strings. package schema -import "go/token" +import "encoding/json" -// ─── Leaf models ───────────────────────────────────────────────────────────── +// SchemaVersion is the canonical schema major this package targets. +const SchemaVersion = "2.0.0" -// GoImport represents a single import declaration in a Go source file. -type GoImport struct { - Module string `json:"module"` - Alias string `json:"alias,omitempty"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` +// Language is the analyzer's language tag in the manifest and `can://///…`. +const Language = "go" + +// ─── Positioning ─────────────────────────────────────────────────────────── + +// Span is the one universal node attribute: where in source the node lives. +// line:col addresses and displays; bytes slices module.source in O(1). Byte +// offsets are UTF-8 offsets into module.source (Go source is natively UTF-8). +type Span struct { + // Start is [line, col] of the first byte (1-based line, 1-based col). + Start [2]int `json:"start"` + // End is [line, col] one past the last byte. + End [2]int `json:"end"` + // Bytes is [from, to) UTF-8 byte offsets into module.source. + Bytes [2]int `json:"bytes"` +} + +// ─── Root envelope ─────────────────────────────────────────────────────────── + +// Analysis is the top-level payload written to analysis.json / stdout. Its +// siblings of `application` carry the manifest; consumers read `max_level` +// rather than sniffing for keys. k_limit (the field-path depth bound of the +// L3 and L4 access paths) is present only at max_level >= 3. +type Analysis struct { + IdentityVersion int `json:"identity_version"` + SchemaVersion string `json:"schema_version"` + Language string `json:"language"` + MaxLevel int `json:"max_level"` + KLimit int `json:"k_limit,omitempty"` + Analyzer AnalyzerTag `json:"analyzer"` + Application Application `json:"application"` + // Degraded records the L4 degradation markers (spec §4.15); absent when + // the run degraded nothing and below -a 4. + Degraded []Degraded `json:"degraded,omitempty"` +} + +// Degraded is one degradation marker: an L4 step that fell back to a coarser +// result. Code is an open vocabulary of plain strings (spec §4.15); Detail, +// Packages and Callables say what was affected. +type Degraded struct { + Code string `json:"code"` + Detail string `json:"detail,omitempty"` + Packages []string `json:"packages,omitempty"` + Callables []string `json:"callables,omitempty"` } -// GoComment represents a comment (line, block, or doc comment). -type GoComment struct { - Content string `json:"content"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` - StartColumn int `json:"start_column"` - EndColumn int `json:"end_column"` - IsDocComment bool `json:"is_doc_comment"` +// AnalyzerTag identifies the producing analyzer and version. +type AnalyzerTag struct { + Name string `json:"name"` + Version string `json:"version"` } -// GoParameter represents a single parameter of a callable. -type GoParameter struct { +// Application is the root node of the containment tree. +type Application struct { + IdentityVersion int `json:"identity_version"` + ApplicationName string `json:"application_name"` + // Name is the application's name: the same value as ApplicationName (additive, + // spec application-name-field). ApplicationName is kept unchanged. + Name string `json:"name"` + IdentityNamespace string `json:"identity_namespace"` + // ID is `can:///` — the app segment is outermost, so a polyglot + // app shares one prefix across languages. is the --app-name value (default: input dir base name). + ID string `json:"id"` + Kind string `json:"kind"` // always "application" + // SymbolTable is the L1 named map keyed by relative file path. + SymbolTable map[string]Module `json:"symbol_table"` + // CallGraph holds the L2 cross-function edges (callable → callable). Empty + // at L1. + CallGraph []Edge `json:"call_graph"` + // ExternalSymbols holds the out-of-project (library) callables the call graph + // reaches, keyed by their `can:////@external//` id. + // Absent when the analysis saw no library call. + ExternalSymbols map[string]ExternalSymbol `json:"external_symbols,omitempty"` + // Artifacts holds every non-.go project file, keyed by its repo-relative path + // (spec artifacts). Level-independent; absent when the project has no files. + Artifacts map[string]Artifact `json:"artifacts,omitempty"` + // Dependencies holds the go.mod requires, sorted by module path. Absent when + // the project has no root go.mod. + Dependencies []Dependency `json:"dependencies,omitempty"` + // ParamIn and ParamOut are the L4 interprocedural parameter edges between + // global body-node ids. Absent below -a 4. + ParamIn []ParamEdge `json:"param_in,omitempty"` + ParamOut []ParamEdge `json:"param_out,omitempty"` +} + +// ParamEdge is an L4 interprocedural parameter edge (call-site actual → +// callee formal for param_in, callee formal/return → call-site result for +// param_out) on the access path Var. +type ParamEdge struct { + Src string `json:"src"` + Dst string `json:"dst"` + Var string `json:"var"` +} + +// ExternalSymbol is a library callable that call-graph edges and call nodes +// target but whose body is not in the project. It is a leaf node: identity and +// signature only. +type ExternalSymbol struct { + ID string `json:"id"` + Kind string `json:"kind"` // always "external" + Name string `json:"name"` + // Module is the package import path the symbol lives in. + Module string `json:"module"` + // Signature is the id's last segment: [Type.]Name, no import-path prefix. + Signature string `json:"signature"` + Parameters []ExternalParameter `json:"parameters"` + ReturnType string `json:"return_type,omitempty"` + // Receiver is the method receiver (absent on a plain function): the name + // is the receiver variable, or _recv when unnamed or `_`; the type is the + // origin's receiver type string. + Receiver *ExternalParameter `json:"receiver,omitempty"` + // Body holds the L4 stand-in body nodes of a library callee (spec §6). + Body map[string]BodyNode `json:"body,omitempty"` +} + +// ExternalParameter is a library callee's formal parameter. It has no span: the +// declaration is not in the project, so there is no location to slice. +type ExternalParameter struct { Name string `json:"name"` Type string `json:"type"` - IsVariadic bool `json:"is_variadic"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` + IsVariadic bool `json:"is_variadic,omitempty"` } -// GoVariableDeclaration represents a variable declaration (var/short-assign). -type GoVariableDeclaration struct { - Name string `json:"name"` - Type string `json:"type,omitempty"` - Initializer string `json:"initializer,omitempty"` - Scope string `json:"scope"` // "package" | "function" - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` - StartColumn int `json:"start_column"` - EndColumn int `json:"end_column"` +// ─── module (per-file compilation unit) ─────────────────────────────────────── + +// Module is one Go source file: the L1 per-file container. +type Module struct { + ID string `json:"id"` + Kind string `json:"kind"` // always "module" + Span Span `json:"span"` + // StartLine and EndLine equal span.start[0] and span.end[0] (the whole file). + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + // Package is the Go package the file belongs to. + Package string `json:"package"` + // Source is the WHOLE file's text, stored once. Every node's text slices + // from this via its span.bytes; there is no per-node `code`. + Source string `json:"source"` + // Imports are the file's import declarations. + Imports []Import `json:"imports"` + // Types is the named map of type declarations in the file. + Types map[string]Type `json:"types"` + // Functions is the named map of module-level callables (keyed by signature). + Functions map[string]Callable `json:"functions"` + // ContentHash supports incremental caching; it is not identity. + ContentHash string `json:"content_hash,omitempty"` } -// GoField represents a struct field, including its struct tags. -type GoField struct { - Name string `json:"name"` - Type string `json:"type"` - Comments []GoComment `json:"comments"` - Tags map[string]string `json:"tags"` // parsed struct tags, e.g. {"json": "name,omitempty"} - IsExported bool `json:"is_exported"` - IsEmbedded bool `json:"is_embedded"` // anonymous/embedded field - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` +// Import is a single import declaration. +type Import struct { + Name string `json:"name"` // imported package name + Path string `json:"path"` // import path, e.g. "hash/fnv" + Alias string `json:"alias,omitempty"` // present only when aliased + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` } -// GoSymbol represents a symbol accessed inside a callable. -type GoSymbol struct { - Name string `json:"name"` - Scope string `json:"scope"` // "local" | "package" | "external" - Kind string `json:"kind"` // "variable" | "function" | "type" | "constant" - Type string `json:"type,omitempty"` - QualifiedName string `json:"qualified_name,omitempty"` - IsBuiltin bool `json:"is_builtin"` - Lineno int `json:"lineno"` - ColOffset int `json:"col_offset"` +// ─── type ───────────────────────────────────────────────────────────────────── + +// Type is a named Go type. Kind is the specific type-declaration shape, not a +// pile of is_* booleans. +type Type struct { + ID string `json:"id"` + Kind string `json:"kind"` // struct | interface | alias | defined + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + // Signature is the type's full import-qualified name (one signatureOf()). The + // id carries only the bare type name, so this is where the package path lives. + Signature string `json:"signature"` + // BaseTypes are embedded type ids (struct/interface embedding — the explicit + // spine). + BaseTypes []string `json:"base_types,omitempty"` + // Interfaces are ids of interfaces this type is computed to satisfy via + // method-set matching (Go's structural implementation). + Interfaces []string `json:"interfaces,omitempty"` + // Callables are the type's methods, resolved to their receiver type + // regardless of source location. Keyed by signature. + Callables map[string]Callable `json:"callables"` + // Fields are the struct fields, keyed by name. + Fields map[string]Field `json:"fields,omitempty"` } -// ─── Call site ──────────────────────────────────────────────────────────────── - -// GoCallsite represents a single call expression inside a callable. -// callee_signature is null when first recorded; the resolver backfills it -// during call-graph construction (never during symbol-table build). -type GoCallsite struct { - MethodName string `json:"method_name"` - ReceiverExpr string `json:"receiver_expr,omitempty"` - ReceiverType string `json:"receiver_type,omitempty"` - ArgumentTypes []string `json:"argument_types"` - ReturnType string `json:"return_type,omitempty"` - CalleeSignature *string `json:"callee_signature"` // null until resolved - // CalleeImportPath is the callee's package import path, set only when the - // resolved callee is an external (library) function; see GoApplication.Externals. - CalleeImportPath string `json:"callee_import_path,omitempty"` - IsConstructorCall bool `json:"is_constructor_call"` - IsGoroutine bool `json:"is_goroutine"` // true when preceded by `go` keyword - IsDeferred bool `json:"is_deferred,omitempty"` // true when preceded by `defer` keyword - StartLine int `json:"start_line"` - StartColumn int `json:"start_column"` - EndLine int `json:"end_line"` - EndColumn int `json:"end_column"` - // Lparen is the call's raw CallExpr.Lparen in the builder's FileSet: the - // in-memory join key from an L1 site to its *ast.CallExpr (L3 body nodes, - // and go/ssa CallCommon.Pos() at L4). Never serialized; meaningless once - // the FileSet is gone. - Lparen token.Pos `json:"-"` +// Field is a struct field. +type Field struct { + ID string `json:"id"` + Kind string `json:"kind"` // always "field" + Type string `json:"type"` + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` } -// ─── Callable ───────────────────────────────────────────────────────────────── +// ─── callable ───────────────────────────────────────────────────────────────── -// GoCallable represents a function, method, or function literal in Go. -// receiver_type / receiver_name are non-empty for methods; empty for functions. -type GoCallable struct { - Name string `json:"name"` - // Path is the declaring file (a symbol_table key). A closure carries its - // enclosing callable's declaring file, so v1 inner_callables have a path. - Path string `json:"path"` - Signature string `json:"signature"` // signatureOf() output — edge id - Comments []GoComment `json:"comments"` - Parameters []GoParameter `json:"parameters"` - ReturnType string `json:"return_type"` // joined, e.g. "(int, error)" - ReturnTypes []string `json:"return_types"` // Go extension: individual return types - Code string `json:"code,omitempty"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` - CodeStartLine int `json:"code_start_line"` - AccessedSymbols []GoSymbol `json:"accessed_symbols"` - CallSites []GoCallsite `json:"call_sites"` - InnerCallables map[string]GoCallable `json:"inner_callables"` - LocalVariables []GoVariableDeclaration `json:"local_variables"` - CyclomaticComplexity int `json:"cyclomatic_complexity"` - IsEntrypoint bool `json:"is_entrypoint"` - EntrypointFramework string `json:"entrypoint_framework,omitempty"` - ReceiverType string `json:"receiver_type,omitempty"` // e.g. "*MyStruct" - ReceiverName string `json:"receiver_name,omitempty"` // e.g. "r" - IsExported bool `json:"is_exported"` +// Callable is a function, method, or closure. span.bytes → get_method_body = +// module.source[bytes]. +type Callable struct { + ID string `json:"id"` + Kind string `json:"kind"` // function | method | lambda + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + // Signature is the full import-qualified name (one signatureOf()). The id + // carries only the bare member name, so this field is where the package path lives. + Signature string `json:"signature"` + // SourceFile names the callable's declaring file (a symbol_table key) when it + // differs from the module this callable is nested under — the Go case where a + // method is declared in a different file than its receiver type, and every + // closure (nested closures included) inside such a method. When set, + // Span.Bytes index symbol_table[SourceFile].source, NOT the nesting module's + // source; text = symbol_table[SourceFile].source[Span.Bytes]. Absent (the + // common case) means the declaring file is the nesting module. See CLAUDE.md + // § Schema decisions → callable.source_file and docs/design/specs/l1-emission.md. + SourceFile string `json:"source_file,omitempty"` + // Parameters are the ordered formal parameters. + Parameters []Parameter `json:"parameters"` + // ReturnType is the joined return type, e.g. "(int, error)". + ReturnType string `json:"return_type,omitempty"` + // ErrorChannel is the generalized error surface: populated from error-typed + // returns (those returns remain in ReturnType too). + ErrorChannel []string `json:"error_channel,omitempty"` + // Metrics is an extensible metrics map (e.g. {"cyclomatic": 3}). + Metrics map[string]int `json:"metrics,omitempty"` + // Body holds call nodes at L1 (keyed by local id), completing at L3. + Body map[string]BodyNode `json:"body"` + // Cfg, Cdg and Ddg are the L3 intra-callable edge lists; endpoints are + // local body keys. Absent below L3 and for a callable with no body. + Cfg []CfgEdge `json:"cfg,omitempty"` + Cdg []CdgEdge `json:"cdg,omitempty"` + Ddg []DdgEdge `json:"ddg,omitempty"` + // Summary is the L4 summary edge list (formal-in → formal-out through the + // callable); endpoints are local body keys. Absent below -a 4. + Summary []SummaryEdge `json:"summary,omitempty"` + // Callables are nested closures / function literals, each with its own + // can:// id. + Callables map[string]Callable `json:"callables,omitempty"` } -// ─── Type (struct or interface) ─────────────────────────────────────────────── +// Parameter is a single formal parameter. +type Parameter struct { + Name string `json:"name"` + Type string `json:"type"` + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + IsVariadic bool `json:"is_variadic,omitempty"` +} -// GoType represents a named Go type — either a struct (is_interface=false) or -// an interface (is_interface=true). This unified model mirrors Go's native type -// system where both are types.Named with different Underlying() values. -// -// base_types carries: embedded struct types (for structs) and the method-set -// signatures of satisfied interfaces (for both) — the Go analog of base_classes. -type GoType struct { - Name string `json:"name"` - Signature string `json:"signature"` // signatureOf() output - Comments []GoComment `json:"comments"` - Code string `json:"code,omitempty"` - IsInterface bool `json:"is_interface"` - TypeKind string `json:"type_kind,omitempty"` // struct | interface | alias | defined - IsExported bool `json:"is_exported"` - Fields []GoField `json:"fields"` // empty for interfaces - Methods map[string]GoCallable `json:"methods"` // sig → callable - BaseTypes []string `json:"base_types"` // embedded types + satisfied interface sigs - InnerTypes map[string]GoType `json:"inner_types"` // Go doesn't nest, but preserves spine - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` +// ─── body nodes ──────────────────────────────────────────────────────────────── + +// BodyNode is a node inside a callable's body, keyed by its local id +// (line:col for real nodes, "@entry"/"@exit" for the synthetic ones). At L1 +// the only kind emitted is "call"; L3 adds statement | branch | loop | switch +// | return | entry | exit. +type BodyNode struct { + Kind string `json:"kind"` // "call" at L1 + // ID is the node's global ordinal id, v2.GlobalOrdinal(callable id, key). + // Emitted at every level (from L1, R15 — Python parity), on every body + // node. + ID string `json:"id,omitempty"` + // Span is the node's source range. Absent (zero) only on the synthetic + // entry/exit nodes, which have no source. + Span Span `json:"span,omitzero"` + // StartLine and EndLine equal span.start[0] and span.end[0]; absent with the span. + StartLine int `json:"start_line,omitempty"` + EndLine int `json:"end_line,omitempty"` + // Parent is, at L3+, the local key of the statement a satellite call + // node is nested in (the sanctioned parent refinement). Absent on CFG + // nodes. + Parent string `json:"parent,omitempty"` + // Callee is the sanctioned null→id refinement slot on a call node: null at + // L1, backfilled to a callable id at L2. A pointer with NO omitempty so it + // always serializes — as JSON null at L1 (the one place null is allowed), + // as an id once backfilled. The keystone requires the field to be present. + Callee *string `json:"callee"` + // IsGoroutine is true when the call is preceded by `go`. + IsGoroutine bool `json:"is_goroutine,omitempty"` + // IsDeferred is true when the call is preceded by `defer`. + IsDeferred bool `json:"is_deferred,omitempty"` + // Of names the value an L4 vertex carries (, :, a + // parameter name, :, :::). Absent below + // -a 4 and on L1-L3 nodes. + Of string `json:"of,omitempty"` } -// ─── File (Module analog) ───────────────────────────────────────────────────── - -// GoFile is the Module analog for Go: one compilation unit (source file). -// symbol_table is keyed by file path relative to the project root. -type GoFile struct { - FilePath string `json:"file_path"` - PackageName string `json:"module_name"` // JSON key = module_name for spine compat - Imports []GoImport `json:"imports"` - Comments []GoComment `json:"comments"` - Types map[string]GoType `json:"classes"` // JSON key = classes for spine compat - Functions map[string]GoCallable `json:"functions"` - Variables []GoVariableDeclaration `json:"variables"` - // Caching metadata - ContentHash *string `json:"content_hash"` - LastModified *float64 `json:"last_modified"` - FileSize *int64 `json:"file_size"` +// SummaryEdge is an L4 summary edge between two local body keys of one callable. +type SummaryEdge struct { + Src string `json:"src"` + Dst string `json:"dst"` } -// ─── Call graph edge ────────────────────────────────────────────────────────── - -// GoCallEdge is an identity-only call-graph edge. source and target are -// GoCallable.signature strings that must exist in the symbol table. -type GoCallEdge struct { - Source string `json:"source"` - Target string `json:"target"` - Type string `json:"type"` // always "CALL_DEP" - Weight int `json:"weight"` // accumulated when merging backends - Provenance []string `json:"provenance"` // e.g. ["go/types"] - Tags map[string]string `json:"tags"` - - // SourcePath is the relative file in which the source callable is declared. - // A signature is not globally unique for package-level init functions: Go - // permits many `func init()` per package (one per file), all sharing the - // signature ".init". Those are distinct callables with distinct - // can:// ids (the id embeds the declaring file via its module), so the v2 - // emitter needs this to resolve the edge's source to the SPECIFIC init that - // owns the call site rather than to an arbitrary one. Empty for callables - // whose signature is already unique (the common case). Internal-only; not - // part of the v2 output schema. - SourcePath string `json:"-"` - - // TargetPath is the relative file declaring the target callable, set only - // when the signature alone may not name it: a VTA target can be a closure - // of a package-level init (".init.closure_1" repeats once per file - // with an init). Empty for L2 edges (a static call never targets an init - // or a closure) and for an external target. Internal-only, like SourcePath. - TargetPath string `json:"-"` +// MarshalJSON writes the callee key on call nodes only: it is the call +// node's refinement slot (always present there, null until resolved), and a +// statement / control / synthetic node has no callee fact to carry. +func (n BodyNode) MarshalJSON() ([]byte, error) { + type plain BodyNode + if n.Kind == "call" { + return json.Marshal(plain(n)) + } + return json.Marshal(struct { + plain + Callee *string `json:"callee,omitempty"` + }{plain: plain(n)}) } -// ─── Root object ────────────────────────────────────────────────────────────── - -// GoApplication is the root of analysis.json. The SDK facade deserializes this. -type GoApplication struct { - SymbolTable map[string]GoFile `json:"symbol_table"` // file_path → GoFile - CallGraph []GoCallEdge `json:"call_graph"` // identity-only edges - Entrypoints map[string][]GoEntrypoint `json:"entrypoints"` // optional, default {} - // Externals holds the library (out-of-project) functions the resolver saw - // called, keyed by the full callee signature (".[Type.]Name"). - Externals map[string]GoExternalCallee `json:"externals,omitempty"` - // Repository holds the repository-artifact facts (non-.go project files and - // go.mod/go.sum dependencies), set by the analyzer after symbol-table - // construction. Never cached or serialized in the v1 model: it is recomputed - // on every run, since it reads files outside the analyzed Go source. - Repository *RepositoryFacts `json:"-"` +// ─── edges ───────────────────────────────────────────────────────────────────── + +// CfgEdge is an L3 control-flow edge between two local body keys. Kind is a +// shared CFG edge kind or the Go add "defer_resume". +type CfgEdge struct { + Src string `json:"src"` + Dst string `json:"dst"` + Kind string `json:"kind"` } -// RepositoryFacts is the repository-artifact layer (spec v2-artifacts): every -// non-.go project file as an artifact, and the go.mod requires as dependencies. -type RepositoryFacts struct { - // Artifacts is keyed by repo-relative POSIX path. - Artifacts map[string]GoArtifact - // Dependencies is sorted by module path. - Dependencies []GoDependency +// CdgEdge is an L3 control-dependence edge between two local body keys. +type CdgEdge struct { + Src string `json:"src"` + Dst string `json:"dst"` } -// GoArtifact is one non-.go project file. -type GoArtifact struct { - Path string - Format string - Roles []string - SizeBytes int64 - SHA256 string - Source string // whole file text, only when --artifact-text is on - Extraction string // none | full +// DdgEdge is a data-dependence edge between two local body keys on the +// k-limited access path Var. Prov is ["ssa"] at L3 (syntactic reaching +// definitions; the keystone's token, shared with the siblings). +type DdgEdge struct { + Src string `json:"src"` + Dst string `json:"dst"` + Var string `json:"var"` + Prov []string `json:"prov"` } -// GoDependency is one go.mod require, evidence-tagged by go.sum. -type GoDependency struct { - Name string - Ecosystem string - Spec string - Kind string - Direct bool - LockedVersion string // go.sum version of Spec, when both its h1 and /go.mod lines exist - LockedIn string // path of the go.sum artifact that gave LockedVersion - ReplacedBy string // go.mod replace target: "@", or a local directory - DeclaredIn string // path of the go.mod artifact - ProvidesImports []string // project import paths that resolve to this module - Prov []string // declared | lockfile +// Edge is a typed edge overlay record. The list it lives in IS its type (there +// is no `type` field). src/dst are node ids; no dangling endpoints. +type Edge struct { + Src string `json:"src"` + Dst string `json:"dst"` + // Prov is open-vocabulary provenance, e.g. ["go/types"]. + Prov []string `json:"prov,omitempty"` + // Weight accumulates when merging edges from multiple backends. + Weight int `json:"weight,omitempty"` } -// GoExternalCallee describes a library function or method called from the -// project. Params exclude the receiver; unnamed parameters are named "_". -type GoExternalCallee struct { - ImportPath string `json:"import_path"` - Sig string `json:"signature"` // callee signature without the "." prefix - Name string `json:"name"` - Params []GoParameter `json:"parameters"` - ReturnType string `json:"return_type,omitempty"` - // Receiver is the method receiver (nil for a plain function): named by the - // receiver variable, or "_recv" when unnamed or "_"; typed by the origin's - // receiver type string. - Receiver *GoParameter `json:"receiver,omitempty"` +// Artifact is one non-.go project file. Its id is can:////artifact/. +// Source is the whole file text only under --artifact-text; otherwise absent. +type Artifact struct { + ID string `json:"id"` + Kind string `json:"kind"` // always "artifact" + Path string `json:"path"` + Format string `json:"format"` + Roles []string `json:"roles,omitempty"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` + Source string `json:"source,omitempty"` + Extraction string `json:"extraction"` // none | full } -// GoEntrypoint marks a callable as a framework entry point. -type GoEntrypoint struct { - Signature string `json:"signature"` - Framework string `json:"framework"` - DetectionSource string `json:"detection_source"` - Tags map[string]string `json:"tags"` +// Dependency is one declared module requirement from go.mod. Its package is +// pkg:/, version-less; the version lives on the record. +type Dependency struct { + Name string `json:"name"` + Ecosystem string `json:"ecosystem"` // always "golang" + Spec string `json:"spec"` // version required by go.mod + Kind string `json:"kind"` // always "runtime" (go.mod has no dev/optional split) + Direct bool `json:"direct"` // false for `// indirect` + LockedVersion string `json:"locked_version,omitempty"` + LockedIn string `json:"locked_in,omitempty"` // the go.sum artifact id that gave locked_version + ReplacedBy string `json:"replaced_by,omitempty"` // go.mod replace target: "@", or a local directory + DeclaredIn string `json:"declared_in"` // the go.mod artifact id + ProvidesImports []string `json:"provides_imports,omitempty"` + Prov []string `json:"prov"` // declared | lockfile } diff --git a/internal/schema/v2/testdata/namespaces.json b/internal/schema/testdata/namespaces.json similarity index 100% rename from internal/schema/v2/testdata/namespaces.json rename to internal/schema/testdata/namespaces.json diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go deleted file mode 100644 index 27d0468..0000000 --- a/internal/schema/v2/schema.go +++ /dev/null @@ -1,402 +0,0 @@ -// Package v2 defines the canonical CLDK schema (v2) types that codeanalyzer-go -// emits. It is a faithful transcript of the keystone -// (designing-cldk-changes/references/canonical-schema.md) and the Go-specific -// leaf additions recorded in the repo-root CLAUDE.md § Schema decisions. -// -// The model is ONE additive containment tree -// (application → module → type → callable → body) with typed edge overlays -// laid over it (a Code Property Graph). This package declares the L1 tree, the -// L2 refinement/edge slots, the L3 body completion (statement nodes, body -// node id/parent, the callable's cfg/cdg/ddg) and the L4 fields (the envelope's -// degraded marker, body node `of`, a callable's summary, the application's -// param_in/param_out, an external symbol's receiver and body). The L4 fields -// are all omitempty and absent below -a 4; they reuse the L1-L3 ids/spans -// unchanged. -// -// Conventions from the keystone, held here: -// - snake_case JSON keys everywhere, so one set of SDK models parses every -// analyzer. -// - a fact is present or absent; there is no null, EXCEPT the one sanctioned -// `callee: null` refinement slot on a call node (null at L1, backfilled at -// L2). Absence is the "no fact" encoding — `omitempty` on optional fields. -// - open-vocabulary fields (prov, tags) are plain strings. -package v2 - -import "encoding/json" - -// SchemaVersion is the canonical schema major this package targets. -const SchemaVersion = "2.0.0" - -// Language is the analyzer's language tag in the manifest and `can://///…`. -const Language = "go" - -// ─── Positioning ─────────────────────────────────────────────────────────── - -// Span is the one universal node attribute: where in source the node lives. -// line:col addresses and displays; bytes slices module.source in O(1). Byte -// offsets are UTF-8 offsets into module.source (Go source is natively UTF-8). -type Span struct { - // Start is [line, col] of the first byte (1-based line, 1-based col). - Start [2]int `json:"start"` - // End is [line, col] one past the last byte. - End [2]int `json:"end"` - // Bytes is [from, to) UTF-8 byte offsets into module.source. - Bytes [2]int `json:"bytes"` -} - -// ─── Root envelope ─────────────────────────────────────────────────────────── - -// Analysis is the top-level payload written to analysis.json / stdout. Its -// siblings of `application` carry the manifest; consumers read `max_level` -// rather than sniffing for keys. k_limit (the field-path depth bound of the -// L3 and L4 access paths) is present only at max_level >= 3. -type Analysis struct { - IdentityVersion int `json:"identity_version"` - SchemaVersion string `json:"schema_version"` - Language string `json:"language"` - MaxLevel int `json:"max_level"` - KLimit int `json:"k_limit,omitempty"` - Analyzer AnalyzerTag `json:"analyzer"` - Application Application `json:"application"` - // Degraded records the L4 degradation markers (spec §4.15); absent when - // the run degraded nothing and below -a 4. - Degraded []Degraded `json:"degraded,omitempty"` -} - -// Degraded is one degradation marker: an L4 step that fell back to a coarser -// result. Code is an open vocabulary of plain strings (spec §4.15); Detail, -// Packages and Callables say what was affected. -type Degraded struct { - Code string `json:"code"` - Detail string `json:"detail,omitempty"` - Packages []string `json:"packages,omitempty"` - Callables []string `json:"callables,omitempty"` -} - -// AnalyzerTag identifies the producing analyzer and version. -type AnalyzerTag struct { - Name string `json:"name"` - Version string `json:"version"` -} - -// Application is the root node of the containment tree. -type Application struct { - IdentityVersion int `json:"identity_version"` - ApplicationName string `json:"application_name"` - // Name is the application's name: the same value as ApplicationName (additive, - // spec v2-application-name-field). ApplicationName is kept unchanged. - Name string `json:"name"` - IdentityNamespace string `json:"identity_namespace"` - // ID is `can:///` — the app segment is outermost, so a polyglot - // app shares one prefix across languages. is the --app-name value (default: input dir base name). - ID string `json:"id"` - Kind string `json:"kind"` // always "application" - // SymbolTable is the L1 named map keyed by relative file path. - SymbolTable map[string]Module `json:"symbol_table"` - // CallGraph holds the L2 cross-function edges (callable → callable). Empty - // at L1. - CallGraph []Edge `json:"call_graph"` - // ExternalSymbols holds the out-of-project (library) callables the call graph - // reaches, keyed by their `can:////@external//` id. - // Absent when the analysis saw no library call. - ExternalSymbols map[string]ExternalSymbol `json:"external_symbols,omitempty"` - // Artifacts holds every non-.go project file, keyed by its repo-relative path - // (spec v2-artifacts). Level-independent; absent when the project has no files. - Artifacts map[string]Artifact `json:"artifacts,omitempty"` - // Dependencies holds the go.mod requires, sorted by module path. Absent when - // the project has no root go.mod. - Dependencies []Dependency `json:"dependencies,omitempty"` - // ParamIn and ParamOut are the L4 interprocedural parameter edges between - // global body-node ids. Absent below -a 4. - ParamIn []ParamEdge `json:"param_in,omitempty"` - ParamOut []ParamEdge `json:"param_out,omitempty"` -} - -// ParamEdge is an L4 interprocedural parameter edge (call-site actual → -// callee formal for param_in, callee formal/return → call-site result for -// param_out) on the access path Var. -type ParamEdge struct { - Src string `json:"src"` - Dst string `json:"dst"` - Var string `json:"var"` -} - -// ExternalSymbol is a library callable that call-graph edges and call nodes -// target but whose body is not in the project. It is a leaf node: identity and -// signature only. -type ExternalSymbol struct { - ID string `json:"id"` - Kind string `json:"kind"` // always "external" - Name string `json:"name"` - // Module is the package import path the symbol lives in. - Module string `json:"module"` - // Signature is the id's last segment: [Type.]Name, no import-path prefix. - Signature string `json:"signature"` - Parameters []ExternalParameter `json:"parameters"` - ReturnType string `json:"return_type,omitempty"` - // Receiver is the method receiver (absent on a plain function): the name - // is the receiver variable, or _recv when unnamed or `_`; the type is the - // origin's receiver type string. - Receiver *ExternalParameter `json:"receiver,omitempty"` - // Body holds the L4 stand-in body nodes of a library callee (spec §6). - Body map[string]BodyNode `json:"body,omitempty"` -} - -// ExternalParameter is a library callee's formal parameter. It has no span: the -// declaration is not in the project, so there is no location to slice. -type ExternalParameter struct { - Name string `json:"name"` - Type string `json:"type"` - IsVariadic bool `json:"is_variadic,omitempty"` -} - -// ─── module (per-file compilation unit) ─────────────────────────────────────── - -// Module is one Go source file: the L1 per-file container. -type Module struct { - ID string `json:"id"` - Kind string `json:"kind"` // always "module" - Span Span `json:"span"` - // StartLine and EndLine equal span.start[0] and span.end[0] (the whole file). - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` - // Package is the Go package the file belongs to. - Package string `json:"package"` - // Source is the WHOLE file's text, stored once. Every node's text slices - // from this via its span.bytes; there is no per-node `code`. - Source string `json:"source"` - // Imports are the file's import declarations. - Imports []Import `json:"imports"` - // Types is the named map of type declarations in the file. - Types map[string]Type `json:"types"` - // Functions is the named map of module-level callables (keyed by signature). - Functions map[string]Callable `json:"functions"` - // ContentHash supports incremental caching; it is not identity. - ContentHash string `json:"content_hash,omitempty"` -} - -// Import is a single import declaration. -type Import struct { - Name string `json:"name"` // imported package name - Path string `json:"path"` // import path, e.g. "hash/fnv" - Alias string `json:"alias,omitempty"` // present only when aliased - Span Span `json:"span"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` -} - -// ─── type ───────────────────────────────────────────────────────────────────── - -// Type is a named Go type. Kind is the specific type-declaration shape, not a -// pile of is_* booleans. -type Type struct { - ID string `json:"id"` - Kind string `json:"kind"` // struct | interface | alias | defined - Span Span `json:"span"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` - // Signature is the type's full import-qualified name (one signatureOf()). The - // id carries only the bare type name, so this is where the package path lives. - Signature string `json:"signature"` - // BaseTypes are embedded type ids (struct/interface embedding — the explicit - // spine). - BaseTypes []string `json:"base_types,omitempty"` - // Interfaces are ids of interfaces this type is computed to satisfy via - // method-set matching (Go's structural implementation). - Interfaces []string `json:"interfaces,omitempty"` - // Callables are the type's methods, resolved to their receiver type - // regardless of source location. Keyed by signature. - Callables map[string]Callable `json:"callables"` - // Fields are the struct fields, keyed by name. - Fields map[string]Field `json:"fields,omitempty"` -} - -// Field is a struct field. -type Field struct { - ID string `json:"id"` - Kind string `json:"kind"` // always "field" - Type string `json:"type"` - Span Span `json:"span"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` -} - -// ─── callable ───────────────────────────────────────────────────────────────── - -// Callable is a function, method, or closure. span.bytes → get_method_body = -// module.source[bytes]. -type Callable struct { - ID string `json:"id"` - Kind string `json:"kind"` // function | method | lambda - Span Span `json:"span"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` - // Signature is the full import-qualified name (one signatureOf()). The id - // carries only the bare member name, so this field is where the package path lives. - Signature string `json:"signature"` - // SourceFile names the callable's declaring file (a symbol_table key) when it - // differs from the module this callable is nested under — the Go case where a - // method is declared in a different file than its receiver type, and every - // closure (nested closures included) inside such a method. When set, - // Span.Bytes index symbol_table[SourceFile].source, NOT the nesting module's - // source; text = symbol_table[SourceFile].source[Span.Bytes]. Absent (the - // common case) means the declaring file is the nesting module. See CLAUDE.md - // § Schema decisions → callable.source_file and docs/design/specs/v2-l1-emission.md. - SourceFile string `json:"source_file,omitempty"` - // Parameters are the ordered formal parameters. - Parameters []Parameter `json:"parameters"` - // ReturnType is the joined return type, e.g. "(int, error)". - ReturnType string `json:"return_type,omitempty"` - // ErrorChannel is the generalized error surface: populated from error-typed - // returns (those returns remain in ReturnType too). - ErrorChannel []string `json:"error_channel,omitempty"` - // Metrics is an extensible metrics map (e.g. {"cyclomatic": 3}). - Metrics map[string]int `json:"metrics,omitempty"` - // Body holds call nodes at L1 (keyed by local id), completing at L3. - Body map[string]BodyNode `json:"body"` - // Cfg, Cdg and Ddg are the L3 intra-callable edge lists; endpoints are - // local body keys. Absent below L3 and for a callable with no body. - Cfg []CfgEdge `json:"cfg,omitempty"` - Cdg []CdgEdge `json:"cdg,omitempty"` - Ddg []DdgEdge `json:"ddg,omitempty"` - // Summary is the L4 summary edge list (formal-in → formal-out through the - // callable); endpoints are local body keys. Absent below -a 4. - Summary []SummaryEdge `json:"summary,omitempty"` - // Callables are nested closures / function literals, each with its own - // can:// id (replaces v1 InnerCallables). - Callables map[string]Callable `json:"callables,omitempty"` -} - -// Parameter is a single formal parameter. -type Parameter struct { - Name string `json:"name"` - Type string `json:"type"` - Span Span `json:"span"` - StartLine int `json:"start_line"` - EndLine int `json:"end_line"` - IsVariadic bool `json:"is_variadic,omitempty"` -} - -// ─── body nodes ──────────────────────────────────────────────────────────────── - -// BodyNode is a node inside a callable's body, keyed by its local id -// (line:col for real nodes, "@entry"/"@exit" for the synthetic ones). At L1 -// the only kind emitted is "call"; L3 adds statement | branch | loop | switch -// | return | entry | exit. -type BodyNode struct { - Kind string `json:"kind"` // "call" at L1 - // ID is the node's global ordinal id, v2.GlobalOrdinal(callable id, key). - // Emitted at every level (from L1, R15 — Python parity), on every body - // node. - ID string `json:"id,omitempty"` - // Span is the node's source range. Absent (zero) only on the synthetic - // entry/exit nodes, which have no source. - Span Span `json:"span,omitzero"` - // StartLine and EndLine equal span.start[0] and span.end[0]; absent with the span. - StartLine int `json:"start_line,omitempty"` - EndLine int `json:"end_line,omitempty"` - // Parent is, at L3+, the local key of the statement a satellite call - // node is nested in (the sanctioned parent refinement). Absent on CFG - // nodes. - Parent string `json:"parent,omitempty"` - // Callee is the sanctioned null→id refinement slot on a call node: null at - // L1, backfilled to a callable id at L2. A pointer with NO omitempty so it - // always serializes — as JSON null at L1 (the one place null is allowed), - // as an id once backfilled. The keystone requires the field to be present. - Callee *string `json:"callee"` - // IsGoroutine is true when the call is preceded by `go`. - IsGoroutine bool `json:"is_goroutine,omitempty"` - // IsDeferred is true when the call is preceded by `defer` (net-new vs v1). - IsDeferred bool `json:"is_deferred,omitempty"` - // Of names the value an L4 vertex carries (, :, a - // parameter name, :, :::). Absent below - // -a 4 and on L1-L3 nodes. - Of string `json:"of,omitempty"` -} - -// SummaryEdge is an L4 summary edge between two local body keys of one callable. -type SummaryEdge struct { - Src string `json:"src"` - Dst string `json:"dst"` -} - -// MarshalJSON writes the callee key on call nodes only: it is the call -// node's refinement slot (always present there, null until resolved), and a -// statement / control / synthetic node has no callee fact to carry. -func (n BodyNode) MarshalJSON() ([]byte, error) { - type plain BodyNode - if n.Kind == "call" { - return json.Marshal(plain(n)) - } - return json.Marshal(struct { - plain - Callee *string `json:"callee,omitempty"` - }{plain: plain(n)}) -} - -// ─── edges ───────────────────────────────────────────────────────────────────── - -// CfgEdge is an L3 control-flow edge between two local body keys. Kind is a -// shared CFG edge kind or the Go add "defer_resume". -type CfgEdge struct { - Src string `json:"src"` - Dst string `json:"dst"` - Kind string `json:"kind"` -} - -// CdgEdge is an L3 control-dependence edge between two local body keys. -type CdgEdge struct { - Src string `json:"src"` - Dst string `json:"dst"` -} - -// DdgEdge is a data-dependence edge between two local body keys on the -// k-limited access path Var. Prov is ["ssa"] at L3 (syntactic reaching -// definitions; the keystone's token, shared with the siblings). -type DdgEdge struct { - Src string `json:"src"` - Dst string `json:"dst"` - Var string `json:"var"` - Prov []string `json:"prov"` -} - -// Edge is a typed edge overlay record. The list it lives in IS its type (there -// is no `type` field). src/dst are node ids; no dangling endpoints. -type Edge struct { - Src string `json:"src"` - Dst string `json:"dst"` - // Prov is open-vocabulary provenance, e.g. ["go/types"]. - Prov []string `json:"prov,omitempty"` - // Weight accumulates when merging edges from multiple backends. - Weight int `json:"weight,omitempty"` -} - -// Artifact is one non-.go project file. Its id is can:////artifact/. -// Source is the whole file text only under --artifact-text; otherwise absent. -type Artifact struct { - ID string `json:"id"` - Kind string `json:"kind"` // always "artifact" - Path string `json:"path"` - Format string `json:"format"` - Roles []string `json:"roles,omitempty"` - SizeBytes int64 `json:"size_bytes"` - SHA256 string `json:"sha256"` - Source string `json:"source,omitempty"` - Extraction string `json:"extraction"` // none | full -} - -// Dependency is one declared module requirement from go.mod. Its package is -// pkg:/, version-less; the version lives on the record. -type Dependency struct { - Name string `json:"name"` - Ecosystem string `json:"ecosystem"` // always "golang" - Spec string `json:"spec"` // version required by go.mod - Kind string `json:"kind"` // always "runtime" (go.mod has no dev/optional split) - Direct bool `json:"direct"` // false for `// indirect` - LockedVersion string `json:"locked_version,omitempty"` - LockedIn string `json:"locked_in,omitempty"` // the go.sum artifact id that gave locked_version - ReplacedBy string `json:"replaced_by,omitempty"` // go.mod replace target: "@", or a local directory - DeclaredIn string `json:"declared_in"` // the go.mod artifact id - ProvidesImports []string `json:"provides_imports,omitempty"` - Prov []string `json:"prov"` // declared | lockfile -} diff --git a/internal/sdg/footprint.go b/internal/sdg/footprint.go index efdd424..3e267e4 100644 --- a/internal/sdg/footprint.go +++ b/internal/sdg/footprint.go @@ -12,7 +12,7 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/astwalk" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -139,7 +139,7 @@ func callGraph(in Input, d *dispatch) ([]Target, map[Target][]Target) { u := Target{Callable: site.unit} callees[u] = append(callees[u], ts...) } - l2 := map[dataflow.L3Key][]schema.GoCallEdge{} + l2 := map[dataflow.L3Key][]model.GoCallEdge{} for _, e := range in.CallGraph { k := dataflow.L3Key{Path: e.SourcePath, Signature: e.Source} l2[k] = append(l2[k], e) @@ -695,8 +695,8 @@ type formalIndex struct { in Input units map[dataflow.L3Key]dataflow.Unit decls map[dataflow.L3Key]*types.Func // project funcs and methods by (declaring file, signature) - strs map[dataflow.L3Key]schema.GoCallable - ext map[string]schema.GoExternalCallee + strs map[dataflow.L3Key]model.GoCallable + ext map[string]model.GoExternalCallee pkgByPath map[string]*types.Package } @@ -705,8 +705,8 @@ func newFormalIndex(in Input, d *dispatch) *formalIndex { in: in, units: make(map[dataflow.L3Key]dataflow.Unit, len(in.Units)), decls: map[dataflow.L3Key]*types.Func{}, - strs: map[dataflow.L3Key]schema.GoCallable{}, - ext: map[string]schema.GoExternalCallee{}, + strs: map[dataflow.L3Key]model.GoCallable{}, + ext: map[string]model.GoExternalCallee{}, pkgByPath: map[string]*types.Package{}, } for _, u := range in.Units { @@ -718,8 +718,8 @@ func newFormalIndex(in Input, d *dispatch) *formalIndex { for sig, e := range d.newExt { x.ext[sig] = e } - var walk func(path string, c schema.GoCallable) - walk = func(path string, c schema.GoCallable) { + var walk func(path string, c model.GoCallable) + walk = func(path string, c model.GoCallable) { x.strs[dataflow.L3Key{Path: path, Signature: c.Signature}] = c for _, ic := range c.InnerCallables { walk(ic.Path, ic) @@ -840,7 +840,7 @@ func (x *formalIndex) external(sig string) []formal { // libraryFunc looks up e's *types.Func: a function of its package's scope, // or a method (Sig "Type.Method") of a type it declares. -func (x *formalIndex) libraryFunc(e schema.GoExternalCallee) *types.Func { +func (x *formalIndex) libraryFunc(e model.GoExternalCallee) *types.Func { pkg := x.pkgByPath[e.ImportPath] if pkg == nil { return nil diff --git a/internal/sdg/footprint_test.go b/internal/sdg/footprint_test.go index fe80df7..d2220ad 100644 --- a/internal/sdg/footprint_test.go +++ b/internal/sdg/footprint_test.go @@ -11,7 +11,7 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) const configSpell = sdgPkg + "::Config" @@ -347,7 +347,7 @@ func TestFootprint_L2FallbackHonoursTargetPath(t *testing.T) { delete(d.sites, site) } } - in.CallGraph = []schema.GoCallEdge{{Source: src.Signature, SourcePath: src.Path, Target: b.Signature, TargetPath: b.Path}} + in.CallGraph = []model.GoCallEdge{{Source: src.Signature, SourcePath: src.Path, Target: b.Signature, TargetPath: b.Path}} _, callees := callGraph(in, d) if got, want := callees[Target{Callable: src}], []Target{{Callable: b}}; !slices.Equal(got, want) { t.Errorf("callees(%s) = %v, want %v", src.Signature, got, want) diff --git a/internal/sdg/ir.go b/internal/sdg/ir.go index a8224c9..4ab5634 100644 --- a/internal/sdg/ir.go +++ b/internal/sdg/ir.go @@ -5,8 +5,8 @@ // summaries. // // The IR here holds no can:// ids: vertices are keyed by (L3Key, local key) -// and cross-callable edges by L3Key pairs and external signatures. The v2 -// emitter mints the global ids. This package must not import v2emit or core. +// and cross-callable edges by L3Key pairs and external signatures. The +// emitter mints the global ids. This package must not import emit or core. package sdg import ( @@ -15,7 +15,7 @@ import ( "golang.org/x/tools/go/packages" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) // Target is a call target: an in-project callable or a library stand-in. @@ -76,10 +76,10 @@ type Degraded struct { // Result is the L4 overlay of a run. type Result struct { Callables map[dataflow.L3Key]CallableSDG - Externals map[string][]Vertex // stand-in formal vertices by full callee sig - NewExternals map[string]schema.GoExternalCallee // externals only VTA reached + Externals map[string][]Vertex // stand-in formal vertices by full callee sig + NewExternals map[string]model.GoExternalCallee // externals only VTA reached ParamIn, ParamOut []ParamEdge - CallEdges []schema.GoCallEdge // prov ["vta"] + CallEdges []model.GoCallEdge // prov ["vta"] Degraded []Degraded } @@ -89,9 +89,9 @@ type Input struct { Pkgs map[string]*packages.Package Variants []*packages.Package // every loaded package, test variants included (SymbolTableBuilder.Loaded); nil = Pkgs' values ProjectDir string - SymbolTable map[string]schema.GoFile - Externals map[string]schema.GoExternalCallee - CallGraph []schema.GoCallEdge // L2 edges (app.CallGraph) + SymbolTable map[string]model.GoFile + Externals map[string]model.GoExternalCallee + CallGraph []model.GoCallEdge // L2 edges (app.CallGraph) Units []dataflow.Unit L3 map[dataflow.L3Key]dataflow.Result K, Jobs int diff --git a/internal/sdg/vertices.go b/internal/sdg/vertices.go index b7067c1..ad02b36 100644 --- a/internal/sdg/vertices.go +++ b/internal/sdg/vertices.go @@ -10,7 +10,7 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/astwalk" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // The `of` markers of the L4 vertices (spec §4.6, D6): Python's spelling, @@ -738,7 +738,7 @@ func (p *ports) capSites(u dataflow.Unit, taken map[string]bool) []capSite { } } pos := p.in.Fset.PositionFor(l.Lit.Pos(), false) - cs := capSite{key: dataflow.NextFreeKey(v2.LocalID(pos.Line, pos.Column), taken), host: host, lit: l.Lit, caps: caps} + cs := capSite{key: dataflow.NextFreeKey(schema.LocalID(pos.Line, pos.Column), taken), host: host, lit: l.Lit, caps: caps} j := 0 for i, v := range caps { cs.ofs = append(cs.ofs, ofCapture+v.Name()) diff --git a/internal/sdg/vta.go b/internal/sdg/vta.go index ee0b0d0..a20ef0c 100644 --- a/internal/sdg/vta.go +++ b/internal/sdg/vta.go @@ -9,7 +9,7 @@ import ( "golang.org/x/tools/go/ssa" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" ) @@ -36,8 +36,8 @@ type dispatch struct { byVTA map[siteTarget]bool // the (site, target) pairs VTA produced: the call_graph edge candidates bySig map[string]dataflow.L3Key // symbol-table callable of each signature (init excepted) l2 map[l2Edge]bool - l2Ext map[string]schema.GoExternalCallee // in.Externals, read-only - newExt map[string]schema.GoExternalCallee // externals L2 never saw + l2Ext map[string]model.GoExternalCallee // in.Externals, read-only + newExt map[string]model.GoExternalCallee // externals L2 never saw } // siteTarget is one target of one call site. @@ -67,13 +67,13 @@ func newDispatch(in Input) *dispatch { byVTA: map[siteTarget]bool{}, l2: make(map[l2Edge]bool, len(in.CallGraph)), l2Ext: in.Externals, - newExt: map[string]schema.GoExternalCallee{}, + newExt: map[string]model.GoExternalCallee{}, } for _, e := range in.CallGraph { d.l2[l2Edge{e.SourcePath, e.Source, e.Target}] = true } - callables := map[dataflow.L3Key]schema.GoCallable{} + callables := map[dataflow.L3Key]model.GoCallable{} bySig := map[string]dataflow.L3Key{} keep := func(sig string, k dataflow.L3Key) { // A signature names one callable, except init (never a callee). @@ -81,8 +81,8 @@ func newDispatch(in Input) *dispatch { bySig[sig] = k } } - var walk func(c schema.GoCallable) - walk = func(c schema.GoCallable) { + var walk func(c model.GoCallable) + walk = func(c model.GoCallable) { callables[dataflow.L3Key{Path: c.Path, Signature: c.Signature}] = c for _, ic := range c.InnerCallables { walk(ic) @@ -341,7 +341,7 @@ func (d *dispatch) result(deg []Degraded) Result { }) res := Result{Degraded: deg} for _, id := range ids { - res.CallEdges = append(res.CallEdges, schema.GoCallEdge{ + res.CallEdges = append(res.CallEdges, model.GoCallEdge{ Source: id.src, Target: id.dst, Type: "CALL_DEP", @@ -364,12 +364,12 @@ func (d *dispatch) result(deg []Degraded) Result { // CallEdges holds only pairs the L2 resolver did not find (result skips // every d.l2 edge), so MergeEdges never meets an existing identity and // appends: an L2 edge VTA also finds keeps its L2 prov and weight. -func (r *Result) ApplyTo(app *schema.GoApplication) { +func (r *Result) ApplyTo(app *model.GoApplication) { if len(r.CallEdges) > 0 { app.CallGraph = semantic_analysis.MergeEdges(app.CallGraph, r.CallEdges) } if len(r.NewExternals) > 0 && app.Externals == nil { - app.Externals = make(map[string]schema.GoExternalCallee, len(r.NewExternals)) + app.Externals = make(map[string]model.GoExternalCallee, len(r.NewExternals)) } for sig, ext := range r.NewExternals { if _, ok := app.Externals[sig]; !ok { diff --git a/internal/sdg/vta_test.go b/internal/sdg/vta_test.go index ddec8e4..788eae0 100644 --- a/internal/sdg/vta_test.go +++ b/internal/sdg/vta_test.go @@ -10,7 +10,7 @@ import ( "golang.org/x/tools/go/ssa" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) const sdgPkg = "example.com/dataflow/sdg" @@ -38,7 +38,7 @@ func runDispatch(t *testing.T) (Input, Result, *dispatch) { // hasEdge reports whether edges holds src → dst (src declared in sdg.go) // with prov ["vta"] and weight 1. -func hasVTAEdge(edges []schema.GoCallEdge, src, dst string) bool { +func hasVTAEdge(edges []model.GoCallEdge, src, dst string) bool { for _, e := range edges { if e.Source == src && e.Target == dst && e.SourcePath == sdgFile { return slices.Equal(e.Provenance, []string{"vta"}) && e.Weight == 1 @@ -47,7 +47,7 @@ func hasVTAEdge(edges []schema.GoCallEdge, src, dst string) bool { return false } -func hasEdgeTo(edges []schema.GoCallEdge, src, dst string) bool { +func hasEdgeTo(edges []model.GoCallEdge, src, dst string) bool { for _, e := range edges { if e.Source == src && e.Target == dst { return true @@ -218,8 +218,8 @@ func TestVTA_EdgesNewSortedAndResolvable(t *testing.T) { units[u.Key] = true } sigs := map[string]bool{} // every callable the emitter indexes, closures included - var walk func(c schema.GoCallable) - walk = func(c schema.GoCallable) { + var walk func(c model.GoCallable) + walk = func(c model.GoCallable) { sigs[c.Signature] = true for _, ic := range c.InnerCallables { walk(ic) @@ -262,7 +262,7 @@ func TestVTA_EdgesNewSortedAndResolvable(t *testing.T) { func TestVTA_Deterministic(t *testing.T) { _, a, da := runDispatch(t) _, b, db := runDispatch(t) - if !slices.EqualFunc(a.CallEdges, b.CallEdges, func(x, y schema.GoCallEdge) bool { + if !slices.EqualFunc(a.CallEdges, b.CallEdges, func(x, y model.GoCallEdge) bool { return x.Source == y.Source && x.Target == y.Target && x.SourcePath == y.SourcePath && x.TargetPath == y.TargetPath && slices.Equal(x.Provenance, y.Provenance) && x.Weight == y.Weight }) { diff --git a/internal/semantic_analysis/call_graph.go b/internal/semantic_analysis/call_graph.go index 33fc1f5..ac79ea8 100644 --- a/internal/semantic_analysis/call_graph.go +++ b/internal/semantic_analysis/call_graph.go @@ -22,7 +22,7 @@ import ( "golang.org/x/tools/go/packages" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -33,7 +33,7 @@ type CallGraphBuilder struct { fset *token.FileSet pkgs map[string]*packages.Package indexes map[*packages.Package]callSiteIndex - externals map[string]schema.GoExternalCallee + externals map[string]model.GoExternalCallee } // NewCallGraphBuilder creates a builder using the same pkgs/fset loaded for the symbol table. @@ -43,13 +43,13 @@ func NewCallGraphBuilder(projectDir string, fset *token.FileSet, pkgs map[string // Externals returns the library callees recorded by Build, keyed by the full // callee signature. Nil before Build or when no library call was seen. -func (cg *CallGraphBuilder) Externals() map[string]schema.GoExternalCallee { return cg.externals } +func (cg *CallGraphBuilder) Externals() map[string]model.GoExternalCallee { return cg.externals } // Build resolves all call sites in symbolTable, backfills callee_signature, and // returns the identity-only edge list. Never crashes on unresolved sites — it logs // and skips the edge while leaving callee_signature nil. -func (cg *CallGraphBuilder) Build(symbolTable map[string]schema.GoFile) []schema.GoCallEdge { - var edges []schema.GoCallEdge +func (cg *CallGraphBuilder) Build(symbolTable map[string]model.GoFile) []model.GoCallEdge { + var edges []model.GoCallEdge seen := map[edgeKey]bool{} cg.externals = nil @@ -106,7 +106,7 @@ func sortedKeys[V any](m map[string]V) []string { } // buildKnownSigs returns the set of all callable signatures present in the symbol table. -func buildKnownSigs(symbolTable map[string]schema.GoFile) map[string]bool { +func buildKnownSigs(symbolTable map[string]model.GoFile) map[string]bool { sigs := make(map[string]bool) for _, f := range symbolTable { for sig := range f.Functions { @@ -132,11 +132,11 @@ func buildKnownSigs(symbolTable map[string]schema.GoFile) map[string]bool { // (e.g. an interface method) is backfilled but gets no edge. func (cg *CallGraphBuilder) resolveCallable( pkg *packages.Package, - callable schema.GoCallable, + callable model.GoCallable, seen map[edgeKey]bool, knownSigs map[string]bool, -) (schema.GoCallable, []schema.GoCallEdge) { - var edges []schema.GoCallEdge +) (model.GoCallable, []model.GoCallEdge) { + var edges []model.GoCallEdge for i := range callable.CallSites { site := &callable.CallSites[i] @@ -169,17 +169,17 @@ func (cg *CallGraphBuilder) resolveCallable( } seen[key] = true - edges = append(edges, schema.GoCallEdge{ + edges = append(edges, model.GoCallEdge{ Source: callable.Signature, Target: calleeSig, Type: "CALL_DEP", Weight: 1, Provenance: []string{"go/types"}, Tags: map[string]string{}, - // Carry the source's declaring file so the v2 emitter can map a + // Carry the source's declaring file so the emitter can map a // non-unique signature (notably ".init", which repeats once per // file in a package) back to the specific callable that owns this - // call site. See schema.GoCallEdge.SourcePath. + // call site. See model.GoCallEdge.SourcePath. SourcePath: callable.Path, }) } @@ -262,7 +262,7 @@ func (cg *CallGraphBuilder) recordExternal(fn *types.Func, fullSig string) { return } if cg.externals == nil { - cg.externals = map[string]schema.GoExternalCallee{} + cg.externals = map[string]model.GoExternalCallee{} } cg.externals[fullSig] = ExternalCallee(fn, fullSig) } @@ -272,7 +272,7 @@ func (cg *CallGraphBuilder) recordExternal(fn *types.Func, fullSig string) { // build their entries with it, so an external has one shape whichever found it. // Parameter names and types come from the callee's *types.Signature; unnamed // parameters become "_". The receiver is not a parameter. -func ExternalCallee(fn *types.Func, fullSig string) schema.GoExternalCallee { +func ExternalCallee(fn *types.Func, fullSig string) model.GoExternalCallee { importPath := fn.Pkg().Path() // Record the declared signature, not the instance the call site selected: a // method on a generic library type (atomic.Pointer[A].Store) must yield one @@ -280,14 +280,14 @@ func ExternalCallee(fn *types.Func, fullSig string) schema.GoExternalCallee { fn = fn.Origin() sig := fn.Type().(*types.Signature) - var params []schema.GoParameter + var params []model.GoParameter for i := 0; i < sig.Params().Len(); i++ { p := sig.Params().At(i) name := p.Name() if name == "" || name == "_" { name = fmt.Sprintf("_%d", i) } - params = append(params, schema.GoParameter{ + params = append(params, model.GoParameter{ Name: name, Type: types.TypeString(p.Type(), nil), IsVariadic: sig.Variadic() && i == sig.Params().Len()-1, @@ -307,16 +307,16 @@ func ExternalCallee(fn *types.Func, fullSig string) schema.GoExternalCallee { ret = "(" + strings.Join(rets, ", ") + ")" } - var receiver *schema.GoParameter + var receiver *model.GoParameter if recv := sig.Recv(); recv != nil { name := recv.Name() if name == "" || name == "_" { name = "_recv" } - receiver = &schema.GoParameter{Name: name, Type: types.TypeString(recv.Type(), nil)} + receiver = &model.GoParameter{Name: name, Type: types.TypeString(recv.Type(), nil)} } - return schema.GoExternalCallee{ + return model.GoExternalCallee{ ImportPath: importPath, Sig: strings.TrimPrefix(fullSig, importPath+"."), Name: fn.Name(), @@ -331,7 +331,7 @@ func ExternalCallee(fn *types.Func, fullSig string) schema.GoExternalCallee { // relPath (the file declaring the enclosing callable) and the site's real // (not //line-adjusted) start and end line:col. Returns nil when the site cannot be // resolved (graceful fallback). -func (cg *CallGraphBuilder) resolveCallSite(pkg *packages.Package, relPath string, site *schema.GoCallsite) *types.Func { +func (cg *CallGraphBuilder) resolveCallSite(pkg *packages.Package, relPath string, site *model.GoCallsite) *types.Func { if pkg.TypesInfo == nil { return nil } @@ -403,12 +403,12 @@ func (cg *CallGraphBuilder) packageForFile(relPath string) *packages.Package { // (SourcePath, Source, Target, TargetPath). A signature is not unique (every // file's func init shares ".init", and so do its closures), so the // declaring files keep two inits' edges apart. -func MergeEdges(primary, secondary []schema.GoCallEdge) []schema.GoCallEdge { +func MergeEdges(primary, secondary []model.GoCallEdge) []model.GoCallEdge { type key struct{ path, src, tgt, tgtPath string } index := map[key]int{} - result := make([]schema.GoCallEdge, 0, len(primary)+len(secondary)) + result := make([]model.GoCallEdge, 0, len(primary)+len(secondary)) - add := func(e schema.GoCallEdge) { + add := func(e model.GoCallEdge) { k := key{e.SourcePath, e.Source, e.Target, e.TargetPath} if idx, exists := index[k]; exists { // Merge provenance (union) and accumulate weight. diff --git a/internal/semantic_analysis/call_graph_test.go b/internal/semantic_analysis/call_graph_test.go index e234ed7..f36c827 100644 --- a/internal/semantic_analysis/call_graph_test.go +++ b/internal/semantic_analysis/call_graph_test.go @@ -7,13 +7,13 @@ import ( "sort" "testing" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) -func edge(src, tgt string, weight int, prov ...string) schema.GoCallEdge { - return schema.GoCallEdge{Source: src, Target: tgt, Weight: weight, Provenance: prov} +func edge(src, tgt string, weight int, prov ...string) model.GoCallEdge { + return model.GoCallEdge{Source: src, Target: tgt, Weight: weight, Provenance: prov} } // ── MergeEdges ──────────────────────────────────────────────────────────────── @@ -26,7 +26,7 @@ func TestMergeEdges_EmptyBoth(t *testing.T) { } func TestMergeEdges_PrimaryOnly(t *testing.T) { - primary := []schema.GoCallEdge{edge("a", "b", 1.0, "resolver")} + primary := []model.GoCallEdge{edge("a", "b", 1.0, "resolver")} result := semantic_analysis.MergeEdges(primary, nil) if len(result) != 1 { t.Fatalf("got %d edges, want 1", len(result)) @@ -37,7 +37,7 @@ func TestMergeEdges_PrimaryOnly(t *testing.T) { } func TestMergeEdges_SecondaryOnly(t *testing.T) { - secondary := []schema.GoCallEdge{edge("x", "y", 2.0, "framework")} + secondary := []model.GoCallEdge{edge("x", "y", 2.0, "framework")} result := semantic_analysis.MergeEdges(nil, secondary) if len(result) != 1 { t.Fatalf("got %d edges, want 1", len(result)) @@ -48,8 +48,8 @@ func TestMergeEdges_SecondaryOnly(t *testing.T) { } func TestMergeEdges_DisjointEdges(t *testing.T) { - primary := []schema.GoCallEdge{edge("a", "b", 1.0, "resolver")} - secondary := []schema.GoCallEdge{edge("c", "d", 1.0, "framework")} + primary := []model.GoCallEdge{edge("a", "b", 1.0, "resolver")} + secondary := []model.GoCallEdge{edge("c", "d", 1.0, "framework")} result := semantic_analysis.MergeEdges(primary, secondary) if len(result) != 2 { t.Errorf("got %d edges, want 2", len(result)) @@ -57,8 +57,8 @@ func TestMergeEdges_DisjointEdges(t *testing.T) { } func TestMergeEdges_DuplicateAccumulatesWeight(t *testing.T) { - primary := []schema.GoCallEdge{edge("a", "b", 3, "resolver")} - secondary := []schema.GoCallEdge{edge("a", "b", 5, "framework")} + primary := []model.GoCallEdge{edge("a", "b", 3, "resolver")} + secondary := []model.GoCallEdge{edge("a", "b", 5, "framework")} result := semantic_analysis.MergeEdges(primary, secondary) if len(result) != 1 { t.Fatalf("duplicate (a→b) should collapse to 1 edge; got %d", len(result)) @@ -69,8 +69,8 @@ func TestMergeEdges_DuplicateAccumulatesWeight(t *testing.T) { } func TestMergeEdges_DuplicateUnionsProvenance(t *testing.T) { - primary := []schema.GoCallEdge{edge("a", "b", 1.0, "resolver")} - secondary := []schema.GoCallEdge{edge("a", "b", 1.0, "framework")} + primary := []model.GoCallEdge{edge("a", "b", 1.0, "resolver")} + secondary := []model.GoCallEdge{edge("a", "b", 1.0, "framework")} result := semantic_analysis.MergeEdges(primary, secondary) if len(result) != 1 { t.Fatalf("got %d edges, want 1", len(result)) @@ -85,8 +85,8 @@ func TestMergeEdges_DuplicateUnionsProvenance(t *testing.T) { } func TestMergeEdges_DuplicateProvenanceNotDuplicated(t *testing.T) { - primary := []schema.GoCallEdge{edge("a", "b", 1.0, "resolver")} - secondary := []schema.GoCallEdge{edge("a", "b", 1.0, "resolver")} + primary := []model.GoCallEdge{edge("a", "b", 1.0, "resolver")} + secondary := []model.GoCallEdge{edge("a", "b", 1.0, "resolver")} result := semantic_analysis.MergeEdges(primary, secondary) if len(result) != 1 { t.Fatalf("got %d edges, want 1", len(result)) @@ -103,11 +103,11 @@ func TestMergeEdges_DuplicateProvenanceNotDuplicated(t *testing.T) { } func TestMergeEdges_OrderPreserved(t *testing.T) { - primary := []schema.GoCallEdge{ + primary := []model.GoCallEdge{ edge("a", "b", 1.0), edge("c", "d", 1.0), } - secondary := []schema.GoCallEdge{ + secondary := []model.GoCallEdge{ edge("e", "f", 1.0), } result := semantic_analysis.MergeEdges(primary, secondary) @@ -124,12 +124,12 @@ func TestMergeEdges_OrderPreserved(t *testing.T) { // files) calling one callee are two edges, and so are two VTA edges to the // same-signature closures of two files' inits; the same file pair merges. func TestMergeEdges_KeepsDeclaringFilesApart(t *testing.T) { - at := func(e schema.GoCallEdge, src, dst string) schema.GoCallEdge { + at := func(e model.GoCallEdge, src, dst string) model.GoCallEdge { e.SourcePath, e.TargetPath = src, dst return e } - primary := []schema.GoCallEdge{at(edge("p.init", "p.setup", 1, "go/types"), "a.go", "")} - secondary := []schema.GoCallEdge{ + primary := []model.GoCallEdge{at(edge("p.init", "p.setup", 1, "go/types"), "a.go", "")} + secondary := []model.GoCallEdge{ at(edge("p.init", "p.setup", 1, "go/types"), "b.go", ""), at(edge("p.Run", "p.init.closure_1", 1, "vta"), "a.go", "a.go"), at(edge("p.Run", "p.init.closure_1", 1, "vta"), "a.go", "b.go"), diff --git a/internal/syntactic_analysis/v2emit/artifact_stream_test.go b/internal/syntactic_analysis/emit/artifact_stream_test.go similarity index 80% rename from internal/syntactic_analysis/v2emit/artifact_stream_test.go rename to internal/syntactic_analysis/emit/artifact_stream_test.go index c9bea78..191016a 100644 --- a/internal/syntactic_analysis/v2emit/artifact_stream_test.go +++ b/internal/syntactic_analysis/emit/artifact_stream_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit import ( "bytes" @@ -8,7 +8,7 @@ import ( "strings" "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // TestWriteJSONString_EqualsMarshal: the streaming string writer writes the @@ -44,20 +44,20 @@ func TestWriteJSONString_EqualsMarshal(t *testing.T) { } } -func artifactTree(sources map[string]string) *v2.Analysis { - arts := map[string]v2.Artifact{} +func artifactTree(sources map[string]string) *schema.Analysis { + arts := map[string]schema.Artifact{} for p, src := range sources { ext := "none" if src != "" { ext = "full" } - arts[p] = v2.Artifact{ID: "can://a/a/artifact/" + p, Kind: "artifact", Path: p, Format: "text", + arts[p] = schema.Artifact{ID: "can://a/a/artifact/" + p, Kind: "artifact", Path: p, Format: "text", SizeBytes: int64(len(src)), SHA256: "x", Source: src, Extraction: ext} } - return &v2.Analysis{IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, - Application: v2.Application{IdentityVersion: 2, ID: "can://a/a", Kind: "application", - SymbolTable: map[string]v2.Module{}, Artifacts: arts, - Dependencies: []v2.Dependency{{Name: "example.com/x", Ecosystem: "golang", Kind: "runtime", Prov: []string{"declared"}}}}} + return &schema.Analysis{IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 1, + Application: schema.Application{IdentityVersion: 2, ID: "can://a/a", Kind: "application", + SymbolTable: map[string]schema.Module{}, Artifacts: arts, + Dependencies: []schema.Dependency{{Name: "example.com/x", Ecosystem: "golang", Kind: "runtime", Prov: []string{"declared"}}}}} } // TestEncode_ArtifactsByteIdenticalToMarshal (#80): with the artifacts written diff --git a/internal/syntactic_analysis/v2emit/artifacts_stream.go b/internal/syntactic_analysis/emit/artifacts_stream.go similarity index 91% rename from internal/syntactic_analysis/v2emit/artifacts_stream.go rename to internal/syntactic_analysis/emit/artifacts_stream.go index 0cadfcd..30c8d38 100644 --- a/internal/syntactic_analysis/v2emit/artifacts_stream.go +++ b/internal/syntactic_analysis/emit/artifacts_stream.go @@ -1,4 +1,4 @@ -package v2emit +package emit import ( "bytes" @@ -8,7 +8,7 @@ import ( "slices" "unicode/utf8" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // The artifacts are written one at a time, and each source is escaped straight @@ -25,7 +25,7 @@ const sourceMarker = "\x00source" // artifactsHole is the bytes json.Marshal writes for the stand-in map. var artifactsHole = func() []byte { - b, err := json.Marshal(map[string]v2.Artifact{artifactsHoleKey: {}}) + b, err := json.Marshal(map[string]schema.Artifact{artifactsHoleKey: {}}) if err != nil { panic(err) } @@ -42,14 +42,14 @@ var sourceNeedle = func() []byte { // writeWithArtifacts writes seg, with the stand-in artifacts map replaced by // arts written one at a time. With no artifacts it writes seg unchanged. -func writeWithArtifacts(w io.Writer, seg []byte, arts map[string]v2.Artifact) error { +func writeWithArtifacts(w io.Writer, seg []byte, arts map[string]schema.Artifact) error { if len(arts) == 0 { _, err := w.Write(seg) return err } i := bytes.Index(seg, artifactsHole) if i < 0 { - return fmt.Errorf("v2emit: no artifacts stand-in in the envelope") + return fmt.Errorf("emit: no artifacts stand-in in the envelope") } if _, err := w.Write(seg[:i]); err != nil { return err @@ -63,7 +63,7 @@ func writeWithArtifacts(w io.Writer, seg []byte, arts map[string]v2.Artifact) er // writeArtifacts writes arts as json.Marshal writes the map: keys in sorted // order, each a JSON string. -func writeArtifacts(w io.Writer, arts map[string]v2.Artifact) error { +func writeArtifacts(w io.Writer, arts map[string]schema.Artifact) error { keys := make([]string, 0, len(arts)) for k := range arts { keys = append(keys, k) @@ -93,7 +93,7 @@ func writeArtifacts(w io.Writer, arts map[string]v2.Artifact) error { } // writeArtifact writes a as json.Marshal does, with its source streamed. -func writeArtifact(w io.Writer, a v2.Artifact) error { +func writeArtifact(w io.Writer, a schema.Artifact) error { src := a.Source if src != "" { a.Source = sourceMarker @@ -108,7 +108,7 @@ func writeArtifact(w io.Writer, a v2.Artifact) error { } i := bytes.Index(data, sourceNeedle) if i < 0 { - return fmt.Errorf("v2emit: no source stand-in in artifact %s", a.Path) + return fmt.Errorf("emit: no source stand-in in artifact %s", a.Path) } if _, err := w.Write(data[:i+len(`"source":`)]); err != nil { return err diff --git a/internal/syntactic_analysis/v2emit/determinism_freshbuild_test.go b/internal/syntactic_analysis/emit/determinism_freshbuild_test.go similarity index 96% rename from internal/syntactic_analysis/v2emit/determinism_freshbuild_test.go rename to internal/syntactic_analysis/emit/determinism_freshbuild_test.go index f0d73ac..ea62d8f 100644 --- a/internal/syntactic_analysis/v2emit/determinism_freshbuild_test.go +++ b/internal/syntactic_analysis/emit/determinism_freshbuild_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit // Fresh-build determinism gate (release-gates.md: `-j N` output byte-identical // to `-j 1`, and run-to-run identical). @@ -33,8 +33,8 @@ import ( "strings" "testing" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) @@ -54,7 +54,7 @@ func chiDir(t *testing.T) string { // a new symbol-table builder (hence a new Go map) + resolver + emit. Each call // is a from-scratch build, which is what makes map-iteration nondeterminism // observable across repeated calls. -func buildChiL2Fresh(t *testing.T, dir string) *v2.Analysis { +func buildChiL2Fresh(t *testing.T, dir string) *schema.Analysis { t.Helper() b := syntactic_analysis.NewSymbolTableBuilder(dir) st, err := b.Build(nil, true) @@ -63,7 +63,7 @@ func buildChiL2Fresh(t *testing.T, dir string) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} return Emit(app, testIdentity("chi"), dir, 2, "gate-test", 0, nil, nil) } diff --git a/internal/syntactic_analysis/v2emit/determinism_test.go b/internal/syntactic_analysis/emit/determinism_test.go similarity index 77% rename from internal/syntactic_analysis/v2emit/determinism_test.go rename to internal/syntactic_analysis/emit/determinism_test.go index b6d2313..7e23602 100644 --- a/internal/syntactic_analysis/v2emit/determinism_test.go +++ b/internal/syntactic_analysis/emit/determinism_test.go @@ -1,8 +1,8 @@ -package v2emit +package emit -// Determinism gate for the v2 emitter. +// Determinism gate for the emitter. // -// release-gates.md requires v2 output to be byte-identical across runs and +// release-gates.md requires the output to be byte-identical across runs and // across -j values. The symbol-table tree is already order-stable (modules // iterated via sortedFileKeys), but the call_graph edge list is assembled by // ranging a Go map in CallGraphBuilder.Build — random iteration order — and @@ -22,8 +22,8 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) @@ -40,7 +40,7 @@ func TestDeterminism_CallGraphStableAcrossEmits(t *testing.T) { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges} // Emit twice from the SAME model. If the edge order is derived from the // edges slice without a stable sort, repeated marshals still match (same @@ -50,11 +50,11 @@ func TestDeterminism_CallGraphStableAcrossEmits(t *testing.T) { // Reverse the input edge order and re-emit: a correct emitter sorts, so the // serialized call_graph must be unchanged. - rev := make([]schema.GoCallEdge, len(edges)) + rev := make([]model.GoCallEdge, len(edges)) for i, e := range edges { rev[len(edges)-1-i] = e } - appRev := &schema.GoApplication{SymbolTable: st, CallGraph: rev} + appRev := &model.GoApplication{SymbolTable: st, CallGraph: rev} second := mustMarshalCallGraph(t, Emit(appRev, testIdentity("multipackage"), dir, 2, "det-test", 0, nil, nil)) if first != second { @@ -62,7 +62,7 @@ func TestDeterminism_CallGraphStableAcrossEmits(t *testing.T) { } } -func mustMarshalCallGraph(t *testing.T, out *v2.Analysis) string { +func mustMarshalCallGraph(t *testing.T, out *schema.Analysis) string { t.Helper() type cgOnly struct { Application struct { @@ -97,8 +97,8 @@ func TestEncode_ByteIdenticalToMarshal(t *testing.T) { if err != nil { t.Fatalf("%s: symbol table build failed: %v", name, err) } - apps := map[int]*schema.GoApplication{1: {SymbolTable: st, CallGraph: []schema.GoCallEdge{}}} - check := func(level int, app *schema.GoApplication, l3 map[dataflow.L3Key]dataflow.Result) { + apps := map[int]*model.GoApplication{1: {SymbolTable: st, CallGraph: []model.GoCallEdge{}}} + check := func(level int, app *model.GoApplication, l3 map[dataflow.L3Key]dataflow.Result) { t.Run(fmt.Sprintf("%s/a%d", name, level), func(t *testing.T) { tree := Emit(app, testIdentity(name), dir, level, "enc-test", 3, l3, nil) want, err := json.Marshal(tree) @@ -124,7 +124,7 @@ func TestEncode_ByteIdenticalToMarshal(t *testing.T) { check(1, apps[1], nil) cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} check(2, app, nil) check(3, app, dataflow.Run(b.Fset(), b.L3Units(st), 3, 4)) } @@ -144,28 +144,28 @@ func firstDiff(a, b []byte) int { // external body) go through the streaming writer's envelope split unchanged. func TestEncode_L4EnvelopeFieldsByteIdentical(t *testing.T) { call := "x" - a := &v2.Analysis{ - SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 4, KLimit: 3, - Analyzer: v2.AnalyzerTag{Name: "codeanalyzer-go", Version: "t"}, - Degraded: []v2.Degraded{{Code: "ssa_build", Detail: `has "symbol_table":{} & `, Packages: []string{"p"}, Callables: []string{"c"}}}, - Application: v2.Application{ + a := &schema.Analysis{ + SchemaVersion: schema.SchemaVersion, Language: schema.Language, MaxLevel: 4, KLimit: 3, + Analyzer: schema.AnalyzerTag{Name: "codeanalyzer-go", Version: "t"}, + Degraded: []schema.Degraded{{Code: "ssa_build", Detail: `has "symbol_table":{} & `, Packages: []string{"p"}, Callables: []string{"c"}}}, + Application: schema.Application{ ID: "can://app/app", Kind: "application", - SymbolTable: map[string]v2.Module{ - "a.go": {ID: "m", Functions: map[string]v2.Callable{"f": { - ID: "f", Summary: []v2.SummaryEdge{{Src: "a", Dst: "b"}}, - Body: map[string]v2.BodyNode{ + SymbolTable: map[string]schema.Module{ + "a.go": {ID: "m", Functions: map[string]schema.Callable{"f": { + ID: "f", Summary: []schema.SummaryEdge{{Src: "a", Dst: "b"}}, + Body: map[string]schema.BodyNode{ "@fin": {Kind: "formal_in", Of: "p0"}, "c1": {Kind: "call", Callee: &call}, }, }}}, }, - ExternalSymbols: map[string]v2.ExternalSymbol{"e": { + ExternalSymbols: map[string]schema.ExternalSymbol{"e": { ID: "e", Kind: "external", - Receiver: &v2.ExternalParameter{Name: "_recv", Type: "*strings.Builder"}, - Body: map[string]v2.BodyNode{"@entry": {Kind: "entry"}}, + Receiver: &schema.ExternalParameter{Name: "_recv", Type: "*strings.Builder"}, + Body: map[string]schema.BodyNode{"@entry": {Kind: "entry"}}, }}, - ParamIn: []v2.ParamEdge{{Src: "s", Dst: "d", Var: "v"}}, - ParamOut: []v2.ParamEdge{{Src: "d", Dst: "s", Var: ""}}, + ParamIn: []schema.ParamEdge{{Src: "s", Dst: "d", Var: "v"}}, + ParamOut: []schema.ParamEdge{{Src: "d", Dst: "s", Var: ""}}, }, } want, err := json.Marshal(a) @@ -185,13 +185,13 @@ func TestEncode_L4EnvelopeFieldsByteIdentical(t *testing.T) { t.Errorf("Encode differs from json.Marshal at byte %d", firstDiff(enc.Bytes(), want)) } // And absent when empty. - plain, _ := json.Marshal(&v2.Analysis{}) + plain, _ := json.Marshal(&schema.Analysis{}) for _, k := range []string{"degraded", "param_in", "param_out", "summary", `"of"`, "receiver"} { if bytes.Contains(plain, []byte(k)) { t.Errorf("empty analysis serialises %s", k) } } - n, _ := json.Marshal(v2.BodyNode{Kind: "statement"}) + n, _ := json.Marshal(schema.BodyNode{Kind: "statement"}) if bytes.Contains(n, []byte(`"of"`)) { t.Errorf("empty Of serialised: %s", n) } diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/emit/emit.go similarity index 76% rename from internal/syntactic_analysis/v2emit/emit.go rename to internal/syntactic_analysis/emit/emit.go index 5c19272..924cd6f 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/emit/emit.go @@ -1,4 +1,4 @@ -package v2emit +package emit import ( "bytes" @@ -14,12 +14,12 @@ import ( "strings" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" ) -// Emit transforms the v1 GoApplication into the v2 Analysis payload. identity is +// Emit transforms the model's GoApplication into the Analysis payload. identity is // the application anchor (--app-name); projectDir is the absolute input root, // used to read each module's source for span slicing. maxLevel records how // deeply the tree was populated (1 = symbol table, 2 = + call_graph, 3 = + @@ -31,13 +31,13 @@ import ( // sdg.Run's result, nil below L4 (and ignored there); see emit_l4.go for how // it merges into the tree and mints every L4 id. // -// This is a pure re-serialization: every fact comes from the v1 model and the +// This is a pure re-serialization: every fact comes from the model and the // L3/L4 side tables, except span byte offsets, which are derived from source // via lineIndex. -func Emit(app *schema.GoApplication, identity v2.Identity, projectDir string, maxLevel int, analyzerVersion string, kLimit int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) *v2.Analysis { +func Emit(app *model.GoApplication, identity schema.Identity, projectDir string, maxLevel int, analyzerVersion string, kLimit int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) *schema.Analysis { e := newEmitter(app, identity, projectDir, maxLevel, l3, l4) out := e.envelope(app, maxLevel, analyzerVersion, kLimit) - out.Application.SymbolTable = make(map[string]v2.Module, len(app.SymbolTable)) + out.Application.SymbolTable = make(map[string]schema.Module, len(app.SymbolTable)) for _, relPath := range sortedFileKeys(app.SymbolTable) { out.Application.SymbolTable[relPath] = e.module(relPath, app.SymbolTable[relPath]) } @@ -54,10 +54,10 @@ func Emit(app *schema.GoApplication, identity v2.Identity, projectDir string, ma // memory is the envelope plus the largest module, not the document. The L4 // param edges follow the modules (they need every callable's id) and are // minted and written one at a time. -func EmitTo(w io.Writer, app *schema.GoApplication, identity v2.Identity, projectDir string, maxLevel int, analyzerVersion string, kLimit int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) error { +func EmitTo(w io.Writer, app *model.GoApplication, identity schema.Identity, projectDir string, maxLevel int, analyzerVersion string, kLimit int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) error { e := newEmitter(app, identity, projectDir, maxLevel, l3, l4) out := e.envelope(app, maxLevel, analyzerVersion, kLimit) - return encode(w, out, func(yield func(string, v2.Module) bool) { + return encode(w, out, func(yield func(string, schema.Module) bool) { for _, relPath := range sortedFileKeys(app.SymbolTable) { if !yield(relPath, e.module(relPath, app.SymbolTable[relPath])) { return @@ -67,11 +67,11 @@ func EmitTo(w io.Writer, app *schema.GoApplication, identity v2.Identity, projec } // collectEdges is seq as a slice, nil when empty (omitempty). -func collectEdges(seq iter.Seq[v2.ParamEdge]) []v2.ParamEdge { +func collectEdges(seq iter.Seq[schema.ParamEdge]) []schema.ParamEdge { if seq == nil { return nil } - var out []v2.ParamEdge + var out []schema.ParamEdge for e := range seq { out = append(out, e) } @@ -81,7 +81,7 @@ func collectEdges(seq iter.Seq[v2.ParamEdge]) []v2.ParamEdge { // Encode writes a to w as the exact bytes json.Marshal(a) produces (no // trailing newline), streaming symbol_table one module at a time so the whole // document never exists as one []byte. -func Encode(w io.Writer, a *v2.Analysis) error { +func Encode(w io.Writer, a *schema.Analysis) error { st := a.Application.SymbolTable if st == nil { // json.Marshal writes null; nothing to stream data, err := json.Marshal(a) @@ -98,7 +98,7 @@ func Encode(w io.Writer, a *v2.Analysis) error { sort.Strings(keys) env := *a env.Application.SymbolTable = nil - return encode(w, &env, func(yield func(string, v2.Module) bool) { + return encode(w, &env, func(yield func(string, schema.Module) bool) { for _, k := range keys { if !yield(k, st[k]) { return @@ -130,15 +130,15 @@ const symbolTableHole = `"symbol_table":{}` // degraded closes the envelope (its last field), as json.Marshal orders // them. Keys are marshalled as JSON strings, which is how encoding/json // writes a string map key (same escaping). -func encode(w io.Writer, env *v2.Analysis, modules iter.Seq2[string, v2.Module], late func() lateFields) error { +func encode(w io.Writer, env *schema.Analysis, modules iter.Seq2[string, schema.Module], late func() lateFields) error { shell := *env - shell.Application.SymbolTable = map[string]v2.Module{} + shell.Application.SymbolTable = map[string]schema.Module{} shell.Application.ParamIn, shell.Application.ParamOut, shell.Degraded = nil, nil, nil // The artifacts follow symbol_table; they are written one at a time, each // source streamed, in place of a stand-in (writeWithArtifacts). arts := env.Application.Artifacts if len(arts) > 0 { - shell.Application.Artifacts = map[string]v2.Artifact{artifactsHoleKey: {}} + shell.Application.Artifacts = map[string]schema.Artifact{artifactsHoleKey: {}} } data, err := json.Marshal(&shell) if err != nil { @@ -146,12 +146,12 @@ func encode(w io.Writer, env *v2.Analysis, modules iter.Seq2[string, v2.Module], } i := bytes.Index(data, []byte(symbolTableHole)) if i < 0 { - return fmt.Errorf("v2emit: no %s in the envelope", symbolTableHole) + return fmt.Errorf("emit: no %s in the envelope", symbolTableHole) } // With param_in, param_out and degraded omitted, the shell ends with the // application's closing '}' and then the envelope's. if !bytes.HasSuffix(data, []byte("}}")) { - return fmt.Errorf("v2emit: the envelope does not end with the application") + return fmt.Errorf("emit: the envelope does not end with the application") } split := i + len(symbolTableHole) - 1 // at the closing '}' if _, err := w.Write(data[:split]); err != nil { @@ -193,7 +193,7 @@ func encode(w io.Writer, env *v2.Analysis, modules iter.Seq2[string, v2.Module], return err } -func writeEntry(w io.Writer, key string, m v2.Module, first bool) error { +func writeEntry(w io.Writer, key string, m schema.Module, first bool) error { k, err := json.Marshal(key) if err != nil { return err @@ -217,8 +217,8 @@ func writeEntry(w io.Writer, key string, m v2.Module, first bool) error { // emitter is the per-run state Emit and EmitTo share. // -// The signature→can:// id index (idx) translates v1 identity (signature -// strings) into v2 node ids. It is what the L2 refinement uses to backfill +// The signature→can:// id index (idx) translates the model's identity (signature +// strings) into node ids. It is what the L2 refinement uses to backfill // body callees and to map call_graph edge endpoints onto real callable ids. // // srcs holds one lineIndex per source file, read once and shared. A method @@ -227,7 +227,7 @@ func writeEntry(w io.Writer, key string, m v2.Module, first bool) error { // Schema decisions → callable.source_file); the cache lets emitCallable reach // any file's index without re-reading it per callable. type emitter struct { - identity v2.Identity + identity schema.Identity appID string idx sigIndex srcs *sourceCache @@ -235,7 +235,7 @@ type emitter struct { sdg *l4Overlay // nil below L4 } -func newEmitter(app *schema.GoApplication, identity v2.Identity, projectDir string, maxLevel int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) *emitter { +func newEmitter(app *model.GoApplication, identity schema.Identity, projectDir string, maxLevel int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) *emitter { appID := identity.ApplicationID idx := buildSigIndex(appID, app.SymbolTable) idx.externals = externalIDs(appID, app.Externals) @@ -247,13 +247,13 @@ func newEmitter(app *schema.GoApplication, identity v2.Identity, projectDir stri // envelope is the payload without its symbol_table (nil): the manifest, the // call graph and the external symbols. -func (e *emitter) envelope(app *schema.GoApplication, maxLevel int, analyzerVersion string, kLimit int) *v2.Analysis { - out := &v2.Analysis{ - IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, - Language: v2.Language, +func (e *emitter) envelope(app *model.GoApplication, maxLevel int, analyzerVersion string, kLimit int) *schema.Analysis { + out := &schema.Analysis{ + IdentityVersion: 2, SchemaVersion: schema.SchemaVersion, + Language: schema.Language, MaxLevel: maxLevel, - Analyzer: v2.AnalyzerTag{Name: "codeanalyzer-go", Version: analyzerVersion}, - Application: v2.Application{ + Analyzer: schema.AnalyzerTag{Name: "codeanalyzer-go", Version: analyzerVersion}, + Application: schema.Application{ IdentityVersion: 2, ApplicationName: e.identity.ApplicationName, Name: e.identity.ApplicationName, IdentityNamespace: e.identity.Namespace, ID: e.appID, Kind: "application", @@ -268,24 +268,24 @@ func (e *emitter) envelope(app *schema.GoApplication, maxLevel int, analyzerVers return out } -func (e *emitter) module(relPath string, file schema.GoFile) v2.Module { +func (e *emitter) module(relPath string, file model.GoFile) schema.Module { return emitModule(e.appID, relPath, file, e.idx, e.srcs, e.flow, e.sdg) } -// emitModule builds a v2 module from a v1 GoFile, reading the file's source so +// emitModule builds a module from a model GoFile, reading the file's source so // spans can slice off it. A file that cannot be read still emits its structure // (with empty source and zeroed byte spans) rather than dropping the module. // // modRel is this module's own file path (a symbol_table key). It is threaded to // callables so a method declared in another file can be detected and given a // span against its own source plus a source_file pointer. -func emitModule(appID, modRel string, file schema.GoFile, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) v2.Module { +func emitModule(appID, modRel string, file model.GoFile, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) schema.Module { li := srcs.index(modRel) source := li.source - modID := v2.ModuleID(appID, modRel) + modID := schema.ModuleID(appID, modRel) msp := wholeFileSpan(li, source) - mod := v2.Module{ + mod := schema.Module{ ID: modID, Kind: "module", Span: msp, @@ -294,8 +294,8 @@ func emitModule(appID, modRel string, file schema.GoFile, idx sigIndex, srcs *so Package: file.PackageName, Source: source, Imports: emitImports(li, file.Imports), - Types: make(map[string]v2.Type, len(file.Types)), - Functions: make(map[string]v2.Callable, len(file.Functions)), + Types: make(map[string]schema.Type, len(file.Types)), + Functions: make(map[string]schema.Callable, len(file.Functions)), } if file.ContentHash != nil { mod.ContentHash = *file.ContentHash @@ -310,15 +310,15 @@ func emitModule(appID, modRel string, file schema.GoFile, idx sigIndex, srcs *so return mod } -// emitType maps a v1 GoType to a v2 type node, collapsing is_interface into the +// emitType maps a model GoType to a type node, collapsing is_interface into the // kind and splitting embedding (base_types) from computed satisfaction. Methods // resolve into the type's callables{}. modRel is the module the type lives in; // its methods may be declared in other files (handled in emitCallable). -func emitType(appID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) v2.Type { +func emitType(appID, modRel string, t model.GoType, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) schema.Type { li := srcs.index(modRel) - typeID := v2.TypeID(v2.ModuleID(appID, modRel), t.Signature) + typeID := schema.TypeID(schema.ModuleID(appID, modRel), t.Signature) tsp := lineSpan(li, t.StartLine, t.EndLine) - out := v2.Type{ + out := schema.Type{ ID: typeID, Kind: typeKind(t), Signature: t.Signature, @@ -326,13 +326,13 @@ func emitType(appID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceC StartLine: tsp.Start[0], EndLine: tsp.End[0], BaseTypes: nonEmpty(t.BaseTypes), - Callables: make(map[string]v2.Callable, len(t.Methods)), + Callables: make(map[string]schema.Callable, len(t.Methods)), } if len(t.Fields) > 0 { - out.Fields = make(map[string]v2.Field, len(t.Fields)) + out.Fields = make(map[string]schema.Field, len(t.Fields)) for _, f := range t.Fields { fsp := lineSpan(li, f.StartLine, f.EndLine) - out.Fields[f.Name] = v2.Field{ + out.Fields[f.Name] = schema.Field{ ID: typeID + "/" + f.Name, Kind: "field", Type: f.Type, @@ -348,7 +348,7 @@ func emitType(appID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceC return out } -// emitCallable maps a v1 GoCallable to a v2 callable node, including its body +// emitCallable maps a model GoCallable to a callable node, including its body // (call nodes) and nested closures. // // modRel is the CONTAINING module's path: the module this callable nests @@ -356,7 +356,7 @@ func emitType(appID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceC // module its outermost enclosing callable nests under). declRel and declLI are // the file the callable's positions are relative to and its lineIndex: the // nesting file for a top-level callable, the enclosing callable's declaring -// file for a closure (Go has no cross-file closures; a v1 closure's Path is +// file for a closure (Go has no cross-file closures; a model closure's Path is // that same file). A callable's own c.Path, when set, is its declaring file. // // When the declaring file differs from the containing module — a method whose @@ -373,8 +373,8 @@ func emitType(appID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceC // // At L4 the same key finds the callable's SDG overlay (emit_l4.go), applied // after the L3 one, and records the callable's id for the param edges. -func emitCallable(parentID, modRel, declRel string, declLI *lineIndex, c schema.GoCallable, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) v2.Callable { - callID := v2.CallableID(parentID, c.Signature) +func emitCallable(parentID, modRel, declRel string, declLI *lineIndex, c model.GoCallable, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) schema.Callable { + callID := schema.CallableID(parentID, c.Signature) // Resolve the file this callable's positions are relative to. li := declLI @@ -388,7 +388,7 @@ func emitCallable(parentID, modRel, declRel string, declLI *lineIndex, c schema. } csp := lineSpan(li, c.StartLine, c.EndLine) - out := v2.Callable{ + out := schema.Callable{ ID: callID, Kind: callableKind(c), Span: csp, @@ -407,7 +407,7 @@ func emitCallable(parentID, modRel, declRel string, declLI *lineIndex, c schema. out.Metrics = map[string]int{"cyclomatic": c.CyclomaticComplexity} } if len(c.InnerCallables) > 0 { - out.Callables = make(map[string]v2.Callable, len(c.InnerCallables)) + out.Callables = make(map[string]schema.Callable, len(c.InnerCallables)) // Closures nest in the same containing module and are declared in the // same file as their enclosing callable. for sig, inner := range c.InnerCallables { @@ -422,25 +422,25 @@ func emitCallable(parentID, modRel, declRel string, declLI *lineIndex, c schema. // emitBody builds the body map: one `call` node per call site, keyed by its // line:col local id, carrying the sanctioned callee null->id refinement slot. -// Every node carries its global id, v2.GlobalOrdinal(callable id, key), from L1 +// Every node carries its global id, schema.GlobalOrdinal(callable id, key), from L1 // on (R15; Python parity: codeanalyzer-python stamps body ids at L1). // // callee resolution: -// - L1: the v1 site has no backfilled signature, so callee stays null. +// - L1: the model's site has no backfilled signature, so callee stays null. // - L2: the resolver backfilled the site's callee signature. When that // signature names an in-tree callable, callee becomes its can:// id; when // it names a library callee, callee becomes its @external id (a key of // application.external_symbols); otherwise (conversions, builtins, calls // through function values) callee stays null. -func emitBody(callableID string, li *lineIndex, sites []schema.GoCallsite, idx sigIndex) map[string]v2.BodyNode { +func emitBody(callableID string, li *lineIndex, sites []model.GoCallsite, idx sigIndex) map[string]schema.BodyNode { keys := callBodyKeys(sites) - body := make(map[string]v2.BodyNode, len(sites)) + body := make(map[string]schema.BodyNode, len(sites)) for i, cs := range sites { local := keys[i] bsp := colSpan(li, cs.StartLine, cs.StartColumn, cs.EndLine, cs.EndColumn) - body[local] = v2.BodyNode{ + body[local] = schema.BodyNode{ Kind: "call", - ID: v2.GlobalOrdinal(callableID, local), + ID: schema.GlobalOrdinal(callableID, local), Span: bsp, StartLine: bsp.Start[0], EndLine: bsp.End[0], @@ -453,20 +453,20 @@ func emitBody(callableID string, li *lineIndex, sites []schema.GoCallsite, idx s } // callBodyKeys maps each call site to its body-map key. It is a thin wrapper: -// the co-positioned-call keying (l:c, l:c/2, …) lives in v2.CallBodyKeys so the +// the co-positioned-call keying (l:c, l:c/2, …) lives in schema.CallBodyKeys so the // L3 body builder shares it. -func callBodyKeys(sites []schema.GoCallsite) []string { +func callBodyKeys(sites []model.GoCallsite) []string { pos := make([][2]int, len(sites)) for i, cs := range sites { pos[i] = [2]int{cs.StartLine, cs.StartColumn} } - return v2.CallBodyKeys(pos) + return schema.CallBodyKeys(pos) } -// calleeID translates a v1 backfilled callee signature into the v2 can:// id +// calleeID translates a backfilled callee signature into the can:// id // refinement slot: nil (JSON null) when unresolved, a pointer to the in-tree // callable id or the library callee's @external id when resolved. Never returns -// the raw v1 signature — a call node's callee is always a node id or null. +// the raw signature — a call node's callee is always a node id or null. func calleeID(sig *string, idx sigIndex) *string { if sig == nil { return nil @@ -482,20 +482,20 @@ func calleeID(sig *string, idx sigIndex) *string { // // The result is the single source of external ids: the call-edge index and // external_symbols both read it, so an edge and its symbol always agree. Ids -// that collide are made distinct (v2.DisambiguateExternalIDs). -func externalIDs(appID string, externals map[string]schema.GoExternalCallee) map[string]string { +// that collide are made distinct (schema.DisambiguateExternalIDs). +func externalIDs(appID string, externals map[string]model.GoExternalCallee) map[string]string { plain := make(map[string]string, len(externals)) for fullSig, ext := range externals { - plain[fullSig] = v2.ExternalID(appID, ext.ImportPath, ext.Sig) + plain[fullSig] = schema.ExternalID(appID, ext.ImportPath, ext.Sig) } - return v2.DisambiguateExternalIDs(plain) + return schema.DisambiguateExternalIDs(plain) } // emitExternalSymbols builds application.external_symbols, keyed by @external // id. Nil (omitted from JSON) when no library callee was recorded. At L4 // standIns (by full callee signature) gives each stand-in its body: its -// formal vertices, id v2.GlobalOrdinal(external id, key). -func emitExternalSymbols(externals map[string]schema.GoExternalCallee, ids map[string]string, standIns map[string][]sdg.Vertex) map[string]v2.ExternalSymbol { +// formal vertices, id schema.GlobalOrdinal(external id, key). +func emitExternalSymbols(externals map[string]model.GoExternalCallee, ids map[string]string, standIns map[string][]sdg.Vertex) map[string]schema.ExternalSymbol { for _, sig := range slices.Sorted(maps.Keys(standIns)) { if _, ok := externals[sig]; !ok { warnf("L4 emit: stand-in %s is not an external symbol; its body is dropped", sig) @@ -504,22 +504,22 @@ func emitExternalSymbols(externals map[string]schema.GoExternalCallee, ids map[s if len(externals) == 0 { return nil } - out := make(map[string]v2.ExternalSymbol, len(externals)) + out := make(map[string]schema.ExternalSymbol, len(externals)) for fullSig, ext := range externals { id := ids[fullSig] - params := make([]v2.ExternalParameter, 0, len(ext.Params)) + params := make([]schema.ExternalParameter, 0, len(ext.Params)) for _, p := range ext.Params { - params = append(params, v2.ExternalParameter{Name: p.Name, Type: p.Type, IsVariadic: p.IsVariadic}) + params = append(params, schema.ExternalParameter{Name: p.Name, Type: p.Type, IsVariadic: p.IsVariadic}) } - sym := v2.ExternalSymbol{ + sym := schema.ExternalSymbol{ ID: id, Kind: "external", Name: ext.Name, Module: ext.ImportPath, Signature: ext.Sig, Parameters: params, ReturnType: ext.ReturnType, } if ext.Receiver != nil { - sym.Receiver = &v2.ExternalParameter{Name: ext.Receiver.Name, Type: ext.Receiver.Type} + sym.Receiver = &schema.ExternalParameter{Name: ext.Receiver.Name, Type: ext.Receiver.Type} } if vs := standIns[fullSig]; len(vs) > 0 { - sym.Body = make(map[string]v2.BodyNode, len(vs)) + sym.Body = make(map[string]schema.BodyNode, len(vs)) for _, v := range vs { sym.Body[v.Key] = vertexNode(id, v) } @@ -529,11 +529,11 @@ func emitExternalSymbols(externals map[string]schema.GoExternalCallee, ids map[s return out } -func emitParams(li *lineIndex, params []schema.GoParameter) []v2.Parameter { - out := make([]v2.Parameter, 0, len(params)) +func emitParams(li *lineIndex, params []model.GoParameter) []schema.Parameter { + out := make([]schema.Parameter, 0, len(params)) for _, p := range params { psp := lineSpan(li, p.StartLine, p.EndLine) - out = append(out, v2.Parameter{ + out = append(out, schema.Parameter{ Name: p.Name, Type: p.Type, Span: psp, @@ -545,11 +545,11 @@ func emitParams(li *lineIndex, params []schema.GoParameter) []v2.Parameter { return out } -func emitImports(li *lineIndex, imports []schema.GoImport) []v2.Import { - out := make([]v2.Import, 0, len(imports)) +func emitImports(li *lineIndex, imports []model.GoImport) []schema.Import { + out := make([]schema.Import, 0, len(imports)) for _, imp := range imports { isp := lineSpan(li, imp.StartLine, imp.EndLine) - out = append(out, v2.Import{ + out = append(out, schema.Import{ Name: packageBase(imp.Module), Path: imp.Module, Alias: imp.Alias, @@ -561,14 +561,14 @@ func emitImports(li *lineIndex, imports []schema.GoImport) []v2.Import { return out } -// emitCallGraph maps v1 identity-only edges to the v2 {src,dst,prov,weight} +// emitCallGraph maps the model's identity-only edges to {src,dst,prov,weight} // shape: the source/target/provenance rename, PLUS the endpoint translation from -// v1 signatures to can:// ids. A dst may be an in-tree callable or a library +// signatures to can:// ids. A dst may be an in-tree callable or a library // callee's @external id (a key of external_symbols). An edge whose src or dst // does not resolve is dropped rather than emitted with a dangling endpoint — // the L2 gate requires every endpoint to be a real node id. -func emitCallGraph(edges []schema.GoCallEdge, idx sigIndex) []v2.Edge { - out := make([]v2.Edge, 0, len(edges)) +func emitCallGraph(edges []model.GoCallEdge, idx sigIndex) []schema.Edge { + out := make([]schema.Edge, 0, len(edges)) for _, e := range edges { // Resolve the source by (signature, declaring file): a package-level // init signature repeats once per file in a package, so the file is @@ -585,7 +585,7 @@ func emitCallGraph(edges []schema.GoCallEdge, idx sigIndex) []v2.Edge { if !srcOK || !dstOK { continue } - out = append(out, v2.Edge{ + out = append(out, schema.Edge{ Src: src, Dst: dst, Prov: nonEmpty(e.Provenance), @@ -619,10 +619,10 @@ func emitCallGraph(edges []schema.GoCallEdge, idx sigIndex) []v2.Edge { // ─── kind mapping ──────────────────────────────────────────────────────────── -// typeKind reports the v2 kind (struct | interface | alias | defined), recorded +// typeKind reports the kind (struct | interface | alias | defined), recorded // by the symbol-table builder from the type declaration. The IsInterface -// fallback covers hand-built v1 types that carry no TypeKind. -func typeKind(t schema.GoType) string { +// fallback covers hand-built model types that carry no TypeKind. +func typeKind(t model.GoType) string { if t.TypeKind != "" { return t.TypeKind } @@ -633,7 +633,7 @@ func typeKind(t schema.GoType) string { } // callableKind classifies a callable: a non-empty receiver type marks a method. -func callableKind(c schema.GoCallable) string { +func callableKind(c model.GoCallable) string { if c.ReceiverType != "" { return "method" } @@ -654,30 +654,30 @@ func errorChannel(returnTypes []string) []string { // ─── span construction ───────────────────────────────────────────────────────── // wholeFileSpan is the module node's span: the entire file. -func wholeFileSpan(li *lineIndex, source string) v2.Span { +func wholeFileSpan(li *lineIndex, source string) schema.Span { lastLine := len(li.lineStart) if lastLine == 0 { lastLine = 1 } - return v2.NewSpan(1, 1, lastLine, li.lineLen(lastLine)+1, 0, len(source)) + return schema.NewSpan(1, 1, lastLine, li.lineLen(lastLine)+1, 0, len(source)) } -// lineSpan builds a span from a line-only v1 position: start at column 1, end at +// lineSpan builds a span from a line-only model position: start at column 1, end at // the last line's end. Byte offsets bound the whole line range. -func lineSpan(li *lineIndex, startLine, endLine int) v2.Span { +func lineSpan(li *lineIndex, startLine, endLine int) schema.Span { if endLine < startLine { endLine = startLine } endCol := li.lineLen(endLine) + 1 - return v2.NewSpan( + return schema.NewSpan( startLine, 1, endLine, endCol, li.offset(startLine, 1), li.lineEndOffset(endLine), ) } -// colSpan builds a span from a v1 position that carries columns (call sites). -func colSpan(li *lineIndex, startLine, startCol, endLine, endCol int) v2.Span { - return v2.NewSpan( +// colSpan builds a span from a model position that carries columns (call sites). +func colSpan(li *lineIndex, startLine, startCol, endLine, endCol int) schema.Span { + return schema.NewSpan( startLine, startCol, endLine, endCol, li.offset(startLine, startCol), li.offset(endLine, endCol), ) @@ -719,7 +719,7 @@ func (c *sourceCache) index(relPath string) *lineIndex { return li } -func sortedFileKeys(m map[string]schema.GoFile) []string { +func sortedFileKeys(m map[string]model.GoFile) []string { keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) diff --git a/internal/syntactic_analysis/v2emit/emit_l3.go b/internal/syntactic_analysis/emit/emit_l3.go similarity index 73% rename from internal/syntactic_analysis/v2emit/emit_l3.go rename to internal/syntactic_analysis/emit/emit_l3.go index ad6f1cb..456cedd 100644 --- a/internal/syntactic_analysis/v2emit/emit_l3.go +++ b/internal/syntactic_analysis/emit/emit_l3.go @@ -1,8 +1,8 @@ -package v2emit +package emit import ( "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // l3Overlay merges dataflow.Run's side table into the emitted tree. on is @@ -27,11 +27,11 @@ func newL3Overlay(maxLevel int, res map[dataflow.L3Key]dataflow.Result) l3Overla // has no edges); a result node on an L1 key only contributes its Parent; // - every other result node (the pruned set's statement, control and // synthetic nodes) is added with its span from Pos/End and its ID = -// v2.GlobalOrdinal(c.ID, key), the rule emitBody applies to the L1 nodes +// schema.GlobalOrdinal(c.ID, key), the rule emitBody applies to the L1 nodes // (R15), so the id field is uniform at every level. // // Run works on local keys only; ids are minted here and in emitBody. -func (o l3Overlay) apply(c *v2.Callable, li *lineIndex, key dataflow.L3Key) { +func (o l3Overlay) apply(c *schema.Callable, li *lineIndex, key dataflow.L3Key) { if !o.on { return } @@ -43,20 +43,20 @@ func (o l3Overlay) apply(c *v2.Callable, li *lineIndex, key dataflow.L3Key) { continue } bn := l3BodyNode(n, li) - bn.ID = v2.GlobalOrdinal(c.ID, n.Key) + bn.ID = schema.GlobalOrdinal(c.ID, n.Key) c.Body[n.Key] = bn } - c.Cfg = make([]v2.CfgEdge, len(r.Cfg)) + c.Cfg = make([]schema.CfgEdge, len(r.Cfg)) for i, e := range r.Cfg { - c.Cfg[i] = v2.CfgEdge{Src: e.Src, Dst: e.Dst, Kind: e.Kind} + c.Cfg[i] = schema.CfgEdge{Src: e.Src, Dst: e.Dst, Kind: e.Kind} } - c.Cdg = make([]v2.CdgEdge, len(r.Cdg)) + c.Cdg = make([]schema.CdgEdge, len(r.Cdg)) for i, e := range r.Cdg { - c.Cdg[i] = v2.CdgEdge{Src: e.Src, Dst: e.Dst} + c.Cdg[i] = schema.CdgEdge{Src: e.Src, Dst: e.Dst} } - c.Ddg = make([]v2.DdgEdge, len(r.Ddg)) + c.Ddg = make([]schema.DdgEdge, len(r.Ddg)) for i, e := range r.Ddg { - c.Ddg[i] = v2.DdgEdge{Src: e.Src, Dst: e.Dst, Var: e.Var, Prov: []string{"ssa"}} // own slice per edge: no aliasing + c.Ddg[i] = schema.DdgEdge{Src: e.Src, Dst: e.Dst, Var: e.Var, Prov: []string{"ssa"}} // own slice per edge: no aliasing } } } @@ -66,8 +66,8 @@ func (o l3Overlay) apply(c *v2.Callable, li *lineIndex, key dataflow.L3Key) { // call L1 did not key — impossible once Run paired every body call with an // L1 key by Lparen (a unit with an unpaired call gets no L3 result) — and // keeps the call shape with a null callee. -func l3BodyNode(n dataflow.Node, li *lineIndex) v2.BodyNode { - bn := v2.BodyNode{Kind: string(n.Kind), Parent: n.Parent} +func l3BodyNode(n dataflow.Node, li *lineIndex) schema.BodyNode { + bn := schema.BodyNode{Kind: string(n.Kind), Parent: n.Parent} if n.Kind != dataflow.KindEntry && n.Kind != dataflow.KindExit { bn.Span = colSpan(li, n.StartLC[0], n.StartLC[1], n.EndLC[0], n.EndLC[1]) bn.StartLine, bn.EndLine = bn.Span.Start[0], bn.Span.End[0] diff --git a/internal/syntactic_analysis/v2emit/emit_l4.go b/internal/syntactic_analysis/emit/emit_l4.go similarity index 85% rename from internal/syntactic_analysis/v2emit/emit_l4.go rename to internal/syntactic_analysis/emit/emit_l4.go index 6e9f6fa..dc00e8e 100644 --- a/internal/syntactic_analysis/v2emit/emit_l4.go +++ b/internal/syntactic_analysis/emit/emit_l4.go @@ -1,4 +1,4 @@ -package v2emit +package emit import ( "cmp" @@ -10,7 +10,7 @@ import ( "strings" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -23,12 +23,12 @@ var warnf = utils.Warn // // The sdg IR holds no ids; this overlay mints every one of them: // - a callable's vertices land in its body under their local keys, with -// id v2.GlobalOrdinal(callable id, key), kind, of and parent (actuals +// id schema.GlobalOrdinal(callable id, key), kind, of and parent (actuals // only); no span and, not being call nodes, no callee key; // - its port edges join its ddg with prov [Prov]; // - its summary edges are its summary; // - a stand-in's formals land in its external_symbols entry's body, with -// id v2.GlobalOrdinal(external id, key) — @formal_in:; +// id schema.GlobalOrdinal(external id, key) — @formal_in:; // - param_in / param_out endpoints and the degraded callables resolve // through ids, the sdg.Target → id map filled in the same walk that // applies the L3 overlay (externals are known up front, from their @@ -77,7 +77,7 @@ func (o *l4Overlay) warn(format string, args ...any) { // and signature, the key the L3 overlay uses) and adds its L4 overlay: the // vertices to its body, the port edges to its ddg (re-sorted by (src, dst, // var, prov)), and its summary. -func (o *l4Overlay) apply(c *v2.Callable, key dataflow.L3Key) { +func (o *l4Overlay) apply(c *schema.Callable, key dataflow.L3Key) { if o == nil { return } @@ -106,31 +106,31 @@ func (o *l4Overlay) apply(c *v2.Callable, key dataflow.L3Key) { if len(r.Ddg) > 0 { ddg := slices.Grow(c.Ddg, len(r.Ddg)) for _, e := range r.Ddg { - ddg = append(ddg, v2.DdgEdge{Src: e.Src, Dst: e.Dst, Var: e.Var, Prov: []string{e.Prov}}) + ddg = append(ddg, schema.DdgEdge{Src: e.Src, Dst: e.Dst, Var: e.Var, Prov: []string{e.Prov}}) } slices.SortStableFunc(ddg, compareDdg) c.Ddg = ddg } if len(r.Summary) > 0 { - c.Summary = make([]v2.SummaryEdge, len(r.Summary)) + c.Summary = make([]schema.SummaryEdge, len(r.Summary)) for i, e := range r.Summary { - c.Summary[i] = v2.SummaryEdge{Src: e.Src, Dst: e.Dst} + c.Summary[i] = schema.SummaryEdge{Src: e.Src, Dst: e.Dst} } - slices.SortFunc(c.Summary, func(a, b v2.SummaryEdge) int { + slices.SortFunc(c.Summary, func(a, b schema.SummaryEdge) int { return cmp.Or(strings.Compare(a.Src, b.Src), strings.Compare(a.Dst, b.Dst)) }) } } // vertexNode is the body node of vertex v of the callable or stand-in owner. -func vertexNode(owner string, v sdg.Vertex) v2.BodyNode { - return v2.BodyNode{Kind: string(v.Kind), ID: v2.GlobalOrdinal(owner, v.Key), Parent: v.Parent, Of: v.Of} +func vertexNode(owner string, v sdg.Vertex) schema.BodyNode { + return schema.BodyNode{Kind: string(v.Kind), ID: schema.GlobalOrdinal(owner, v.Key), Parent: v.Parent, Of: v.Of} } // compareDdg orders a callable's ddg by (src, dst, var, prov). L3's own // list is sorted by (src, dst, var) with prov ["ssa"] throughout, so the // L3 edges keep their relative order. -func compareDdg(a, b v2.DdgEdge) int { +func compareDdg(a, b schema.DdgEdge) int { return cmp.Or( strings.Compare(a.Src, b.Src), strings.Compare(a.Dst, b.Dst), strings.Compare(a.Var, b.Var), slices.Compare(a.Prov, b.Prov), @@ -173,7 +173,7 @@ type mintedEdge struct { // owner ids and local keys (compareOrdinal compares the joined ids without // building them), so the whole list is never minted at once: on the // streaming path each edge's ids exist only while it is written. -func (o *l4Overlay) paramEdges(list string, edges []sdg.ParamEdge) iter.Seq[v2.ParamEdge] { +func (o *l4Overlay) paramEdges(list string, edges []sdg.ParamEdge) iter.Seq[schema.ParamEdge] { ms := make([]mintedEdge, 0, len(edges)) for i := range edges { e := &edges[i] @@ -191,14 +191,14 @@ func (o *l4Overlay) paramEdges(list string, edges []sdg.ParamEdge) iter.Seq[v2.P ) } slices.SortFunc(ms, compare) - return func(yield func(v2.ParamEdge) bool) { + return func(yield func(schema.ParamEdge) bool) { for i, m := range ms { if i > 0 && compare(ms[i-1], m) == 0 { continue } - if !yield(v2.ParamEdge{ - Src: v2.GlobalOrdinal(m.src, m.e.Src.Key), - Dst: v2.GlobalOrdinal(m.dst, m.e.Dst.Key), + if !yield(schema.ParamEdge{ + Src: schema.GlobalOrdinal(m.src, m.e.Src.Key), + Dst: schema.GlobalOrdinal(m.dst, m.e.Dst.Key), Var: m.e.Var, }) { return @@ -228,13 +228,13 @@ func describeTarget(t sdg.Target) string { // degraded mints the degradation markers: each callable as its id (sorted, // unique), entries sorted by (code, detail); nil when nothing degraded. -func (o *l4Overlay) degraded() []v2.Degraded { +func (o *l4Overlay) degraded() []schema.Degraded { if len(o.res.Degraded) == 0 { return nil } - out := make([]v2.Degraded, 0, len(o.res.Degraded)) + out := make([]schema.Degraded, 0, len(o.res.Degraded)) for _, d := range o.res.Degraded { - v := v2.Degraded{Code: d.Code, Detail: d.Detail, Packages: nonEmpty(d.Packages)} + v := schema.Degraded{Code: d.Code, Detail: d.Detail, Packages: nonEmpty(d.Packages)} for _, k := range d.Callables { if id, ok := o.resolve("degraded "+d.Code, sdg.Target{Callable: k}); ok { v.Callables = append(v.Callables, id) @@ -244,7 +244,7 @@ func (o *l4Overlay) degraded() []v2.Degraded { v.Callables = slices.Compact(v.Callables) out = append(out, v) } - slices.SortStableFunc(out, func(a, b v2.Degraded) int { + slices.SortStableFunc(out, func(a, b schema.Degraded) int { return cmp.Or(strings.Compare(a.Code, b.Code), strings.Compare(a.Detail, b.Detail)) }) return out @@ -263,7 +263,7 @@ func compareOrdinal(o1, k1, o2, k2 string) int { return compareJoined([3]string{o1, ordinalSep(k1), k1}, [3]string{o2, ordinalSep(k2), k2}) } -// ordinalSep is what v2.GlobalOrdinal puts between a callable id and k. +// ordinalSep is what schema.GlobalOrdinal puts between a callable id and k. func ordinalSep(k string) string { if strings.HasPrefix(k, "@") { return "" @@ -303,13 +303,13 @@ func compareJoined(a, b [3]string) int { // the whole tree's ids: the application's param_in / param_out (its last // two fields) and the envelope's degraded (its last field). type lateFields struct { - paramIn, paramOut iter.Seq[v2.ParamEdge] - degraded []v2.Degraded + paramIn, paramOut iter.Seq[schema.ParamEdge] + degraded []schema.Degraded } // writeParamList writes `,"":[e,e,…]` with each edge as json.Marshal // writes it, or nothing when seq is empty (omitempty). -func writeParamList(w io.Writer, key string, seq iter.Seq[v2.ParamEdge]) error { +func writeParamList(w io.Writer, key string, seq iter.Seq[schema.ParamEdge]) error { if seq == nil { return nil } diff --git a/internal/syntactic_analysis/v2emit/emit_l4_test.go b/internal/syntactic_analysis/emit/emit_l4_test.go similarity index 89% rename from internal/syntactic_analysis/v2emit/emit_l4_test.go rename to internal/syntactic_analysis/emit/emit_l4_test.go index 1357509..2979bc1 100644 --- a/internal/syntactic_analysis/v2emit/emit_l4_test.go +++ b/internal/syntactic_analysis/emit/emit_l4_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit import ( "fmt" @@ -7,12 +7,12 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" ) // TestCompareOrdinal_MatchesMintedIds: compareOrdinal orders (owner, key) -// pairs exactly as their minted ids v2.GlobalOrdinal(owner, key) compare, +// pairs exactly as their minted ids schema.GlobalOrdinal(owner, key) compare, // including an owner that is a prefix of the other (a callable and its // closure) and the "@"-tag keys, whose ids carry no extra "@". func TestCompareOrdinal_MatchesMintedIds(t *testing.T) { @@ -26,7 +26,7 @@ func TestCompareOrdinal_MatchesMintedIds(t *testing.T) { pick := func(s []string) string { return s[r.IntN(len(s))] } for range 20000 { o1, k1, o2, k2 := pick(owners), pick(keys), pick(owners), pick(keys) - want := strings.Compare(v2.GlobalOrdinal(o1, k1), v2.GlobalOrdinal(o2, k2)) + want := strings.Compare(schema.GlobalOrdinal(o1, k1), schema.GlobalOrdinal(o2, k2)) if got := compareOrdinal(o1, k1, o2, k2); got != want { t.Fatalf("compareOrdinal(%q, %q, %q, %q) = %d, want %d", o1, k1, o2, k2, got, want) } @@ -49,7 +49,7 @@ func TestL4Overlay_DuplicateKeyKeepsSmallerID(t *testing.T) { warned = nil o := newL4Overlay(4, &sdg.Result{}, sigIndex{}) for _, id := range order { - o.apply(&v2.Callable{ID: id, Body: map[string]v2.BodyNode{}}, key) + o.apply(&schema.Callable{ID: id, Body: map[string]schema.BodyNode{}}, key) } if got := o.ids[sdg.Target{Callable: key}]; got != small { t.Errorf("apply order %v: target routes to %s, want %s", order, got, small) @@ -72,7 +72,7 @@ func TestL4Overlay_QuietSecondWalk(t *testing.T) { o := newL4Overlay(4, &sdg.Result{}, sigIndex{}) walk := func() { for _, id := range ids { - o.apply(&v2.Callable{ID: id, Body: map[string]v2.BodyNode{}}, key) + o.apply(&schema.Callable{ID: id, Body: map[string]schema.BodyNode{}}, key) } } walk() diff --git a/internal/syntactic_analysis/v2emit/emit_test.go b/internal/syntactic_analysis/emit/emit_test.go similarity index 91% rename from internal/syntactic_analysis/v2emit/emit_test.go rename to internal/syntactic_analysis/emit/emit_test.go index 9bc1dc3..f9db144 100644 --- a/internal/syntactic_analysis/v2emit/emit_test.go +++ b/internal/syntactic_analysis/emit/emit_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit import ( "encoding/json" @@ -7,8 +7,8 @@ import ( "strings" "testing" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) @@ -24,7 +24,7 @@ func greeterDir(t *testing.T) string { } // buildGreeter runs the real symbol-table builder over the greeter fixture. -func buildGreeter(t *testing.T) (*schema.GoApplication, string) { +func buildGreeter(t *testing.T) (*model.GoApplication, string) { t.Helper() dir := greeterDir(t) b := syntactic_analysis.NewSymbolTableBuilder(dir) @@ -32,7 +32,7 @@ func buildGreeter(t *testing.T) (*schema.GoApplication, string) { if err != nil { t.Fatalf("symbol table build failed: %v", err) } - return &schema.GoApplication{SymbolTable: st, CallGraph: []schema.GoCallEdge{}}, dir + return &model.GoApplication{SymbolTable: st, CallGraph: []model.GoCallEdge{}}, dir } func TestEmit_Envelope(t *testing.T) { @@ -87,7 +87,7 @@ func TestEmit_CallableBodyAndSpanSlice(t *testing.T) { out := Emit(app, testIdentity("greeter"), dir, 1, "test", 0, nil, nil) mod := out.Application.SymbolTable["main.go"] - var main v2.Callable + var main schema.Callable found := false for _, fn := range mod.Functions { if fn.Signature != "" && strings.HasSuffix(fn.Signature, ".main") { @@ -131,14 +131,14 @@ func TestEmit_CalleeSerializesAsNull(t *testing.T) { if !strings.Contains(string(data), `"callee":null`) { t.Error("expected at least one call node to serialize callee as null at L1") } - // The v1-only keys must be gone. + // The model-only keys must be gone. for _, banned := range []string{`"symbol_table"`, `"call_graph"`} { if !strings.Contains(string(data), banned) { - t.Errorf("expected v2 payload to contain %s", banned) + t.Errorf("expected the payload to contain %s", banned) } } if strings.Contains(string(data), `"is_constructor_call"`) { - t.Error("v2 payload should not contain dropped is_constructor_call") + t.Error("the payload should not contain dropped is_constructor_call") } } @@ -184,8 +184,8 @@ func keys[V any](m map[string]V) []string { return out } -func testIdentity(name string) v2.Identity { - i, e := v2.ResolveIdentity(name, nil) +func testIdentity(name string) schema.Identity { + i, e := schema.ResolveIdentity(name, nil) if e != nil { panic(e) } diff --git a/internal/syntactic_analysis/v2emit/gate_l2_inits_test.go b/internal/syntactic_analysis/emit/gate_l2_inits_test.go similarity index 90% rename from internal/syntactic_analysis/v2emit/gate_l2_inits_test.go rename to internal/syntactic_analysis/emit/gate_l2_inits_test.go index 3953e2a..4adbfbc 100644 --- a/internal/syntactic_analysis/v2emit/gate_l2_inits_test.go +++ b/internal/syntactic_analysis/emit/gate_l2_inits_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit // Repeated `.init` gate. Go allows a func init() in every file of a // package, and all of them share the signature ".init". The resolver must @@ -14,15 +14,15 @@ import ( "runtime" "testing" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) // buildDataflowL2Fresh runs an independent L2 analysis of testdata/dataflow // (new symbol table, resolver and externals), so map order varies per call. -func buildDataflowL2Fresh(t *testing.T) *v2.Analysis { +func buildDataflowL2Fresh(t *testing.T) *schema.Analysis { t.Helper() _, thisFile, _, _ := runtime.Caller(0) dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "testdata", "dataflow")) @@ -36,7 +36,7 @@ func buildDataflowL2Fresh(t *testing.T) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} return Emit(app, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) } @@ -46,7 +46,7 @@ func TestGateL2_EveryInitKeepsItsEdges(t *testing.T) { out := buildDataflowL2Fresh(t) const initSig = "example.com/dataflow/inits.init" setup := functionByName(t, mustModule(t, out, "inits/a.go"), "setup").ID - getenv := v2.ExternalID(out.Application.ID, "os", "Getenv") + getenv := schema.ExternalID(out.Application.ID, "os", "Getenv") has := map[[2]string]bool{} for _, e := range out.Application.CallGraph { diff --git a/internal/syntactic_analysis/v2emit/gate_l2_test.go b/internal/syntactic_analysis/emit/gate_l2_test.go similarity index 87% rename from internal/syntactic_analysis/v2emit/gate_l2_test.go rename to internal/syntactic_analysis/emit/gate_l2_test.go index 412d424..7156234 100644 --- a/internal/syntactic_analysis/v2emit/gate_l2_test.go +++ b/internal/syntactic_analysis/emit/gate_l2_test.go @@ -1,11 +1,11 @@ -package v2emit +package emit -// L2 conformance gate for the v2 emitter. +// L2 conformance gate for the emitter. // // L2 is a pure refinement over L1: it backfills the callee null->id slot and // emits the call_graph edge list, both endpoints callable ids. This gate builds // the multipackage fixture through the REAL resolver (the same wiring the -// analyzer uses at -a 2), emits v2, and asserts every item on the L2 checklist +// analyzer uses at -a 2), emits, and asserts every item on the L2 checklist // in designing-cldk-changes/references/testing-and-validation.md: // // - no dangling endpoints — every edge src/dst is a real callable id @@ -23,15 +23,15 @@ import ( "strings" "testing" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) // buildMultipackageL2 builds the fixture AND runs the resolver, so the emitted -// v2 payload carries L2 facts (backfilled callees, call_graph edges). -func buildMultipackageL2(t *testing.T) *v2.Analysis { +// payload carries L2 facts (backfilled callees, call_graph edges). +func buildMultipackageL2(t *testing.T) *schema.Analysis { t.Helper() dir := multipackageDir(t) b := syntactic_analysis.NewSymbolTableBuilder(dir) @@ -41,15 +41,15 @@ func buildMultipackageL2(t *testing.T) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) // mutates st in place: backfills callee_signature - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} return Emit(app, testIdentity("multipackage"), dir, 2, "gate-test", 0, nil, nil) } // allCallableIDs collects every callable/type id in the emitted tree. -func allCallableIDs(out *v2.Analysis) map[string]bool { +func allCallableIDs(out *schema.Analysis) map[string]bool { ids := map[string]bool{} - var walk func(c v2.Callable) - walk = func(c v2.Callable) { + var walk func(c schema.Callable) + walk = func(c schema.Callable) { ids[c.ID] = true for _, inner := range c.Callables { walk(inner) @@ -150,7 +150,7 @@ func TestGateL2_CrossPackageEdge(t *testing.T) { // TestGateL2_CalleeBackfilled locks the refinement: the goroutine call site in // Worker.Run has its callee backfilled to Worker.execute's can:// id (not null, -// not the raw v1 signature). +// not the raw signature). func TestGateL2_CalleeBackfilled(t *testing.T) { out := buildMultipackageL2(t) ids := allCallableIDs(out) @@ -189,12 +189,12 @@ func TestGateL2_SupersetOfL1(t *testing.T) { t.Fatalf("symbol table build failed: %v", err) } // L1 snapshot BEFORE the resolver mutates call sites. - l1 := Emit(&schema.GoApplication{SymbolTable: st, CallGraph: nil}, testIdentity("multipackage"), dir, 1, "gate-test", 0, nil, nil) + l1 := Emit(&model.GoApplication{SymbolTable: st, CallGraph: nil}, testIdentity("multipackage"), dir, 1, "gate-test", 0, nil, nil) // Now run the resolver (mutates st) and emit L2. cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - l2 := Emit(&schema.GoApplication{SymbolTable: st, CallGraph: edges}, testIdentity("multipackage"), dir, 2, "gate-test", 0, nil, nil) + l2 := Emit(&model.GoApplication{SymbolTable: st, CallGraph: edges}, testIdentity("multipackage"), dir, 2, "gate-test", 0, nil, nil) if len(l1.Application.SymbolTable) != len(l2.Application.SymbolTable) { t.Fatalf("module count changed L1->L2: %d vs %d", @@ -218,7 +218,7 @@ func TestGateL2_SupersetOfL1(t *testing.T) { // assertCallablesEqualModuloCallee checks two callable maps are identical except // that a body node's callee may have gone from null (L1) to a non-null id (L2). -func assertCallablesEqualModuloCallee(t *testing.T, where string, a, b map[string]v2.Callable) { +func assertCallablesEqualModuloCallee(t *testing.T, where string, a, b map[string]schema.Callable) { t.Helper() if len(a) != len(b) { t.Errorf("%s: callable count changed L1->L2: %d vs %d", where, len(a), len(b)) @@ -251,10 +251,10 @@ func assertCallablesEqualModuloCallee(t *testing.T, where string, a, b map[strin } } -func anyCallNodeHasCallee(out *v2.Analysis, id string) bool { +func anyCallNodeHasCallee(out *schema.Analysis, id string) bool { found := false - var walk func(c v2.Callable) - walk = func(c v2.Callable) { + var walk func(c schema.Callable) + walk = func(c schema.Callable) { for _, n := range c.Body { if n.Callee != nil && *n.Callee == id { found = true @@ -277,7 +277,7 @@ func anyCallNodeHasCallee(out *v2.Analysis, id string) bool { return found } -func anyEdgeTo(edges []v2.Edge, dst string) bool { +func anyEdgeTo(edges []schema.Edge, dst string) bool { for _, e := range edges { if e.Dst == dst { return true @@ -291,13 +291,13 @@ func anyEdgeTo(edges []v2.Edge, dst string) bool { // the call node's callee is its @external id, and a call_graph edge targets it. func TestGateL2_ExternalCalleeBackfilled(t *testing.T) { out := buildMultipackageL2(t) - ext := v2.ExternalID(out.Application.ID, "fmt", "Println") + ext := schema.ExternalID(out.Application.ID, "fmt", "Println") sym, ok := out.Application.ExternalSymbols[ext] if !ok { t.Fatalf("external_symbols missing %s", ext) } - want := v2.ExternalSymbol{ID: ext, Kind: "external", Name: "Println", Module: "fmt", Signature: "Println"} + want := schema.ExternalSymbol{ID: ext, Kind: "external", Name: "Println", Module: "fmt", Signature: "Println"} if sym.ID != want.ID || sym.Kind != want.Kind || sym.Name != want.Name || sym.Module != want.Module || sym.Signature != want.Signature { t.Errorf("external symbol = %+v, want identity fields %+v", sym, want) @@ -326,7 +326,7 @@ func F() string { return sb.String() } `) - ext := v2.ExternalID(out.Application.ID, "strings", "Builder.WriteString") + ext := schema.ExternalID(out.Application.ID, "strings", "Builder.WriteString") sym, ok := out.Application.ExternalSymbols[ext] if !ok { t.Fatalf("external_symbols missing %s; have %v", ext, out.Application.ExternalSymbols) @@ -350,7 +350,7 @@ import "strings" func F() string { return strings.ToUpper("x") } `) - sym, ok := out.Application.ExternalSymbols[v2.ExternalID(out.Application.ID, "strings", "ToUpper")] + sym, ok := out.Application.ExternalSymbols[schema.ExternalID(out.Application.ID, "strings", "ToUpper")] if !ok { t.Fatalf("external_symbols missing strings.ToUpper") } @@ -392,8 +392,8 @@ func F(b []byte) string { } // emitTemp builds a one-file module (p.go) in a temp dir through the real -// builder + resolver and emits v2 at L2. -func emitTemp(t *testing.T, src string) *v2.Analysis { +// builder + resolver and emits at L2. +func emitTemp(t *testing.T, src string) *schema.Analysis { t.Helper() dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module example.com/p\n\ngo 1.21\n"), 0o644); err != nil { @@ -409,7 +409,7 @@ func emitTemp(t *testing.T, src string) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} return Emit(app, testIdentity("p"), dir, 2, "gate-test", 0, nil, nil) } @@ -417,7 +417,7 @@ func emitTemp(t *testing.T, src string) *v2.Analysis { // without a span key (no fabricated location). func TestGateL2_ExternalParamsHaveNoSpan(t *testing.T) { out := buildMultipackageL2(t) - ext := v2.ExternalID(out.Application.ID, "fmt", "Println") + ext := schema.ExternalID(out.Application.ID, "fmt", "Println") raw, err := json.Marshal(out.Application.ExternalSymbols[ext]) if err != nil { t.Fatal(err) @@ -442,8 +442,8 @@ func TestGateL2_GenericLibraryMethodUsesDeclaredSignature(t *testing.T) { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - out := Emit(&schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) - ext := v2.ExternalID(out.Application.ID, "sync/atomic", "Pointer.Store") + out := Emit(&model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) + ext := schema.ExternalID(out.Application.ID, "sync/atomic", "Pointer.Store") sym, ok := out.Application.ExternalSymbols[ext] if !ok { t.Fatalf("missing %s; have %v", ext, out.Application.ExternalSymbols) @@ -466,7 +466,7 @@ func TestGateL2_IncrementalModeKeepsProjectCalleesInternal(t *testing.T) { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - out := Emit(&schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("multipackage"), dir, 2, "gate-test", 0, nil, nil) + out := Emit(&model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("multipackage"), dir, 2, "gate-test", 0, nil, nil) const projectModule = "example.com/multipackage" for id, sym := range out.Application.ExternalSymbols { @@ -474,7 +474,7 @@ func TestGateL2_IncrementalModeKeepsProjectCalleesInternal(t *testing.T) { t.Errorf("project callee minted as external: %s (module %s)", id, sym.Module) } } - if _, ok := out.Application.ExternalSymbols[v2.ExternalID(out.Application.ID, "fmt", "Println")]; !ok { + if _, ok := out.Application.ExternalSymbols[schema.ExternalID(out.Application.ID, "fmt", "Println")]; !ok { t.Error("fmt.Println should still be external in incremental mode") } } @@ -492,9 +492,9 @@ func TestGateL2_VendoredCalleeIsExternal(t *testing.T) { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - out := Emit(&schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) + out := Emit(&model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) - ext := v2.ExternalID(out.Application.ID, "example.com/vlib", "F") + ext := schema.ExternalID(out.Application.ID, "example.com/vlib", "F") sym, ok := out.Application.ExternalSymbols[ext] if !ok { t.Fatalf("external_symbols missing %s; have %v", ext, out.Application.ExternalSymbols) @@ -519,7 +519,7 @@ func TestGateL2_LineDirectiveCallsResolve(t *testing.T) { out := buildDataflowL2Fresh(t) fn := functionByName(t, mustModule(t, out, "linedir/linedir.go"), "Caller") helper := functionByName(t, mustModule(t, out, "linedir/linedir.go"), "helper").ID - getenv := v2.ExternalID(out.Application.ID, "os", "Getenv") + getenv := schema.ExternalID(out.Application.ID, "os", "Getenv") callees := map[string]bool{} for k, n := range fn.Body { @@ -564,10 +564,10 @@ func TestGateL2_ExternalUnnamedParamsArePositional(t *testing.T) { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - out := Emit(&schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) + out := Emit(&model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) for sig, want := range map[string][]string{"G": {"_0", "_1"}, "H": {"_0", "n"}} { - ext := v2.ExternalID(out.Application.ID, "example.com/vlib", sig) + ext := schema.ExternalID(out.Application.ID, "example.com/vlib", sig) sym, ok := out.Application.ExternalSymbols[ext] if !ok { t.Errorf("external_symbols missing %s", ext) @@ -583,8 +583,8 @@ func TestGateL2_ExternalUnnamedParamsArePositional(t *testing.T) { } } -// emitDirL2 builds dir through the real builder + resolver and emits v2 at L2. -func emitDirL2(t *testing.T, dir, app string) *v2.Analysis { +// emitDirL2 builds dir through the real builder + resolver and emits at L2. +func emitDirL2(t *testing.T, dir, app string) *schema.Analysis { t.Helper() b := syntactic_analysis.NewSymbolTableBuilder(dir) st, err := b.Build(nil, true) @@ -593,12 +593,12 @@ func emitDirL2(t *testing.T, dir, app string) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - return Emit(&schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity(app), dir, 2, "gate-test", 0, nil, nil) + return Emit(&model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()}, testIdentity(app), dir, 2, "gate-test", 0, nil, nil) } // assertNoDanglingEdges fails when an edge endpoint is neither a callable id // nor an external_symbols key. -func assertNoDanglingEdges(t *testing.T, out *v2.Analysis) { +func assertNoDanglingEdges(t *testing.T, out *schema.Analysis) { t.Helper() ids := allCallableIDs(out) for id := range out.Application.ExternalSymbols { @@ -620,7 +620,7 @@ func TestGateL2_ClosureCallSitesResolve(t *testing.T) { if len(closure.Callables) != 1 { t.Fatalf("Closure has %d closures, want 1", len(closure.Callables)) } - var lit v2.Callable + var lit schema.Callable for _, c := range closure.Callables { lit = c } @@ -653,8 +653,8 @@ func TestGateL2_ClosureCallSitesResolve(t *testing.T) { func TestGateL2_ChiClosureCallsResolve(t *testing.T) { out := buildChiL2Fresh(t, chiDir(t)) resolved := 0 - var walk func(c v2.Callable, inClosure bool) - walk = func(c v2.Callable, inClosure bool) { + var walk func(c schema.Callable, inClosure bool) + walk = func(c schema.Callable, inClosure bool) { if inClosure { for _, n := range c.Body { if n.Kind == "call" && n.Callee != nil { @@ -703,11 +703,11 @@ func TestGateL2_CrossFileMethodClosureEdge(t *testing.T) { t.Fatalf("Run has %d closures, want 1", len(run.Callables)) } helper := functionByName(t, mustModule(t, out, "b.go"), "helper").ID - var fn v2.Callable + var fn schema.Callable for _, c := range run.Callables { fn = c } - var inner v2.Callable + var inner schema.Callable for _, c := range fn.Callables { inner = c } @@ -715,7 +715,7 @@ func TestGateL2_CrossFileMethodClosureEdge(t *testing.T) { for _, e := range out.Application.CallGraph { has[[2]string{e.Src, e.Dst}] = true } - for _, c := range []v2.Callable{fn, inner} { + for _, c := range []schema.Callable{fn, inner} { if c.ID == "" || !has[[2]string{c.ID, helper}] { t.Errorf("missing edge %s -> %s", c.ID, helper) } diff --git a/internal/syntactic_analysis/v2emit/gate_l3_test.go b/internal/syntactic_analysis/emit/gate_l3_test.go similarity index 85% rename from internal/syntactic_analysis/v2emit/gate_l3_test.go rename to internal/syntactic_analysis/emit/gate_l3_test.go index 3b98d89..393ce1e 100644 --- a/internal/syntactic_analysis/v2emit/gate_l3_test.go +++ b/internal/syntactic_analysis/emit/gate_l3_test.go @@ -1,6 +1,6 @@ -package v2emit +package emit -// L3 conformance gate for the v2 emitter. +// L3 conformance gate for the emitter. // // L3 completes each callable's body (statement / branch / loop / switch / // return / entry / exit nodes around the L1 call nodes) and adds the @@ -11,7 +11,7 @@ package v2emit // - every callable with a body has @entry / @exit and a non-empty cfg // - no dangling endpoint: every cfg / cdg / ddg endpoint and every parent // is a key of the callable's own body; ddg prov is ["ssa"] -// - every body node id is v2.GlobalOrdinal(callable id, key) +// - every body node id is schema.GlobalOrdinal(callable id, key) // - json(-a 2) ⊆ json(-a 3), modulo the sanctioned additions // - spans slice to the statement text, cross-file methods included // - every side-table entry lands on an emitted callable @@ -27,15 +27,15 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) type l3Fixture struct { - st map[string]schema.GoFile - l2, l3 *v2.Analysis + st map[string]model.GoFile + l2, l3 *schema.Analysis res map[dataflow.L3Key]dataflow.Result } @@ -65,7 +65,7 @@ func buildL3(t *testing.T, name string) *l3Fixture { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} res := dataflow.Run(b.Fset(), b.L3Units(st), 3, 4) fx := &l3Fixture{ st: st, @@ -77,19 +77,19 @@ func buildL3(t *testing.T, name string) *l3Fixture { return fx } -// emitted is one callable of the v2 tree with its v1 source and the file its +// emitted is one callable of the output tree with its model source and the file its // spans index. type emitted struct { - v1 schema.GoCallable - v2 v2.Callable + in model.GoCallable + out schema.Callable declFile string } -// pairCallables walks the v1 symbol table and the v2 tree in parallel. -func pairCallables(st map[string]schema.GoFile, out *v2.Analysis) []emitted { +// pairCallables walks the model's symbol table and the output tree in parallel. +func pairCallables(st map[string]model.GoFile, out *schema.Analysis) []emitted { var all []emitted - var walk func(c1 schema.GoCallable, c2 v2.Callable, encl string) - walk = func(c1 schema.GoCallable, c2 v2.Callable, encl string) { + var walk func(c1 model.GoCallable, c2 schema.Callable, encl string) + walk = func(c1 model.GoCallable, c2 schema.Callable, encl string) { file := encl if c2.SourceFile != "" { file = c2.SourceFile @@ -110,7 +110,7 @@ func pairCallables(st map[string]schema.GoFile, out *v2.Analysis) []emitted { } } } - sort.Slice(all, func(i, j int) bool { return all[i].v2.ID < all[j].v2.ID }) + sort.Slice(all, func(i, j int) bool { return all[i].out.ID < all[j].out.ID }) return all } @@ -127,17 +127,17 @@ func gateEntryExit(t *testing.T, name string, floor int) { } withBody := 0 for _, e := range pairCallables(fx.st, fx.l3) { - if e.v1.Code == "" { + if e.in.Code == "" { continue // bodyless (interface method) } withBody++ for _, k := range []string{"@entry", "@exit"} { - if _, ok := e.v2.Body[k]; !ok { - t.Errorf("%s: no %s body node", e.v2.ID, k) + if _, ok := e.out.Body[k]; !ok { + t.Errorf("%s: no %s body node", e.out.ID, k) } } - if len(e.v2.Cfg) == 0 { - t.Errorf("%s: empty cfg", e.v2.ID) + if len(e.out.Cfg) == 0 { + t.Errorf("%s: empty cfg", e.out.ID) } } if withBody < floor { @@ -150,7 +150,7 @@ func TestGateL3_EveryEdgeEndpointIsABodyKey(t *testing.T) { fx := buildL3(t, name) edges := 0 for _, e := range pairCallables(fx.st, fx.l3) { - c := e.v2 + c := e.out in := func(list, k string) { if _, ok := c.Body[k]; !ok { t.Errorf("%s: %s endpoint %q is not a body key", c.ID, list, k) @@ -188,21 +188,21 @@ func TestGateL3_EveryEdgeEndpointIsABodyKey(t *testing.T) { func TestGateL3_BodyNodeIDsAreGlobalOrdinals(t *testing.T) { fx := buildL3(t, "dataflow") for _, e := range pairCallables(fx.st, fx.l3) { - for k, n := range e.v2.Body { - if want := v2.GlobalOrdinal(e.v2.ID, k); n.ID != want { - t.Errorf("%s body %s id = %q, want %q", e.v2.ID, k, n.ID, want) + for k, n := range e.out.Body { + if want := schema.GlobalOrdinal(e.out.ID, k); n.ID != want { + t.Errorf("%s body %s id = %q, want %q", e.out.ID, k, n.ID, want) } } } // Below L3 every body node carries the same id (R15, Python parity: // stamp_body_ids runs at L1); parent is still L3+ only. for _, e := range pairCallables(fx.st, fx.l2) { - for k, n := range e.v2.Body { - if want := v2.GlobalOrdinal(e.v2.ID, k); n.ID != want { - t.Errorf("L2 %s body %s id = %q, want %q", e.v2.ID, k, n.ID, want) + for k, n := range e.out.Body { + if want := schema.GlobalOrdinal(e.out.ID, k); n.ID != want { + t.Errorf("L2 %s body %s id = %q, want %q", e.out.ID, k, n.ID, want) } if n.Parent != "" { - t.Errorf("L2 %s body %s carries parent %q", e.v2.ID, k, n.Parent) + t.Errorf("L2 %s body %s carries parent %q", e.out.ID, k, n.Parent) } } } @@ -234,7 +234,7 @@ func TestGateL3_SupersetOfL2(t *testing.T) { } } -func toAny(t *testing.T, a *v2.Analysis) map[string]any { +func toAny(t *testing.T, a *schema.Analysis) map[string]any { t.Helper() data, err := json.Marshal(a) if err != nil { @@ -311,25 +311,25 @@ func TestGateL3_SpansSliceToStatementText(t *testing.T) { } for _, name := range []string{"dataflow", "multipackage"} { fx := buildL3(t, name) - l2 := map[string]v2.Callable{} + l2 := map[string]schema.Callable{} for _, e := range pairCallables(fx.st, fx.l2) { - l2[e.v2.ID] = e.v2 + l2[e.out.ID] = e.out } checked, crossFile := 0, 0 for _, e := range pairCallables(fx.st, fx.l3) { src := fx.l3.Application.SymbolTable[e.declFile].Source - for k, n := range e.v2.Body { + for k, n := range e.out.Body { text := n.Span.Slice(src) switch n.Kind { case "entry", "exit": continue case "call": - if l1 := l2[e.v2.ID].Body[k]; l1.Span != n.Span { - t.Errorf("%s call %s span %v, L1 %v", e.v2.ID, k, n.Span, l1.Span) + if l1 := l2[e.out.ID].Body[k]; l1.Span != n.Span { + t.Errorf("%s call %s span %v, L1 %v", e.out.ID, k, n.Span, l1.Span) } case "statement": if strings.TrimSpace(text) == "" || text != strings.TrimSpace(text) { - t.Errorf("%s %s statement span slices to %q", e.v2.ID, k, text) + t.Errorf("%s %s statement span slices to %q", e.out.ID, k, text) } default: ok := false @@ -337,14 +337,14 @@ func TestGateL3_SpansSliceToStatementText(t *testing.T) { ok = ok || strings.HasPrefix(text, p) } if !ok { - t.Errorf("%s %s (%s) span slices to %q", e.v2.ID, k, n.Kind, text) + t.Errorf("%s %s (%s) span slices to %q", e.out.ID, k, n.Kind, text) } } - if want := v2.LocalID(n.Span.Start[0], n.Span.Start[1]); n.Kind != "call" && !strings.HasPrefix(k, want) { - t.Errorf("%s %s span starts at %s", e.v2.ID, k, want) + if want := schema.LocalID(n.Span.Start[0], n.Span.Start[1]); n.Kind != "call" && !strings.HasPrefix(k, want) { + t.Errorf("%s %s span starts at %s", e.out.ID, k, want) } checked++ - if e.v2.SourceFile != "" { + if e.out.SourceFile != "" { crossFile++ } } @@ -362,7 +362,7 @@ func TestEmitL3_NoOrphanSideTableEntries(t *testing.T) { fx := buildL3(t, "dataflow") seen := map[dataflow.L3Key]bool{} for _, e := range pairCallables(fx.st, fx.l3) { - seen[dataflow.L3Key{Path: e.declFile, Signature: e.v2.Signature}] = true + seen[dataflow.L3Key{Path: e.declFile, Signature: e.out.Signature}] = true } for k := range fx.res { if !seen[k] { @@ -383,7 +383,7 @@ func TestEmitL3_NoOrphanSideTableEntries(t *testing.T) { // closure and for every body node inside it. func TestGateL3_CrossFileClosureSourceFile(t *testing.T) { fx := buildL3(t, "dataflow") - for _, out := range []*v2.Analysis{fx.l2, fx.l3} { + for _, out := range []*schema.Analysis{fx.l2, fx.l3} { mod := mustModule(t, out, "xfile/a.go") run, ok := mod.Types["T"].Callables["example.com/dataflow/xfile.T.Run"] if !ok { @@ -398,16 +398,16 @@ func TestGateL3_CrossFileClosureSourceFile(t *testing.T) { t.Fatalf("nested closure missing; have %v", keys(add.Callables)) } src := mustModule(t, out, "xfile/b.go").Source - for _, c := range []v2.Callable{run, add, inc} { + for _, c := range []schema.Callable{run, add, inc} { if c.SourceFile != "xfile/b.go" { t.Errorf("L%d %s source_file = %q, want xfile/b.go", out.MaxLevel, c.ID, c.SourceFile) } } - // Callable spans are line-level (v1 records closure lines only), so + // Callable spans are line-level (the model records closure lines only), so // the slice starts at the line's first column: it holds the closure's // func literal from its opening to its closing brace. for _, w := range []struct { - c v2.Callable + c schema.Callable head string }{{add, "add := func(d int) int {"}, {inc, "inc := func() {"}} { text := strings.TrimSpace(w.c.Span.Slice(src)) @@ -419,7 +419,7 @@ func TestGateL3_CrossFileClosureSourceFile(t *testing.T) { continue } for _, w := range []struct { - c v2.Callable + c schema.Callable key string text string }{{add, "6:3", "t.n += d"}, {add, "11:3", "return t.n"}, {inc, "8:4", "t.n++"}} { @@ -503,7 +503,7 @@ func TestSymbolTable_MethodDeclaredAboveItsType(t *testing.T) { fx := buildL3(t, "dataflow") const sig = "example.com/dataflow/flow.early.Bump" - find := func(out *v2.Analysis) (v2.Callable, bool) { + find := func(out *schema.Analysis) (schema.Callable, bool) { for _, mod := range out.Application.SymbolTable { for _, ty := range mod.Types { for _, m := range ty.Callables { @@ -513,14 +513,14 @@ func TestSymbolTable_MethodDeclaredAboveItsType(t *testing.T) { } } } - return v2.Callable{}, false + return schema.Callable{}, false } bump, ok := find(fx.l2) if !ok { t.Fatalf("no callable %s under type early at -a 2", sig) } - var call *v2.BodyNode + var call *schema.BodyNode for _, n := range bump.Body { n := n if n.Kind == "call" { diff --git a/internal/syntactic_analysis/v2emit/gate_l4_done_test.go b/internal/syntactic_analysis/emit/gate_l4_done_test.go similarity index 89% rename from internal/syntactic_analysis/v2emit/gate_l4_done_test.go rename to internal/syntactic_analysis/emit/gate_l4_done_test.go index c22142b..a2d561c 100644 --- a/internal/syntactic_analysis/v2emit/gate_l4_done_test.go +++ b/internal/syntactic_analysis/emit/gate_l4_done_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit // The L4 "done" gate (spec §8): on the HTTP → SQL fixture // testdata/dataflow/httpsql, the emitted JSON graph carries a flow from an @@ -15,8 +15,8 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" @@ -24,7 +24,7 @@ import ( // sdgGraph is the emitted JSON's dependence graph over global body node ids: // every callable's ddg, cdg and summary edges (local keys minted with -// v2.GlobalOrdinal) and the application's param_in and param_out — the +// schema.GlobalOrdinal) and the application's param_in and param_out — the // edge families the SDK's slice and taint walks follow. Each edge records // its family, so a path can be checked for the hops it takes. type sdgGraph struct { @@ -36,11 +36,11 @@ type sdgHop struct { v string // the edge's var (ddg, param_in, param_out); "" for cdg and summary } -func newSDGGraph(a *v2.Analysis) *sdgGraph { +func newSDGGraph(a *schema.Analysis) *sdgGraph { g := &sdgGraph{succ: map[string][]sdgHop{}} add := func(src, dst, family, v string) { g.succ[src] = append(g.succ[src], sdgHop{dst, family, v}) } for _, c := range l4Callables(a) { - id := func(k string) string { return v2.GlobalOrdinal(c.ID, k) } + id := func(k string) string { return schema.GlobalOrdinal(c.ID, k) } for _, e := range c.Ddg { add(id(e.Src), id(e.Dst), "ddg", e.Var) } @@ -137,13 +137,13 @@ func TestGateL4_HTTPToSQLPath(t *testing.T) { } return found[0] } - mod := v2.ModuleID(app, "httpsql.go") + mod := schema.ModuleID(app, "httpsql.go") pkg := "example.com/dataflow/httpsql." - fn := func(name string) string { return v2.CallableID(mod, pkg+name) } - closure := func(name string) string { return v2.CallableID(fn(name), pkg+name+".closure_1") } - method := func(typ, m string) string { return v2.CallableID(v2.TypeID(mod, pkg+typ), pkg+typ+"."+m) } + fn := func(name string) string { return schema.CallableID(mod, pkg+name) } + closure := func(name string) string { return schema.CallableID(fn(name), pkg+name+".closure_1") } + method := func(typ, m string) string { return schema.CallableID(schema.TypeID(mod, pkg+typ), pkg+typ+"."+m) } - sink := vertex(v2.ExternalID(app, "database/sql", "DB.Query"), "formal_in", "query") + sink := vertex(schema.ExternalID(app, "database/sql", "DB.Query"), "formal_in", "query") if sink != "can://httpsql/httpsql/@external/database/sql/DB/Query@formal_in:1" { t.Fatalf("sink vertex %s", sink) } @@ -209,7 +209,7 @@ func TestGateL4_HTTPToSQLPath(t *testing.T) { // buildHTTPSQLWithModels is buildL4 over testdata/dataflow/httpsql with // --library-models models, uncached. -func buildHTTPSQLWithModels(t *testing.T, models sdg.Models) *v2.Analysis { +func buildHTTPSQLWithModels(t *testing.T, models sdg.Models) *schema.Analysis { t.Helper() _, thisFile, _, _ := runtime.Caller(0) dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "testdata", "dataflow", "httpsql")) @@ -223,7 +223,7 @@ func buildHTTPSQLWithModels(t *testing.T, models sdg.Models) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} units := b.L3Units(st) res := dataflow.RunWithSideTables(b.Fset(), units, 3, 4) l4 := sdg.Run(sdg.Input{ @@ -263,26 +263,26 @@ func TestGateL4_HTTPToSQLSanitizerIsSDKSemantics(t *testing.T) { plain := buildL4(t, "dataflow/httpsql").l4 modelled := buildHTTPSQLWithModels(t, sdg.Models{"strconv/Atoi": {}}) app := modelled.Application.ID - mod := v2.ModuleID(app, "httpsql.go") + mod := schema.ModuleID(app, "httpsql.go") pkg := "example.com/dataflow/httpsql." - sanFind := v2.CallableID(v2.TypeID(mod, pkg+"sqlRepo"), pkg+"sqlRepo.SanitizedFind") - handler := v2.CallableID(v2.CallableID(mod, pkg+"SanitizedHandler"), pkg+"SanitizedHandler.closure_1") - sink := v2.ExternalID(app, "database/sql", "DB.Query") + "@formal_in:1" - r := v2.GlobalOrdinal(handler, "@formal_in:1") - id := v2.GlobalOrdinal(sanFind, "@formal_in:1") - recv := v2.GlobalOrdinal(sanFind, "@formal_in:0") + sanFind := schema.CallableID(schema.TypeID(mod, pkg+"sqlRepo"), pkg+"sqlRepo.SanitizedFind") + handler := schema.CallableID(schema.CallableID(mod, pkg+"SanitizedHandler"), pkg+"SanitizedHandler.closure_1") + sink := schema.ExternalID(app, "database/sql", "DB.Query") + "@formal_in:1" + r := schema.GlobalOrdinal(handler, "@formal_in:1") + id := schema.GlobalOrdinal(sanFind, "@formal_in:1") + recv := schema.GlobalOrdinal(sanFind, "@formal_in:0") - callable := func(a *v2.Analysis, cid string) v2.Callable { + callable := func(a *schema.Analysis, cid string) schema.Callable { for _, c := range l4Callables(a) { if c.ID == cid { return c } } t.Fatalf("no callable %s", cid) - return v2.Callable{} + return schema.Callable{} } // The Atoi call site: the actual_in whose param_in reaches strconv/Atoi. - atoi := v2.ExternalID(app, "strconv", "Atoi") + atoi := schema.ExternalID(app, "strconv", "Atoi") var atoiSite string for _, e := range modelled.Application.ParamIn { if strings.HasPrefix(e.Dst, atoi+"@") && strings.HasPrefix(e.Src, sanFind+"@") { @@ -293,7 +293,7 @@ func TestGateL4_HTTPToSQLSanitizerIsSDKSemantics(t *testing.T) { if atoiSite == "" { t.Fatal("no param_in from SanitizedFind to strconv/Atoi") } - sitesSummary := func(a *v2.Analysis) int { + sitesSummary := func(a *schema.Analysis) int { n := 0 for _, e := range callable(a, sanFind).Summary { if strings.HasPrefix(e.Src, atoiSite+"/") { diff --git a/internal/syntactic_analysis/v2emit/gate_l4_test.go b/internal/syntactic_analysis/emit/gate_l4_test.go similarity index 90% rename from internal/syntactic_analysis/v2emit/gate_l4_test.go rename to internal/syntactic_analysis/emit/gate_l4_test.go index fafbfba..5059ba7 100644 --- a/internal/syntactic_analysis/v2emit/gate_l4_test.go +++ b/internal/syntactic_analysis/emit/gate_l4_test.go @@ -1,6 +1,6 @@ -package v2emit +package emit -// L4 conformance harness for the v2 emitter. +// L4 conformance harness for the emitter. // // buildL4 runs the -a 4 pipeline: the -a 3 one, then sdg.Run, whose VTA // call_graph edges and VTA-only externals are merged into the application @@ -20,19 +20,19 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) type l4Fixture struct { - st map[string]schema.GoFile - l3, l4 *v2.Analysis + st map[string]model.GoFile + l3, l4 *schema.Analysis res map[dataflow.L3Key]dataflow.Result sdg *sdg.Result - app *schema.GoApplication + app *model.GoApplication dir string } @@ -45,7 +45,7 @@ var ( // L3 and the L4 payload from the same resolved symbol table. The app name is // name's last element (cango's default: the input directory's base name). func buildL4(t *testing.T, name string) *l4Fixture { return buildL4Identity(t, name, nil) } -func buildL4Identity(t *testing.T, name string, identity *v2.Identity) *l4Fixture { +func buildL4Identity(t *testing.T, name string, identity *schema.Identity) *l4Fixture { t.Helper() l4Mu.Lock() defer l4Mu.Unlock() @@ -68,7 +68,7 @@ func buildL4Identity(t *testing.T, name string, identity *v2.Identity) *l4Fixtur } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} units := b.L3Units(st) res := dataflow.RunWithSideTables(b.Fset(), units, 3, 4) appName := filepath.Base(dir) @@ -182,14 +182,14 @@ func jsonKey(v any) string { func TestGateL4_CallGraphHasVTAProv(t *testing.T) { fx := buildL4(t, "dataflow") app := fx.l4.Application - mod := v2.ModuleID(app.ID, "sdg/sdg.go") + mod := schema.ModuleID(app.ID, "sdg/sdg.go") fn := func(sig string) string { - return v2.CallableID(mod, "example.com/dataflow/sdg."+sig) + return schema.CallableID(mod, "example.com/dataflow/sdg."+sig) } method := func(typ, m string) string { - return v2.CallableID(v2.TypeID(mod, "example.com/dataflow/sdg."+typ), "example.com/dataflow/sdg."+typ+"."+m) + return schema.CallableID(schema.TypeID(mod, "example.com/dataflow/sdg."+typ), "example.com/dataflow/sdg."+typ+"."+m) } - bufWrite := v2.ExternalID(app.ID, "bytes", "Buffer.Write") + bufWrite := schema.ExternalID(app.ID, "bytes", "Buffer.Write") want := [][2]string{ {fn("UseStore"), method("memStore", "Get")}, {fn("UseStore"), method("sqlStore", "Get")}, @@ -201,7 +201,7 @@ func TestGateL4_CallGraphHasVTAProv(t *testing.T) { for _, e := range fx.l3.Application.CallGraph { l3[[2]string{e.Src, e.Dst}] = true } - vta := map[[2]string]v2.Edge{} + vta := map[[2]string]schema.Edge{} for _, e := range app.CallGraph { if slices.Contains(e.Prov, "vta") { k := [2]string{e.Src, e.Dst} @@ -231,11 +231,11 @@ func TestGateL4_CallGraphHasVTAProv(t *testing.T) { } // Each file's init closure is its own target: the edges keep both. initClosure := func(file string) string { - m := v2.ModuleID(app.ID, "initclosure/"+file) - init := v2.CallableID(m, "example.com/dataflow/initclosure.init") - return v2.CallableID(init, "example.com/dataflow/initclosure.init.closure_1") + m := schema.ModuleID(app.ID, "initclosure/"+file) + init := schema.CallableID(m, "example.com/dataflow/initclosure.init") + return schema.CallableID(init, "example.com/dataflow/initclosure.init.closure_1") } - run := v2.CallableID(v2.ModuleID(app.ID, "initclosure/a.go"), "example.com/dataflow/initclosure.Run") + run := schema.CallableID(schema.ModuleID(app.ID, "initclosure/a.go"), "example.com/dataflow/initclosure.Run") for _, file := range []string{"a.go", "b.go"} { if _, ok := vta[[2]string{run, initClosure(file)}]; !ok { t.Errorf("no VTA edge Run -> %s's init closure", file) @@ -261,10 +261,10 @@ func isVertexKind(k string) bool { } // l4Callables is every callable of the tree (methods and closures included). -func l4Callables(a *v2.Analysis) []v2.Callable { - var out []v2.Callable - var walk func(c v2.Callable) - walk = func(c v2.Callable) { +func l4Callables(a *schema.Analysis) []schema.Callable { + var out []schema.Callable + var walk func(c schema.Callable) + walk = func(c schema.Callable) { out = append(out, c) for _, in := range c.Callables { walk(in) @@ -288,10 +288,10 @@ func l4Callables(a *v2.Analysis) []v2.Callable { type ownedNode struct { owner string key string - node v2.BodyNode + node schema.BodyNode } -func bodyIndex(a *v2.Analysis) map[string]ownedNode { +func bodyIndex(a *schema.Analysis) map[string]ownedNode { idx := map[string]ownedNode{} for _, c := range l4Callables(a) { for k, n := range c.Body { @@ -351,7 +351,7 @@ func TestGateL4_NoDanglingEndpoints(t *testing.T) { } summary += len(c.Summary) } - for list, edges := range map[string][]v2.ParamEdge{"param_in": a.Application.ParamIn, "param_out": a.Application.ParamOut} { + for list, edges := range map[string][]schema.ParamEdge{"param_in": a.Application.ParamIn, "param_out": a.Application.ParamOut} { for _, e := range edges { for _, id := range []string{e.Src, e.Dst} { if _, ok := idx[id]; !ok { @@ -416,7 +416,7 @@ func TestGateL4_NoDanglingEndpoints(t *testing.T) { } // TestGateL4_VertexIdsAreGlobalOrdinals: every vertex — a callable's or a -// stand-in's — has id v2.GlobalOrdinal(owner id, key), a kind, an `of`, no +// stand-in's — has id schema.GlobalOrdinal(owner id, key), a kind, an `of`, no // span and no callee key; only actual vertices carry a parent. A stand-in // vertex id is @formal_in: (one "@" after the external id). func TestGateL4_VertexIdsAreGlobalOrdinals(t *testing.T) { @@ -424,7 +424,7 @@ func TestGateL4_VertexIdsAreGlobalOrdinals(t *testing.T) { fx := buildL4(t, name) for id, on := range bodyIndex(fx.l4) { n := on.node - if want := v2.GlobalOrdinal(on.owner, on.key); id != want { + if want := schema.GlobalOrdinal(on.owner, on.key); id != want { t.Errorf("%s: body id %s, want %s", name, id, want) } if !isVertexKind(n.Kind) { @@ -433,7 +433,7 @@ func TestGateL4_VertexIdsAreGlobalOrdinals(t *testing.T) { } continue } - if n.Of == "" || n.Span != (v2.Span{}) || n.Callee != nil { + if n.Of == "" || n.Span != (schema.Span{}) || n.Callee != nil { t.Errorf("%s: vertex %s = %+v, want an of, no span, no callee", name, id, n) } actual := n.Kind == string(sdg.KindActualIn) || n.Kind == string(sdg.KindActualOut) @@ -466,7 +466,7 @@ func TestGateL4_ArityMatchesFormals(t *testing.T) { for _, name := range l4Fixtures { fx := buildL4(t, name) idx := bodyIndex(fx.l4) - check := func(list string, e v2.ParamEdge, actual, formal string, formalEnd string) { + check := func(list string, e schema.ParamEdge, actual, formal string, formalEnd string) { src, dst := idx[e.Src], idx[e.Dst] act, form := src, dst if formalEnd == "src" { @@ -495,7 +495,7 @@ func TestGateL4_ArityMatchesFormals(t *testing.T) { func TestGateL4_ParamEdgesSorted(t *testing.T) { for _, name := range l4Fixtures { fx := buildL4(t, name) - for list, edges := range map[string][]v2.ParamEdge{"param_in": fx.l4.Application.ParamIn, "param_out": fx.l4.Application.ParamOut} { + for list, edges := range map[string][]schema.ParamEdge{"param_in": fx.l4.Application.ParamIn, "param_out": fx.l4.Application.ParamOut} { for i := 1; i < len(edges); i++ { a, b := edges[i-1], edges[i] if cmpStrings(a.Src, b.Src, a.Dst, b.Dst, a.Var, b.Var) >= 0 { @@ -537,12 +537,12 @@ func cmpStrings(xs ...string) int { func TestGateL4_UseStoreEdges(t *testing.T) { fx := buildL4(t, "dataflow") app := fx.l4.Application - mod := v2.ModuleID(app.ID, "sdg/sdg.go") - useStore := v2.CallableID(mod, "example.com/dataflow/sdg.UseStore") + mod := schema.ModuleID(app.ID, "sdg/sdg.go") + useStore := schema.CallableID(mod, "example.com/dataflow/sdg.UseStore") method := func(typ, m string) string { - return v2.CallableID(v2.TypeID(mod, "example.com/dataflow/sdg."+typ), "example.com/dataflow/sdg."+typ+"."+m) + return schema.CallableID(schema.TypeID(mod, "example.com/dataflow/sdg."+typ), "example.com/dataflow/sdg."+typ+"."+m) } - var c v2.Callable + var c schema.Callable for _, x := range l4Callables(fx.l4) { if x.ID == useStore { c = x @@ -554,7 +554,7 @@ func TestGateL4_UseStoreEdges(t *testing.T) { "34:9/actual_out:0": "", "34:9/actual_out:1": "_recv", } { n, ok := c.Body[k] - if !ok || n.Of != of || n.ID != v2.GlobalOrdinal(useStore, k) { + if !ok || n.Of != of || n.ID != schema.GlobalOrdinal(useStore, k) { t.Errorf("UseStore body %s = %+v, want of %q", k, n, of) } } @@ -569,7 +569,7 @@ func TestGateL4_UseStoreEdges(t *testing.T) { for _, e := range app.ParamOut { out[[3]string{e.Src, e.Dst, e.Var}] = true } - site := func(k string) string { return v2.GlobalOrdinal(useStore, "34:9/"+k) } + site := func(k string) string { return schema.GlobalOrdinal(useStore, "34:9/"+k) } for _, e := range [][3]string{ {site("actual_in:0"), method("Store", "Get") + "@formal_in:0", "_recv"}, {site("actual_in:0"), method("memStore", "Get") + "@formal_in:0", "s"}, @@ -588,8 +588,8 @@ func TestGateL4_UseStoreEdges(t *testing.T) { t.Errorf("no param_out %v", e) } } - stores := v2.CallableID(mod, "example.com/dataflow/sdg.Stores") - if !in[[3]string{v2.GlobalOrdinal(stores, "40:2/actual_in:1"), useStore + "@formal_in:1", "k"}] { + stores := schema.CallableID(mod, "example.com/dataflow/sdg.Stores") + if !in[[3]string{schema.GlobalOrdinal(stores, "40:2/actual_in:1"), useStore + "@formal_in:1", "k"}] { t.Errorf("no param_in Stores@40:2/actual_in:1 -> UseStore@formal_in:1") } } @@ -600,7 +600,7 @@ func TestGateL4_UseStoreEdges(t *testing.T) { func TestGateL4_StandInBody(t *testing.T) { fx := buildL4(t, "dataflow") app := fx.l4.Application - id := v2.ExternalID(app.ID, "fmt", "Sprintf") + id := schema.ExternalID(app.ID, "fmt", "Sprintf") ext, ok := app.ExternalSymbols[id] if !ok { t.Fatalf("no external %s", id) @@ -651,7 +651,7 @@ func TestGateL4_DegradedMintsCallables(t *testing.T) { } if d.Code == sdg.CodeRangeFunc { found = true - want := v2.CallableID(v2.ModuleID(fx.l4.Application.ID, "r.go"), "example.com/rangefunc.RangeFunc") + want := schema.CallableID(schema.ModuleID(fx.l4.Application.ID, "r.go"), "example.com/rangefunc.RangeFunc") if !slices.Contains(d.Callables, want) { t.Errorf("range_func callables %v lack %s", d.Callables, want) } @@ -681,7 +681,7 @@ func TestGateL4_StoredLiteralGlobalReachable(t *testing.T) { a := fx.l4 succ := map[string][]string{} for _, c := range l4Callables(a) { - g := func(k string) string { return v2.GlobalOrdinal(c.ID, k) } + g := func(k string) string { return schema.GlobalOrdinal(c.ID, k) } for _, e := range c.Ddg { succ[g(e.Src)] = append(succ[g(e.Src)], g(e.Dst)) } @@ -709,8 +709,8 @@ func TestGateL4_StoredLiteralGlobalReachable(t *testing.T) { } return seen } - mod := v2.ModuleID(a.Application.ID, "storedlit.go") - fn := func(name string) string { return v2.CallableID(mod, "example.com/storedlit."+name) } + mod := schema.ModuleID(a.Application.ID, "storedlit.go") + fn := func(name string) string { return schema.CallableID(mod, "example.com/storedlit."+name) } idx := bodyIndex(a) formal := func(owner, kind, of string) string { for id, on := range idx { @@ -735,7 +735,7 @@ func TestGateL4_StoredLiteralGlobalReachable(t *testing.T) { // summary), v does not reach sink's formal_out — sink's formal_out is fed // only by its formal_in, the identity edge, as the literal's write has no // param_out. Update this when the gap closes. - var pub v2.Callable + var pub schema.Callable for _, c := range l4Callables(a) { if c.ID == fn("Publish") { pub = c @@ -789,7 +789,7 @@ func buildL4Jobs(t *testing.T, dir, name string, jobs int) []byte { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges, Externals: cg.Externals()} units := b.L3Units(st) res := dataflow.RunWithSideTables(b.Fset(), units, 3, jobs) l4 := sdg.Run(sdg.Input{ @@ -856,7 +856,7 @@ func TestEmitL4_UnresolvedRefIsDroppedAndWarned(t *testing.T) { prev := warnf warnf = func(format string, args ...any) { warned = append(warned, fmt.Sprintf(format, args...)) } defer func() { warnf = prev }() - app := &schema.GoApplication{SymbolTable: fx.st, Externals: map[string]schema.GoExternalCallee{}} + app := &model.GoApplication{SymbolTable: fx.st, Externals: map[string]model.GoExternalCallee{}} out := Emit(app, testIdentity("dataflow"), fx.dir, 4, "t", 3, fx.res, &res) for _, e := range out.Application.ParamIn { if strings.Contains(e.Src, "nowhere") || strings.Contains(e.Dst, "nowhere") { @@ -874,8 +874,8 @@ func TestEmitL4_UnresolvedRefIsDroppedAndWarned(t *testing.T) { // endpoints. func TestGateL4_PointsToEdges(t *testing.T) { fx := buildL4(t, "dataflow") - mod := v2.ModuleID(fx.l4.Application.ID, "sdg/sdg.go") - id := v2.CallableID(mod, "example.com/dataflow/sdg.AliasPtr") + mod := schema.ModuleID(fx.l4.Application.ID, "sdg/sdg.go") + id := schema.CallableID(mod, "example.com/dataflow/sdg.AliasPtr") var got [][3]string for _, c := range l4Callables(fx.l4) { if c.ID != id { @@ -934,7 +934,7 @@ func TestSupersetL4_DetectsEveryViolation(t *testing.T) { func TestNamespaceNestedReferences(t *testing.T) { ns := "team space" - identity, err := v2.ResolveIdentity("billing", &ns) + identity, err := schema.ResolveIdentity("billing", &ns) if err != nil { t.Fatal(err) } diff --git a/internal/syntactic_analysis/v2emit/gate_l4_wrap_test.go b/internal/syntactic_analysis/emit/gate_l4_wrap_test.go similarity index 83% rename from internal/syntactic_analysis/v2emit/gate_l4_wrap_test.go rename to internal/syntactic_analysis/emit/gate_l4_wrap_test.go index 2cff0b1..b10ebee 100644 --- a/internal/syntactic_analysis/v2emit/gate_l4_wrap_test.go +++ b/internal/syntactic_analysis/emit/gate_l4_wrap_test.go @@ -1,13 +1,13 @@ -package v2emit +package emit import ( "testing" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" ) // l4Vertex is the one body node of owner with kind and of in a's tree. -func l4Vertex(t *testing.T, a *v2.Analysis, owner, kind, of string) string { +func l4Vertex(t *testing.T, a *schema.Analysis, owner, kind, of string) string { t.Helper() var found []string for id, on := range bodyIndex(a) { @@ -22,7 +22,7 @@ func l4Vertex(t *testing.T, a *v2.Analysis, owner, kind, of string) string { } // hasVertex reports whether owner has a body node of kind and of in a's tree. -func hasVertex(a *v2.Analysis, owner, kind, of string) bool { +func hasVertex(a *schema.Analysis, owner, kind, of string) bool { for _, on := range bodyIndex(a) { if on.owner == owner && on.node.Kind == kind && on.node.Of == of { return true @@ -41,9 +41,9 @@ func TestGateL4_FlowBehindSyntheticWrappers(t *testing.T) { if len(a.Degraded) != 0 { t.Fatalf("wrap degraded: %+v", a.Degraded) } - mod := v2.ModuleID(a.Application.ID, "wrap.go") + mod := schema.ModuleID(a.Application.ID, "wrap.go") pkg := "example.com/dataflow/wrap." - fn := func(name string) string { return v2.CallableID(mod, pkg+name) } + fn := func(name string) string { return schema.CallableID(mod, pkg+name) } sink := l4Vertex(t, a, fn("Exec"), "formal_in", "query") g := newSDGGraph(a) for _, h := range []string{"HandleDirect", "HandleBound", "HandleDecorated"} { @@ -67,9 +67,9 @@ func TestGateL4_FlowThroughLibraryStorage(t *testing.T) { if len(a.Degraded) != 0 { t.Fatalf("libstore degraded: %+v", a.Degraded) } - mod := v2.ModuleID(a.Application.ID, "libstore.go") + mod := schema.ModuleID(a.Application.ID, "libstore.go") pkg := "example.com/dataflow/libstore." - fn := func(name string) string { return v2.CallableID(mod, pkg+name) } + fn := func(name string) string { return schema.CallableID(mod, pkg+name) } sink := l4Vertex(t, a, fn("Exec"), "formal_in", "query") g := newSDGGraph(a) for _, h := range []string{"HandleCtx", "HandleMap"} { @@ -93,10 +93,10 @@ func TestGateL4_FlowThroughProjectCode(t *testing.T) { if len(a.Degraded) != 0 { t.Fatalf("libflow degraded: %+v", a.Degraded) } - mod := v2.ModuleID(a.Application.ID, "libflow.go") + mod := schema.ModuleID(a.Application.ID, "libflow.go") pkg := "example.com/dataflow/libflow." - fn := func(name string) string { return v2.CallableID(mod, pkg+name) } - method := func(typ, m string) string { return v2.CallableID(v2.TypeID(mod, pkg+typ), pkg+typ+"."+m) } + fn := func(name string) string { return schema.CallableID(mod, pkg+name) } + method := func(typ, m string) string { return schema.CallableID(schema.TypeID(mod, pkg+typ), pkg+typ+"."+m) } sink := l4Vertex(t, a, fn("Exec"), "formal_in", "query") g := newSDGGraph(a) for _, src := range []string{ diff --git a/internal/syntactic_analysis/v2emit/gate_test.go b/internal/syntactic_analysis/emit/gate_test.go similarity index 86% rename from internal/syntactic_analysis/v2emit/gate_test.go rename to internal/syntactic_analysis/emit/gate_test.go index 86382da..d13d5dd 100644 --- a/internal/syntactic_analysis/v2emit/gate_test.go +++ b/internal/syntactic_analysis/emit/gate_test.go @@ -1,9 +1,9 @@ -package v2emit +package emit -// L1 conformance gate for the v2 emitter. +// L1 conformance gate for the emitter. // // This is the fixture gate the codeanalyzer-backend ladder requires before L1 -// advances: it locks the v2 L1 OUTPUT SHAPE against a known multi-file fixture, +// advances: it locks the L1 OUTPUT SHAPE against a known multi-file fixture, // asserting concrete values (not just "a key exists") for every item on the L1 // coverage checklist in // designing-cldk-changes/references/testing-and-validation.md: @@ -16,7 +16,7 @@ package v2emit // - a language-specific call flag (is_goroutine on `go w.execute(...)`) // - the sanctioned callee:null refinement slot present at L1 // - can:// durable ids at module/type/callable depth -// - the SUPERSET gate: every v1 fact survives into v2 modulo sanctioned drops +// - the SUPERSET gate: every model fact survives into the output modulo sanctioned drops // (is_constructor_call is dropped; per-node `code` folds into module.source). // // If any of these regress, this gate fails and the level does not advance. @@ -29,8 +29,8 @@ import ( "strings" "testing" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" ) @@ -46,10 +46,10 @@ func multipackageDir(t *testing.T) string { return abs } -// buildMultipackageV2 runs the real symbol-table builder over the multipackage -// fixture and emits the v2 L1 payload. skipTests=true keeps *_test.go out so the +// buildMultipackage runs the real symbol-table builder over the multipackage +// fixture and emits the L1 payload. skipTests=true keeps *_test.go out so the // module set is deterministic. -func buildMultipackageV2(t *testing.T) *v2.Analysis { +func buildMultipackage(t *testing.T) *schema.Analysis { t.Helper() dir := multipackageDir(t) b := syntactic_analysis.NewSymbolTableBuilder(dir) @@ -57,12 +57,12 @@ func buildMultipackageV2(t *testing.T) *v2.Analysis { if err != nil { t.Fatalf("symbol table build failed: %v", err) } - app := &schema.GoApplication{SymbolTable: st, CallGraph: []schema.GoCallEdge{}} + app := &model.GoApplication{SymbolTable: st, CallGraph: []model.GoCallEdge{}} return Emit(app, testIdentity("multipackage"), dir, 1, "gate-test", 0, nil, nil) } // mustModule fetches a module by relative path or fails. -func mustModule(t *testing.T, out *v2.Analysis, rel string) v2.Module { +func mustModule(t *testing.T, out *schema.Analysis, rel string) schema.Module { t.Helper() mod, ok := out.Application.SymbolTable[rel] if !ok { @@ -74,7 +74,7 @@ func mustModule(t *testing.T, out *v2.Analysis, rel string) v2.Module { // TestGateL1_ModuleSet locks the exact multi-file compilation unit: the four // non-test source files, each a module keyed by its relative path. func TestGateL1_ModuleSet(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) want := []string{ "main.go", @@ -104,7 +104,7 @@ func TestGateL1_ModuleSet(t *testing.T) { // TestGateL1_InterfaceKind locks the Processor interface: is_interface collapses // into kind=interface, and its method resolves as a callable under the type. func TestGateL1_InterfaceKind(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) worker := mustModule(t, out, "worker/worker.go") proc, ok := worker.Types["Processor"] @@ -131,7 +131,7 @@ func TestGateL1_InterfaceKind(t *testing.T) { // TestGateL1_ExportedAndUnexported locks that both an exported (Run) and an // unexported (execute) method survive, each a method callable under Worker. func TestGateL1_ExportedAndUnexported(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) worker := mustModule(t, out, "worker/worker.go") wtype, ok := worker.Types["Worker"] @@ -156,7 +156,7 @@ func TestGateL1_ExportedAndUnexported(t *testing.T) { // TestGateL1_VariadicParameter locks the variadic-parameter fact: // Combine(results ...Result) → is_variadic=true on the sole parameter. func TestGateL1_VariadicParameter(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) worker := mustModule(t, out, "worker/worker.go") const combineID = "example.com/multipackage/worker.Combine" @@ -176,7 +176,7 @@ func TestGateL1_VariadicParameter(t *testing.T) { // contains `go w.execute(...)`, which must surface as a body call node with // is_goroutine=true AND callee null at L1. func TestGateL1_GoroutineCallNode(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) worker := mustModule(t, out, "worker/worker.go") run, ok := worker.Types["Worker"].Callables["example.com/multipackage/worker.Worker.Run"] @@ -207,14 +207,14 @@ func TestGateL1_GoroutineCallNode(t *testing.T) { // calling into server/ and worker/) is present as its own module with body call // nodes — the compilation unit spans packages, not a single file. func TestGateL1_CrossPackageStructure(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) main := mustModule(t, out, "main.go") if main.Package != "main" { t.Errorf("main.go package = %q, want main", main.Package) } // main() drives the cross-package calls; its body must carry call nodes. - var mainFn v2.Callable + var mainFn schema.Callable found := false for _, fn := range main.Functions { if strings.HasSuffix(fn.Signature, ".main") { @@ -242,7 +242,7 @@ func TestGateL1_CrossPackageStructure(t *testing.T) { // the method text — the check that regressed to "" before the fix (empty span // against the wrong file's source). func TestGateL1_CrossFileMethodSourceFile(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) // Server's type node lives in server/server.go. server := mustModule(t, out, "server/server.go") @@ -290,10 +290,10 @@ func TestGateL1_CrossFileMethodSourceFile(t *testing.T) { // TestGateL1_Envelope locks the manifest envelope at L1. func TestGateL1_Envelope(t *testing.T) { - out := buildMultipackageV2(t) + out := buildMultipackage(t) - if out.SchemaVersion != v2.SchemaVersion { - t.Errorf("schema_version = %q, want %q", out.SchemaVersion, v2.SchemaVersion) + if out.SchemaVersion != schema.SchemaVersion { + t.Errorf("schema_version = %q, want %q", out.SchemaVersion, schema.SchemaVersion) } if out.Language != "go" { t.Errorf("language = %q, want go", out.Language) @@ -310,40 +310,40 @@ func TestGateL1_Envelope(t *testing.T) { } } -// TestGateL1_SupersetOfV1 is the superset gate: every v1 fact must survive into -// v2 modulo the sanctioned drops. It walks the SAME v1 model the emitter walked -// and asserts each callable/type/function reappears in v2, and that the +// TestGateL1_SupersetOfModel is the superset gate: every model fact must survive into +// the output modulo the sanctioned drops. It walks the SAME model the emitter walked +// and asserts each callable/type/function reappears in the output, and that the // sanctioned drops are gone from the serialized payload. -func TestGateL1_SupersetOfV1(t *testing.T) { +func TestGateL1_SupersetOfModel(t *testing.T) { dir := multipackageDir(t) b := syntactic_analysis.NewSymbolTableBuilder(dir) st, err := b.Build(nil, true) if err != nil { t.Fatalf("symbol table build failed: %v", err) } - app := &schema.GoApplication{SymbolTable: st, CallGraph: []schema.GoCallEdge{}} + app := &model.GoApplication{SymbolTable: st, CallGraph: []model.GoCallEdge{}} out := Emit(app, testIdentity("multipackage"), dir, 1, "gate-test", 0, nil, nil) - // Every v1 file, type, method and function reappears in v2. + // Every model file, type, method and function reappears in the output. for rel, v1file := range st { mod, ok := out.Application.SymbolTable[rel] if !ok { - t.Errorf("v1 file %q dropped from v2 symbol_table", rel) + t.Errorf("model file %q dropped from the output symbol_table", rel) continue } for name := range v1file.Types { if _, ok := mod.Types[name]; !ok { - t.Errorf("%s: v1 type %q dropped from v2", rel, name) + t.Errorf("%s: model type %q dropped from the output", rel, name) } for msig := range v1file.Types[name].Methods { if _, ok := mod.Types[name].Callables[msig]; !ok { - t.Errorf("%s: v1 method %q dropped from v2 type %q", rel, msig, name) + t.Errorf("%s: model method %q dropped from output type %q", rel, msig, name) } } } for sig := range v1file.Functions { if _, ok := mod.Functions[sig]; !ok { - t.Errorf("%s: v1 function %q dropped from v2", rel, sig) + t.Errorf("%s: model function %q dropped from the output", rel, sig) } } } @@ -354,7 +354,7 @@ func TestGateL1_SupersetOfV1(t *testing.T) { t.Fatalf("marshal failed: %v", err) } if strings.Contains(string(data), `"is_constructor_call"`) { - t.Error("v2 payload should not carry the dropped is_constructor_call") + t.Error("the payload should not carry the dropped is_constructor_call") } // The sanctioned callee:null slot must be present at L1. if !strings.Contains(string(data), `"callee":null`) { @@ -373,8 +373,8 @@ func contains(ss []string, want string) bool { // ─── L1 fixes: type kinds, defer marker, co-positioned calls ───────────────── -// buildDataflowL1V2 emits the L1 payload for the testdata/dataflow fixture. -func buildDataflowL1V2(t *testing.T) *v2.Analysis { +// buildDataflowL1 emits the L1 payload for the testdata/dataflow fixture. +func buildDataflowL1(t *testing.T) *schema.Analysis { t.Helper() _, thisFile, _, _ := runtime.Caller(0) dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "testdata", "dataflow")) @@ -386,12 +386,12 @@ func buildDataflowL1V2(t *testing.T) *v2.Analysis { if err != nil { t.Fatalf("symbol table build failed: %v", err) } - app := &schema.GoApplication{SymbolTable: st, CallGraph: []schema.GoCallEdge{}} + app := &model.GoApplication{SymbolTable: st, CallGraph: []model.GoCallEdge{}} return Emit(app, testIdentity("dataflow"), dir, 1, "gate-test", 0, nil, nil) } func TestGateL1_TypeKindsAliasAndDefined(t *testing.T) { - mod := mustModule(t, buildDataflowL1V2(t), "l1/l1.go") + mod := mustModule(t, buildDataflowL1(t), "l1/l1.go") want := map[string]string{"Celsius": "defined", "Alias": "alias", "S": "struct", "Base": "struct", "MyErr": "struct", "I1": "interface", "I2": "interface"} for name, kind := range want { @@ -407,7 +407,7 @@ func TestGateL1_TypeKindsAliasAndDefined(t *testing.T) { } // functionByName finds a package-level function node by name. -func functionByName(t *testing.T, mod v2.Module, name string) v2.Callable { +func functionByName(t *testing.T, mod schema.Module, name string) schema.Callable { t.Helper() for sig, c := range mod.Functions { if strings.HasSuffix(sig, "."+name) { @@ -415,11 +415,11 @@ func functionByName(t *testing.T, mod v2.Module, name string) v2.Callable { } } t.Fatalf("function %q missing; have %v", name, keys(mod.Functions)) - return v2.Callable{} + return schema.Callable{} } func TestGateL1_DeferredCallNode(t *testing.T) { - d := functionByName(t, mustModule(t, buildDataflowL1V2(t), "l1/l1.go"), "D") + d := functionByName(t, mustModule(t, buildDataflowL1(t), "l1/l1.go"), "D") var deferred, goroutine int for _, n := range d.Body { if n.Kind != "call" { @@ -441,7 +441,7 @@ func TestGateL1_DeferredCallNode(t *testing.T) { } func TestGateL1_CoPositionedCallsBothKept(t *testing.T) { - c := functionByName(t, mustModule(t, buildDataflowL1V2(t), "l1/l1.go"), "Chain") + c := functionByName(t, mustModule(t, buildDataflowL1(t), "l1/l1.go"), "Chain") if len(c.Body) != 2 { t.Fatalf("Chain body has %d nodes, want 2: %v", len(c.Body), c.Body) } @@ -462,8 +462,8 @@ func TestGateL1_CoPositionedCallsBothKept(t *testing.T) { } } -// buildDataflowL2V2 emits the L2 payload (resolver run) for the dataflow fixture. -func buildDataflowL2V2(t *testing.T) *v2.Analysis { +// buildDataflowL2 emits the L2 payload (resolver run) for the dataflow fixture. +func buildDataflowL2(t *testing.T) *schema.Analysis { t.Helper() _, thisFile, _, _ := runtime.Caller(0) dir, err := filepath.Abs(filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "testdata", "dataflow")) @@ -477,7 +477,7 @@ func buildDataflowL2V2(t *testing.T) *v2.Analysis { } cg := semantic_analysis.NewCallGraphBuilder(dir, b.Fset(), b.Pkgs()) edges := cg.Build(st) - app := &schema.GoApplication{SymbolTable: st, CallGraph: edges} + app := &model.GoApplication{SymbolTable: st, CallGraph: edges} return Emit(app, testIdentity("dataflow"), dir, 2, "gate-test", 0, nil, nil) } @@ -485,7 +485,7 @@ func buildDataflowL2V2(t *testing.T) *v2.Analysis { // (bare key) resolves to B and the inner s.A() (key /2) resolves to A; the call // graph has exactly the edges Chain->A and Chain->B. func TestGateL2_CoPositionedCallsResolveSeparately(t *testing.T) { - out := buildDataflowL2V2(t) + out := buildDataflowL2(t) mod := mustModule(t, out, "l1/l1.go") chain := functionByName(t, mod, "Chain") s := mod.Types["S"] @@ -536,15 +536,15 @@ func TestGateL2_CoPositionedCallsResolveSeparately(t *testing.T) { } // TestGateL1_BodyNodeIDs (R15): from L1 on, every body node carries its global -// id, v2.GlobalOrdinal(callable id, local key) — Python parity (its +// id, schema.GlobalOrdinal(callable id, local key) — Python parity (its // stamp_body_ids runs at L1) — and no parent (an L3 refinement). func TestGateL1_BodyNodeIDs(t *testing.T) { - out := buildDataflowL1V2(t) + out := buildDataflowL1(t) checked := 0 - var walk func(c v2.Callable) - walk = func(c v2.Callable) { + var walk func(c schema.Callable) + walk = func(c schema.Callable) { for k, n := range c.Body { - if want := v2.GlobalOrdinal(c.ID, k); n.ID != want { + if want := schema.GlobalOrdinal(c.ID, k); n.ID != want { t.Errorf("%s body %s id = %q, want %q", c.ID, k, n.ID, want) } if n.Parent != "" { @@ -576,7 +576,7 @@ func TestGateL1_BodyNodeIDs(t *testing.T) { // call nodes with resolved callees and call_graph edges — evaluated in the // launching goroutine, so only the launched call carries is_goroutine. func TestGateL2_GoStatementArgumentCalls(t *testing.T) { - out := buildDataflowL2V2(t) + out := buildDataflowL2(t) fn := functionByName(t, mustModule(t, out, "flow/flow.go"), "GoArgs") for _, w := range []struct { key, callee string @@ -611,7 +611,7 @@ func TestGateL2_GoStatementArgumentCalls(t *testing.T) { } } -func anyEdgeFromTo(edges []v2.Edge, src, dst string) bool { +func anyEdgeFromTo(edges []schema.Edge, src, dst string) bool { for _, e := range edges { if e.Src == src && e.Dst == dst { return true @@ -637,7 +637,7 @@ func TestGate_LineDirectiveSpansSliceToText(t *testing.T) { if err != nil { t.Fatalf("symbol table build failed: %v", err) } - out := Emit(&schema.GoApplication{SymbolTable: st, CallGraph: []schema.GoCallEdge{}}, testIdentity("dataflow"), dir, 1, "gate-test", 0, nil, nil) + out := Emit(&model.GoApplication{SymbolTable: st, CallGraph: []model.GoCallEdge{}}, testIdentity("dataflow"), dir, 1, "gate-test", 0, nil, nil) const rel = "linedir/linedir.go" mod := mustModule(t, out, rel) calls := 0 @@ -647,7 +647,7 @@ func TestGate_LineDirectiveSpansSliceToText(t *testing.T) { if c.Span.Bytes[0] >= c.Span.Bytes[1] || !strings.HasPrefix(text, "func "+fn.Name+"(") { t.Errorf("callable %s: span %v slices to %q, want func %s(…", sig, c.Span, text, fn.Name) } - keys := v2.CallBodyKeys(siteStarts(fn.CallSites)) + keys := schema.CallBodyKeys(siteStarts(fn.CallSites)) for i, cs := range fn.CallSites { n, ok := c.Body[keys[i]] if !ok { @@ -673,7 +673,7 @@ func TestGate_LineDirectiveSpansSliceToText(t *testing.T) { } } -func siteStarts(sites []schema.GoCallsite) [][2]int { +func siteStarts(sites []model.GoCallsite) [][2]int { pos := make([][2]int, len(sites)) for i, cs := range sites { pos[i] = [2]int{cs.StartLine, cs.StartColumn} diff --git a/internal/syntactic_analysis/v2emit/offsets.go b/internal/syntactic_analysis/emit/offsets.go similarity index 87% rename from internal/syntactic_analysis/v2emit/offsets.go rename to internal/syntactic_analysis/emit/offsets.go index e9d3160..4b88cfa 100644 --- a/internal/syntactic_analysis/v2emit/offsets.go +++ b/internal/syntactic_analysis/emit/offsets.go @@ -1,15 +1,15 @@ -// Package v2emit transforms the v1 in-memory model (internal/schema) into the -// v2 canonical schema (internal/schema/v2). It is an EMISSION layer only: it +// Package emit transforms the in-memory model (internal/model) into the +// canonical schema (internal/schema). It is an EMISSION layer only: it // computes no new facts beyond source byte offsets, it just re-serializes what // the parser/resolver already produced into the additive-tree shape. // -// The one genuinely new datum is span byte offsets. The v1 model records +// The one genuinely new datum is span byte offsets. The model records // line/col but not UTF-8 byte offsets (and only line-level positions for -// callables/types). Rather than change the v1 model, the emitter reads each +// callables/types). Rather than change the model, the emitter reads each // file's source once and derives byte offsets from the existing line/col // positions via a lineIndex. That same source string is emitted once per module // as module.source, off which every node's text slices. -package v2emit +package emit // lineIndex maps 1-based (line, col) positions in a source file to UTF-8 byte // offsets. Built once per file. Columns are byte columns within the line, which @@ -62,7 +62,7 @@ func (li *lineIndex) offset(line, col int) int { // lineEndOffset returns the byte offset of the end of a 1-based line: the // position just before its terminating '\n' (or end of file for the last line). -// Used to give a line-only position (no column in the v1 model) a precise end. +// Used to give a line-only position (no column in the model) a precise end. func (li *lineIndex) lineEndOffset(line int) int { if line < 1 || len(li.lineStart) == 0 { return 0 diff --git a/internal/syntactic_analysis/v2emit/offsets_test.go b/internal/syntactic_analysis/emit/offsets_test.go similarity index 99% rename from internal/syntactic_analysis/v2emit/offsets_test.go rename to internal/syntactic_analysis/emit/offsets_test.go index 69b61b9..c25299a 100644 --- a/internal/syntactic_analysis/v2emit/offsets_test.go +++ b/internal/syntactic_analysis/emit/offsets_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit import "testing" diff --git a/internal/syntactic_analysis/v2emit/repository.go b/internal/syntactic_analysis/emit/repository.go similarity index 72% rename from internal/syntactic_analysis/v2emit/repository.go rename to internal/syntactic_analysis/emit/repository.go index 473c8e8..6bc26d5 100644 --- a/internal/syntactic_analysis/v2emit/repository.go +++ b/internal/syntactic_analysis/emit/repository.go @@ -1,28 +1,28 @@ -package v2emit +package emit import ( + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" ) // artifactID is an artifact's durable id: the application root, then the -// artifact segment and the repo-relative path (spec v2-artifacts). +// artifact segment and the repo-relative path (spec artifacts). func artifactID(appID, relPath string) string { return appID + "/artifact/" + relPath } -// emitRepository maps the repository facts onto the v2 layer. Artifacts are +// emitRepository maps the repository facts onto the output layer. Artifacts are // keyed by path; dependencies keep the facts' order (sorted by module path) and // point at their go.mod artifact, and a locked one at its go.sum artifact, by id. A nil facts set emits nothing. -func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2.Artifact, []v2.Dependency) { +func emitRepository(appID string, facts *model.RepositoryFacts) (map[string]schema.Artifact, []schema.Dependency) { if facts == nil { return nil, nil } - var arts map[string]v2.Artifact + var arts map[string]schema.Artifact if len(facts.Artifacts) > 0 { - arts = make(map[string]v2.Artifact, len(facts.Artifacts)) + arts = make(map[string]schema.Artifact, len(facts.Artifacts)) for path, a := range facts.Artifacts { - arts[path] = v2.Artifact{ + arts[path] = schema.Artifact{ ID: artifactID(appID, path), Kind: "artifact", Path: a.Path, @@ -35,7 +35,7 @@ func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2. } } } - var deps []v2.Dependency + var deps []schema.Dependency for _, d := range facts.Dependencies { declared, lockedIn := "", "" if d.DeclaredIn != "" { @@ -44,7 +44,7 @@ func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2. if d.LockedIn != "" { lockedIn = artifactID(appID, d.LockedIn) } - deps = append(deps, v2.Dependency{ + deps = append(deps, schema.Dependency{ Name: d.Name, Ecosystem: d.Ecosystem, Spec: d.Spec, diff --git a/internal/syntactic_analysis/v2emit/repository_test.go b/internal/syntactic_analysis/emit/repository_test.go similarity index 83% rename from internal/syntactic_analysis/v2emit/repository_test.go rename to internal/syntactic_analysis/emit/repository_test.go index e4ff1cd..cd84205 100644 --- a/internal/syntactic_analysis/v2emit/repository_test.go +++ b/internal/syntactic_analysis/emit/repository_test.go @@ -1,9 +1,9 @@ -package v2emit +package emit import ( "testing" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" ) // TestEmitRepository_LockedInIsTheLockfileArtifactID (#72): a locked @@ -11,7 +11,7 @@ import ( // declared_in points at its go.mod. An unlocked one has no locked_in. func TestEmitRepository_LockedInIsTheLockfileArtifactID(t *testing.T) { const app = "can://app/app" - _, deps := emitRepository(app, &schema.RepositoryFacts{Dependencies: []schema.GoDependency{ + _, deps := emitRepository(app, &model.RepositoryFacts{Dependencies: []model.GoDependency{ {Name: "github.com/gorilla/mux", LockedVersion: "v1.8.0", LockedIn: "go.sum", DeclaredIn: "go.mod"}, {Name: "golang.org/x/text", DeclaredIn: "go.mod"}, }}) diff --git a/internal/syntactic_analysis/v2emit/sigindex.go b/internal/syntactic_analysis/emit/sigindex.go similarity index 86% rename from internal/syntactic_analysis/v2emit/sigindex.go rename to internal/syntactic_analysis/emit/sigindex.go index e808349..933d6e4 100644 --- a/internal/syntactic_analysis/v2emit/sigindex.go +++ b/internal/syntactic_analysis/emit/sigindex.go @@ -1,14 +1,14 @@ -package v2emit +package emit import ( + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" ) -// sigIndex maps a v1 callable signature to its v2 can:// callable id. +// sigIndex maps a model callable signature to its can:// callable id. // -// v1 identifies every callable by its signatureOf() string and uses that string -// as call-graph edge endpoints and as a call site's backfilled callee. v2 +// The model identifies every callable by its signatureOf() string and uses that string +// as call-graph edge endpoints and as a call site's backfilled callee. The output // addresses callables by durable can:// id. The L2 refinement therefore needs a // signature→id translation: this index is built in one pass over the same tree // the emitter walks, using the SAME id builders emitCallable uses, so an id here @@ -44,13 +44,13 @@ type sigPathKey struct { // buildSigIndex walks the symbol table and records, for every callable // (functions, methods, and nested closures), signature → can:// id. It mirrors // emitModule/emitType/emitCallable's parent-id computation exactly. -func buildSigIndex(appID string, symbolTable map[string]schema.GoFile) sigIndex { +func buildSigIndex(appID string, symbolTable map[string]model.GoFile) sigIndex { idx := sigIndex{ bySig: make(map[string]string), bySigPath: make(map[sigPathKey]string), } for relPath, file := range symbolTable { - modID := v2.ModuleID(appID, relPath) + modID := schema.ModuleID(appID, relPath) for _, fn := range file.Functions { idx.addCallable(modID, relPath, fn) } @@ -66,22 +66,22 @@ func buildSigIndex(appID string, symbolTable map[string]schema.GoFile) sigIndex // methodParentID is the id a method nests under. A method declared in its // receiver type's file nests under that type's id. A method declared in another // file nests under the same type in the DECLARING file's module, so its id names -// where the method is written (spec v2-go-ids § Amendment). The JSON node itself +// where the method is written (spec go-ids § Amendment). The JSON node itself // stays in the receiver type's callables{}; only its id moves. modRel is the // receiver's module (the file the type lives in). -func methodParentID(appID, modRel string, t schema.GoType, c schema.GoCallable) string { +func methodParentID(appID, modRel string, t model.GoType, c model.GoCallable) string { mod := modRel if c.Path != "" { mod = c.Path } - return v2.TypeID(v2.ModuleID(appID, mod), t.Signature) + return schema.TypeID(schema.ModuleID(appID, mod), t.Signature) } // addCallable records one callable and recurses into its closures, matching the // id nesting emitCallable produces. relPath is the module file this callable is // reached through; it keys the disambiguating (signature,path) entry. -func (idx sigIndex) addCallable(parentID, relPath string, c schema.GoCallable) { - callID := v2.CallableID(parentID, c.Signature) +func (idx sigIndex) addCallable(parentID, relPath string, c model.GoCallable) { + callID := schema.CallableID(parentID, c.Signature) // Flat entry: deterministic on collision — keep the lexicographically // smallest id so a repeated signature (package-level init) resolves to a @@ -107,7 +107,7 @@ func (idx sigIndex) addCallable(parentID, relPath string, c schema.GoCallable) { } } -// idFor returns the can:// id for a v1 signature, or ("", false) when the +// idFor returns the can:// id for a model signature, or ("", false) when the // signature names a callable outside the project (stdlib/external) — those // resolve to no in-tree node and must not become an edge endpoint. For a // signature shared by multiple callables (package-level init) it returns the diff --git a/internal/syntactic_analysis/v2emit/stream.go b/internal/syntactic_analysis/emit/stream.go similarity index 66% rename from internal/syntactic_analysis/v2emit/stream.go rename to internal/syntactic_analysis/emit/stream.go index b010017..1b5dd0b 100644 --- a/internal/syntactic_analysis/v2emit/stream.go +++ b/internal/syntactic_analysis/emit/stream.go @@ -1,11 +1,11 @@ -package v2emit +package emit import ( "iter" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" ) @@ -13,30 +13,30 @@ import ( // Each Modules walk emits the modules again, so no walk holds the whole tree. // A Stream is not safe for concurrent use. type Stream struct { - app *schema.GoApplication + app *model.GoApplication e *emitter - env *v2.Analysis + env *schema.Analysis walked bool lateCache lateFields lateDone bool } // Open prepares a Stream. It takes the same arguments as Emit. -func Open(app *schema.GoApplication, identity v2.Identity, projectDir string, maxLevel int, analyzerVersion string, kLimit int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) *Stream { +func Open(app *model.GoApplication, identity schema.Identity, projectDir string, maxLevel int, analyzerVersion string, kLimit int, l3 map[dataflow.L3Key]dataflow.Result, l4 *sdg.Result) *Stream { e := newEmitter(app, identity, projectDir, maxLevel, l3, l4) return &Stream{app: app, e: e, env: e.envelope(app, maxLevel, analyzerVersion, kLimit)} } // Envelope returns the payload without symbol_table, param_in, param_out and degraded. -func (s *Stream) Envelope() *v2.Analysis { return s.env } +func (s *Stream) Envelope() *schema.Analysis { return s.env } // ModuleKeys returns the sorted symbol_table keys. func (s *Stream) ModuleKeys() []string { return sortedFileKeys(s.app.SymbolTable) } // Modules emits each module in symbol_table key order. // The first complete walk fills the L4 id map. Later walks print no warnings. -func (s *Stream) Modules() iter.Seq2[string, v2.Module] { - return func(yield func(string, v2.Module) bool) { +func (s *Stream) Modules() iter.Seq2[string, schema.Module] { + return func(yield func(string, schema.Module) bool) { if s.walked { s.e.sdg.setQuiet() } @@ -50,18 +50,18 @@ func (s *Stream) Modules() iter.Seq2[string, v2.Module] { } // ParamIn streams application.param_in. Call it after one complete Modules walk. -func (s *Stream) ParamIn() iter.Seq[v2.ParamEdge] { return orEmpty(s.late().paramIn) } +func (s *Stream) ParamIn() iter.Seq[schema.ParamEdge] { return orEmpty(s.late().paramIn) } // ParamOut streams application.param_out. Call it after one complete Modules walk. -func (s *Stream) ParamOut() iter.Seq[v2.ParamEdge] { return orEmpty(s.late().paramOut) } +func (s *Stream) ParamOut() iter.Seq[schema.ParamEdge] { return orEmpty(s.late().paramOut) } // Degraded returns the envelope degraded list. Call it after one complete Modules walk. -func (s *Stream) Degraded() []v2.Degraded { return s.late().degraded } +func (s *Stream) Degraded() []schema.Degraded { return s.late().degraded } // late mints the param lists and the degraded list once, after the first walk. func (s *Stream) late() lateFields { if !s.walked { - panic("v2emit: Stream late fields read before one complete Modules walk") + panic("emit: Stream late fields read before one complete Modules walk") } if s.lateDone { return s.lateCache @@ -71,9 +71,9 @@ func (s *Stream) late() lateFields { } // orEmpty replaces a nil sequence (no L4) with an empty one, so a range over it is safe. -func orEmpty(seq iter.Seq[v2.ParamEdge]) iter.Seq[v2.ParamEdge] { +func orEmpty(seq iter.Seq[schema.ParamEdge]) iter.Seq[schema.ParamEdge] { if seq == nil { - return func(func(v2.ParamEdge) bool) {} + return func(func(schema.ParamEdge) bool) {} } return seq } diff --git a/internal/syntactic_analysis/v2emit/stream_test.go b/internal/syntactic_analysis/emit/stream_test.go similarity index 94% rename from internal/syntactic_analysis/v2emit/stream_test.go rename to internal/syntactic_analysis/emit/stream_test.go index b6f3787..a6a7062 100644 --- a/internal/syntactic_analysis/v2emit/stream_test.go +++ b/internal/syntactic_analysis/emit/stream_test.go @@ -1,4 +1,4 @@ -package v2emit +package emit import ( "bytes" @@ -8,7 +8,7 @@ import ( "testing" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" ) @@ -20,7 +20,7 @@ func TestStream_EqualsEmit(t *testing.T) { s := Open(fx.app, testIdentity(name), fx.dir, 4, "gate-test", 3, fx.res, fx.sdg) for range 2 { // the second walk must give the same modules got := *s.Envelope() - got.Application.SymbolTable = map[string]v2.Module{} + got.Application.SymbolTable = map[string]schema.Module{} for k, m := range s.Modules() { got.Application.SymbolTable[k] = m } diff --git a/internal/syntactic_analysis/l3units.go b/internal/syntactic_analysis/l3units.go index c4ada70..1b63065 100644 --- a/internal/syntactic_analysis/l3units.go +++ b/internal/syntactic_analysis/l3units.go @@ -7,8 +7,8 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/astwalk" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" - v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -27,13 +27,13 @@ import ( // recurses per literal, so walking the same way pairs each literal with // InnerCallables[name]. Its start line is checked too. Its key's Path is // the enclosing callable's declaring file. -// - Calls is v2.CallBodyKeys over the callable's L1 call sites, the exact +// - Calls is schema.CallBodyKeys over the callable's L1 call sites, the exact // keys the L1 emitter writes, each with its site's Lparen. // // A mismatch (which would mean the walk drifted from L1's) is logged and the // callable is left at L1. -func (b *SymbolTableBuilder) L3Units(symbolTable map[string]schema.GoFile) []dataflow.Unit { - byKey := map[dataflow.L3Key]schema.GoCallable{} +func (b *SymbolTableBuilder) L3Units(symbolTable map[string]model.GoFile) []dataflow.Unit { + byKey := map[dataflow.L3Key]model.GoCallable{} for _, f := range symbolTable { for _, c := range f.Functions { byKey[dataflow.L3Key{Path: c.Path, Signature: c.Signature}] = c @@ -93,7 +93,7 @@ func (b *SymbolTableBuilder) L3Units(symbolTable map[string]schema.GoFile) []dat // closureUnits appends a unit for every function literal of body, walking // astwalk.Literals as buildInnerCallables does. -func (b *SymbolTableBuilder) closureUnits(units []dataflow.Unit, path string, body *ast.BlockStmt, outer schema.GoCallable, info *types.Info) []dataflow.Unit { +func (b *SymbolTableBuilder) closureUnits(units []dataflow.Unit, path string, body *ast.BlockStmt, outer model.GoCallable, info *types.Info) []dataflow.Unit { for _, l := range astwalk.Literals(body) { ic, ok := outer.InnerCallables[l.Name] if !ok || ic.StartLine != b.position(l.Lit.Pos()).Line { @@ -106,12 +106,12 @@ func (b *SymbolTableBuilder) closureUnits(units []dataflow.Unit, path string, bo return units } -func unit(key dataflow.L3Key, fn ast.Node, info *types.Info, c schema.GoCallable) dataflow.Unit { +func unit(key dataflow.L3Key, fn ast.Node, info *types.Info, c model.GoCallable) dataflow.Unit { pos := make([][2]int, len(c.CallSites)) for i, cs := range c.CallSites { pos[i] = [2]int{cs.StartLine, cs.StartColumn} } - keys := v2.CallBodyKeys(pos) + keys := schema.CallBodyKeys(pos) calls := make([]dataflow.UnitCall, len(c.CallSites)) for i, cs := range c.CallSites { calls[i] = dataflow.UnitCall{Key: keys[i], Lparen: cs.Lparen} diff --git a/internal/syntactic_analysis/symbol_table.go b/internal/syntactic_analysis/symbol_table.go index 2cbf58f..1fc57d1 100644 --- a/internal/syntactic_analysis/symbol_table.go +++ b/internal/syntactic_analysis/symbol_table.go @@ -13,7 +13,7 @@ import ( "golang.org/x/tools/go/packages" "github.com/codellm-devkit/codeanalyzer-go/internal/astwalk" - "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + "github.com/codellm-devkit/codeanalyzer-go/internal/model" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" ) @@ -55,7 +55,7 @@ func (b *SymbolTableBuilder) position(p token.Pos) token.Position { // Build loads all packages under projectDir (or only targetFiles if non-empty), // walks each file, and returns the symbol table keyed by relative file path. -func (b *SymbolTableBuilder) Build(targetFiles []string, skipTests bool) (map[string]schema.GoFile, error) { +func (b *SymbolTableBuilder) Build(targetFiles []string, skipTests bool) (map[string]model.GoFile, error) { cfg := &packages.Config{ Mode: packages.NeedName | packages.NeedFiles | @@ -107,7 +107,7 @@ func (b *SymbolTableBuilder) Build(targetFiles []string, skipTests bool) (map[st } tooNew.warn() - symbolTable := map[string]schema.GoFile{} + symbolTable := map[string]model.GoFile{} for _, pkg := range b.pkgs { for i, astFile := range pkg.Syntax { @@ -142,7 +142,7 @@ func (b *SymbolTableBuilder) Build(targetFiles []string, skipTests bool) (map[st // reconcileCrossFileMethods attaches methods to their type's owner file when // the method and its receiver type are declared in different files of the same package. -func (b *SymbolTableBuilder) reconcileCrossFileMethods(symbolTable map[string]schema.GoFile) { +func (b *SymbolTableBuilder) reconcileCrossFileMethods(symbolTable map[string]model.GoFile) { // Build index: (pkgPath, shortTypeName) → relPath of the file that owns the type. type typeKey struct{ pkgPath, typeName string } typeOwner := make(map[typeKey]string) @@ -218,7 +218,7 @@ func (b *SymbolTableBuilder) buildGoFile( pkg *packages.Package, astFile *ast.File, absPath, relPath string, -) schema.GoFile { +) model.GoFile { info, _ := os.Stat(absPath) hash, _ := utils.FileHash(absPath) @@ -235,13 +235,13 @@ func (b *SymbolTableBuilder) buildGoFile( contentHash = &hash } - gf := schema.GoFile{ + gf := model.GoFile{ FilePath: relPath, PackageName: astFile.Name.Name, Imports: b.buildImports(astFile), Comments: b.buildFileComments(astFile), - Types: map[string]schema.GoType{}, - Functions: map[string]schema.GoCallable{}, + Types: map[string]model.GoType{}, + Functions: map[string]model.GoCallable{}, Variables: b.buildPackageVars(pkg, astFile), ContentHash: contentHash, LastModified: lastMod, @@ -253,7 +253,7 @@ func (b *SymbolTableBuilder) buildGoFile( // file is known. type pendingMethod struct { typeName string - callable *schema.GoCallable + callable *model.GoCallable } var methods []pendingMethod for _, decl := range astFile.Decls { @@ -288,8 +288,8 @@ func (b *SymbolTableBuilder) buildGoFile( // ─── Imports ────────────────────────────────────────────────────────────────── -func (b *SymbolTableBuilder) buildImports(astFile *ast.File) []schema.GoImport { - var imports []schema.GoImport +func (b *SymbolTableBuilder) buildImports(astFile *ast.File) []model.GoImport { + var imports []model.GoImport for _, imp := range astFile.Imports { path := strings.Trim(imp.Path.Value, `"`) alias := "" @@ -298,7 +298,7 @@ func (b *SymbolTableBuilder) buildImports(astFile *ast.File) []schema.GoImport { } pos := b.position(imp.Pos()) end := b.position(imp.End()) - imports = append(imports, schema.GoImport{ + imports = append(imports, model.GoImport{ Module: path, Alias: alias, StartLine: pos.Line, @@ -310,13 +310,13 @@ func (b *SymbolTableBuilder) buildImports(astFile *ast.File) []schema.GoImport { // ─── Comments ───────────────────────────────────────────────────────────────── -func (b *SymbolTableBuilder) buildFileComments(astFile *ast.File) []schema.GoComment { - var comments []schema.GoComment +func (b *SymbolTableBuilder) buildFileComments(astFile *ast.File) []model.GoComment { + var comments []model.GoComment for _, cg := range astFile.Comments { for _, c := range cg.List { pos := b.position(c.Pos()) end := b.position(c.End()) - comments = append(comments, schema.GoComment{ + comments = append(comments, model.GoComment{ Content: c.Text, StartLine: pos.Line, EndLine: end.Line, @@ -329,15 +329,15 @@ func (b *SymbolTableBuilder) buildFileComments(astFile *ast.File) []schema.GoCom return comments } -func (b *SymbolTableBuilder) docComments(doc *ast.CommentGroup) []schema.GoComment { +func (b *SymbolTableBuilder) docComments(doc *ast.CommentGroup) []model.GoComment { if doc == nil { return nil } - var comments []schema.GoComment + var comments []model.GoComment for _, c := range doc.List { pos := b.position(c.Pos()) end := b.position(c.End()) - comments = append(comments, schema.GoComment{ + comments = append(comments, model.GoComment{ Content: c.Text, StartLine: pos.Line, EndLine: end.Line, @@ -355,7 +355,7 @@ func (b *SymbolTableBuilder) processGenDecl( pkg *packages.Package, astFile *ast.File, decl *ast.GenDecl, - gf *schema.GoFile, + gf *model.GoFile, ) { for _, spec := range decl.Specs { switch s := spec.(type) { @@ -375,7 +375,7 @@ func (b *SymbolTableBuilder) buildType( astFile *ast.File, decl *ast.GenDecl, spec *ast.TypeSpec, -) *schema.GoType { +) *model.GoType { typeName := spec.Name.Name isExported := unicode.IsUpper(rune(typeName[0])) @@ -393,15 +393,15 @@ func (b *SymbolTableBuilder) buildType( pos := b.position(spec.Pos()) end := b.position(spec.End()) - gt := &schema.GoType{ + gt := &model.GoType{ Name: typeName, Signature: typSig, Comments: b.docComments(decl.Doc), IsExported: isExported, - Fields: []schema.GoField{}, - Methods: map[string]schema.GoCallable{}, + Fields: []model.GoField{}, + Methods: map[string]model.GoCallable{}, BaseTypes: []string{}, - InnerTypes: map[string]schema.GoType{}, + InnerTypes: map[string]model.GoType{}, StartLine: pos.Line, EndLine: end.Line, } @@ -454,8 +454,8 @@ func (b *SymbolTableBuilder) typeKindOf(pkg *packages.Package, spec *ast.TypeSpe return "defined" } -func (b *SymbolTableBuilder) buildStructFields(pkg *packages.Package, st *ast.StructType) []schema.GoField { - var fields []schema.GoField +func (b *SymbolTableBuilder) buildStructFields(pkg *packages.Package, st *ast.StructType) []model.GoField { + var fields []model.GoField if st.Fields == nil { return fields } @@ -467,7 +467,7 @@ func (b *SymbolTableBuilder) buildStructFields(pkg *packages.Package, st *ast.St if isEmbedded { pos := b.position(field.Pos()) end := b.position(field.End()) - fields = append(fields, schema.GoField{ + fields = append(fields, model.GoField{ Name: typStr, Type: typStr, Tags: tags, @@ -481,7 +481,7 @@ func (b *SymbolTableBuilder) buildStructFields(pkg *packages.Package, st *ast.St for _, name := range field.Names { pos := b.position(name.Pos()) end := b.position(field.End()) - fields = append(fields, schema.GoField{ + fields = append(fields, model.GoField{ Name: name.Name, Type: typStr, Tags: tags, @@ -508,7 +508,7 @@ func (b *SymbolTableBuilder) embeddedTypes(pkg *packages.Package, st *ast.Struct return embedded } -func (b *SymbolTableBuilder) collectInterfaceMethods(pkg *packages.Package, it *ast.InterfaceType, gt *schema.GoType) { +func (b *SymbolTableBuilder) collectInterfaceMethods(pkg *packages.Package, it *ast.InterfaceType, gt *model.GoType) { if it.Methods == nil { return } @@ -532,7 +532,7 @@ func (b *SymbolTableBuilder) collectInterfaceMethods(pkg *packages.Package, it * } sig := pkg.Types.Path() + "." + gt.Name + "." + name.Name - callable := schema.GoCallable{ + callable := model.GoCallable{ Name: name.Name, Path: "", Signature: sig, @@ -541,8 +541,8 @@ func (b *SymbolTableBuilder) collectInterfaceMethods(pkg *packages.Package, it * ReturnTypes: retTypes, IsExported: unicode.IsUpper(rune(name.Name[0])), ReceiverType: gt.Signature, - CallSites: []schema.GoCallsite{}, - InnerCallables: map[string]schema.GoCallable{}, + CallSites: []model.GoCallsite{}, + InnerCallables: map[string]model.GoCallable{}, StartLine: pos.Line, EndLine: end.Line, } @@ -557,7 +557,7 @@ func (b *SymbolTableBuilder) buildCallable( pkg *packages.Package, astFile *ast.File, decl *ast.FuncDecl, -) *schema.GoCallable { +) *model.GoCallable { name := decl.Name.Name // Skip declarations whose file is outside the input root. cgo synthesizes @@ -592,7 +592,7 @@ func (b *SymbolTableBuilder) buildCallable( bodyStart = b.position(decl.Body.Pos()).Line } - callable := &schema.GoCallable{ + callable := &model.GoCallable{ Name: name, Path: utils.RelativePath(b.projectDir, declFile.Name()), Signature: sig, @@ -603,10 +603,10 @@ func (b *SymbolTableBuilder) buildCallable( IsExported: isExported, ReceiverType: recvType, ReceiverName: recvName, - CallSites: []schema.GoCallsite{}, - InnerCallables: map[string]schema.GoCallable{}, - LocalVariables: []schema.GoVariableDeclaration{}, - AccessedSymbols: []schema.GoSymbol{}, + CallSites: []model.GoCallsite{}, + InnerCallables: map[string]model.GoCallable{}, + LocalVariables: []model.GoVariableDeclaration{}, + AccessedSymbols: []model.GoSymbol{}, StartLine: pos.Line, EndLine: end.Line, CodeStartLine: bodyStart, @@ -675,11 +675,11 @@ func (b *SymbolTableBuilder) declSignature(pkg *packages.Package, decl *ast.Func // ─── Parameters ─────────────────────────────────────────────────────────────── -func (b *SymbolTableBuilder) buildParams(pkg *packages.Package, ft *ast.FuncType) []schema.GoParameter { +func (b *SymbolTableBuilder) buildParams(pkg *packages.Package, ft *ast.FuncType) []model.GoParameter { if ft == nil || ft.Params == nil { return nil } - var params []schema.GoParameter + var params []model.GoParameter for _, field := range ft.Params.List { typStr := b.typeString(pkg, field.Type) isVariadic := false @@ -689,14 +689,14 @@ func (b *SymbolTableBuilder) buildParams(pkg *packages.Package, ft *ast.FuncType pos := b.position(field.Pos()) end := b.position(field.End()) if len(field.Names) == 0 { - params = append(params, schema.GoParameter{ + params = append(params, model.GoParameter{ Name: "_", Type: typStr, IsVariadic: isVariadic, StartLine: pos.Line, EndLine: end.Line, }) continue } for _, name := range field.Names { - params = append(params, schema.GoParameter{ + params = append(params, model.GoParameter{ Name: name.Name, Type: typStr, IsVariadic: isVariadic, StartLine: pos.Line, EndLine: end.Line, }) @@ -705,7 +705,7 @@ func (b *SymbolTableBuilder) buildParams(pkg *packages.Package, ft *ast.FuncType return params } -func (b *SymbolTableBuilder) buildFuncTypeParams(pkg *packages.Package, expr ast.Expr) []schema.GoParameter { +func (b *SymbolTableBuilder) buildFuncTypeParams(pkg *packages.Package, expr ast.Expr) []model.GoParameter { if ft, ok := expr.(*ast.FuncType); ok { return b.buildParams(pkg, ft) } @@ -748,8 +748,8 @@ func (b *SymbolTableBuilder) joinReturnTypes(parts []string) string { // order astwalk.Calls lists them (the order L3 pairs its call nodes with by // Lparen). callee_signature is left nil here — the resolver backfills it in // the call-graph stage. -func (b *SymbolTableBuilder) buildCallSites(pkg *packages.Package, body *ast.BlockStmt) []schema.GoCallsite { - var sites []schema.GoCallsite +func (b *SymbolTableBuilder) buildCallSites(pkg *packages.Package, body *ast.BlockStmt) []model.GoCallsite { + var sites []model.GoCallsite for _, c := range astwalk.Calls(body) { site := b.callExprToSite(pkg, c.Expr, c.Goroutine) site.IsDeferred = c.Deferred @@ -758,7 +758,7 @@ func (b *SymbolTableBuilder) buildCallSites(pkg *packages.Package, body *ast.Blo return sites } -func (b *SymbolTableBuilder) callExprToSite(pkg *packages.Package, call *ast.CallExpr, isGoroutine bool) *schema.GoCallsite { +func (b *SymbolTableBuilder) callExprToSite(pkg *packages.Package, call *ast.CallExpr, isGoroutine bool) *model.GoCallsite { pos := b.position(call.Pos()) end := b.position(call.End()) @@ -800,7 +800,7 @@ func (b *SymbolTableBuilder) callExprToSite(pkg *packages.Package, call *ast.Cal argTypes = append(argTypes, "") } - return &schema.GoCallsite{ + return &model.GoCallsite{ MethodName: methodName, ReceiverExpr: receiverExpr, ReceiverType: receiverType, @@ -818,8 +818,8 @@ func (b *SymbolTableBuilder) callExprToSite(pkg *packages.Package, call *ast.Cal // ─── Local variables ────────────────────────────────────────────────────────── -func (b *SymbolTableBuilder) buildLocalVars(pkg *packages.Package, body *ast.BlockStmt) []schema.GoVariableDeclaration { - var vars []schema.GoVariableDeclaration +func (b *SymbolTableBuilder) buildLocalVars(pkg *packages.Package, body *ast.BlockStmt) []model.GoVariableDeclaration { + var vars []model.GoVariableDeclaration ast.Inspect(body, func(n ast.Node) bool { switch node := n.(type) { case *ast.AssignStmt: @@ -837,7 +837,7 @@ func (b *SymbolTableBuilder) buildLocalVars(pkg *packages.Package, body *ast.Blo if i < len(node.Rhs) { init = b.exprString(node.Rhs[i]) } - vars = append(vars, schema.GoVariableDeclaration{ + vars = append(vars, model.GoVariableDeclaration{ Name: ident.Name, Type: typStr, Initializer: init, Scope: "function", StartLine: pos.Line, EndLine: pos.Line, }) @@ -862,7 +862,7 @@ func (b *SymbolTableBuilder) buildLocalVars(pkg *packages.Package, body *ast.Blo if i < len(vs.Values) { init = b.exprString(vs.Values[i]) } - vars = append(vars, schema.GoVariableDeclaration{ + vars = append(vars, model.GoVariableDeclaration{ Name: name.Name, Type: typStr, Initializer: init, Scope: "function", StartLine: pos.Line, EndLine: pos.Line, }) @@ -882,8 +882,8 @@ func (b *SymbolTableBuilder) buildLocalVars(pkg *packages.Package, body *ast.Blo // built by the recursion on lit.Body. Every closure carries the enclosing // callable's declaring file as its Path (Go has no cross-file closures), so // the resolver keys its call sites and edges like any other callable's. -func (b *SymbolTableBuilder) buildInnerCallables(pkg *packages.Package, outerSig, path string, body *ast.BlockStmt) map[string]schema.GoCallable { - inner := map[string]schema.GoCallable{} +func (b *SymbolTableBuilder) buildInnerCallables(pkg *packages.Package, outerSig, path string, body *ast.BlockStmt) map[string]model.GoCallable { + inner := map[string]model.GoCallable{} for _, l := range astwalk.Literals(body) { lit, name := l.Lit, l.Name sig := outerSig + "." + name @@ -892,16 +892,16 @@ func (b *SymbolTableBuilder) buildInnerCallables(pkg *packages.Package, outerSig _, retTypes := b.buildReturnTypes(pkg, lit.Type) retType := b.joinReturnTypes(retTypes) - ic := schema.GoCallable{ + ic := model.GoCallable{ Name: name, Path: path, Signature: sig, Parameters: b.buildParams(pkg, lit.Type), ReturnType: retType, ReturnTypes: retTypes, - CallSites: []schema.GoCallsite{}, - InnerCallables: map[string]schema.GoCallable{}, - LocalVariables: []schema.GoVariableDeclaration{}, + CallSites: []model.GoCallsite{}, + InnerCallables: map[string]model.GoCallable{}, + LocalVariables: []model.GoVariableDeclaration{}, StartLine: pos.Line, EndLine: endPos.Line, } @@ -918,8 +918,8 @@ func (b *SymbolTableBuilder) buildInnerCallables(pkg *packages.Package, outerSig // ─── Package-level variables ────────────────────────────────────────────────── -func (b *SymbolTableBuilder) buildPackageVars(pkg *packages.Package, astFile *ast.File) []schema.GoVariableDeclaration { - var vars []schema.GoVariableDeclaration +func (b *SymbolTableBuilder) buildPackageVars(pkg *packages.Package, astFile *ast.File) []model.GoVariableDeclaration { + var vars []model.GoVariableDeclaration for _, decl := range astFile.Decls { gen, ok := decl.(*ast.GenDecl) if !ok { @@ -947,7 +947,7 @@ func (b *SymbolTableBuilder) buildPackageVars(pkg *packages.Package, astFile *as if i < len(vs.Values) { init = b.exprString(vs.Values[i]) } - vars = append(vars, schema.GoVariableDeclaration{ + vars = append(vars, model.GoVariableDeclaration{ Name: name.Name, Type: typStr, Initializer: init, Scope: "package", StartLine: pos.Line, EndLine: pos.Line, }) diff --git a/internal/utils/fs_test.go b/internal/utils/fs_test.go index 4e12166..302a972 100644 --- a/internal/utils/fs_test.go +++ b/internal/utils/fs_test.go @@ -18,8 +18,8 @@ func TestIsTestFile(t *testing.T) { {"foo_test.go", true}, {"server_test.go", true}, {"foo.go", false}, - {"test.go", false}, // doesn't end with _test.go - {"_test.go", true}, // edge case: file is literally "_test.go" + {"test.go", false}, // doesn't end with _test.go + {"_test.go", true}, // edge case: file is literally "_test.go" {"", false}, {"foo_test.go.bak", false}, } From 613b2b4f86d91830154f21e1d13084f9645c5ad6 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Mon, 30 Nov 2026 15:49:10 -0500 Subject: [PATCH 2/3] docs: describe the schema as it is, without versions (#63) The seven v2- specs lose the prefix, and every link to them is updated. The living docs (CLAUDE.md, README.md, the undated specs, the Neo4j projection spec) no longer tell a v1 to v2 migration story. The migration records under docs/design/issues/ are deleted: they describe finished work. The other records only get their links and code references updated. --- CLAUDE.md | 40 +++++------ README.md | 20 +++--- .../issues/child-m1-schema-contract.md | 4 +- docs/design/Neo4j_projection/roadmap.md | 4 +- .../specs/neo4j-projection.md | 16 ++--- docs/design/issues/child-1-l1-emission.md | 40 ----------- docs/design/issues/child-2-l2-refinement.md | 39 ----------- docs/design/issues/epic-v2-migration.md | 67 ------------------- docs/design/issues/parent-v2-migration.md | 41 ------------ docs/design/issues/pr-body-v2-l1-l2.md | 52 -------------- docs/design/notes/l3-dataflow-metrics.md | 4 +- docs/design/notes/l3-eval-2026-10.md | 2 +- docs/design/roadmap.md | 2 +- .../specs/2026-11-24-neo4j-streaming-push.md | 22 +++--- ...ame-field.md => application-name-field.md} | 4 +- .../specs/{v2-artifacts.md => artifacts.md} | 14 ++-- docs/design/specs/{v2-go-ids.md => go-ids.md} | 12 ++-- .../{v2-l1-emission.md => l1-emission.md} | 26 ++++--- ...v2-l3-l4-dataflow.md => l3-l4-dataflow.md} | 34 +++++----- ...chema-structure.md => schema-structure.md} | 12 ++-- .../specs/{v2-span-lines.md => span-lines.md} | 4 +- 21 files changed, 109 insertions(+), 350 deletions(-) delete mode 100644 docs/design/issues/child-1-l1-emission.md delete mode 100644 docs/design/issues/child-2-l2-refinement.md delete mode 100644 docs/design/issues/epic-v2-migration.md delete mode 100644 docs/design/issues/parent-v2-migration.md delete mode 100644 docs/design/issues/pr-body-v2-l1-l2.md rename docs/design/specs/{v2-application-name-field.md => application-name-field.md} (86%) rename docs/design/specs/{v2-artifacts.md => artifacts.md} (94%) rename docs/design/specs/{v2-go-ids.md => go-ids.md} (91%) rename docs/design/specs/{v2-l1-emission.md => l1-emission.md} (87%) rename docs/design/specs/{v2-l3-l4-dataflow.md => l3-l4-dataflow.md} (98%) rename docs/design/specs/{v2-schema-structure.md => schema-structure.md} (96%) rename docs/design/specs/{v2-span-lines.md => span-lines.md} (91%) diff --git a/CLAUDE.md b/CLAUDE.md index 13b02d5..eeed843 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,13 +6,13 @@ layer serializes them into the schema shape. ## Schema decisions -Decisions made with the user during the v1 → v2 migration design loop +Decisions made with the user in the schema design loop (`designing-cldk-changes`), spine order. Each is a leaf-level addition to the shared -v2 vocabulary (parity clause: add at the leaves, never rename shared names). The -committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. +vocabulary (parity clause: add at the leaves, never rename shared names). The +committed spec is the full transcript: `docs/design/specs/l1-emission.md`. ### Identity & positioning (Group A — reused verbatim by L3/L4) -- **`application.name`** [user, 2026-11-20; spec `docs/design/specs/v2-application-name-field.md`]: an additive +- **`application.name`** [user, 2026-11-20; spec `docs/design/specs/application-name-field.md`]: an additive field with the same value as `application_name`. `application_name` is kept unchanged (renaming a shared field is forbidden), and `:GoApplication.name` carries the same value in Neo4j. - **`application.id`** = `can://` (app outermost, so a polyglot app shares one prefix), @@ -20,7 +20,7 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. (per the CLI contract; the SDK's Neo4j backend must use the same anchor). Module ids are `can:///go/`; externals are language-neutral `can:///@external///` (see § Id member segments). L3/L4 build ids on this unchanged. -- **Id member segments (spec `docs/design/specs/v2-go-ids.md`, issue #46)**: a type is +- **Id member segments (spec `docs/design/specs/go-ids.md`, issue #46)**: a type is `/`; a method is `//`; a package-level function is `/` (a method declared in another file uses that file as ``, see § Cross-file method ids below); a closure is `/closure_N`. The package import path is dropped: @@ -45,10 +45,10 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. type gets `//`, e.g. `…/handlers.go/frontendServer/logoutHandler`. The node stays in the receiver type's `callables{}`. `source_file` is kept for text recovery. Neo4j adds `GO_DECLARES` from the declaring `:GoModule` to the method, beside `GO_HAS_METHOD`. - Spec: `docs/design/specs/v2-go-ids.md` § Amendment. + Spec: `docs/design/specs/go-ids.md` § Amendment. - **Generic types**: `signatureOf()` carries no type parameters, so a generic type or method ids as `//`, with no `[T]` in the id. -- **`start_line` / `end_line`** [user, 2026-11-21; spec `docs/design/specs/v2-span-lines.md`]: top-level keys next +- **`start_line` / `end_line`** [user, 2026-11-21; spec `docs/design/specs/span-lines.md`]: top-level keys next to `span` on `Module` (added 2026-11-21 so the JSON and Neo4j modules match), `Import`, `Parameter`, `Callable`, `Type`, `Field` and `BodyNode`, equal to `span.start[0]` and `span.end[0]`. No `code_start_line`. Neo4j nodes carry the same two properties beside `span_json`. - **`span.bytes`** = **UTF-8 byte offsets** into `module.source` (Go strings are @@ -56,8 +56,8 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. ### `type` node - **`kind`** ∈ `struct | interface | alias | defined` — Go's four type-declaration - shapes. Collapses v1's `is_interface` boolean. (`alias` = `type X = Y`; - `defined` = `type X Y` over a non-struct, e.g. `type Celsius float64`.) + shapes (`alias` = `type X = Y`; `defined` = `type X Y` over a non-struct, e.g. + `type Celsius float64`). - **Methods** (declared outside the type in Go source) are resolved to their receiver type and placed in that `type.callables{}`; receiver recorded as a field. The tree reflects containment, not source location. @@ -68,8 +68,8 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. ### `callable` node - **`error_channel[]`** populated from `error`-typed return values (Go's error idiom); those returns remain in `return_type` too. Maps Go onto the shared field. -- **Closures / function literals** → nested `callables{}` on the enclosing callable - (replaces v1 `InnerCallables`); each closure gets its own `can://` id. +- **Closures / function literals** → nested `callables{}` on the enclosing callable; + each closure gets its own `can://` id. - **`source_file`** (optional; added in the 2026-09-29 design loop): Go allows a method to be declared in a *different file* than its receiver type. The method node stays nested under its receiver type (containment-by-receiver, above), but its `span.bytes` @@ -87,8 +87,8 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. shared keystone vocabulary when a second language needs it. ### `call` body node -- Typed **`is_goroutine`** and **`is_deferred`** boolean fields (`defer` is net-new vs - v1). `is_constructor_call` **dropped** — Go has no constructors. +- Typed **`is_goroutine`** and **`is_deferred`** boolean fields. No + `is_constructor_call`: Go has no constructors. - `callee` is the sanctioned `null → id` refinement slot (null at L1, backfilled at L2). ### `external_symbols` (L2 library calls) @@ -108,8 +108,8 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. - Mirrors the Python/Java precedent (library callees are leaf nodes at application scope); on by default at L2, no flag. -### L3 body and edges (`-a 3`; spec `docs/design/specs/v2-l3-l4-dataflow.md`) -- **Body node `id`** = `@` (`v2.GlobalOrdinal`) on **every** body node, +### L3 body and edges (`-a 3`; spec `docs/design/specs/l3-l4-dataflow.md`) +- **Body node `id`** = `@` (`schema.GlobalOrdinal`) on **every** body node, **from `-a 1` on** (not L3+ only) — Python parity (codeanalyzer-python stamps body ids at L1). **`parent`** (L3 only) = the local key of the statement a satellite call sits in. - **Body kinds: shared vocabulary only, no Go-specific kinds** — `if` → `branch`; @@ -128,7 +128,7 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. - **`k_limit`** (envelope, L3+ only) = `--graph-field-depth` (default 3), the access-path bound of the syntactic `ddg` (`x.f.g.h` → `x.f.g.*`); `ddg.prov` is `["ssa"]` (parity). -### L4 SDG (`-a 4`; spec `docs/design/specs/v2-l3-l4-dataflow.md` §4.6–§4.16, §6) +### L4 SDG (`-a 4`; spec `docs/design/specs/l3-l4-dataflow.md` §4.6–§4.16, §6) Reuses Group A ids/spans and the L3 vocabulary unchanged; every L4 fact is an addition (`-a 3` ⊆ `-a 4`, gated). Leaves: - **Vertices** (body nodes, span-less, no `callee`): `@formal_in:`, `@formal_out[:]`, @@ -162,20 +162,20 @@ Reuses Group A ids/spans and the L3 vocabulary unchanged; every L4 fact is an ad - A Go-specific `select` cfg kind was not added (`select` is a `switch` with `switch_case` edges). -### Repository-artifact decisions (spec `docs/design/specs/v2-artifacts.md`, branch `feat/artifacts`) +### Repository-artifact decisions (spec `docs/design/specs/artifacts.md`, branch `feat/artifacts`) Made with the user in the 2026-11-19 design loop, anchored on `codeanalyzer-python`'s `PyArtifact` / `PyDependency`. - **Placement:** `application.artifacts{: artifact}` (map); `application.dependencies[]` (list). - **Scope:** all non-`.go` project files [user, 2026-11-19]. Binaries are metadata only (`source:""`) [user]. Discovery skips what the Go analysis skips (`utils.IsVendored`: `vendor`, `testdata`, `.git`, also a `.git` file), and the tool's own outputs (the `-o` and `-c` directories whole unless they hold the project; `graph.cypher` in the working directory for `--emit neo4j` without `-o`). A symlinked file is followed only to a file inside the project. - **Artifact id:** `can:///artifact/`, app-scoped (Python parity) [user]. The Go projector's `:Artifact` flips to `CanNode=true`. - **Package id:** version-less `pkg:golang/` [user]; version lives on the dependency edge. - **Source text:** `--artifact-text`, on by default; `--no-artifact-text` drops it (Python and TypeScript parity) [user]. `config_keys` deferred [user]. -- **Dependencies:** every `go.mod` require; `direct=false` on `// indirect`; `kind:"runtime"`; `go.sum` supplies `locked_version` only, `go.sum`-only entries excluded [user]. `locked_in` names the `go.sum` artifact that locked it; the projector reads it, and `v2.PackageID` is the one package-id builder. A `replace` keeps the dependency's `name` and `spec`, records `replaced_by` (`@` or a local directory, which also adds `"replace"` to `prov`), and takes `locked_version` from the replacement, by Go's replace rule. +- **Dependencies:** every `go.mod` require; `direct=false` on `// indirect`; `kind:"runtime"`; `go.sum` supplies `locked_version` only, `go.sum`-only entries excluded [user]. `locked_in` names the `go.sum` artifact that locked it; the projector reads it, and `schema.PackageID` is the one package-id builder. A `replace` keeps the dependency's `name` and `spec`, records `replaced_by` (`@` or a local directory, which also adds `"replace"` to `prov`), and takes `locked_version` from the replacement, by Go's replace rule. - **`provides_imports`:** longest-prefix match against `go.mod` module paths [user]. A `-t` run reads every project package's imports with a light package load, so it matches a full run. - **Level:** L1, every level, not gated [user]. ## Neo4j-projection decisions -The graph projection (`--emit neo4j`) is a **second projection of the same v2 envelope**, +The graph projection (`--emit neo4j`) is a **second projection of the same envelope**, keyed on the identical `can://` ids — JSON and graph join on one string, never recomposed. These are the Go leaf decisions, made with the user in the 2026-10-04 design loop (`designing-cldk-changes`), under the parity clause (add `GO_`/`Go` leaves; reuse the @@ -257,7 +257,7 @@ shared neutral vocabulary verbatim; never rename a sibling's shared name). Spec: ### L3 overlay (live at `-a 3`) - `GO_CFG_NEXT {kind}`, `GO_CDG`, `GO_DDG {var, prov}` are no longer reserved; the projector emits one row per JSON `cfg[]`/`cdg[]`/`ddg[]` entry (cross-projection count gate). - Endpoints are `:GoBodyNode` **global ids** (`v2.GlobalOrdinal(callable-id, local-key)`), + Endpoints are `:GoBodyNode` **global ids** (`schema.GlobalOrdinal(callable-id, local-key)`), never recomposed by hand. `prov` is a string-array prop. - `:GoBodyNode` covers every body node incl. synthetic `@entry`/`@exit` (id `@entry`, no `span_json`), each with `GO_HAS_BODY_NODE` from its callable. diff --git a/README.md b/README.md index cf09344..1e20f45 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ The binary is fully self-contained: a single static executable with no runtime d dependencies for SDK users. - **CLDK canonical schema** — output is spine-compatible with the Java/Python/TypeScript analyzers, loadable directly by the Python SDK. -- **Neo4j projection** — the same v2 envelope projected into a property graph (`--emit neo4j`), +- **Neo4j projection** — the same envelope projected into a property graph (`--emit neo4j`), either as a replayable `graph.cypher` snapshot or pushed live over Bolt, keyed on the identical `can://` ids so JSON and graph join on one string. @@ -248,7 +248,7 @@ cango -i /path/to/go/app -a 2 -o /path/to/output/ # → writes /path/to/output/analysis.json ``` -> **Schema.** `cango` emits the **canonical CLDK v2** tree (the shape the Python SDK's v2 +> **Schema.** `cango` emits the **canonical CLDK** tree (the shape the Python SDK's > loader and the sections below describe). Omit `-o` to stream the JSON to stdout instead > of writing a file. @@ -354,10 +354,10 @@ subset of `-a 4` output, and `-j 1` and `-j N` output are byte-identical. ## Output schema -`cango` emits the **canonical CLDK v2** shape — the shape the v2 Python SDK loader consumes +`cango` emits the **canonical CLDK** shape — the shape the Python SDK loader consumes and the [step-by-step section above](#generating-analysisjson-for-a-go-app) produces. -### Canonical v2 shape +### Canonical shape The document is a manifest envelope wrapping one `application` containment tree. Every node carries a `can:////…` `id`, a `kind`, and a `span`: @@ -431,7 +431,7 @@ node carries a `can:////…` `id`, a `kind`, and a `span`: } ``` -Key v2 schema properties: +Key schema properties: - **Envelope** — `schema_version` (`"2.0.0"`), `language` (`"go"`), `max_level` (1–4), `k_limit` (L3+: the `--graph-field-depth` value), `degraded[]` (L4, only when something degraded) and `analyzer{name,version}` wrap a single `application` node. @@ -440,8 +440,8 @@ Key v2 schema properties: - **`id`** — every node carries a durable `can:////go///` id; `` is the `--app-name` anchor. A body node is keyed by `line:col` in its callable's `body` map and carries `id` = `@` at every level, from `-a 1` on. -- **`kind`** — `module` · `type` kinds `struct | interface | alias | defined` (collapses v1's - `is_interface`) · `callable` kinds `function | method | lambda` · body `call`. +- **`kind`** — `module` · `type` kinds `struct | interface | alias | defined` · + `callable` kinds `function | method | lambda` · body `call`. - **`base_types: []`** (type, optional) — embedded type ids (struct/interface embedding — the explicit spine), as opposed to interfaces the type is *computed* to satisfy. - **`span`** — `{start:[line,col], end:[line,col], bytes:[from,to]}`; `bytes` are **UTF-8 byte @@ -468,7 +468,7 @@ Key v2 schema properties: (`@`). A call nested in a statement carries `parent`, the statement's key. The callable gains `cfg[] {src, dst, kind}`, `cdg[] {src, dst}` and `ddg[] {src, dst, var, prov}`, whose - endpoints are `body` keys. See `docs/design/specs/v2-schema-structure.md`. + endpoints are `body` keys. See `docs/design/specs/schema-structure.md`. - **L4 (`-a 4`)** — `body` gains span-less vertices `@formal_in:`, `@formal_out[:]`, `/actual_in:`, `/actual_out[:]`, each with `of` (the bound name: a parameter or receiver name, `_`, `_recv`, ``, `:`, @@ -481,7 +481,7 @@ Key v2 schema properties: ## Neo4j projection (`--emit neo4j`) -`--emit neo4j` projects the **same v2 envelope** into a Neo4j property graph. It is a *second +`--emit neo4j` projects the **same envelope** into a Neo4j property graph. It is a *second projection of the identical analysis* — JSON nodes and graph nodes carry the same `can:////…` ids, so the two join on one string and are never recomposed. The graph vocabulary is `Go`-prefixed labels (`:GoModule`, `:GoType`, `:GoCallable`, `:GoField`, `:GoBodyNode`, `:GoExternal`, plus the @@ -533,7 +533,7 @@ What a re-emit replaces depends on the path: > — symbol table, call graph, every callable's body nodes with `GO_CFG_NEXT` / `GO_CDG` / > `GO_DDG`, and the SDG: vertex `:GoBodyNode`s with `var`, `GO_PARAM_IN` / `GO_PARAM_OUT {var}`, > `GO_SUMMARY`, stand-in vertices under their `:GoExternal`, and `degraded_json` on -> `:GoApplication`) and canonical schema v2. Do **not** pass `-a`/`--analysis-level` +> `:GoApplication`) and the canonical schema. Do **not** pass `-a`/`--analysis-level` > with it — an explicit level is a flag error (`--analysis-level does not apply to --emit neo4j`), > because there is no shallower graph to ask for. diff --git a/docs/design/Neo4j_projection/issues/child-m1-schema-contract.md b/docs/design/Neo4j_projection/issues/child-m1-schema-contract.md index c095bc4..00b8ff4 100644 --- a/docs/design/Neo4j_projection/issues/child-m1-schema-contract.md +++ b/docs/design/Neo4j_projection/issues/child-m1-schema-contract.md @@ -17,7 +17,7 @@ roadmap — the foundation every later milestone depends on. **Describe the solution you'd like** -A new `internal/neo4j/schema.go` (sibling to `internal/syntactic_analysis/v2emit/`, off the +A new `internal/neo4j/schema.go` (sibling to `internal/syntactic_analysis/emit/`, off the JSON hot path) that is the declarative contract: - [ ] Node labels + merge keys + typed properties — `:GoApplication`, `:GoModule`, `:GoType` @@ -58,4 +58,4 @@ Full catalog + rationale: `docs/design/Neo4j_projection/specs/neo4j-projection.m **Additional context** Parent: the Neo4j projection coordination issue under epic #94. Mirror the existing test idiom -(`TestGateL1_*`, `TestDeterminism_*` in `v2emit`) for the Neo4j gates. +(`TestGateL1_*`, `TestDeterminism_*` in `emit`) for the Neo4j gates. diff --git a/docs/design/Neo4j_projection/roadmap.md b/docs/design/Neo4j_projection/roadmap.md index 740e1b9..d682462 100644 --- a/docs/design/Neo4j_projection/roadmap.md +++ b/docs/design/Neo4j_projection/roadmap.md @@ -27,7 +27,7 @@ M1 schema.go (contract + conformance test + --emit schema) M2 rows.go (GraphRows + RowBuilder: MERGE-dedup, deferred edges, prune, scoping, literals) │ (the IR both writers consume) ▼ -M3 project.go (pure projector: v2.Analysis tree → GraphRows) ◄── the intellectual core +M3 project.go (pure projector: schema.Analysis tree → GraphRows) ◄── the intellectual core │ ├─────────────────────────────┬──────────────────────────────┐ ▼ ▼ ▼ @@ -102,7 +102,7 @@ imports + external ghosts; (d) neutral artifact/package layer + reserved-overlay - **No dangling** (`TestNeo4j_NoDangling`): every edge endpoint is an emitted node. - **Two-projection agreement** (`TestNeo4j_IdParity`): every graph `can://`/ordinal id has a matching JSON-tree node and vice-versa (modulo containment edges) — cross-checks against - `v2emit.Emit` output on the same fixture. + `emit.Emit` output on the same fixture. - **Go-specific** gates: `:GoType.kind` carries the four kinds; `GO_EMBEDS` vs `GO_SATISFIES` split correct; `source_file` prop present only on a cross-file method; `is_goroutine` set on a `go`-statement call node; reserved overlay sections emit zero rows at L2. diff --git a/docs/design/Neo4j_projection/specs/neo4j-projection.md b/docs/design/Neo4j_projection/specs/neo4j-projection.md index bd1f350..65e8f74 100644 --- a/docs/design/Neo4j_projection/specs/neo4j-projection.md +++ b/docs/design/Neo4j_projection/specs/neo4j-projection.md @@ -5,7 +5,7 @@ > **Canonical home:** `codellm-devkit/.github → docs/design/specs/2026-10-04-codeanalyzer-go-neo4j-projection.md` > — staged here on the fork because `lamwassi` has pull-only access upstream; a maintainer > ports it. **Tracked under epic** `codellm-devkit/.github#94` (`codeanalyzer-go → canonical -> schema v2`), whose summary already scopes "both projections (analysis.json + Neo4j)" and +> schema`), whose summary already scopes "both projections (analysis.json + Neo4j)" and > lists the Neo4j backend rung + SDK frontend rung. > > This is the *what* (the contract + decisions). The sequenced *how* is the sibling @@ -16,8 +16,8 @@ ## 1. Contract-Impact Triage -**Does this change the schema v2 JSON output?** No. The Neo4j backend is a **second -projection of the frozen v2 envelope** the JSON path already emits, keyed on the identical +**Does this change the JSON output?** No. The Neo4j backend is a **second +projection of the frozen envelope** the JSON path already emits, keyed on the identical `can://` ids and `@line:col` ordinal ids — JSON and graph join on one string, built once upstream, never recomposed. No new JSON node/field/id shape. @@ -145,7 +145,7 @@ Python encoding only. ## 5. Package layout -Analyzer (new, sibling to `internal/syntactic_analysis/v2emit/`, off the JSON hot path): +Analyzer (new, sibling to `internal/syntactic_analysis/emit/`, off the JSON hot path): ``` internal/neo4j/ @@ -155,7 +155,7 @@ internal/neo4j/ rows.go output-agnostic row IR: GraphRows/NodeRow/EdgeRow/NodeRef, RowBuilder (in-memory MERGE, deferred edges), applicationPrefix/descendantPrefix, prune(), Cypher-literal rendering, in-memory-only `module` grouping field - project.go pure projector: v2.Analysis tree → GraphRows. No I/O, no driver + project.go pure projector: schema.Analysis tree → GraphRows. No I/O, no driver cypher.go snapshot writer → self-contained idempotent graph.cypher bolt.go incremental writer → content-hash-diffed per-module Bolt push, schema-version gate, --eager purge/prune (lazy driver dependency) @@ -183,13 +183,13 @@ Plus `GoBackend` union + `cache_subdir` "go" key in `cldk/analysis/commons/backe Epic #94's release plan already states: **"Neo4j projection and the JSON schema move in lockstep."** Concretely: -- **Analyzer** ships the `internal/neo4j/` projection as part of the v2 line. `--emit neo4j` +- **Analyzer** ships the `internal/neo4j/` projection as part of the 2.0.0 schema line. `--emit neo4j` is independently landable behind the existing flag stubs; it produces a graph at full-depth = L4, the max implemented level (L3 and then L4 landed additively, each with no contract change — the L1 reserve). -- **SDK** (`GoAnalysisBackend`) pins the analyzer version **only after** the analyzer v2 +- **SDK** (`GoAnalysisBackend`) pins the analyzer version **only after** the analyzer release is cut — same ordering constraint as the JSON wiring (the SDK's Go models can't - parse v2 until then, and there is no Go wiring yet, so this is net-new, not a migration). + parse the output until then, and there is no Go wiring yet, so this is net-new, not a migration). - **Version lockstep:** `SCHEMA_VERSION = "2.0.0"` on both sides; the SDK gates on the analyzer-version floor (additive-MINOR suspended for the 2.0.0 line). diff --git a/docs/design/issues/child-1-l1-emission.md b/docs/design/issues/child-1-l1-emission.md deleted file mode 100644 index 0a33e82..0000000 --- a/docs/design/issues/child-1-l1-emission.md +++ /dev/null @@ -1,40 +0,0 @@ - - -**Is your feature request related to a problem? Please describe.** - -The Go analyzer serializes the v1 shape. L1 is the structural keystone of the v2 -migration: it introduces the additive containment tree and every Group A identity -decision the later levels build on. Do L1 first and get the symbol-table gate green -before touching the L2 call graph. The parser/resolver stay; only the emission layer -changes (golden rule: replace what serializes, keep what computes). - -**Describe the solution you'd like** - -- [ ] `application.id` = `can://go/`, `` = `--app-name` (default: input dir base name) -- [ ] Durable `can://` ids on module/type/callable; `signatureOf()` is the last segment -- [ ] `span: {start:[l,c], end:[l,c], bytes:[from,to]}` with UTF-8 byte offsets; drop flat `start_line`/`end_line` -- [ ] `source` emitted once per module; drop per-callable `code` -- [ ] `type.kind` ∈ `struct|interface|alias|defined`; methods grouped under receiver type's `callables{}` -- [ ] `base_types[]` = embedded ids, `interfaces[]` = computed structural satisfaction -- [ ] `body{}` holds `call` nodes with `callee:null`, typed `is_goroutine`/`is_deferred`; closures nest in `callables{}` - -**Describe alternatives you've considered** - -Does NOT emit the `call_graph` (that is the L2 child), nor any L3/L4 `body` statements -or edges. `body{}` at L1 holds only `call` nodes. - -**Additional context** - -- Emitter approach: walk the existing in-memory model, add a v2 emitter behind a flag; keep v1 emitter as the compat shim during transition. -- One genuinely new datum: thread parser byte offsets into `span.bytes`. -- Structural interface satisfaction needs method-set matching — cost lives here, not in the resolver. -- Validate each node against the SDK v2 Go models as they land; superset check vs v1 output. -- Schema decisions recorded in repo `CLAUDE.md`; full transcript in the spec. diff --git a/docs/design/issues/child-2-l2-refinement.md b/docs/design/issues/child-2-l2-refinement.md deleted file mode 100644 index 51c0ee5..0000000 --- a/docs/design/issues/child-2-l2-refinement.md +++ /dev/null @@ -1,39 +0,0 @@ - - -**Is your feature request related to a problem? Please describe.** - -L1 emits the v2 containment tree with `call` body nodes whose `callee` is `null` — the -sanctioned refinement slot. L2 fills it: resolve each call site and each call-graph edge -endpoint from a v1 `signatureOf()` string to the durable `can://` id of the callable it -names. L2 is pure refinement over the L1 tree — it computes no new facts, it only -translates identity. The parser/resolver stay; only the emission layer gains the -signature→id index (golden rule: replace what serializes, keep what computes). - -**Describe the solution you'd like** - -- [ ] `buildSigIndex` maps every v1 callable signature (functions, methods, nested closures) → its `can://` id, using the SAME id builders `emitCallable` uses (byte-identical ids) -- [ ] `callee` on each `call` body node backfilled from `null` to the resolved `can://` id -- [ ] `call_graph` emitted at application scope as `[{src, dst, prov, weight}]` -- [ ] External/stdlib callees (outside the project) resolve to no endpoint — never a dangling edge -- [ ] L2 gate green: every edge endpoint and every non-null `callee` resolves to a real in-tree node id -- [ ] Determinism: `call_graph` edge order stable across runs (sorted before emit) - -**Describe alternatives you've considered** - -Does NOT compute any new call-graph facts — it reuses the v1 call graph and only -translates endpoints to `can://` ids. Does NOT emit L3/L4 `body` statements or edges. - -**Additional context** - -- v1 signatures are globally unique (a method signature embeds its receiver), so the flat signature→id map has no collisions. -- The index mirrors `emitModule`/`emitType`/`emitCallable` parent-id computation exactly; drift there would silently dangle endpoints. -- Determinism risk: edge order was nondeterministic before sorting — the determinism gate fails without a stable sort. -- Depends on the L1 child: L2 refines the tree L1 produces; file/land L1 first. -- Full transcript in the spec; schema decisions in repo `CLAUDE.md`. diff --git a/docs/design/issues/epic-v2-migration.md b/docs/design/issues/epic-v2-migration.md deleted file mode 100644 index 1072e35..0000000 --- a/docs/design/issues/epic-v2-migration.md +++ /dev/null @@ -1,67 +0,0 @@ - - -## Spec - -https://github.com/codellm-devkit/codeanalyzer-go/blob/main/docs/design/specs/v2-l1-emission.md - -## Summary - -Migrate `codeanalyzer-go` from the legacy v1 output to the **canonical schema v2** (one -additive tree: `application → module → type → callable → body` with typed edge overlays) -and bring it to **analysis level 2** — L1 structural containment + L2 identity-only -`call_graph`, in both projections (`analysis.json` + Neo4j). This is a **schema-major** -change (new envelope, `can://` ids, `span` with UTF-8 byte offsets, `source` per module, -`body` call nodes, `{src,dst,prov}` edges). The `python-sdk` Go wiring lands in lockstep -behind a frozen public API. **Reach for this train: L1 + L2 to parity; L3/L4 deferred.** - -Golden rule: keep everything that *computes* facts (parser, resolver, call-graph -builder); replace only what *serializes* them. - -## Affected repos (from Contract-Impact Triage) - -- `codeanalyzer-go` — analyzer emission (L1 + L2) + Neo4j v2 projection — backend rung -- `python-sdk` — net-new Go model wiring to v2 (`cldk/analysis/` has no `go` package today) — frontend rung -- docs (user-facing schema/levels) — later, `finishing-cldk-work` - -## Design decisions - -- **D1** Pure canonical v2 (drop per-callable `code`/flat `start_line`/`end_line`; recover text by slicing `module.source`) -- **D2** `application.id` = `can://go/`, `` = `--app-name` (default: input dir base name) -- **D3** `span.bytes` = UTF-8 byte offsets into `module.source` (Go strings are UTF-8; avoids the UTF-16/rune mismatch) -- **D4** Single type `kind` ∈ `struct|interface|alias|defined` (collapses v1 `is_interface`); methods nest under receiver type's `callables{}` -- **D5** `base_types[]` = embedded ids (explicit spine) vs `interfaces[]` = computed structural satisfaction (method-set matching) -- **D6** `error_channel[]` from `error`-typed returns; closures → nested `callables{}`; `is_constructor_call` dropped (Go has none) -- **D7** `call` body nodes carry typed `is_goroutine`/`is_deferred`; `callee` is the null→id refinement slot (null at L1, backfilled at L2) -- **D8** `source_file` on a callable when a method is declared apart from its receiver type (cross-file-method span fix) -- **Scope guard:** analyzer is a **pure graph provider** — no slicing/taint in the analyzer (those are SDK queries) - -## Release plan - -- Analyzer = **major** release (breaking output). L1 and L2 are independently shippable behind `--analysis-schema 2`; v1 stays the default until the SDK migrates. -- SDK = **major** release; pins the analyzer **only after** the analyzer v2 release is cut (old SDK Go wiring can't parse v2 until then — and there is no Go wiring yet, so this is net-new). -- Neo4j projection and the JSON schema move in lockstep. - -## Deferred (not this train) - -- **L3** (CFG/CDG/DDG) and **L4** (SDG `param_in`/`param_out`/`summary`) — a later train reusing this train's `can://` ids and `{src,dst,prov}` edge shape verbatim (Group A/C vocabulary, coined once here per the parity clause). -- Go-specific `cfg` edge kinds (`defer_resume`, `select`) — recorded when L3 is designed. -- Points-to oracle (L4 prerequisite); `--materialize-expressions`/`--materialize-basic-blocks`; framework detection. - -## Definition of done (epic-level) - -- Every sub-issue closed and its PR's gate green. -- Analyzer output validates against the SDK v2 Go models; the `L1 ⊆ L2` superset gate holds; parity clause holds (no renamed/repurposed shared vocabulary). -- Superset gate: v2 output carries every v1 fact modulo the sanctioned drops (`code`, `is_*` booleans folded into `kind`, `is_constructor_call`). -- `--analysis-schema 2` output is deterministic across runs (ids and edge order stable). -- SDK public API unchanged (major bump + documented semantic shifts); analyzer↔SDK versions pinned in lockstep. -- Docs / CHANGELOG updated. -- The two switch-over steps: (1) flip the default output from v1 to v2; (2) remove the v1 emitter once `python-sdk` has migrated and nothing reads v1 — both filed as their own units when due. diff --git a/docs/design/issues/parent-v2-migration.md b/docs/design/issues/parent-v2-migration.md deleted file mode 100644 index c0bd54d..0000000 --- a/docs/design/issues/parent-v2-migration.md +++ /dev/null @@ -1,41 +0,0 @@ - - -**Is your feature request related to a problem? Please describe.** - -`codeanalyzer-go` emits the v1 schema (`internal/schema/schema.go`): two-key -`{symbol_table, call_graph}`, flat `start_line`/`end_line`, per-callable `code`, -`is_*` booleans, `signature` as id. Every sibling analyzer has moved to the v2 -keystone (`can://` ids, additive tree, `span` with byte offsets, `source` per module, -`{src,dst,prov}` edges). Go is the last on v1, so `CLDK(language="go")` cannot share -the one-model SDK surface. This is a coordinated schema major across two repos: -`codeanalyzer-go` (emission rewrite) and `python-sdk` (Go model remap), released in -lockstep. Reach for this train: L1 + L2 to parity; L3/L4 deferred. - -**Describe the solution you'd like** - -- [ ] `codeanalyzer-go`: L1 emission — additive tree, `source` per module, `can://` ids, `body{}` with `call` nodes -- [ ] `codeanalyzer-go`: L2 emission — `call_graph: [{src,dst,prov,weight}]` at application scope -- [ ] `codeanalyzer-go`: Neo4j projection relabelled to v2 node/edge families -- [ ] `python-sdk`: Go v2 model remap, every public accessor name/return type unchanged -- [ ] Release v2.0.0 and pin analyzer in SDK **only once both are cut** -- [ ] Superset gate green: v2 output contains every v1 fact modulo sanctioned drops - -**Describe alternatives you've considered** - -Does NOT build L3 (CFG/CDG/DDG) or L4 (SDG). Those are a later train reusing this -train's `can://` ids and edge shape unchanged. Does NOT add framework detection. - -**Additional context** - -- Design transcript: `docs/design/specs/v2-l1-emission.md` (linked, not pasted). -- Group A vocabulary (`can://` ids, `span.bytes` UTF-8) is reused verbatim by L3/L4 — coined once here per the parity clause. -- Sanctioned drops: `code` (slice from `source`), `is_*` booleans (folded into `kind`), `is_constructor_call` (Go has no constructors). -- Ordering risk: SDK's v1 Go models will not parse v2 output; do not pin the new major prematurely. -- go.mod-derived `` slug must be deterministic across runs, else ids churn. diff --git a/docs/design/issues/pr-body-v2-l1-l2.md b/docs/design/issues/pr-body-v2-l1-l2.md deleted file mode 100644 index 9258919..0000000 --- a/docs/design/issues/pr-body-v2-l1-l2.md +++ /dev/null @@ -1,52 +0,0 @@ -Migrate `codeanalyzer-go` to emit the canonical CLDK **v2** `analysis.json` for analysis levels **L1** (additive containment tree) and **L2** (call-graph refinement). v1 output is unchanged and remains the default; v2 is opt-in behind `--analysis-schema 2`. - -## Motivation and Context - -Closes #8 -Closes #9 - -Part of epic codellm-devkit/.github#94. Go was the last analyzer on v1; this moves it onto the shared v2 keystone (`can://` ids, additive tree, `span` with UTF-8 byte offsets, `source` per module, `{src,dst,prov}` edges) so `CLDK(language="go")` can share the one-model SDK surface. Design transcript: `docs/design/specs/v2-l1-emission.md`. - -## How Has This Been Tested? - -Gates run on this commit (analyzer matrix; `testdata/multipackage` fixture): - -``` -# Fixture suite (forced, uncached) -$ go test -count=1 ./... -ok cmd/codeanalyzer ok internal/core ok internal/schema/v2 ok internal/syntactic_analysis/v2emit (all green, exit 0) - -# Determinism: -j 1 vs -j 8, v2 L2 -$ cango -i testdata/multipackage --analysis-schema 2 -a 2 -j 1 -o j1/ ; ... -j 8 -o jN/ -$ diff j1/analysis.json jN/analysis.json # byte-identical -> PASS - -# Monotonicity: v2 L1 ⊆ v2 L2 -L1 node ids: 33; L2 node ids: 33; L1 ids missing from L2: 0 -L1 call_graph: 0 edges; L2 call_graph: 9 edges # L2 adds, never rewrites -> PASS -``` - -Schema-conformance gate (validate against the SDK CPG model) is **deferred**: `python-sdk` has no Go model yet (`cldk/analysis/` has no `go` package) — that is the separate SDK-wiring child of epic #94. Structural self-check passed: valid JSON, `schema_version 2.0.0`, `application.id can://go/multipackage`, edge keys exactly `src/dst/prov/weight`. - -## Breaking Changes - -None for existing users: v1 is still the default output. v2 is additive and opt-in behind `--analysis-schema 2`. The v2 contract itself is a new major, consumed by nothing yet (no SDK Go pin); the default flip and v1-emitter removal are later units, filed when due. - -## Types of changes -- [ ] Bug fix (non-breaking change which fixes an issue) -- [x] New feature (non-breaking change which adds functionality) -- [ ] Breaking change (fix or feature that would cause existing functionality to change) -- [x] Documentation update - -## Checklist -- [x] I have read the [Codellm-Devkit Documentation](https://codellm-devkit.info) -- [x] My code follows the repository's style guidelines -- [x] New and existing tests pass locally -- [x] I have added appropriate error handling -- [x] I have added or updated documentation as needed - -## Additional context - -- L1 computes no new facts beyond span offsets; L2 is pure refinement (signature→`can://` id via `buildSigIndex`). Parser/resolver unchanged (golden rule: replace what serializes, keep what computes). -- `span.bytes` are UTF-8 byte offsets into `module.source` (Go strings are UTF-8). -- `source_file` carried on a callable only when a method is declared apart from its receiver type. -- L3/L4 deferred to a later train; Group A ids/spans already designed for verbatim reuse. diff --git a/docs/design/notes/l3-dataflow-metrics.md b/docs/design/notes/l3-dataflow-metrics.md index a078db5..06073ec 100644 --- a/docs/design/notes/l3-dataflow-metrics.md +++ b/docs/design/notes/l3-dataflow-metrics.md @@ -7,7 +7,7 @@ statement-granular body nodes and three edge lists: - `cdg`: Cooper-Harvey-Kennedy post-dominators plus Ferrante-Ottenstein-Warren. - `ddg`: syntactic may-reaching definitions over k-limited access paths, `prov:["ssa"]`. -The semantics are in [`v2-l3-l4-dataflow.md`](../specs/v2-l3-l4-dataflow.md) §4.2–§4.5. +The semantics are in [`l3-l4-dataflow.md`](../specs/l3-l4-dataflow.md) §4.2–§4.5. This note records how L3 behaves on the corpus of [`l3-eval-2026-10.md`](l3-eval-2026-10.md), which it accompanies. It covers volume, the shape of the graphs, cost, output size and internal @@ -803,7 +803,7 @@ gets `formal_in` / `formal_out` vertices, and every resolved call site gets `act application carries `param_in` / `param_out`, every call site carries `summary` edges, VTA adds dispatch targets to `call_graph` (`prov:["vta"]`), library callees get stand-in formals in `external_symbols[].body`, and a type-based may-alias oracle adds `ddg` edges with -`prov:["points-to"]`. The semantics are in [`v2-l3-l4-dataflow.md`](../specs/v2-l3-l4-dataflow.md) +`prov:["points-to"]`. The semantics are in [`l3-l4-dataflow.md`](../specs/l3-l4-dataflow.md) §4.6–§4.16 and §6. - **When and where:** measured 2026-10-28 on the same host, an Apple M3 Max (16 cores, 64 GB, diff --git a/docs/design/notes/l3-eval-2026-10.md b/docs/design/notes/l3-eval-2026-10.md index 8c04d19..7a91b94 100644 --- a/docs/design/notes/l3-eval-2026-10.md +++ b/docs/design/notes/l3-eval-2026-10.md @@ -204,7 +204,7 @@ rerun results are below. but short. - Fix (`679f995`): `seen` is keyed on `(callable.Path, callable.Signature, calleeSig)`, so every init keeps its own edges, and `Build` walks files, types and callables in sorted key order. - Regression tests: `internal/syntactic_analysis/v2emit/gate_l2_inits_test.go` over the + Regression tests: `internal/syntactic_analysis/emit/gate_l2_inits_test.go` over the `testdata/dataflow/inits` fixture (two files, each `init()` calling `setup()` and `os.Getenv`), asserting each init's edges and 10 byte-identical fresh builds. - Rerun after the fix (same pinned commits, `--eager`, `-j 16`), with `-a 3 -j 1`, `-a 3 -j 16` diff --git a/docs/design/roadmap.md b/docs/design/roadmap.md index 42143df..cd31946 100644 --- a/docs/design/roadmap.md +++ b/docs/design/roadmap.md @@ -71,7 +71,7 @@ A/B/C ─► D (Neo4j relabel) ─► SDK v2 model remap ─► pin SDK→analyz signatures (nondeterministic, dropped edges) and the Neo4j `--eager` purge failing on Neo4j 5.x. The release tag is the user's decision. - **Release B — L4 (`-a 4`, SDG).** Implemented on `feat/l4-sdg` - (spec `docs/design/specs/v2-l3-l4-dataflow.md` Phase 2). It adds: + (spec `docs/design/specs/l3-l4-dataflow.md` Phase 2). It adds: - VTA dispatch over `go/ssa`; - formal/actual vertices, `param_in`/`param_out`, call-site `summary` edges and port-wiring `ddg`; diff --git a/docs/design/specs/2026-11-24-neo4j-streaming-push.md b/docs/design/specs/2026-11-24-neo4j-streaming-push.md index 62ceedb..5434b41 100644 --- a/docs/design/specs/2026-11-24-neo4j-streaming-push.md +++ b/docs/design/specs/2026-11-24-neo4j-streaming-push.md @@ -16,8 +16,8 @@ This design bounds the client memory of the projection and the push. | Stage | Live heap | Note | |---|---|---| | After `Analyze` | 10.9 GB | analysis results (SSA, L3, L4) | -| After `v2emit.Emit`, analyzer kept | 34.1 GB | the full `v2` tree adds 23 GB | -| After `v2emit.Emit`, analyzer released | 24.5 GB | the tree alone is 13.6 GB | +| After `emit.Emit`, analyzer kept | 34.1 GB | the full `v2` tree adds 23 GB | +| After `emit.Emit`, analyzer released | 24.5 GB | the tree alone is 13.6 GB | | During `Project` | more than 69 GB (RAM) | `GraphRows` copy, heavy swap, stopped after 30 min | Largest parts of the `v2` tree: @@ -62,18 +62,18 @@ Anti-goals (a failure even if memory goes down): ## 5. Design -### 5.1 Emitter: a re-iterable module stream (`internal/syntactic_analysis/v2emit`) +### 5.1 Emitter: a re-iterable module stream (`internal/syntactic_analysis/emit`) -Add an exported stream type next to `EmitTo`, for example `v2emit.Open(...) *Stream`. +Add an exported stream type next to `EmitTo`, for example `emit.Open(...) *Stream`. It takes the same arguments as `Emit` and exposes: -- `Envelope() *v2.Analysis`: the manifest, call graph, external symbols, artifacts and dependencies. +- `Envelope() *schema.Analysis`: the manifest, call graph, external symbols, artifacts and dependencies. Its `SymbolTable`, `ParamIn`, `ParamOut` and `Degraded` fields are empty. -- `Modules() iter.Seq2[string, v2.Module]`: each module in `sortedFileKeys` order. +- `Modules() iter.Seq2[string, schema.Module]`: each module in `sortedFileKeys` order. Each call emits the modules again. A module is garbage after its loop step. -- `ParamIn()`, `ParamOut() iter.Seq[v2.ParamEdge]`: the same streams `EmitTo` writes. +- `ParamIn()`, `ParamOut() iter.Seq[schema.ParamEdge]`: the same streams `EmitTo` writes. They are valid only after one full `Modules()` walk, because that walk fills the `l4Overlay` id map. -- `Degraded() []v2.Degraded`: valid only after one full `Modules()` walk. +- `Degraded() []schema.Degraded`: valid only after one full `Modules()` walk. The second walk must not print the `l4Overlay.apply` warnings again. `EmitTo` and `Emit` must keep their exact output (the JSON golden and parity tests prove this). @@ -98,7 +98,7 @@ It does not hold body-node ids, so it stays small. Within one module, a `RowBuilder` still removes duplicate nodes and duplicate edge facts. Across modules, the DB `MERGE` makes a duplicate edge row a no-op. -`Project(a *v2.Analysis) GraphRows` stays. +`Project(a *schema.Analysis) GraphRows` stays. It drives the same per-module code over an in-memory tree and collects every row. The unit tests and the parity gate (§6) use it as the reference. @@ -135,7 +135,7 @@ The push message reports the number of node rows and edge rows sent. ### 5.4 CLI (`cmd/codeanalyzer/main.go`) The neo4j branch opens the stream and passes it to the new entry point. -It no longer calls `v2emit.Emit`. The analysis results stay live, because both passes read them. +It no longer calls `emit.Emit`. The analysis results stay live, because both passes read them. ## 6. Verification @@ -143,7 +143,7 @@ It no longer calls `v2emit.Emit`. The analysis results stay live, because both p The test collects the streamed rows through a fake sink. It sorts them, removes duplicates, and compares them with the reference rows. - **Order test (fake DB):** no edge statement runs before the last node statement. For each module, its purge runs before its nodes and its L4 vertices. -- **Existing tests:** every test in `bolt_session_test.go`, `project_test.go` and the v2emit golden tests passes without change. +- **Existing tests:** every test in `bolt_session_test.go`, `project_test.go` and the emit golden tests passes without change. The exception is a test that checks the internal call order which this design changes on purpose. - **Live checks:** run the nats-server push against the `cango-neo4j` container. Record the peak RSS and the wall time. diff --git a/docs/design/specs/v2-application-name-field.md b/docs/design/specs/application-name-field.md similarity index 86% rename from docs/design/specs/v2-application-name-field.md rename to docs/design/specs/application-name-field.md index f7983b7..7b44395 100644 --- a/docs/design/specs/v2-application-name-field.md +++ b/docs/design/specs/application-name-field.md @@ -2,7 +2,7 @@ ## Contract-Impact Triage -**Does this change schema v2 output?** Yes, additively. The v2 `application` node gains a +**Does this change the output?** Yes, additively. The `application` node gains a `name` field. No existing field is renamed or removed. | Change type | Analyzers | SDKs | Docs | @@ -13,7 +13,7 @@ Made with the user on 2026-11-20. -1. **Field.** `application.name` is added to the v2 application node in `analysis.json`. Its +1. **Field.** `application.name` is added to the application node in `analysis.json`. Its value is the same as `application_name`. 2. **Keep `application_name`.** Renaming it was rejected. The parity rule forbids renaming shared fields, and `codeanalyzer-python` and `python-sdk` read `application_name`. diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/artifacts.md similarity index 94% rename from docs/design/specs/v2-artifacts.md rename to docs/design/specs/artifacts.md index 874c61e..5b7a24a 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/artifacts.md @@ -2,32 +2,32 @@ > **Cross-repo spec.** Canonical home is `codellm-devkit/.github → docs/design/specs/`, > beside the coordinating parent issue. Staged locally on `feat/artifacts` until that repo -> is available (same precedent as `v2-l1-emission.md`). This is the design transcript of the +> is available (same precedent as `l1-emission.md`). This is the design transcript of the > datamodel loop, linked from the tracking record, not pasted into it. ## Contract-Impact Triage -**Does this change schema v2 output?** Yes. It adds two application-scoped fields +**Does this change the output?** Yes. It adds two application-scoped fields (`artifacts`, `dependencies`), new id shapes for artifact and package nodes, one new CLI flag (`--artifact-text`), and populates the already-declared Neo4j neutral layer (`:Artifact`, `:Package`, `HAS_ARTIFACT`, `DECLARES_DEPENDENCY`, `LOCKS`). | Change type | Analyzers | SDKs | Docs | | --- | --- | --- | --- | -| Schema v2 evolution (additive) | **codeanalyzer-go** (emit + projector); codeanalyzer-python: none (parity adopted, no id change) | **python-sdk** (Go backend reconstruction of `:Artifact` / `:Package`) | `CLAUDE.md` § Schema decisions, this spec | +| Schema evolution (additive) | **codeanalyzer-go** (emit + projector); codeanalyzer-python: none (parity adopted, no id change) | **python-sdk** (Go backend reconstruction of `:Artifact` / `:Package`) | `CLAUDE.md` § Schema decisions, this spec | Anchor: `codeanalyzer-python` already emits this layer (`PyArtifact`, `PyDependency`, `PyConfigKey`, `application.artifacts`, `application.dependencies`, `codeanalyzer/schema/py_schema.py`), and `python-sdk/cldk/analysis/commons/artifacts.py` rebuilds it from Neo4j, with the neutral labels shared across analyzers. -In Go: `schema.GoArtifact` and `schema.GoDependency` (`internal/schema/schema.go`, the -analyzer model), emitted as `v2.Artifact` and `v2.Dependency` (`internal/schema/v2/schema.go`); +In Go: `model.GoArtifact` and `model.GoDependency` (`internal/model/model.go`, the +analyzer model), emitted as `schema.Artifact` and `schema.Dependency` (`internal/schema/schema.go`); there is no config-key type, because `config_keys` is deferred. ## Problem -The v2 schema and projector declare the neutral repository-artifact layer, but the Go +The schema and projector declare the neutral repository-artifact layer, but the Go analyzer never populates it. `go.mod` is read only for `go mod download`. Against the Go analysis of `microservices-demo/src/frontend`, `MATCH (n:Artifact)` returns 0 rows. @@ -115,7 +115,7 @@ Each decision was made with the user, one question per decision, in the order be by `id`, `CanNode=true`), under `HAS_ARTIFACT` from `:GoApplication`. These are the JSON artifact's fields; empty values are left out. Python writes the same set, TypeScript the same set plus `kind` (#81; the original `{id, path, format}` left the text and hash out). -- `:Package {id, ecosystem, name}` keyed by `id`. The id comes from `v2.PackageID`, the one +- `:Package {id, ecosystem, name}` keyed by `id`. The id comes from `schema.PackageID`, the one place a package id is built (#72). - `DECLARES_DEPENDENCY` `(:Artifact)→(:Package)`, `_k = kind` (`runtime`), carrying `spec`, `direct`, `prov` and, when a replace applies, `replaced_by` as properties. diff --git a/docs/design/specs/v2-go-ids.md b/docs/design/specs/go-ids.md similarity index 91% rename from docs/design/specs/v2-go-ids.md rename to docs/design/specs/go-ids.md index b35ba2d..12eeb98 100644 --- a/docs/design/specs/v2-go-ids.md +++ b/docs/design/specs/go-ids.md @@ -1,20 +1,20 @@ -# Spec: schema v2 id format for Go callables and types (codeanalyzer-go) +# Spec: id format for Go callables and types (codeanalyzer-go) > **Cross-repo spec.** The python-sdk Go backend keys types and fields by the last id segment, > so the canonical home is `codellm-devkit/.github → docs/design/specs/`, beside the -> coordinating record. Staged locally on `feat/v2-go-ids` until that repo is available (same -> precedent as `v2-l1-emission.md` and `v2-artifacts.md`). This is the design transcript of the +> coordinating record. Staged locally on `feat/go-ids` until that repo is available (same +> precedent as `l1-emission.md` and `artifacts.md`). This is the design transcript of the > datamodel loop, linked from the tracking issue, not pasted into it. ## Contract-Impact Triage -**Does this change schema v2 output?** Yes. It changes the id shape of `type`, method, and +**Does this change the output?** Yes. It changes the id shape of `type`, method, and function nodes, and of `external_symbols` keys. It does not change the module, field, artifact, or ordinal-id shapes, and it adds no field. | Change type | Analyzers | SDKs | Docs | | --- | --- | --- | --- | -| Schema v2 id-format change | **codeanalyzer-go** (`internal/schema/v2/ids.go`, `v2emit`, Neo4j projector) | **python-sdk** Go backend (`cldk/analysis/go/neo4j/neo4j_backend.py` keys types and fields by last id segment; verify methods at the SDK rung) | `CLAUDE.md` § Schema decisions, `canonical-schema.md` references, this spec | +| Schema id-format change | **codeanalyzer-go** (`internal/schema/ids.go`, `emit`, Neo4j projector) | **python-sdk** Go backend (`cldk/analysis/go/neo4j/neo4j_backend.py` keys types and fields by last id segment; verify methods at the SDK rung) | `CLAUDE.md` § Schema decisions, `canonical-schema.md` references, this spec | Convention anchor: `codeanalyzer-typescript/src/schema/ids.ts` (`idFromSig`: strip the module prefix from the dotted signature, split the tail on `.`) and `codeanalyzer-python/codeanalyzer/schema/ids.py` @@ -149,7 +149,7 @@ frontend app are affected (those with `source_file` set). the declaring `:GoModule` to the method, so "which file declares this method" is one query. No new relationship kind. -**Release.** Same PR and release as the id format (feat/v2-go-ids). Tracked in #46. +**Release.** Same PR and release as the id format (feat/go-ids). Tracked in #46. ## Out of scope diff --git a/docs/design/specs/v2-l1-emission.md b/docs/design/specs/l1-emission.md similarity index 87% rename from docs/design/specs/v2-l1-emission.md rename to docs/design/specs/l1-emission.md index 5ff7201..837c889 100644 --- a/docs/design/specs/v2-l1-emission.md +++ b/docs/design/specs/l1-emission.md @@ -1,4 +1,4 @@ -# Spec: v2 schema migration — Group A + L1 emission (codeanalyzer-go) +# Spec: canonical schema — Group A + L1 emission (codeanalyzer-go) > **Cross-repo spec.** Canonical home is `codellm-devkit/.github → docs/design/specs/`, > beside the coordinating parent issue. Staged locally until that repo is available. @@ -7,14 +7,13 @@ ## Contract-Impact Triage -**Does this change schema v2 output?** Yes — it is the schema-major migration that -introduces the v2 shape for Go: `application.id`, the `can://` id grammar, `@line:col` +**Does this change the output?** Yes — it introduces the canonical shape for Go: `application.id`, the `can://` id grammar, `@line:col` ordinal ids (defined here, populated by L3/L4), `span` with UTF-8 byte offsets, the additive tree, `source` per module, and `body{}` with `call` nodes. | Change type | Analyzers | SDKs | Docs | | --- | --- | --- | --- | -| Schema v2 migration | **codeanalyzer-go** (emission rewrite) | **python-sdk** (Go model remap, lockstep) | CLAUDE.md, this spec | +| Canonical schema | **codeanalyzer-go** (emission rewrite) | **python-sdk** (Go model remap, lockstep) | CLAUDE.md, this spec | Arrived from `planning-cldk-work` with collision **Group A** known (identity + span); its vocabulary is designed once here and reused verbatim by the deferred L3/L4 train. @@ -23,7 +22,7 @@ its vocabulary is designed once here and reused verbatim by the deferred L3/L4 t Every decision below was made with the user, node by node in spine order. Full copy in `codeanalyzer-go/CLAUDE.md` § Schema decisions. Anchored on the keystone -(`canonical-schema.md`) and the completed **TypeScript** v2 migration (closest structural +(`canonical-schema.md`) and the completed **TypeScript** analyzer (closest structural analog: module functions + interfaces + structural types). ### Root envelope (settled spine, kept as-is) @@ -44,7 +43,7 @@ application:{ id, kind:"application", symbol_table, call_graph, param_in, param_ ### `type` | Decision | Choice | | --- | --- | -| `kind` | `struct \| interface \| alias \| defined` (collapses v1 `is_interface`) | +| `kind` | `struct \| interface \| alias \| defined` | | Method placement | resolved to receiver type's `callables{}`; receiver as a field | | `base_types[]` | embedded type ids (struct/interface embedding) | | `interfaces[]` | computed structural satisfaction (method-set matching) | @@ -59,7 +58,7 @@ application:{ id, kind:"application", symbol_table, call_graph, param_in, param_ #### Cross-file methods — the `source_file` amendment (design loop, 2026-09-29) The eval on real Go apps (dae/openbao/cockroach, ~3292 empty spans; cobra clean) -exposed a datamodel collision: v2 nests a method under its **receiver type** +exposed a datamodel collision: the schema nests a method under its **receiver type** (containment-by-receiver, § `type` above), but Go lets a method be declared in a *different file* than its type. The keystone and the **Java** reference both fix `span.bytes` as offsets into the **nesting module's** `source` (Java's SDK slices a @@ -95,8 +94,7 @@ spelling). Recorded so the promotion is a known follow-up, not a rediscovery. | `callee` | sanctioned `null → id` refinement slot (null at L1, backfilled L2) | ### Edges (Group C, settled here for L2) -`call_graph: [{src, dst, prov, weight}]` at application scope (rename from v1 -`{source, target, type, provenance}`). +`call_graph: [{src, dst, prov, weight}]` at application scope. ### CLI conformance (cli-contract.md) The current `cango` CLI is non-conformant. Bring it to the contract as part of this @@ -115,12 +113,12 @@ train (the SDK facade depends on a uniform flag surface across backends): ## Release plan -- **Train 1 — v2.0.0 (coordinated major, lockstep).** codeanalyzer-go emission rewrite +- **Train 1 — schema 2.0.0 (coordinated major, lockstep).** codeanalyzer-go emission rewrite (L1 tree/source/ids/body-with-calls, then L2 call_graph) + Neo4j relabel; python-sdk - Go model remap to v2 keeping every public accessor name/return type identical. + Go model remap keeping every public accessor name/return type identical. - **Ordering constraint (first-class):** pin the analyzer version in the SDK **only once - both are released**. Until then the SDK's old Go models won't parse v2 output. -- **Superset gate:** v2 output must contain every fact v1 did, modulo sanctioned drops + both are released**. Until then the SDK's old Go models won't parse the output. +- **Superset gate:** the output must contain every fact the internal model holds, modulo sanctioned drops (`code`, `is_*` booleans folded into `kind`, `is_constructor_call`). - **Deferred (Train 2+):** L3 (CFG/CDG/DDG), L4 (SDG). Reuse Group A ids/spans + Group C edge shape unchanged; no new schema-major coordination. @@ -138,7 +136,7 @@ work spans two repos on their own clocks and needs a coordination record: 2. codeanalyzer-go: L1 emission (tree, source, ids, body-with-call-nodes) 3. codeanalyzer-go: L2 emission (call_graph rename @ app scope) 4. codeanalyzer-go: Neo4j projection (implements the deferred `--emit neo4j`/`schema`) -5. python-sdk: Go v2 model remap (accessors stable) +5. python-sdk: Go model remap (accessors stable) 6. release + pin (once both cut) Children filed just-in-time as picked up; this spec records the full plan. diff --git a/docs/design/specs/v2-l3-l4-dataflow.md b/docs/design/specs/l3-l4-dataflow.md similarity index 98% rename from docs/design/specs/v2-l3-l4-dataflow.md rename to docs/design/specs/l3-l4-dataflow.md index e0b8875..7f8c8c8 100644 --- a/docs/design/specs/v2-l3-l4-dataflow.md +++ b/docs/design/specs/l3-l4-dataflow.md @@ -36,7 +36,7 @@ siblings is required too; and the id grammar has to change for polyglot apps any with the shared SDK taint code unchanged (§6). 6. Neo4j projection fills the already-reserved `GO_CFG_NEXT/GO_CDG/GO_DDG/GO_PARAM_IN/GO_PARAM_OUT/ GO_SUMMARY` overlay. -7. python-sdk: a v2 Go model, a `GoAnalysis` facade, a local `GoCodeanalyzer` backend and a +7. python-sdk: a Go model, a `GoAnalysis` facade, a local `GoCodeanalyzer` backend and a `GoNeo4jBackend`, answering the same L1/L2/L3/L4 surface the Python/Java/TS facades do. ### Non-goals @@ -68,8 +68,8 @@ siblings is required too; and the id grammar has to change for polyglot apps any `cli-contract.md`. Where the keystone and the **shipped siblings** disagree, this design follows the shipped siblings (Python 1.6.x, Java 3.3.x) because the SDK is written against them; each such case is called out. -- **Golden rule** (from the v2 migration): keep everything that computes facts; add L3/L4 as new - computation; the v2 emitter stays the single serialization point. +- **Golden rule:** keep everything that computes facts; add L3/L4 as new + computation; the emitter stays the single serialization point. - **Substrate:** `golang.org/x/tools v0.52.0` (`go.mod`, `go 1.26.0`) is already a dependency — `go/cfg`, `go/ssa`, `go/ssa/ssautil` and `go/callgraph/vta` are available with no new module. VTA is seeded with no initial call graph (its internal lazy CHA, §4.8); `go/callgraph/cha` is @@ -80,7 +80,7 @@ siblings is required too; and the id grammar has to change for polyglot apps any run must not pay L4 cost; `--emit neo4j` runs at max implemented depth (now 4) and rejects `-a` and `--graph-field-depth`. - python-sdk rules: the Iron Rule (no public accessor changes name/signature/return type); new - capability only as new methods; models are `extra="ignore"` mirrors of v2 (PR #434's choice; + capability only as new methods; models are `extra="ignore"` mirrors of the schema (PR #434's choice; the TypeScript and Java wire models are `extra="ignore"` since python-sdk #386, per their module docstrings on `main` — an additive analyzer release parses without an SDK edit; §7). @@ -89,8 +89,8 @@ siblings is required too; and the id grammar has to change for polyglot apps any As of 2026-10-25 (code at `3504445`, branch `feat/l3-dataflow` = `feat/l4-sdg`): - **Phases 0 and 1 were implemented together on PR #16** (§9; merged as `f9a39bb`). L1/L2/L3 on - v2, Neo4j projection live through L3 (as of this snapshot; L4 is now live too, Status header). -- **Phase 0 (live):** `can:///go/…` ids (§4.1, `internal/schema/v2/ids.go`); L2 library calls + the canonical schema, Neo4j projection live through L3 (as of this snapshot; L4 is now live too, Status header). +- **Phase 0 (live):** `can:///go/…` ids (§4.1, `internal/schema/ids.go`); L2 library calls with `application.external_symbols` (§4.14); co-positioned call keys `l:c/n`; `is_deferred`; `typeKind` emits `alias`/`defined`; `GO_DDG` `_k = var|prov`; the per-package call-site index (`callsite_index.go`) replacing the per-site AST walk; body-node `id` from `-a 1`. @@ -106,10 +106,10 @@ As of 2026-10-25 (code at `3504445`, branch `feat/l3-dataflow` = `feat/l4-sdg`): adds VTA (§4.8). - **Not yet built (Phase 2)** — *superseded: Phase 2 is now implemented; see the Status header. Kept as the 2026-10-25 snapshot.* `-a 4` is rejected by the CLI; no `LevelSDG` in `internal/options`; - no `--strict`; `--emit neo4j` forces `LevelDataflow` (L3); `v2.Analysis` has no `degraded` and + no `--strict`; `--emit neo4j` forces `LevelDataflow` (L3); `schema.Analysis` has no `degraded` and the package doc says L4 fields are not declared; `ExternalSymbol` has no receiver or body; `GO_PARAM_IN`/`GO_PARAM_OUT`/`GO_SUMMARY` stay `Reserved`. -- **python-sdk:** Go v2 L1/L2 support is on PR #434 (branch `pr-434-v3`; merged into python-sdk +- **python-sdk:** Go L1/L2 support is on PR #434 (branch `pr-434-v3`; merged into python-sdk `main` on 2026-10-26, after this section was written); the SDK work builds on it (§7). It cannot yet parse `-a 3` output (§7 prerequisites). `add-go-support` is obsolete. @@ -137,7 +137,7 @@ Reason: polyglot applications — one `` prefix scopes every language's nod `under_callable` / Neo4j prune prefixes assume app-outermost, and `@external` homes merge across languages. Ships as its own release **before** L3 (Phase 0), so L3/L4 are built on final ids. Breaking change; acceptable now because no released SDK consumes Go output. Update CLAUDE.md -§ Identity, `v2-schema-structure.md`, Neo4j prune/scope Cypher (`cypher.go`, `bolt.go`), and the +§ Identity, `schema-structure.md`, Neo4j prune/scope Cypher (`cypher.go`, `bolt.go`), and the `:GoApplication` id. Mirror Python's application-root handling (`id = can://` matched separately from the `can:///` descendant prefix). @@ -817,7 +817,7 @@ Fill the reserved overlay, no contract renames: `--graph-field-depth` help says "at -a 3 only". Phase 2 adds `LevelSDG`, accepts `-a 4`, adds `--strict`, sets the neo4j level per D4, handles `-t` per D9, and updates the help to "L3+". - **`--emit neo4j` level (D4) [user].** `--emit neo4j` runs at max implemented depth = **L4**, and - `-a` / `--graph-field-depth` with it stay an error — the same as Python and Java v2. (Letting + `-a` / `--graph-field-depth` with it stay an error — the same as Python and Java. (Letting `--emit neo4j` accept `-a ≤ max` would be a CLI-contract change shared with the siblings; not decided here.) - **`--target-files` with L4 (D9) [user].** L4 is whole-program, so a targeted run cannot produce @@ -833,7 +833,7 @@ Fill the reserved overlay, no contract renames: - The README documents both rules under Neo4j and in Upgrading. - Envelope: emit `k_limit` at L3+ (Python precedent; harmless superset of the keystone's "at L4"). - `max_level` = requested level. -- **Envelope and tree fields (amended, A18).** `v2.Analysis` gains `degraded` (§4.15); `BodyNode` +- **Envelope and tree fields (amended, A18).** `schema.Analysis` gains `degraded` (§4.15); `BodyNode` gains `of`; `Callable` gains `summary`; `Application` gains `param_in`/`param_out`; `ExternalSymbol` gains `receiver` and `body` (§6). All absent below `-a 4` (the `schema.go` package doc's "L4 fields … are not declared here" is retired). @@ -966,7 +966,7 @@ amendments are folded into the sections above. Decisions: `-a 4` peak RSS and its ratio to `-a 3`), not gated: L4 is whole-program. (Was: `-a 4` peak RSS ≤ 1.5× `-a 3` on the Kubernetes root.) Export-data loading is a separate follow-up (§4.13). - **D4 [user]:** `--emit neo4j` runs at max implemented depth = L4; `-a`/`--graph-field-depth` - with it stay an error, as in Python and Java v2 (§4.12). + with it stay an error, as in Python and Java (§4.12). - **D5 [call]:** a lazy Bolt push upserts every L4 row on every push; removing stale L4 rows needs `--eager`, documented in the README (§4.11). - **D6 [call]:** `of` = `` / `:` (never user names); unnamed or `_` params @@ -1065,7 +1065,7 @@ addition now; the cross-language SDK taint revisit is deferred (§11). ## 7. SDK (python-sdk) [user: in scope; Claude may write it] Build on python-sdk PR #434 (L1/L2 Go support: models, ABC, local + Neo4j backends, facade, factory; -branch `pr-434-v3`, unmerged as of 2026-10-25), fixing it first against the v2-only analyzer. +branch `pr-434-v3`, unmerged as of 2026-10-25), fixing it first against the current analyzer. `add-go-support` is obsolete. - **Phase 3 prerequisites (amended, A22)** — on `pr-434-v3` today: @@ -1085,7 +1085,7 @@ branch `pr-434-v3`, unmerged as of 2026-10-25), fixing it first against the v2-o - **`of`, not `parameters[]` (A9).** Go backends resolve formals by `of`; `formal_in:0` is the receiver for a method. - **Models** `cldk/models/go/`: `extra="ignore"` (PR #434's choice, matching TS/Java since #386) - mirror of Go v2 (module/type/field/callable/body node/edges/external symbols incl. `receiver` and + mirror of the Go schema (module/type/field/callable/body node/edges/external symbols incl. `receiver` and `body`, `degraded`), mirroring how `cldk/models/python` and `java` model L3/L4. - **Facade** `GoAnalysis` via `CLDK.go(...)` and the legacy shim; `GoAnalysisBackend` ABC with `N="Go"`, `P="GO_"`. @@ -1209,13 +1209,13 @@ final-review fixes: 31.5 s at 7.7 GB.) The full results, insights and limitation | 0 | analyzer | **merged (PR #16, `f9a39bb`).** id grammar `can:///go/…`; **L2 external calls (§4.14)**; L1 co-positioned call keys; `is_deferred`; `typeKind` alias/defined; `GO_DDG` `_k`; call-site position index (perf) | analyzer next **breaking** version (wheel is at 0.1.0 with no local tags — builder confirms the released version and bumps the major, or the minor if still 0.x) | | 1 | analyzer | **merged (PR #16, `f9a39bb`).** L3: body statements, CFG (+defer chain, panic), CDG, syntactic DDG, CLI `-a 3`/`--graph-field-depth`, Neo4j CFG/CDG/DDG, gates | minor | | 2 | analyzer | **Prerequisites, in order (A24):** (1) #26 shared call/closure walker (incl. `//line` spans), first — returns `(*ast.CallExpr, key)`, `(*ast.FuncLit, closure name)` and call → host maps, replacing the index-paired L1/L3 walks; (2) #17 closure call resolution, after #26 — closures carry a declaring `Path` and `call_graph` gains edges from closures; (3) the #22 L3 fixes (D1, §4.5), then the #28 satellite-`parent` tests and a Go 1.23+ fixture — before L4 port wiring (changing L3 after L4 would re-baseline every L4 gate); (4) #27 streaming JSON and AST release — before the real-app L4 eval, can run in parallel with the L4 core; (5) schema and CLI scaffolding (A14, A18, A19, A17 declarations, a `-a 1..4` monotonicity harness) — the first L4 task. Dependencies: #26 → #17 → (VTA, summaries); #22 fixes → port wiring and gates; scaffolding → all of L4; #27 → the Kubernetes eval. **Then L4:** SSA spike (D3 measurement) and build (D2), SSA → L3 join, VTA, `degraded` marker (§4.15), external stand-ins (`external_symbols` `receiver`/`body`), vertices, param edges, summaries, port wiring, type-based alias delta, Neo4j L4 overlay, `--emit neo4j` at L4 (per D4), real-app eval | minor | -| 3 | python-sdk | Go v2 models (first the §7 prerequisites: `GoType.kind`, L3 fields), facade, local + Neo4j backends, L1–L4 accessors, taint e2e | minor; pins the analyzer only after Phase 2 is released | +| 3 | python-sdk | Go models (first the §7 prerequisites: `GoType.kind`, L3 fields), facade, local + Neo4j backends, L1–L4 accessors, taint e2e | minor; pins the analyzer only after Phase 2 is released | Tracking: `codellm-devkit/.github` parent issue + one sub-issue per PR (Phase 0+1 as one) (filed just-in-time), per `issue-and-pr-tracking.md`. Each phase gets its own implementation plan. Docs updated per phase: CLAUDE.md § Schema decisions (new Go leaves: `defer_resume`, stand-ins, `:`, kind mapping), `docs/design/roadmap.md` (L3/L4 un-deferred), -`v2-schema-structure.md`, README "Architecture & Tooling" (substrate slots: CFG = go/ast hand-built +`schema-structure.md`, README "Architecture & Tooling" (substrate slots: CFG = go/ast hand-built with go/cfg differential; def-use = syntactic reaching-defs with go/ssa differential; oracle = VTA dispatch + type-based may-alias). @@ -1264,4 +1264,4 @@ dispatch + type-based may-alias). | Over-approximation noise (defer chain, pass-through, CDG in summaries) | acceptable by anti-goal; library models file narrows hot spots | | Breaking id change disrupts users | ship alone in Phase 0, before SDK pin; no released SDK consumes Go output | | Determinism with parallel L3 / map iteration | collect-then-sort, ids minted outside workers, `-j` gate | -| Divergence between JSON and Neo4j | cross-projection gate; shared projector over the same v2 tree | +| Divergence between JSON and Neo4j | cross-projection gate; shared projector over the same tree | diff --git a/docs/design/specs/v2-schema-structure.md b/docs/design/specs/schema-structure.md similarity index 96% rename from docs/design/specs/v2-schema-structure.md rename to docs/design/specs/schema-structure.md index 8d50f2d..f4e337f 100644 --- a/docs/design/specs/v2-schema-structure.md +++ b/docs/design/specs/schema-structure.md @@ -1,9 +1,9 @@ -# v2 `analysis.json` — structure reference (keys only) +# `analysis.json` — structure reference (keys only) -The key skeleton of the canonical CLDK v2 output (`--analysis-schema 2`). This is a +The key skeleton of the canonical CLDK output. This is a quick map of the node tree and every field; the *decisions* behind the shape live in -[`v2-l1-emission.md`](./v2-l1-emission.md) and `CLAUDE.md` § Schema decisions, and the -authoritative Go definitions are `internal/schema/v2/schema.go`. Field names here are +[`l1-emission.md`](./l1-emission.md) and `CLAUDE.md` § Schema decisions, and the +authoritative Go definitions are `internal/schema/schema.go`. Field names here are the JSON tags from that file. ## Tree @@ -156,13 +156,13 @@ The same shape whether it sits under a type's `callables` (methods), a module's `points-to` edges add that). The D1 gaps of the 2026-10-25 re-check — closure capture writes, writes through reference fields of value structs, and deferred-operand writes — are closed at L3 (#22). A deferred call's receiver/argument paths are keyed on the variable at exit, so a - reassignment after the `defer` can add a spurious edge. See `v2-l3-l4-dataflow.md` §4.5 + reassignment after the `defer` can add a spurious edge. See `l3-l4-dataflow.md` §4.5 "L3 precision". - **L4 vertex keys (L4).** Formals `@formal_in:`, `@formal_out` / `@formal_out:`; actuals `/actual_in:`, `/actual_out` / `…/actual_out:`. `formal_in` and `actual_in` are always indexed; `formal_out`/`actual_out` are bare iff the group has exactly one vertex. The SDK reads `of`, never an index into `parameters[]` (`formal_in:0` is a method's - receiver). See `v2-l3-l4-dataflow.md` §4.6–§4.7. + receiver). See `l3-l4-dataflow.md` §4.6–§4.7. - **Spans.** A statement node's span is its AST node's range, and a clause head ends at its colon. For a callable with `source_file` (a method declared apart from its receiver type, or a closure inside one), body spans index `symbol_table[source_file].source`, as the diff --git a/docs/design/specs/v2-span-lines.md b/docs/design/specs/span-lines.md similarity index 91% rename from docs/design/specs/v2-span-lines.md rename to docs/design/specs/span-lines.md index 70edc4e..6e1aee5 100644 --- a/docs/design/specs/v2-span-lines.md +++ b/docs/design/specs/span-lines.md @@ -2,7 +2,7 @@ ## Contract-Impact Triage -**Does this change schema v2 output?** Yes, additively. Six Go model types gain two integer +**Does this change the output?** Yes, additively. Six Go model types gain two integer fields. No existing field changes. | Change type | Analyzers | SDKs | Docs | @@ -37,4 +37,4 @@ whole-file `span.start[0]` and `span.end[0]`. The module is therefore a seventh ## Out of scope - `code_start_line` (decision 3). -- Comments and variable declarations, which Python emits and v2 Go does not carry. +- Comments and variable declarations, which Python emits and the Go schema does not carry. From 7a52c9d4e99b0e1d4a51293d66059fe83492a0e2 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Tue, 1 Dec 2026 10:26:35 -0500 Subject: [PATCH 3/3] fix(emit): write invalid UTF-8 in artifact text as this Go's encoding/json does Go 1.26 escapes an invalid UTF-8 byte as \ufffd; Go 1.27 writes the character U+FFFD. writeJSONString always wrote the character, so on CI's Go 1.26 it differed from json.Marshal and TestWriteJSONString_EqualsMarshal failed on every run since #86. It now asks encoding/json once how it writes one. --- .../emit/artifact_stream_test.go | 2 +- .../syntactic_analysis/emit/artifacts_stream.go | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/internal/syntactic_analysis/emit/artifact_stream_test.go b/internal/syntactic_analysis/emit/artifact_stream_test.go index 191016a..f5d5214 100644 --- a/internal/syntactic_analysis/emit/artifact_stream_test.go +++ b/internal/syntactic_analysis/emit/artifact_stream_test.go @@ -14,7 +14,7 @@ import ( // TestWriteJSONString_EqualsMarshal: the streaming string writer writes the // bytes json.Marshal writes for the same string: HTML escaping, \b \f \n \r // \t, other control bytes as \u00XX, U+2028 / U+2029, and invalid UTF-8 as -// \ufffd. +// U+FFFD in whichever form this Go's encoding/json writes it. func TestWriteJSONString_EqualsMarshal(t *testing.T) { cases := []string{ "", "plain", `quote " and backslash \`, "", diff --git a/internal/syntactic_analysis/emit/artifacts_stream.go b/internal/syntactic_analysis/emit/artifacts_stream.go index 30c8d38..ff87986 100644 --- a/internal/syntactic_analysis/emit/artifacts_stream.go +++ b/internal/syntactic_analysis/emit/artifacts_stream.go @@ -134,10 +134,23 @@ var asciiEscapes = func() (t [utf8.RuneSelf]string) { return t }() +// invalidUTF8 is how encoding/json writes one invalid UTF-8 byte: Go 1.26 +// escapes it as \ufffd, Go 1.27 writes the character U+FFFD. Asking +// encoding/json keeps writeJSONString byte-identical to json.Marshal on the Go +// that builds cango. +var invalidUTF8 = func() string { + b, err := json.Marshal("\xff") + if err != nil || len(b) < 2 { + return `\ufffd` + } + return string(b[1 : len(b)-1]) +}() + // writeJSONString writes s as a JSON string, byte for byte as encoding/json // writes it with HTML escaping (its default): '<', '>' and '&' as \u003c, // \u003e, \u0026; \b \f \n \r \t; other bytes below 0x20 as \u00XX; U+2028 -// and U+2029 escaped; each invalid UTF-8 byte as the character U+FFFD. Runs of plain bytes are written +// and U+2029 escaped; each invalid UTF-8 byte as U+FFFD, written the way this +// build's encoding/json writes it (invalidUTF8). Runs of plain bytes are written // as they are, so no escaped copy of s is built. func writeJSONString(w io.Writer, s string) error { if _, err := io.WriteString(w, `"`); err != nil { @@ -172,7 +185,7 @@ func writeJSONString(w io.Writer, s string) error { var esc string switch { case r == utf8.RuneError && size == 1: - esc = string(utf8.RuneError) // written as the character, not escaped + esc = invalidUTF8 case r == '\u2028': esc = `\u2028` case r == '\u2029':