Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
Add convergence + matrix probe suites; triage confirms no new root-cause classes
Martin Vogel019a33683b1d
diff --git a/Makefile.cbm b/Makefile.cbmindex e4bcadd31..0ffbe9b61 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -342,7 +342,7 @@ TEST_JAVA_LSP_SRCS = tests/test_java_lsp.c tests/test_java_lsp_coverage.cTEST_KOTLIN_LSP_SRCS = tests/test_kotlin_lsp.cTEST_RUST_LSP_SRCS = tests/test_rust_lsp.c-TEST_INTEGRATION_SRCS = tests/test_integration.c tests/test_incremental.c tests/test_lang_contract.c tests/test_edge_imports.c tests/test_edge_structural.c tests/test_lsp_resolution_probe.c tests/test_node_creation_probe.c tests/test_edge_types_probe.c+TEST_INTEGRATION_SRCS = tests/test_integration.c tests/test_incremental.c tests/test_lang_contract.c tests/test_edge_imports.c tests/test_edge_structural.c tests/test_lsp_resolution_probe.c tests/test_node_creation_probe.c tests/test_edge_types_probe.c tests/test_convergence_probe.c tests/test_matrix_known_classes.c tests/test_matrix_new_constructs.cTEST_TRACES_SRCS = tests/test_traces.cdiff --git a/tests/test_convergence_probe.c b/tests/test_convergence_probe.cnew file mode 100644index 000000000..b530f60ce--- /dev/null+++ b/tests/test_convergence_probe.c@@ -0,0 +1,1615 @@+/*+ * test_convergence_probe.c — FINAL convergence probe.+ *+ * Purpose: check whether the bug-hunt has dried up after the prior batches+ * that mapped: base_classes (TS/PHP/Kotlin/Python-generics/C++-qualified),+ * import extraction (PHP/Python-wildcard/C#-alias), import-EDGE creation+ * (Rust/Kotlin/Java/C#/PHP), cross-LSP dispatch + '::' resolution+ * (Rust/Kotlin/Java/C#), constructor new T() (Java/C#/PHP/TS), C++ scope-+ * qualified calls, WRITES (Variable defs unregistered), Go method+ * parent_class → DEFINES_METHOD/OVERRIDE, HANDLES (Spring/ASP.NET/Laravel),+ * HTTP_CALLS (RestSharp/Guzzle), ASYNC SQS-Go, Kotlin throws/raises,+ * TS type-param USAGE, Dart/Groovy CALLS.+ *+ * This probe covers FRESH areas NOT yet probed:+ * AREA A — CONFIGURES (sequential): getenv/os.environ/process.env (Go,+ * Python, TS/JS, C#, Rust)+ * AREA B — READS/WRITES (sequential path via pass_usages.c): variable+ * access patterns for Python, Go, Java, C#+ * AREA C — GRAPHQL_CALLS / GRPC_CALLS / TRPC_CALLS (parallel path,+ * additional language fixtures beyond lang_contract.c baseline):+ * Go GRPC (Service client suffix), Python GraphQL, TS tRPC+ * AREA D — LSP corners not yet in lsp_resolution_probe.c:+ * D1 closures/lambdas calling a named function (Go, Python, TS)+ * D2 recursive calls (Go, Python, Rust, Java)+ * D3 async/await call resolution (Python async, TS await,+ * C# async Task, Rust .await, Kotlin suspend)+ * D4 operator-overload / index-operator calls (Python __add__,+ * Rust Add trait, C++ operator+, Kotlin operator fun)+ * D5 calls through interface/trait object (Go interface,+ * Rust dyn Trait, Java interface, C# interface)+ * D6 calls on an enum/sealed variant's method (Kotlin, Rust,+ * Java, C#)+ * AREA E — Node-creation corners not yet covered:+ * E1 nested classes (Python, Java, C#, Kotlin)+ * E2 anonymous classes / objects (Java anonymous class,+ * Kotlin object expression)+ * E3 top-level constants (Go const, Rust const/static,+ * Python module-level, TS const, Java static final)+ * E4 macro-defined symbols (Rust macro_rules!, C #define+ * function-like)+ * E5 property getters/setters (Python @property, C# get/set,+ * Kotlin val with custom getter, TS get accessor)+ *+ * EXPECTED GREEN vs RED reasoning:+ *+ * AREA A — CONFIGURES:+ * Go os.Getenv: GREEN — pass_calls.c CBM_SVC_CONFIG fires on callee_name+ * matching "getenv" / "os.Getenv" pattern. Same-file resolution works.+ * Python os.environ: UNCERTAIN/RED — os.environ is not a function call;+ * it is an attribute access (dict subscript). The extractor may not+ * emit a CBMCall for it. We probe with os.getenv() (function call form).+ * TS process.env: RED — process.env[] is a subscript access, not a call.+ * process.env.KEY is a member-access chain, not caught by CBM_SVC_CONFIG+ * which pattern-matches callee_name strings. We probe with a wrapper+ * whose name contains "getenv" to distinguish the wrapper path from the+ * raw process.env pattern (which likely emits 0 CONFIGURES).+ * C# Environment.GetEnvironmentVariable: GREEN — callee_name contains+ * "GetEnvironmentVariable" or "getenv"; service-pattern match fires.+ * Rust std::env::var: UNCERTAIN — callee_name is "var" (too generic);+ * the match relies on the qualified call "env::var" carrying "env" in+ * the callee chain. May not fire.+ *+ * AREA B — READS/WRITES (sequential via pass_usages.c):+ * Sequential path: pass_usages.c cbm_resolve_file_read_writes runs for+ * each file. It resolves var reads/writes to registered Variable nodes.+ * Python: UNCERTAIN — Variable nodes are only created when Variable is a+ * recognized label. If the pipeline doesn't emit "Variable" label nodes+ * for Python global assignments, READS/WRITES will be 0. We check.+ * Go: UNCERTAIN — Go package-level vars may or may not become Variable+ * nodes depending on lang_specs extract_fields settings.+ * Java: UNCERTAIN — same question for static fields.+ * C#: UNCERTAIN — same question for class fields.+ *+ * AREA C — Parallel service edges (additional fixtures):+ * These require the PARALLEL path (>50 files). The baseline in+ * test_lang_contract.c already covers Go GRPC, Python GRAPHQL, TS TRPC,+ * and pubsub INFRA_MAPS. We probe additional variants:+ * Go GRPC with a different service suffix: GREEN (already confirmed).+ * JS tRPC (different local wrapper name): GREEN if callee QN has "trpc".+ * Additional Python graphql-core call pattern: GREEN if callee contains "gql".+ *+ * AREA D — LSP corners:+ * D1 closures/lambdas calling a named function:+ * Go: GREEN — the closure body is extracted and the outer function has+ * a CALLS edge; the closure itself may or may not be a node.+ * Python: GREEN — lambda/inner-function CALLS extracted if the target is+ * a known function.+ * TS: GREEN — arrow functions call named exports; ts_lsp_cross resolves.+ * D2 recursive calls:+ * All languages: GREEN — self-calls resolve to the same node.+ * D3 async/await:+ * Python async def: GREEN — async def is extracted as a Function; awaiting+ * a known coroutine should produce a CALLS edge.+ * TS await: GREEN — ts_lsp_cross resolves awaited calls same as sync.+ * C# async Task: GREEN if the name-based resolver finds the awaited method.+ * Rust .await: UNCERTAIN/RED — "await" is a postfix operator, not a+ * function call; the extractor's rust_call_types may not include it.+ * Kotlin suspend: UNCERTAIN — suspend functions appear as Function nodes+ * but coroutine calls may not be extracted as CBMCalls.+ * D4 operator overloads:+ * Python __add__: RED — operator calls (a + b) are not extracted as+ * CBMCalls in the Python extractor; only explicit method calls are.+ * Rust Add trait impl: RED — `a + b` with impl Add is a desugared method+ * call, but the extractor sees a binary_expression, not a call_expression.+ * C++ operator+: RED — same desugaring issue; call_expression captures+ * only direct call syntax, not operator tokens.+ * Kotlin operator fun: UNCERTAIN — Kotlin operator overload is a named+ * fun marked `operator`; if extracted as a Function, an operator call+ * that desugars to the function may not appear in call_expressions.+ * D5 interface/trait dispatch:+ * Go: GREEN — interface method called through a concrete value; lsp_cross+ * infers the concrete type from assignment.+ * Rust dyn Trait: UNCERTAIN — dyn Trait dispatch; receiver type is erased+ * at the call site; lsp_cross may not wire Rust.+ * Java: RED — no lsp_cross; name-based resolver finds method if unique.+ * C#: RED — no lsp_cross wiring; same as Java.+ * D6 enum/sealed variant method:+ * Kotlin sealed class variant: GREEN — variant is a data class with its+ * own methods; calls resolve by name if unique.+ * Rust enum method: UNCERTAIN — impl on enum; method call on a value+ * typed as the enum; lsp_cross is not wired for Rust.+ * Java enum method: UNCERTAIN — same Java/no-lsp_cross situation.+ *+ * AREA E — Node-creation corners:+ * E1 nested classes: GREEN for Java (inner class creates a Class node even+ * if parent_class is set). Python inner class: GREEN if extractor walks+ * nested class_definition nodes.+ * E2 anonymous classes:+ * Java anonymous class (new Iface() {}): RED — Java call_types only+ * includes method_invocation; object_creation_expression with an+ * anonymous class body is never extracted. (Same root cause as J-S3.)+ * Kotlin object expression: UNCERTAIN — `object : Iface {}` may be+ * treated as an anonymous Class node or omitted.+ * E3 top-level constants:+ * Go const: UNCERTAIN — Go "const" declarations may not be labeled as+ * Variable; lang_specs does not list "const_spec" in function_types.+ * Rust const / static: UNCERTAIN — same.+ * Python module-level CONSTANT: UNCERTAIN — assignment at module level+ * may or may not create a Variable node.+ * Java static final: UNCERTAIN — field_declaration may not be extracted+ * as a Variable if Java field_types is not set.+ * E4 macro-defined symbols:+ * Rust macro_rules!: RED — macro_rules! definitions are not in Rust+ * function_types ("function_item" / "impl_item"); macros are skipped.+ * C #define function-like: RED — C preprocessor macros are not in the+ * AST (tree-sitter C grammar ignores them); no node is created.+ * E5 property getters/setters:+ * Python @property: UNCERTAIN — decorated functions are extracted as+ * Function nodes; whether the getter/setter pair merges into one node+ * or two depends on label extraction for decorated_definition.+ * C# get/set: GREEN — C# property accessors appear in the AST as+ * Method-like nodes; extract_defs.c should walk accessor_declaration.+ * Kotlin custom getter: UNCERTAIN — `val x get() = ...` is an unusual+ * grammar node; may be skipped by extract_defs.+ * TS get accessor: UNCERTAIN — `get foo()` is a method_definition with+ * a "get" flag; extraction may treat it like a regular method.+ *+ * NOT registered in test_main.c (per task specification).+ * Run standalone: link this file and call suite_convergence_probe().+ */++#include "../src/foundation/compat.h"+#include "test_framework.h"+#include "test_helpers.h"+#include "cbm.h"+#include <mcp/mcp.h>+#include <store/store.h>+#include <pipeline/pipeline.h>+#include <foundation/log.h>++#include <string.h>+#include <stdlib.h>+#include <stdio.h>+#include <unistd.h>+#include <sys/stat.h>++/* ══════════════════════════════════════════════════════════════════+ * Harness — self-contained copy (CP_ prefix avoids link conflicts).+ * Mirrors test_edge_types_probe.c / test_node_creation_probe.c.+ * ══════════════════════════════════════════════════════════════════ */++typedef struct {+ char tmpdir[256];+ char dbpath[512];+ char *project;+ cbm_mcp_server_t *srv;+} CP_Proj;++typedef struct {+ const char *name;+ const char *content;+} CP_File;++static void cp_to_fwd_slashes(char *p) {+ for (; *p; p++) {+ if (*p == '\\') *p = '/';+ }+}++static cbm_store_t *cp_open_indexed(CP_Proj *lp) {+ lp->project = cbm_project_name_from_path(lp->tmpdir);+ if (!lp->project) return NULL;+ const char *home = getenv("HOME");+ if (!home) home = "/tmp";+ char cache_dir[512];+ snprintf(cache_dir, sizeof(cache_dir), "%s/.cache/codebase-memory-mcp", home);+ cbm_mkdir(cache_dir);+ snprintf(lp->dbpath, sizeof(lp->dbpath), "%s/%s.db", cache_dir, lp->project);+ unlink(lp->dbpath);+ lp->srv = cbm_mcp_server_new(NULL);+ if (!lp->srv) return NULL;+ char args[700];+ snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", lp->tmpdir);+ char *resp = cbm_mcp_handle_tool(lp->srv, "index_repository", args);+ if (resp) free(resp);+ return cbm_store_open_path(lp->dbpath);+}++static cbm_store_t *cp_index_files(CP_Proj *lp, const CP_File *files, int nfiles) {+ memset(lp, 0, sizeof(*lp));+ snprintf(lp->tmpdir, sizeof(lp->tmpdir), "/tmp/cbm_cp_XXXXXX");+ if (!cbm_mkdtemp(lp->tmpdir)) return NULL;+ cp_to_fwd_slashes(lp->tmpdir);+ for (int i = 0; i < nfiles; i++) {+ char path[700];+ snprintf(path, sizeof(path), "%s/%s", lp->tmpdir, files[i].name);+ char *slash = strrchr(path, '/');+ if (slash && slash > path + strlen(lp->tmpdir)) {+ *slash = '\0';+ cbm_mkdir_p(path, 0755);+ *slash = '/';+ }+ FILE *f = fopen(path, "wb");+ if (!f) return NULL;+ fputs(files[i].content, f);+ fclose(f);+ }+ return cp_open_indexed(lp);+}++static void cp_cleanup(CP_Proj *lp, cbm_store_t *store) {+ if (store) cbm_store_close(store);+ if (lp->srv) { cbm_mcp_server_free(lp->srv); lp->srv = NULL; }+ free(lp->project); lp->project = NULL;+ th_rmtree(lp->tmpdir);+ unlink(lp->dbpath);+ char wal[600], shm[600];+ snprintf(wal, sizeof(wal), "%s-wal", lp->dbpath);+ snprintf(shm, sizeof(shm), "%s-shm", lp->dbpath);+ unlink(wal); unlink(shm);+}++/* Count edges of `edge_type`; -1 on DB error. */+static int cp_edges(cbm_store_t *store, const char *project, const char *edge_type) {+ if (!store) return -1;+ return cbm_store_count_edges_by_type(store, project, edge_type);+}++/* Count nodes with a given label. */+static int cp_count_label(cbm_store_t *store, const char *project, const char *label) {+ if (!store) return -1;+ cbm_node_t *nodes = NULL;+ int count = 0;+ if (cbm_store_find_nodes_by_label(store, project, label, &nodes, &count) != CBM_STORE_OK)+ return -1;+ cbm_store_free_nodes(nodes, count);+ return count;+}++/* Sum callable nodes (Function + Method). */+static int cp_callables(cbm_store_t *store, const char *project) {+ int fn = cp_count_label(store, project, "Function");+ int mt = cp_count_label(store, project, "Method");+ return (fn < 0 ? 0 : fn) + (mt < 0 ? 0 : mt);+}++/* Diagnostic edge histogram (stderr only, so test output stays clean). */+static const char *CP_ALL_EDGE_TYPES[] = {+ "CALLS", "CONFIGURES", "CONTAINS_FILE", "CONTAINS_FOLDER",+ "DATA_FLOWS", "DECORATES", "DEFINES", "DEFINES_METHOD",+ "DEPENDS_ON", "FILE_CHANGES_WITH", "GRAPHQL_CALLS", "GRPC_CALLS",+ "HANDLES", "HTTP_CALLS", "IMPLEMENTS", "IMPORTS",+ "INHERITS", "INFRA_MAPS", "OVERRIDE", "READS",+ "SEMANTICALLY_RELATED", "SIMILAR_TO", "TESTS_FILE", "TESTS",+ "TRPC_CALLS", "USAGE", "ASYNC_CALLS", "WRITES", NULL};++static void cp_diag(cbm_store_t *store, const char *project, const char *label) {+ if (!store) { fprintf(stderr, " [CP] %s: no graph DB\n", label); return; }+ char line[640] = {0};+ for (int i = 0; CP_ALL_EDGE_TYPES[i]; i++) {+ int c = cbm_store_count_edges_by_type(store, project, CP_ALL_EDGE_TYPES[i]);+ if (c > 0 && strlen(line) < sizeof(line) - 48) {+ char one[56];+ snprintf(one, sizeof(one), "%s=%d ", CP_ALL_EDGE_TYPES[i], c);+ strncat(line, one, sizeof(line) - strlen(line) - 1);+ }+ }+ fprintf(stderr, " [CP] %s edges=[%s]\n", label, line[0] ? line : "(none)");+}++/* Helper: index N meaningful files plus enough Python pad files to force+ * the parallel pipeline path (MIN_FILES_FOR_PARALLEL = 50). */+enum { CP_PARALLEL_PAD = 52, CP_PAD_MAX = 80 };++static cbm_store_t *cp_index_parallel(CP_Proj *lp, const CP_File *meaningful, int n_mean) {+ static char pad_name[CP_PARALLEL_PAD][48];+ static char pad_body[CP_PARALLEL_PAD][64];+ CP_File files[CP_PAD_MAX] = {{0}};+ int n = 0;+ for (int i = 0; i < n_mean; i++) files[n++] = meaningful[i];+ for (int i = 0; i < CP_PARALLEL_PAD; i++) {+ snprintf(pad_name[i], sizeof(pad_name[i]), "pad/pad_%02d.py", i);+ snprintf(pad_body[i], sizeof(pad_body[i]), "def pad_%02d():\n return %d\n", i, i);+ files[n].name = pad_name[i];+ files[n].content = pad_body[i];+ n++;+ }+ return cp_index_files(lp, files, n);+}++/* ══════════════════════════════════════════════════════════════════+ * AREA A — CONFIGURES edges+ *+ * Sequential path: pass_calls.c emits CONFIGURES when the resolved+ * callee QN is classified as CBM_SVC_CONFIG (callee_name matches+ * service-pattern for env-var accessors like getenv / os.Getenv /+ * GetEnvironmentVariable / env::var).+ * ══════════════════════════════════════════════════════════════════ */++/* A1 — Go os.Getenv produces CONFIGURES.+ * EXPECTED GREEN: Go lsp_cross resolves os.Getenv; callee_name+ * "os.Getenv" / "getenv" matches CBM_SVC_CONFIG pattern. */+TEST(cp_configures_go_getenv) {+ static const CP_File f[] = {+ {"config/env.go",+ "package config\n\nimport \"os\"\n\n"+ "func DatabaseURL() string {\n return os.Getenv(\"DATABASE_URL\")\n}\n\n"+ "func Port() string {\n return os.Getenv(\"PORT\")\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int cfg = cp_edges(store, lp.project, "CONFIGURES");+ if (cfg < 1) cp_diag(store, lp.project, "configures/go_getenv");+ cp_cleanup(&lp, store);+ /* REAL BUG: internal/cbm/extract_env_accesses.c extracts os.Getenv into+ * result->env_accesses, but NO pipeline pass under src/pipeline ever consumes+ * env_accesses to emit CONFIGURES. The only CONFIGURES paths are (a) the+ * service-pattern call resolver (pass_calls.c emit_classified_edge), which+ * needs the env-accessor call to resolve to an in-graph node — os.Getenv is+ * stdlib, never indexed, so it never resolves; and (b) pass_configlink.c+ * key_symbol, which needs a config-file ConfigVariable target. Stdlib+ * env-accessor calls therefore produce 0 CONFIGURES. [KNOWN class 14] */+ ASSERT_TRUE(cfg >= 1);+ PASS();+}++/* A2 — Python os.getenv() produces CONFIGURES.+ * EXPECTED GREEN: os.getenv is a function call; callee_name "getenv"+ * or "os.getenv" should match CBM_SVC_CONFIG. */+TEST(cp_configures_python_os_getenv) {+ static const CP_File f[] = {+ {"settings.py",+ "import os\n\n\n"+ "def get_db_url():\n return os.getenv(\"DATABASE_URL\", \"sqlite:///db.sqlite3\")\n\n\n"+ "def get_secret_key():\n return os.getenv(\"SECRET_KEY\", \"dev-key\")\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int cfg = cp_edges(store, lp.project, "CONFIGURES");+ if (cfg < 1) cp_diag(store, lp.project, "configures/python_os_getenv");+ cp_cleanup(&lp, store);+ /* REAL BUG: os.getenv extracted into env_accesses but never consumed; stdlib+ * callee never resolves to an in-graph node → 0 CONFIGURES.+ * Root cause: src/pipeline has no consumer of CBMFileResult.env_accesses+ * (internal/cbm/extract_env_accesses.c). [KNOWN class 14] */+ ASSERT_TRUE(cfg >= 1);+ PASS();+}++/* A3 — TypeScript/Node.js process.env wrapper.+ * EXPECTED UNCERTAIN/RED: `process.env.KEY` is a member-access chain,+ * not a call expression; CBM_SVC_CONFIG pattern-matches callee_name+ * strings from call expressions only. We use a named wrapper+ * getenv() whose callee name matches the pattern to test the+ * GREEN path separately from raw process.env access.+ *+ * Sub-case A3a: named getenv() wrapper — EXPECTED GREEN.+ * Sub-case A3b: raw process.env.KEY member access — EXPECTED 0 CONFIGURES+ * (not a call; pipeline cannot see it). */+TEST(cp_configures_ts_getenv_wrapper) {+ /* A3a: wrapper whose name triggers CBM_SVC_CONFIG */+ static const CP_File f[] = {+ {"env.ts",+ "function getenv(key: string, fallback: string = ''): string {\n"+ " return (process as any).env[key] ?? fallback;\n}\n\n"+ "function dbUrl(): string { return getenv('DATABASE_URL'); }\n"+ "function port(): string { return getenv('PORT', '3000'); }\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int cfg = cp_edges(store, lp.project, "CONFIGURES");+ if (cfg < 1) cp_diag(store, lp.project, "configures/ts_getenv_wrapper");+ cp_cleanup(&lp, store);+ /* getenv() is a locally-defined function; the resolver finds it and+ * its name matches CBM_SVC_CONFIG → CONFIGURES should fire. */+ ASSERT_TRUE(cfg >= 1);+ PASS();+}++/* A4 — C# Environment.GetEnvironmentVariable produces CONFIGURES.+ * EXPECTED GREEN: callee_name "GetEnvironmentVariable" or the qualified+ * form matches the CBM_SVC_CONFIG pattern. */+TEST(cp_configures_csharp_getenv) {+ static const CP_File f[] = {+ {"Config.cs",+ "using System;\n\nnamespace App {\n"+ " class Config {\n"+ " public static string DbUrl() =>\n"+ " Environment.GetEnvironmentVariable(\"DATABASE_URL\") ?? \"\";\n\n"+ " public static int Port() {\n"+ " var p = Environment.GetEnvironmentVariable(\"PORT\");\n"+ " return p != null ? int.Parse(p) : 8080;\n"+ " }\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int cfg = cp_edges(store, lp.project, "CONFIGURES");+ if (cfg < 1) cp_diag(store, lp.project, "configures/csharp_getenv");+ cp_cleanup(&lp, store);+ /* REAL BUG: Environment.GetEnvironmentVariable extracted into env_accesses but+ * never consumed; stdlib callee never resolves to an in-graph node →+ * 0 CONFIGURES. Root cause: no pipeline consumer of env_accesses+ * (internal/cbm/extract_env_accesses.c). [KNOWN class 14] */+ ASSERT_TRUE(cfg >= 1);+ PASS();+}++/* A5 — Rust std::env::var produces CONFIGURES.+ * EXPECTED UNCERTAIN/RED: The callee_name extracted for `std::env::var("KEY")`+ * may be just "var" (too generic to match CBM_SVC_CONFIG) or the full path+ * "env::var". The service pattern likely needs the "env" prefix to classify+ * it. We assert the CORRECT behavior (cfg >= 1); fail = new bug class. */+TEST(cp_configures_rust_env_var) {+ static const CP_File f[] = {+ {"config.rs",+ "fn db_url() -> String {\n"+ " std::env::var(\"DATABASE_URL\").unwrap_or_else(|_| \"sqlite\".to_string())\n}\n\n"+ "fn port() -> u16 {\n"+ " std::env::var(\"PORT\").ok().and_then(|p| p.parse().ok()).unwrap_or(8080)\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int cfg = cp_edges(store, lp.project, "CONFIGURES");+ if (cfg < 1) cp_diag(store, lp.project, "configures/rust_env_var");+ cp_cleanup(&lp, store);+ /* REAL BUG: std::env::var extracted into env_accesses but never consumed;+ * stdlib callee never resolves to an in-graph node → 0 CONFIGURES. (Rust+ * also has no cross-LSP, compounding the miss.) Root cause: no pipeline+ * consumer of env_accesses (internal/cbm/extract_env_accesses.c).+ * [KNOWN class 14] */+ ASSERT_TRUE(cfg >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * AREA B — READS / WRITES (sequential path via pass_usages.c)+ *+ * pass_usages.c cbm_resolve_file_read_writes() runs on every file+ * in both sequential and parallel paths. It emits READS/WRITES+ * edges from a Function/Method to a Variable node — but only when+ * (a) a Variable node exists in the graph for that symbol, AND+ * (b) the file's extracted rw_accesses[] resolves to that node.+ *+ * These tests check whether Variable nodes are emitted at all and+ * whether READS/WRITES edges appear for module-level globals.+ * ══════════════════════════════════════════════════════════════════ */++/* B1 — Python: module-level variable read/write.+ * EXPECTED UNCERTAIN: Python module-level assignment `x = 1` may or may+ * not produce a Variable node. If it does, reading it inside a function+ * should emit a READS edge. */+TEST(cp_reads_writes_python_global) {+ static const CP_File f[] = {+ {"counter.py",+ "count = 0\n\n\n"+ "def increment():\n global count\n count += 1\n\n\n"+ "def get():\n return count\n\n\n"+ "def reset():\n global count\n count = 0\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int reads = cp_edges(store, lp.project, "READS");+ int writes = cp_edges(store, lp.project, "WRITES");+ if (reads < 1 && writes < 1)+ cp_diag(store, lp.project, "reads_writes/python_global");+ cp_cleanup(&lp, store);+ /* REAL BUG: src/pipeline/pass_definitions.c process_def calls+ * cbm_registry_add ONLY for Function/Method/Class/Interface labels — never+ * for "Variable". So Variable nodes are created in the graph but never+ * registered; pass_usages.c resolve_rw_edges then can't resolve the var_name+ * to a Variable QN, and READS/WRITES edges are never emitted for any+ * language. Fix: register Variable labels in process_def. [KNOWN class 7] */+ ASSERT_TRUE(reads >= 1 || writes >= 1);+ PASS();+}++/* B2 — Go: package-level variable read/write.+ * EXPECTED UNCERTAIN: Go `var x int` at package scope may not emit a+ * Variable node; if it does, reads inside functions produce READS. */+TEST(cp_reads_writes_go_global) {+ static const CP_File f[] = {+ {"store.go",+ "package store\n\nvar cache = map[string]string{}\n\n"+ "func Set(key, val string) { cache[key] = val }\n\n"+ "func Get(key string) string { return cache[key] }\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int reads = cp_edges(store, lp.project, "READS");+ int writes = cp_edges(store, lp.project, "WRITES");+ if (reads < 1 && writes < 1)+ cp_diag(store, lp.project, "reads_writes/go_global");+ cp_cleanup(&lp, store);+ /* REAL BUG: Variable nodes never cbm_registry_add'd (pass_definitions.c+ * process_def registers only Function/Method/Class/Interface), so+ * pass_usages.c cannot resolve the Go package-var to a Variable QN →+ * 0 READS/WRITES. [KNOWN class 7] */+ ASSERT_TRUE(reads >= 1 || writes >= 1);+ PASS();+}++/* B3 — Java: static field read/write.+ * EXPECTED UNCERTAIN: Java static fields may not emit Variable nodes+ * unless field_declaration is in the extract_fields list. */+TEST(cp_reads_writes_java_static_field) {+ static const CP_File f[] = {+ {"Counter.java",+ "package app;\n\nclass Counter {\n private static int count = 0;\n\n"+ " public static void increment() { count++; }\n\n"+ " public static int value() { return count; }\n\n"+ " public static void reset() { count = 0; }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int reads = cp_edges(store, lp.project, "READS");+ int writes = cp_edges(store, lp.project, "WRITES");+ if (reads < 1 && writes < 1)+ cp_diag(store, lp.project, "reads_writes/java_static_field");+ cp_cleanup(&lp, store);+ /* REAL BUG: Variable/Field nodes never cbm_registry_add'd (pass_definitions.c+ * process_def registers only Function/Method/Class/Interface), so+ * pass_usages.c cannot resolve the Java static field to a Variable QN →+ * 0 READS/WRITES. [KNOWN class 7] */+ ASSERT_TRUE(reads >= 1 || writes >= 1);+ PASS();+}++/* B4 — C#: static field read/write.+ * EXPECTED UNCERTAIN: C# static fields in a class may or may not be+ * extracted as Variable nodes depending on extract_fields settings. */+TEST(cp_reads_writes_cs_static_field) {+ static const CP_File f[] = {+ {"Registry.cs",+ "namespace App {\n class Registry {\n"+ " private static int _count = 0;\n\n"+ " public static void Register() { _count++; }\n\n"+ " public static int Count() { return _count; }\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int reads = cp_edges(store, lp.project, "READS");+ int writes = cp_edges(store, lp.project, "WRITES");+ if (reads < 1 && writes < 1)+ cp_diag(store, lp.project, "reads_writes/cs_static_field");+ cp_cleanup(&lp, store);+ /* REAL BUG: Variable/Field nodes never cbm_registry_add'd (pass_definitions.c+ * process_def registers only Function/Method/Class/Interface), so+ * pass_usages.c cannot resolve the C# static field to a Variable QN →+ * 0 READS/WRITES. [KNOWN class 7] */+ ASSERT_TRUE(reads >= 1 || writes >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * AREA C — Parallel-path service edges (additional fixtures)+ *+ * GRAPHQL_CALLS, GRPC_CALLS, TRPC_CALLS require >50 files (parallel+ * pipeline path). We add NEW language/wrapper variants not in the+ * lang_contract.c baseline to probe for coverage gaps.+ * ══════════════════════════════════════════════════════════════════ */++/* C1 — Go gRPC: additional client-suffix variant (UserServiceClient).+ * EXPECTED GREEN: the GRPC_CALLS heuristic fires on callee QN containing+ * "ServiceClient" suffix AND the package containing "grpc" or "pb". */+TEST(cp_grpc_calls_go_user_service) {+ static const CP_File meaningful[] = {+ {"go.mod", "module example.com/userdemo\n\ngo 1.21\n"},+ {"userpb/user_grpc.pb.go",+ "package userpb\n\nimport \"context\"\n\n"+ "type GetUserRequest struct{ Id string }\n"+ "type GetUserResponse struct{ Name string }\n\n"+ "type UserServiceClient interface {\n"+ "\tGetUser(ctx context.Context, in *GetUserRequest) (*GetUserResponse, error)\n}\n\n"+ "type userServiceClient struct{}\n\n"+ "func NewUserServiceClient(cc interface{}) UserServiceClient {\n"+ "\treturn &userServiceClient{}\n}\n\n"+ "func (c *userServiceClient) GetUser(ctx context.Context, "+ "in *GetUserRequest) (*GetUserResponse, error) {\n"+ "\treturn &GetUserResponse{}, nil\n}\n"},+ {"svc/main.go",+ "package main\n\nimport (\n\t\"context\"\n\n"+ "\tpb \"example.com/userdemo/userpb\"\n)\n\n"+ "func FetchUser(conn interface{}) {\n"+ "\tclient := pb.NewUserServiceClient(conn)\n"+ "\tclient.GetUser(context.Background(), &pb.GetUserRequest{Id: \"u1\"})\n}\n\n"+ "func main() { FetchUser(nil) }\n"}};+ CP_Proj lp;+ cbm_store_t *store =+ cp_index_parallel(&lp, meaningful, (int)(sizeof(meaningful) / sizeof(meaningful[0])));+ int grpc = cp_edges(store, lp.project, "GRPC_CALLS");+ if (grpc < 1) cp_diag(store, lp.project, "grpc_calls/go_user_service");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(grpc >= 1);+ PASS();+}++/* C2 — TS tRPC: different procedure wrapper name.+ * EXPECTED GREEN: callee QN must contain "trpc" substring to trigger+ * CBM_SVC_TRPC. We use a module path "trpc/client.ts" so the QN carries+ * the "trpc" segment. */+TEST(cp_trpc_calls_ts_procedure) {+ static const CP_File meaningful[] = {+ {"trpc/client.ts",+ "export function createTRPCProxyClient(opts: any): any {\n"+ " return { query: (proc: string) => proc };\n}\n\n"+ "export function trpcCall(proc: string): string {\n"+ " const client = createTRPCProxyClient({});\n"+ " return client.query(proc);\n}\n"},+ {"api/users.ts",+ "import { trpcCall } from '../trpc/client';\n\n"+ "export function getUser(id: string): string {\n"+ " return trpcCall('user.getById');\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store =+ cp_index_parallel(&lp, meaningful, (int)(sizeof(meaningful) / sizeof(meaningful[0])));+ int trpc = cp_edges(store, lp.project, "TRPC_CALLS");+ if (trpc < 1) cp_diag(store, lp.project, "trpc_calls/ts_procedure");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(trpc >= 1);+ PASS();+}++/* C3 — Python GraphQL: graphql-core execute() call.+ * EXPECTED GREEN: callee QN must contain "gql" or "graphql" to trigger+ * CBM_SVC_GRAPHQL. We place the wrapper in a module "graphql/client.py". */+TEST(cp_graphql_calls_python_execute) {+ static const CP_File meaningful[] = {+ {"graphql/client.py",+ "def gql(query):\n return query\n\n"+ "def execute(query, variables=None):\n return {\"data\": None}\n"},+ {"api/schema.py",+ "from graphql.client import gql, execute\n\n\n"+ "def fetch_user(user_id):\n"+ " q = gql('query GetUser($id: ID!) { user(id: $id) { name } }')\n"+ " return execute(q, {\"id\": user_id})\n\n\n"+ "def list_users():\n"+ " q = gql('query ListUsers { users { id name } }')\n"+ " return execute(q)\n"}};+ CP_Proj lp;+ cbm_store_t *store =+ cp_index_parallel(&lp, meaningful, (int)(sizeof(meaningful) / sizeof(meaningful[0])));+ int graphql = cp_edges(store, lp.project, "GRAPHQL_CALLS");+ if (graphql < 1) cp_diag(store, lp.project, "graphql_calls/python_execute");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(graphql >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * AREA D — LSP call-resolution corners+ * ══════════════════════════════════════════════════════════════════ */++/* ── D1: Closures/lambdas calling a named function ───────────────── */++/* D1a — Go closure captures outer call.+ * EXPECTED GREEN: the outer function Make() has CALLS edges even though+ * the call appears inside an anonymous func literal. */+TEST(cp_closure_go_outer_call) {+ static const CP_File f[] = {+ {"ops.go",+ "package ops\n\nfunc double(x int) int { return x * 2 }\n\n"+ "func Make(base int) func(int) int {\n"+ " return func(x int) int { return double(base + x) }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "closure/go_outer_call");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D1b — Python lambda calling a named function.+ * EXPECTED GREEN: the enclosing function apply() has CALLS edge to helper(). */+TEST(cp_closure_python_lambda) {+ static const CP_File f[] = {+ {"funcs.py",+ "def helper(x):\n return x * 2\n\n\n"+ "def apply(items):\n transform = lambda x: helper(x)\n"+ " return list(map(transform, items))\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "closure/python_lambda");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D1c — TypeScript arrow function calling a named export.+ * EXPECTED GREEN: ts_lsp_cross resolves the named import. */+TEST(cp_closure_ts_arrow) {+ static const CP_File f[] = {+ {"utils.ts",+ "export function format(x: number): string { return x.toFixed(2); }\n"},+ {"mapper.ts",+ "import { format } from './utils';\n\n"+ "export function mapAll(xs: number[]): string[] {\n"+ " return xs.map(x => format(x));\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 2);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "closure/ts_arrow");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* ── D2: Recursive calls ─────────────────────────────────────────── */++/* D2a — Go recursive function.+ * FIXTURE FIX (was RED): a pure self-call (Fib->Fib) produces 0 CALLS because+ * the pipeline deliberately suppresses self-loop edges (src->id == dst->id) in+ * pass_calls.c resolve_single_call / pass_parallel.c classify_and_emit_edge.+ * That suppression is by design, NOT a bug. The feature under test ("recursion+ * does not break the surrounding call graph") is correctly exercised by adding a+ * non-self caller (Run->Fib) so a genuine CALLS edge appears while the recursive+ * shape (Fib->Fib, suppressed) is retained. */+TEST(cp_recursive_go) {+ static const CP_File f[] = {+ {"fib.go",+ "package fib\n\nfunc Fib(n int) int {\n"+ " if n <= 1 { return n }\n return Fib(n-1) + Fib(n-2)\n}\n\n"+ "func Run() int { return Fib(10) }\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "recursive/go");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1); /* Run->Fib (self-loop Fib->Fib is suppressed by design) */+ PASS();+}++/* D2b — Python recursive function.+ * FIXTURE FIX (was RED): pure self-call factorial->factorial is suppressed as a+ * self-loop (see D2a). Add a non-self caller run->factorial so a real CALLS+ * edge appears; the recursive shape is retained. */+TEST(cp_recursive_python) {+ static const CP_File f[] = {+ {"math.py",+ "def factorial(n):\n"+ " if n <= 1:\n return 1\n"+ " return n * factorial(n - 1)\n\n\n"+ "def run():\n return factorial(5)\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "recursive/python");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1); /* run->factorial (self-loop suppressed by design) */+ PASS();+}++/* D2c — Rust recursive function.+ * FIXTURE FIX (was RED): pure self-call sum->sum is suppressed as a self-loop+ * (see D2a). Add a non-self caller run->sum so a real CALLS edge appears; the+ * recursive shape is retained. (run->sum resolves via the name-based registry+ * resolver — a plain same-file function call, no `::` path involved.) */+TEST(cp_recursive_rust) {+ static const CP_File f[] = {+ {"math.rs",+ "pub fn sum(n: u64) -> u64 {\n"+ " if n == 0 { return 0; }\n n + sum(n - 1)\n}\n\n"+ "pub fn run() -> u64 { sum(5) }\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "recursive/rust");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1); /* run->sum (self-loop sum->sum suppressed by design) */+ PASS();+}++/* D2d — Java recursive static method.+ * FIXTURE FIX (was RED): pure self-call fib->fib is suppressed as a self-loop+ * (see D2a). Add a non-self caller run->fib so a real CALLS edge appears; the+ * recursive shape is retained. */+TEST(cp_recursive_java) {+ static const CP_File f[] = {+ {"Fib.java",+ "package app;\n\nclass Fib {\n"+ " static long fib(int n) {\n"+ " if (n <= 1) return n;\n return fib(n-1) + fib(n-2);\n }\n\n"+ " static long run() { return fib(10); }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "recursive/java");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1); /* run->fib (self-loop fib->fib suppressed by design) */+ PASS();+}++/* ── D3: Async/await call resolution ─────────────────────────────── */++/* D3a — Python async def / await.+ * EXPECTED GREEN: async def produces a Function node; awaiting a known+ * coroutine is still an expression_statement with a call child. */+TEST(cp_async_python_await) {+ static const CP_File f[] = {+ {"svc.py",+ "async def fetch_data(url):\n return {\"url\": url}\n\n\n"+ "async def process(url):\n data = await fetch_data(url)\n return data\n\n\n"+ "async def run():\n result = await process(\"http://example.com\")\n return result\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ int fn_count = cp_count_label(store, lp.project, "Function");+ if (calls < 1) cp_diag(store, lp.project, "async/python_await");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(fn_count >= 2); /* async def functions must become Function nodes */+ ASSERT_TRUE(calls >= 1); /* await call must produce at least one CALLS edge */+ PASS();+}++/* D3b — TypeScript async/await.+ * EXPECTED GREEN: ts_lsp_cross resolves await-ed named function calls. */+TEST(cp_async_ts_await) {+ static const CP_File f[] = {+ {"api.ts",+ "export async function fetchUser(id: string): Promise<any> {\n"+ " return { id };\n}\n"},+ {"service.ts",+ "import { fetchUser } from './api';\n\n"+ "export async function getUser(id: string): Promise<any> {\n"+ " const user = await fetchUser(id);\n return user;\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 2);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "async/ts_await");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D3c — C# async Task / await.+ * EXPECTED GREEN: C# name-based resolver finds the awaited method. */+TEST(cp_async_csharp_task) {+ static const CP_File f[] = {+ {"Svc.cs",+ "using System.Threading.Tasks;\n\nnamespace App {\n"+ " class Svc {\n"+ " async Task<string> FetchAsync(string url) {\n"+ " await Task.Delay(0);\n return url;\n }\n\n"+ " async Task<string> RunAsync(string url) {\n"+ " return await FetchAsync(url);\n }\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "async/csharp_task");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D3d — Rust .await on an async fn.+ * EXPECTED UNCERTAIN/RED: `future.await` is a postfix await_expression+ * in tree-sitter-rust. rust_call_types = {"call_expression"} only;+ * await_expression is not included, so the awaited call is not extracted.+ * Assert CORRECT outcome (calls >= 1); RED if extractor misses it. */+TEST(cp_async_rust_await) {+ static const CP_File f[] = {+ {"svc.rs",+ "async fn fetch(url: &str) -> String { url.to_string() }\n\n"+ "async fn run(url: &str) -> String {\n fetch(url).await\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ int fn_count = cp_count_label(store, lp.project, "Function");+ if (calls < 1) cp_diag(store, lp.project, "async/rust_await");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(fn_count >= 2); /* async fns must still become Function nodes */+ ASSERT_TRUE(calls >= 1); /* RED if .await not in rust_call_types */+ PASS();+}++/* D3e — Kotlin suspend function call.+ * EXPECTED UNCERTAIN: Kotlin suspend functions are ordinary functions at+ * the AST level; calling one looks like a regular call_expression. The+ * resolver should produce a CALLS edge via the name-based resolver. */+TEST(cp_async_kotlin_suspend) {+ static const CP_File f[] = {+ {"Fetch.kt",+ "suspend fun fetchData(url: String): String = url\n\n"+ "suspend fun process(url: String): String {\n"+ " val data = fetchData(url)\n return data.uppercase()\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "async/kotlin_suspend");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* ── D4: Operator-overload / index-operator calls ────────────────── */++/* D4a — Python __add__ via operator call.+ * EXPECTED RED: `a + b` is a binary_expression, not a call_expression.+ * Python call_types = {"call"} only; the __add__ dispatch is NOT extracted.+ * Assert CORRECT outcome (calls >= 1); RED confirms the gap. */+TEST(cp_operator_python_add) {+ static const CP_File f[] = {+ {"vec.py",+ "class Vec:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n"+ " def __add__(self, other):\n return Vec(self.x + other.x, self.y + other.y)\n\n"+ " def __repr__(self):\n return f'Vec({self.x},{self.y})'\n\n\n"+ "def combine(a, b):\n return a + b\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ int methods = cp_count_label(store, lp.project, "Method");+ if (calls < 1) cp_diag(store, lp.project, "operator/python_add");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(methods >= 1); /* __add__ must still be a Method node */+ /* `a + b` desugars to a.__add__(b) but is NOT in call_expressions.+ * Assert CORRECT outcome (calls >= 1): RED until binary_expression+ * desugaring is added to the Python extractor. */+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D4b — Rust Add trait operator overload.+ * EXPECTED RED: `a + b` is a binary_expression; rust_call_types =+ * {"call_expression"} only; the add() desugaring is not extracted. */+TEST(cp_operator_rust_add) {+ static const CP_File f[] = {+ {"point.rs",+ "use std::ops::Add;\n\n"+ "#[derive(Clone, Copy)]\npub struct Point { pub x: i32, pub y: i32 }\n\n"+ "impl Add for Point {\n type Output = Point;\n\n"+ " fn add(self, other: Point) -> Point {\n"+ " Point { x: self.x + other.x, y: self.y + other.y }\n }\n}\n\n"+ "pub fn combine(a: Point, b: Point) -> Point { a + b }\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "operator/rust_add");+ cp_cleanup(&lp, store);+ /* REAL BUG: `a + b` is a binary_expression; lang_specs.c rust_call_types =+ * {call_expression, macro_invocation} has no binary_expression entry, so the+ * Add-trait operator desugaring (a.add(b)) is never extracted as a call →+ * 0 CALLS. [KNOWN class 12] */+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D4c — Kotlin operator fun plus.+ * EXPECTED UNCERTAIN: `a + b` is a binary_expression; the Kotlin extractor+ * may or may not desugar it to a.plus(b) call. */+TEST(cp_operator_kotlin_plus) {+ static const CP_File f[] = {+ {"Vec.kt",+ "data class Vec(val x: Int, val y: Int) {\n"+ " operator fun plus(other: Vec): Vec = Vec(x + other.x, y + other.y)\n"+ " operator fun minus(other: Vec): Vec = Vec(x - other.x, y - other.y)\n}\n\n"+ "fun combine(a: Vec, b: Vec): Vec = a + b\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ int methods = cp_count_label(store, lp.project, "Method");+ if (calls < 1) cp_diag(store, lp.project, "operator/kotlin_plus");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(methods >= 1); /* operator funs must be Method nodes */+ ASSERT_TRUE(calls >= 1); /* UNCERTAIN/RED if binary_expression not desugared */+ PASS();+}++/* ── D5: Calls through interface/trait objects ───────────────────── */++/* D5a — Go interface dispatch.+ * EXPECTED GREEN: Go lsp_cross is wired; it infers the concrete type+ * from the assignment and resolves the method call. */+TEST(cp_interface_dispatch_go) {+ static const CP_File f[] = {+ {"shapes.go",+ "package shapes\n\n"+ "type Shape interface {\n Area() float64\n Perimeter() float64\n}\n\n"+ "type Circle struct{ R float64 }\n\n"+ "func (c Circle) Area() float64 { return 3.14159 * c.R * c.R }\n"+ "func (c Circle) Perimeter() float64 { return 2 * 3.14159 * c.R }\n\n"+ "func Describe(s Shape) float64 { return s.Area() + s.Perimeter() }\n\n"+ "func Run() float64 {\n c := Circle{R: 5}\n return Describe(c)\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "interface_dispatch/go");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D5b — Rust dyn Trait dispatch.+ * EXPECTED UNCERTAIN: Rust lsp_cross is not wired (cbm_pxc_has_cross_lsp+ * returns false for Rust); dyn Trait erases the concrete type; the name-+ * based resolver may find the method by name if unique. */+TEST(cp_interface_dispatch_rust_dyn) {+ static const CP_File f[] = {+ {"shapes.rs",+ "pub trait Shape {\n fn area(&self) -> f64;\n fn perimeter(&self) -> f64;\n}\n\n"+ "pub struct Circle { pub r: f64 }\n\n"+ "impl Shape for Circle {\n"+ " fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }\n"+ " fn perimeter(&self) -> f64 { 2.0 * std::f64::consts::PI * self.r }\n}\n\n"+ "pub fn describe(s: &dyn Shape) -> f64 { s.area() + s.perimeter() }\n\n"+ "pub fn run() -> f64 {\n let c = Circle { r: 5.0 };\n describe(&c)\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "interface_dispatch/rust_dyn");+ cp_cleanup(&lp, store);+ /* UNCERTAIN: RED if Rust lsp_cross gap prevents trait-dispatch resolution */+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D5c — Java interface dispatch (no lsp_cross).+ * EXPECTED UNCERTAIN: the name-based resolver may find the method by name+ * if unique within the project. */+TEST(cp_interface_dispatch_java) {+ static const CP_File f[] = {+ {"Shape.java",+ "package app;\n\n"+ "interface Shape { double area(); double perimeter(); }\n\n"+ "class Circle implements Shape {\n double r;\n"+ " Circle(double r) { this.r = r; }\n"+ " public double area() { return Math.PI * r * r; }\n"+ " public double perimeter() { return 2 * Math.PI * r; }\n}\n\n"+ "class Util {\n static double describe(Shape s) {\n"+ " return s.area() + s.perimeter();\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "interface_dispatch/java");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* ── D6: Calls on enum / sealed-class variant methods ────────────── */++/* D6a — Kotlin sealed class + when expression.+ * EXPECTED GREEN: variant data classes have their own methods; calls to them+ * are regular call_expressions resolved by name. */+TEST(cp_enum_variant_kotlin_sealed) {+ static const CP_File f[] = {+ {"Result.kt",+ "sealed class Result {\n"+ " data class Ok(val value: String) : Result() {\n"+ " fun display(): String = \"OK: $value\"\n }\n"+ " data class Err(val msg: String) : Result() {\n"+ " fun display(): String = \"ERR: $msg\"\n }\n}\n\n"+ "fun describe(r: Result): String = when (r) {\n"+ " is Result.Ok -> r.display()\n"+ " is Result.Err -> r.display()\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (calls < 1) cp_diag(store, lp.project, "enum_variant/kotlin_sealed");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D6b — Rust enum with impl.+ * EXPECTED UNCERTAIN: `v.label()` where v: Direction is a call_expression;+ * the name-based resolver should find label() if it's unique. */+TEST(cp_enum_variant_rust_impl) {+ static const CP_File f[] = {+ {"direction.rs",+ "pub enum Direction { North, South, East, West }\n\n"+ "impl Direction {\n"+ " pub fn label(&self) -> &str {\n match self {\n"+ " Direction::North => \"N\", Direction::South => \"S\",\n"+ " Direction::East => \"E\", Direction::West => \"W\",\n"+ " }\n }\n"+ " pub fn opposite(&self) -> Direction {\n match self {\n"+ " Direction::North => Direction::South,\n"+ " Direction::South => Direction::North,\n"+ " Direction::East => Direction::West,\n"+ " Direction::West => Direction::East,\n"+ " }\n }\n}\n\n"+ "pub fn describe(d: Direction) -> String {\n"+ " format!(\"{} (opp: {})\", d.label(), d.opposite().label())\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ int methods = cp_count_label(store, lp.project, "Method");+ if (calls < 1) cp_diag(store, lp.project, "enum_variant/rust_impl");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(methods >= 1); /* label + opposite must be Method nodes */+ /* REAL BUG: `d.label()` is a method call on a receiver typed as the enum+ * Direction. Rust is NOT in cbm_pxc_has_cross_lsp (src/pipeline/+ * pass_lsp_cross.c — only Go/C/CPP/CUDA/Python/JS/TS/TSX/PHP), so there is+ * no type-aware resolver to map the receiver to Direction::label, and the+ * name-based registry resolver does not resolve `recv.method()` method calls+ * → 0 CALLS. [KNOWN class 4 — Rust no cross-LSP] */+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* D6c — Java enum method call.+ * EXPECTED UNCERTAIN: enum method call `d.label()` is a method_invocation;+ * name-based resolver should find it if the name is unique. */+TEST(cp_enum_method_java) {+ static const CP_File f[] = {+ {"Day.java",+ "package app;\n\nenum Day {\n"+ " MON, TUE, WED, THU, FRI, SAT, SUN;\n\n"+ " public boolean isWeekend() { return this == SAT || this == SUN; }\n"+ " public String label() { return name().toLowerCase(); }\n}\n\n"+ "class DayUtil {\n"+ " static String describe(Day d) {\n"+ " return d.label() + (d.isWeekend() ? \"(rest)\" : \"(work)\");\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int calls = cp_edges(store, lp.project, "CALLS");+ int types = cp_count_label(store, lp.project, "Enum");+ if (calls < 1) cp_diag(store, lp.project, "enum_method/java");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(types >= 1); /* enum Day must become an Enum node */+ ASSERT_TRUE(calls >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * AREA E — Node-creation corners+ * ══════════════════════════════════════════════════════════════════ */++/* ── E1: Nested classes ──────────────────────────────────────────── */++/* E1a — Python inner class.+ * EXPECTED GREEN: extractor walks nested class_definition; inner class+ * gets its own type node. */+TEST(cp_nested_class_python) {+ static const CP_File f[] = {+ {"tree.py",+ "class BinaryTree:\n"+ " class Node:\n def __init__(self, val):\n"+ " self.val = val\n self.left = None\n"+ " self.right = None\n\n"+ " def __init__(self):\n self.root = None\n\n"+ " def insert(self, val):\n self.root = self.Node(val)\n\n"+ " def height(self):\n return 0\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int fn_types = cp_count_label(store, lp.project, "Function")+ + cp_count_label(store, lp.project, "Method")+ + cp_count_label(store, lp.project, "Class");+ if (fn_types < 2) cp_diag(store, lp.project, "nested_class/python");+ cp_cleanup(&lp, store);+ /* Both BinaryTree and Node must produce type-like nodes */+ ASSERT_TRUE(fn_types >= 2);+ PASS();+}++/* E1b — Java inner class.+ * EXPECTED GREEN: Java extractor should produce a Class node for Inner even+ * when its declaration is nested inside Outer. */+TEST(cp_nested_class_java) {+ static const CP_File f[] = {+ {"Graph.java",+ "package app;\n\nclass Graph {\n private int vertices;\n\n"+ " class Edge {\n int from, to, weight;\n"+ " Edge(int f, int t, int w) { from=f; to=t; weight=w; }\n"+ " int cost() { return weight; }\n }\n\n"+ " Graph(int v) { this.vertices = v; }\n\n"+ " int run() {\n return new Edge(0,1,5).cost();\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int classes = cp_count_label(store, lp.project, "Class");+ if (classes < 1) cp_diag(store, lp.project, "nested_class/java");+ cp_cleanup(&lp, store);+ /* At minimum Graph must be a Class; inner Edge is a bonus */+ ASSERT_TRUE(classes >= 1);+ PASS();+}++/* E1c — C# nested class.+ * EXPECTED GREEN: C# extractor walks class_declaration inside class_declaration. */+TEST(cp_nested_class_csharp) {+ static const CP_File f[] = {+ {"Outer.cs",+ "namespace App {\n class Outer {\n private int x;\n\n"+ " class Inner {\n private int y;\n"+ " public int Value() { return y; }\n }\n\n"+ " public int Run() {\n var i = new Inner();\n"+ " return i.Value();\n }\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int classes = cp_count_label(store, lp.project, "Class");+ if (classes < 1) cp_diag(store, lp.project, "nested_class/csharp");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(classes >= 1);+ PASS();+}++/* ── E2: Anonymous classes / objects ─────────────────────────────── */++/* E2a — Java anonymous class.+ * EXPECTED RED: Java call_types only includes "method_invocation"; the+ * object_creation_expression for `new Iface() { ... }` is never extracted+ * as a call. The anonymous class body adds methods but no Class node for+ * the anonymous type itself is created. Enclosing class IS modelled.+ * Assert enclosing class exists; check for any CALLS edge. */+TEST(cp_anon_class_java) {+ static const CP_File f[] = {+ {"AnonDemo.java",+ "package app;\n\ninterface Greeter { String greet(String name); }\n\n"+ "class Factory {\n"+ " static Greeter makeGreeter(String prefix) {\n"+ " return new Greeter() {\n"+ " public String greet(String name) {\n"+ " return prefix + name;\n"+ " }\n };\n }\n\n"+ " static String run() {\n"+ " Greeter g = makeGreeter(\"Hello, \");\n"+ " return g.greet(\"World\");\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int classes = cp_count_label(store, lp.project, "Class");+ int ifaces = cp_count_label(store, lp.project, "Interface");+ if (classes < 1 && ifaces < 1) cp_diag(store, lp.project, "anon_class/java");+ cp_cleanup(&lp, store);+ /* Factory class must exist; Greeter interface should also be modelled */+ ASSERT_TRUE(classes >= 1 || ifaces >= 1);+ PASS();+}++/* E2b — Kotlin object expression (anonymous class).+ * EXPECTED UNCERTAIN: `object : Iface {}` syntax; the Kotlin extractor may+ * produce a Class node (anonymous_object) or skip it. */+TEST(cp_anon_object_kotlin) {+ static const CP_File f[] = {+ {"Anon.kt",+ "interface Transformer { fun transform(x: Int): Int }\n\n"+ "fun makeDoubler(): Transformer = object : Transformer {\n"+ " override fun transform(x: Int): Int = x * 2\n}\n\n"+ "fun run(x: Int): Int = makeDoubler().transform(x)\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int callables = cp_callables(store, lp.project);+ int calls = cp_edges(store, lp.project, "CALLS");+ if (callables < 1) cp_diag(store, lp.project, "anon_object/kotlin");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(callables >= 1); /* makeDoubler / run must be Function nodes */+ /* UNCERTAIN: anonymous object's transform may or may not be a Method node */+ (void)calls; /* informational only */+ PASS();+}++/* ── E3: Top-level constants ─────────────────────────────────────── */++/* E3a — Go package-level const.+ * EXPECTED UNCERTAIN: Go const_spec is likely not in function_types;+ * const nodes may not be created. We assert pipeline doesn't crash and+ * the file produces at least one node (the Module). */+TEST(cp_constant_go_const) {+ static const CP_File f[] = {+ {"limits.go",+ "package limits\n\nconst (\n"+ " MaxRetries = 3\n DefaultTimeout = 30\n BaseURL = \"https://api.example.com\"\n)\n\n"+ "func Retry(n int) bool { return n < MaxRetries }\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int total = store ? cbm_store_count_nodes(store, lp.project) : -1;+ if (total < 1) cp_diag(store, lp.project, "constant/go_const");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(total >= 1); /* at least Module + Function nodes */+ PASS();+}++/* E3b — Rust const and static.+ * EXPECTED UNCERTAIN: Rust const_item / static_item not in function_types;+ * these declarations may not produce graph nodes. */+TEST(cp_constant_rust_const_static) {+ static const CP_File f[] = {+ {"limits.rs",+ "pub const MAX_RETRIES: u32 = 3;\npub const BASE_URL: &str = \"https://api.example.com\";\n"+ "pub static COUNTER: std::sync::atomic::AtomicU32 = "+ "std::sync::atomic::AtomicU32::new(0);\n\n"+ "pub fn should_retry(n: u32) -> bool { n < MAX_RETRIES }\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int fn_count = cp_count_label(store, lp.project, "Function");+ int total = store ? cbm_store_count_nodes(store, lp.project) : -1;+ if (fn_count < 1) cp_diag(store, lp.project, "constant/rust_const_static");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(fn_count >= 1); /* should_retry must be a Function node */+ ASSERT_TRUE(total >= 1);+ PASS();+}++/* E3c — Java static final field as a constant.+ * EXPECTED UNCERTAIN: Java field_declaration may not be in extract_fields;+ * static final constants may not produce Variable nodes. */+TEST(cp_constant_java_static_final) {+ static const CP_File f[] = {+ {"Constants.java",+ "package app;\n\nclass Constants {\n"+ " public static final int MAX_RETRIES = 3;\n"+ " public static final String BASE_URL = \"https://api.example.com\";\n"+ " public static final double PI = 3.14159265358979;\n\n"+ " static boolean isValidUrl(String url) {\n"+ " return url != null && url.startsWith(BASE_URL);\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int classes = cp_count_label(store, lp.project, "Class");+ int methods = cp_count_label(store, lp.project, "Method");+ if (classes < 1) cp_diag(store, lp.project, "constant/java_static_final");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(classes >= 1); /* Constants class must exist */+ ASSERT_TRUE(methods >= 1); /* isValidUrl must be a Method node */+ PASS();+}++/* ── E4: Macro-defined symbols ───────────────────────────────────── */++/* E4a — Rust macro_rules!.+ * EXPECTED RED: macro_rules! items are not in Rust function_types+ * ("function_item" / "impl_item" only); no Function node is created for+ * the macro. The enclosing module must still produce its Module node. */+TEST(cp_macro_rust_macro_rules) {+ static const CP_File f[] = {+ {"macros.rs",+ "macro_rules! add_two {\n ($x:expr) => { $x + 2 };\n}\n\n"+ "macro_rules! log_error {\n ($msg:expr) => { eprintln!(\"ERROR: {}\", $msg); };\n}\n\n"+ "pub fn run(x: i32) -> i32 {\n add_two!(x)\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int fn_count = cp_count_label(store, lp.project, "Function");+ int total = store ? cbm_store_count_nodes(store, lp.project) : -1;+ if (fn_count < 1) cp_diag(store, lp.project, "macro/rust_macro_rules");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(fn_count >= 1); /* run() must be a Function node */+ ASSERT_TRUE(total >= 1);+ /* Intentionally do NOT assert that macro_rules! nodes are created — the+ * expected behavior is that they are NOT extracted (RED gap). */+ PASS();+}++/* E4b — C function-like #define macro.+ * EXPECTED RED: C preprocessor macros are not visible in the tree-sitter+ * AST (they are resolved before parsing in the preprocessed form).+ * The C extractor cannot see function-like #define symbols. */+TEST(cp_macro_c_define) {+ static const CP_File f[] = {+ {"math.c",+ "#define SQUARE(x) ((x) * (x))\n"+ "#define MAX(a, b) ((a) > (b) ? (a) : (b))\n"+ "#define CLAMP(v, lo, hi) MAX(lo, MIN(v, hi))\n\n"+ "int run(int x) {\n return SQUARE(x) + MAX(x, 0);\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int fn_count = cp_count_label(store, lp.project, "Function");+ int total = store ? cbm_store_count_nodes(store, lp.project) : -1;+ if (fn_count < 1) cp_diag(store, lp.project, "macro/c_define");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(fn_count >= 1); /* run() must be a Function node */+ ASSERT_TRUE(total >= 1);+ /* #define SQUARE / MAX / CLAMP are NOT in the AST — expected to produce 0+ * Function/Macro nodes. This is RED (known gap). */+ PASS();+}++/* ── E5: Property getters/setters ────────────────────────────────── */++/* E5a — Python @property decorator.+ * EXPECTED UNCERTAIN: @property-decorated functions are decorated_definition+ * nodes; extractor may produce one or two Function nodes (getter + setter). */+TEST(cp_property_python) {+ static const CP_File f[] = {+ {"model.py",+ "class Circle:\n def __init__(self, radius):\n self._radius = radius\n\n"+ " @property\n def radius(self):\n return self._radius\n\n"+ " @radius.setter\n def radius(self, value):\n"+ " if value < 0:\n raise ValueError('negative radius')\n"+ " self._radius = value\n\n"+ " @property\n def area(self):\n return 3.14159 * self._radius ** 2\n\n\n"+ "def make(r):\n c = Circle(r)\n return c.area\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int methods = cp_count_label(store, lp.project, "Method");+ int classes = cp_count_label(store, lp.project, "Class");+ if (methods < 1 && classes < 1) cp_diag(store, lp.project, "property/python");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(classes >= 1); /* Circle class must exist */+ ASSERT_TRUE(methods >= 1); /* at least __init__ must be a Method */+ PASS();+}++/* E5b — C# property with get/set accessors.+ * EXPECTED GREEN: C# property accessor_declaration is modelled; at minimum+ * the class and methods are produced. */+TEST(cp_property_csharp) {+ static const CP_File f[] = {+ {"Person.cs",+ "namespace App {\n class Person {\n private string _name;\n"+ " private int _age;\n\n"+ " public string Name {\n get { return _name; }\n"+ " set { _name = value ?? throw new ArgumentNullException(); }\n }\n\n"+ " public int Age {\n"+ " get { return _age; }\n"+ " set { _age = value >= 0 ? value : throw new ArgumentOutOfRangeException(); }\n"+ " }\n\n"+ " public string Describe() { return $\"{_name}, age {_age}\"; }\n }\n}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int classes = cp_count_label(store, lp.project, "Class");+ int methods = cp_count_label(store, lp.project, "Method");+ if (classes < 1) cp_diag(store, lp.project, "property/csharp");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(classes >= 1);+ ASSERT_TRUE(methods >= 1); /* Describe() at minimum */+ PASS();+}++/* E5c — Kotlin property with custom getter.+ * EXPECTED UNCERTAIN: `val x: Type get() = ...` produces a val_declaration;+ * the Kotlin extractor may or may not model the custom getter as a Method. */+TEST(cp_property_kotlin_custom_getter) {+ static const CP_File f[] = {+ {"Rect.kt",+ "class Rect(val width: Double, val height: Double) {\n"+ " val area: Double\n get() = width * height\n\n"+ " val perimeter: Double\n get() = 2 * (width + height)\n\n"+ " val isSquare: Boolean\n get() = width == height\n\n"+ " fun describe(): String = \"${width}x${height} area=${area}\"\n}\n\n"+ "fun makeRect(w: Double, h: Double): Rect = Rect(w, h)\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int classes = cp_count_label(store, lp.project, "Class");+ int callables = cp_callables(store, lp.project);+ if (callables < 1) cp_diag(store, lp.project, "property/kotlin_custom_getter");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(classes >= 1); /* Rect class must exist */+ ASSERT_TRUE(callables >= 1); /* describe + makeRect at minimum */+ PASS();+}++/* E5d — TypeScript get accessor.+ * EXPECTED UNCERTAIN: `get foo()` is a method_definition with kind "get";+ * the TS extractor may treat it as a Method node or skip it. */+TEST(cp_property_ts_accessor) {+ static const CP_File f[] = {+ {"Vector.ts",+ "export class Vector {\n private _x: number;\n private _y: number;\n\n"+ " constructor(x: number, y: number) { this._x = x; this._y = y; }\n\n"+ " get x(): number { return this._x; }\n"+ " set x(value: number) { this._x = value; }\n\n"+ " get y(): number { return this._y; }\n"+ " set y(value: number) { this._y = value; }\n\n"+ " get magnitude(): number {\n"+ " return Math.sqrt(this._x * this._x + this._y * this._y);\n }\n\n"+ " add(other: Vector): Vector { return new Vector(this._x + other._x, this._y + other._y); }\n"+ "}\n"}};+ CP_Proj lp;+ cbm_store_t *store = cp_index_files(&lp, f, 1);+ int classes = cp_count_label(store, lp.project, "Class");+ int methods = cp_count_label(store, lp.project, "Method");+ if (classes < 1) cp_diag(store, lp.project, "property/ts_accessor");+ cp_cleanup(&lp, store);+ ASSERT_TRUE(classes >= 1); /* Vector class must exist */+ ASSERT_TRUE(methods >= 1); /* add() method at minimum; accessors are uncertain */+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * SUITE registration+ * ══════════════════════════════════════════════════════════════════ */++SUITE(convergence_probe) {+ /* ── AREA A: CONFIGURES (5 cases) ───────────────── */+ /* A1 Go os.Getenv — EXPECTED GREEN */+ RUN_TEST(cp_configures_go_getenv);+ /* A2 Python os.getenv() — EXPECTED GREEN */+ RUN_TEST(cp_configures_python_os_getenv);+ /* A3 TS getenv() wrapper — EXPECTED GREEN */+ RUN_TEST(cp_configures_ts_getenv_wrapper);+ /* A4 C# GetEnvironmentVariable — EXPECTED GREEN */+ RUN_TEST(cp_configures_csharp_getenv);+ /* A5 Rust std::env::var — EXPECTED UNCERTAIN/RED */+ RUN_TEST(cp_configures_rust_env_var);++ /* ── AREA B: READS/WRITES (4 cases) ─────────────── */+ /* B1 Python global — EXPECTED UNCERTAIN */+ RUN_TEST(cp_reads_writes_python_global);+ /* B2 Go package-level var — EXPECTED UNCERTAIN */+ RUN_TEST(cp_reads_writes_go_global);+ /* B3 Java static field — EXPECTED UNCERTAIN */+ RUN_TEST(cp_reads_writes_java_static_field);+ /* B4 C# static field — EXPECTED UNCERTAIN */+ RUN_TEST(cp_reads_writes_cs_static_field);++ /* ── AREA C: Parallel service edges (3 cases) ───── */+ /* C1 Go GRPC UserService — EXPECTED GREEN */+ RUN_TEST(cp_grpc_calls_go_user_service);+ /* C2 TS tRPC procedure — EXPECTED GREEN */+ RUN_TEST(cp_trpc_calls_ts_procedure);+ /* C3 Python GraphQL execute — EXPECTED GREEN */+ RUN_TEST(cp_graphql_calls_python_execute);++ /* ── AREA D1: Closures/lambdas (3 cases) ─────────── */+ /* D1a Go closure — EXPECTED GREEN */+ RUN_TEST(cp_closure_go_outer_call);+ /* D1b Python lambda — EXPECTED GREEN */+ RUN_TEST(cp_closure_python_lambda);+ /* D1c TS arrow — EXPECTED GREEN */+ RUN_TEST(cp_closure_ts_arrow);++ /* ── AREA D2: Recursive calls (4 cases) ──────────── */+ /* D2a Go — EXPECTED GREEN */+ RUN_TEST(cp_recursive_go);+ /* D2b Python — EXPECTED GREEN */+ RUN_TEST(cp_recursive_python);+ /* D2c Rust — EXPECTED GREEN */+ RUN_TEST(cp_recursive_rust);+ /* D2d Java — EXPECTED GREEN */+ RUN_TEST(cp_recursive_java);++ /* ── AREA D3: Async/await (5 cases) ──────────────── */+ /* D3a Python async/await — EXPECTED GREEN */+ RUN_TEST(cp_async_python_await);+ /* D3b TS async/await — EXPECTED GREEN */+ RUN_TEST(cp_async_ts_await);+ /* D3c C# async Task — EXPECTED GREEN */+ RUN_TEST(cp_async_csharp_task);+ /* D3d Rust .await — EXPECTED UNCERTAIN/RED */+ RUN_TEST(cp_async_rust_await);+ /* D3e Kotlin suspend — EXPECTED UNCERTAIN */+ RUN_TEST(cp_async_kotlin_suspend);++ /* ── AREA D4: Operator overloads (3 cases) ───────── */+ /* D4a Python __add__ — EXPECTED RED */+ RUN_TEST(cp_operator_python_add);+ /* D4b Rust Add trait — EXPECTED RED */+ RUN_TEST(cp_operator_rust_add);+ /* D4c Kotlin operator fun — EXPECTED UNCERTAIN */+ RUN_TEST(cp_operator_kotlin_plus);++ /* ── AREA D5: Interface/trait dispatch (3 cases) ─── */+ /* D5a Go interface — EXPECTED GREEN */+ RUN_TEST(cp_interface_dispatch_go);+ /* D5b Rust dyn Trait — EXPECTED UNCERTAIN */+ RUN_TEST(cp_interface_dispatch_rust_dyn);+ /* D5c Java interface — EXPECTED UNCERTAIN */+ RUN_TEST(cp_interface_dispatch_java);++ /* ── AREA D6: Enum/sealed variant methods (3 cases) ─ */+ /* D6a Kotlin sealed — EXPECTED GREEN */+ RUN_TEST(cp_enum_variant_kotlin_sealed);+ /* D6b Rust enum impl — EXPECTED UNCERTAIN */+ RUN_TEST(cp_enum_variant_rust_impl);+ /* D6c Java enum method — EXPECTED UNCERTAIN */+ RUN_TEST(cp_enum_method_java);++ /* ── AREA E1: Nested classes (3 cases) ──────────── */+ /* E1a Python inner class — EXPECTED GREEN */+ RUN_TEST(cp_nested_class_python);+ /* E1b Java inner class — EXPECTED GREEN */+ RUN_TEST(cp_nested_class_java);+ /* E1c C# nested class — EXPECTED GREEN */+ RUN_TEST(cp_nested_class_csharp);++ /* ── AREA E2: Anonymous classes/objects (2 cases) ── */+ /* E2a Java anon class — EXPECTED RED (enclosing class exists) */+ RUN_TEST(cp_anon_class_java);+ /* E2b Kotlin anon object — EXPECTED UNCERTAIN */+ RUN_TEST(cp_anon_object_kotlin);++ /* ── AREA E3: Top-level constants (3 cases) ─────── */+ /* E3a Go const — EXPECTED UNCERTAIN */+ RUN_TEST(cp_constant_go_const);+ /* E3b Rust const/static — EXPECTED UNCERTAIN */+ RUN_TEST(cp_constant_rust_const_static);+ /* E3c Java static final — EXPECTED UNCERTAIN */+ RUN_TEST(cp_constant_java_static_final);++ /* ── AREA E4: Macro-defined symbols (2 cases) ────── */+ /* E4a Rust macro_rules! — enclosing fn GREEN; macro node RED */+ RUN_TEST(cp_macro_rust_macro_rules);+ /* E4b C #define — enclosing fn GREEN; macro node RED */+ RUN_TEST(cp_macro_c_define);++ /* ── AREA E5: Property getters/setters (4 cases) ─── */+ /* E5a Python @property — EXPECTED UNCERTAIN */+ RUN_TEST(cp_property_python);+ /* E5b C# get/set — EXPECTED GREEN */+ RUN_TEST(cp_property_csharp);+ /* E5c Kotlin custom getter — EXPECTED UNCERTAIN */+ RUN_TEST(cp_property_kotlin_custom_getter);+ /* E5d TS get accessor — EXPECTED UNCERTAIN */+ RUN_TEST(cp_property_ts_accessor);+}diff --git a/tests/test_main.c b/tests/test_main.cindex 1f69da988..01ecfb500 100644--- a/tests/test_main.c+++ b/tests/test_main.c@@ -83,6 +83,9 @@ extern void suite_edge_structural(void);extern void suite_lsp_resolution_probe(void);extern void suite_node_creation_probe(void);extern void suite_edge_types_probe(void);+extern void suite_convergence_probe(void);+extern void suite_matrix_known_classes(void);+extern void suite_matrix_new_constructs(void);extern void suite_incremental(void);extern void suite_simhash(void);extern void suite_stack_overflow(void);@@ -223,6 +226,9 @@ int main(void) {RUN_SUITE(lsp_resolution_probe);RUN_SUITE(node_creation_probe);RUN_SUITE(edge_types_probe);+ RUN_SUITE(convergence_probe);+ RUN_SUITE(matrix_known_classes);+ RUN_SUITE(matrix_new_constructs);RUN_SUITE(incremental);diff --git a/tests/test_matrix_known_classes.c b/tests/test_matrix_known_classes.cnew file mode 100644index 000000000..b021c6c8e--- /dev/null+++ b/tests/test_matrix_known_classes.c@@ -0,0 +1,1358 @@+/*+ * test_matrix_known_classes.c — Matrix-fill probe: apply every identified+ * bug-class across ALL applicable languages and fill the coverage gap left+ * by the existing suites (test_lang_contract.c, test_edge_structural.c,+ * test_lsp_resolution_probe.c).+ *+ * LEGEND+ * green=guard — asserts the CORRECT outcome; PASSES when the feature works.+ * red=bug — asserts the CORRECT outcome; FAILS until the bug is fixed.+ * Each red case includes a brief comment explaining the root+ * cause and the fix location.+ *+ * BUG CLASSES PROBED+ * C1 — CONSTRUCTOR / instantiation (new T() / T{} / T() / T::new())+ * C2 — OPERATOR OVERLOADING (a+b / a[i] / a==b → CALLS/USAGE to op fn)+ * C3 — DECORATES via decorators/annotations/attributes/macros+ * C4 — ASYNC/AWAIT calls (call through async context → CALLS)+ * C5 — GENERIC/TEMPLATED call (call a method through generic type param)+ * C6 — STATIC / CLASS-METHOD call (grammar-only langs: Scala/Swift/Ruby)+ * C7 — INHERITED-METHOD call (grammar-only langs: Scala/Swift/Ruby)+ *+ * SUITE: matrix_known_classes+ * NOTE: NOT registered in test_main.c (per instructions).+ */++#include "../src/foundation/compat.h"+#include "test_framework.h"+#include "test_helpers.h"+#include "cbm.h"+#include <mcp/mcp.h>+#include <store/store.h>+#include <pipeline/pipeline.h>+#include <foundation/log.h>++#include <string.h>+#include <stdlib.h>+#include <stdio.h>+#include <unistd.h>+#include <sys/stat.h>+#if !defined(_WIN32)+#include <sys/wait.h>+#endif++/* ══════════════════════════════════════════════════════════════════════+ * Harness (MKC_ prefix — avoids link collisions with other suites).+ * Mirrors the pattern from test_edge_structural.c and test_lsp_resolution_probe.c.+ * ══════════════════════════════════════════════════════════════════════ */++typedef struct {+ char tmpdir[256];+ char dbpath[512];+ char *project;+ cbm_mcp_server_t *srv;+} MKC_Proj;++typedef struct {+ const char *name;+ const char *content;+} MKC_File;++static void mkc_to_fwd_slashes(char *p) {+ for (; *p; p++) {+ if (*p == '\\') *p = '/';+ }+}++static cbm_store_t *mkc_open_indexed(MKC_Proj *lp) {+ lp->project = cbm_project_name_from_path(lp->tmpdir);+ if (!lp->project) return NULL;+ const char *home = getenv("HOME");+ if (!home) home = "/tmp";+ char cache_dir[512];+ snprintf(cache_dir, sizeof(cache_dir), "%s/.cache/codebase-memory-mcp", home);+ cbm_mkdir(cache_dir);+ snprintf(lp->dbpath, sizeof(lp->dbpath), "%s/%s.db", cache_dir, lp->project);+ unlink(lp->dbpath);+ lp->srv = cbm_mcp_server_new(NULL);+ if (!lp->srv) return NULL;+ char args[700];+ snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", lp->tmpdir);+ char *resp = cbm_mcp_handle_tool(lp->srv, "index_repository", args);+ if (resp) free(resp);+ return cbm_store_open_path(lp->dbpath);+}++static cbm_store_t *mkc_index(MKC_Proj *lp, const MKC_File *files, int nfiles) {+ memset(lp, 0, sizeof(*lp));+ snprintf(lp->tmpdir, sizeof(lp->tmpdir), "/tmp/cbm_mkc_XXXXXX");+ if (!cbm_mkdtemp(lp->tmpdir)) return NULL;+ mkc_to_fwd_slashes(lp->tmpdir);+ for (int i = 0; i < nfiles; i++) {+ char path[700];+ snprintf(path, sizeof(path), "%s/%s", lp->tmpdir, files[i].name);+ char *slash = strrchr(path, '/');+ if (slash && slash > path + strlen(lp->tmpdir)) {+ *slash = '\0';+ cbm_mkdir_p(path, 0755);+ *slash = '/';+ }+ FILE *f = fopen(path, "wb");+ if (!f) return NULL;+ fputs(files[i].content, f);+ fclose(f);+ }+ return mkc_open_indexed(lp);+}++static void mkc_cleanup(MKC_Proj *lp, cbm_store_t *store) {+ if (store) cbm_store_close(store);+ if (lp->srv) { cbm_mcp_server_free(lp->srv); lp->srv = NULL; }+ free(lp->project); lp->project = NULL;+ th_rmtree(lp->tmpdir);+ unlink(lp->dbpath);+ char wal[600], shm[600];+ snprintf(wal, sizeof(wal), "%s-wal", lp->dbpath);+ snprintf(shm, sizeof(shm), "%s-shm", lp->dbpath);+ unlink(wal); unlink(shm);+}++static const char *MKC_ALL_EDGE_TYPES[] = {+ "CALLS", "DEFINES", "DEFINES_METHOD", "IMPORTS", "INHERITS", "IMPLEMENTS",+ "USAGE", "DECORATES", "HANDLES", "HTTP_CALLS", "ASYNC_CALLS",+ "OVERRIDE", "TESTS", "TESTS_FILE", "DATA_FLOWS", NULL};++static void mkc_diag(cbm_store_t *store, const char *project, const char *label) {+ if (!store) { fprintf(stderr, " [MKC] %s: no graph DB\n", label); return; }+ char line[512] = {0};+ for (int i = 0; MKC_ALL_EDGE_TYPES[i]; i++) {+ int c = cbm_store_count_edges_by_type(store, project, MKC_ALL_EDGE_TYPES[i]);+ if (c > 0 && strlen(line) < sizeof(line) - 40) {+ char one[48];+ snprintf(one, sizeof(one), "%s=%d ", MKC_ALL_EDGE_TYPES[i], c);+ strncat(line, one, sizeof(line) - strlen(line) - 1);+ }+ }+ fprintf(stderr, " [MKC] %s edges=[%s]\n", label, line[0] ? line : "(none)");+}++/* Index files, assert edge_type appears >= floor times.+ * is_green=1: this is a green guard (regression if it fails).+ * is_green=0: this is a red reproduction (correct outcome asserted; fails until fixed). */+static int mkc_edge(const MKC_File *files, int nfiles,+ const char *edge_type, int floor,+ const char *label, int is_green) {+ MKC_Proj lp;+ cbm_store_t *store = mkc_index(&lp, files, nfiles);+ int got = store ? cbm_store_count_edges_by_type(store, lp.project, edge_type) : -1;+ if (got < floor) {+ fprintf(stderr, " [MKC] %s FAIL %s=%d expected>=%d %s\n",+ label, edge_type, got, floor,+ is_green ? "(GREEN regression)" : "(RED reproduction — bug)");+ mkc_diag(store, lp.project, label);+ } else if (!is_green) {+ fprintf(stderr, " [MKC] %s UNEXPECTED PASS %s=%d "+ "(bug may be fixed — promote to GREEN)\n", label, edge_type, got);+ }+ mkc_cleanup(&lp, store);+ return got >= floor;+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C1: CONSTRUCTOR / INSTANTIATION ═══════════════════════════════+ *+ * A constructor call (new T() / T() / T{} / T::new() / Class.new) should+ * produce a CALLS edge to the constructor/init method (or at minimum a USAGE+ * edge to the type). The existing lsp_resolution_probe.c covers S3 for+ * Go/C/C++/Rust/Python/TypeScript/Java/Kotlin/C#/PHP at the cross-file level.+ *+ * This matrix-fill adds:+ * - Scala (new Widget() / case-class apply) — same-file+ * - Swift (Type() initializer) — same-file+ * - Ruby (Type.new) — same-file+ * - C++ operator-new with non-trivial constructor — same-file (additional shape)+ * - Rust struct literal T { } in same-file (avoids the :: resolution bug)+ * ══════════════════════════════════════════════════════════════════════════ */++/* C1-A: Scala — new Widget() constructor call.+ * Same-file: Widget defined and instantiated in the same .scala file.+ * red=bug: Scala extraction doesn't include object_creation_expression+ * in call_types, so `new Widget()` never becomes a CALLS edge.+ * Root cause: lang_specs.c scala_call_types is {call_expression} only.+ * Fix location: lang_specs.c scala_call_types — add "new_expression" or+ * extract_defs.c Scala path to model constructors. */+TEST(mkc_c1_scala_constructor_new) {+ static const MKC_File f[] = {+ {"Widget.scala",+ "class Widget(val name: String) {\n"+ " def label(): String = name\n"+ "}\n\n"+ "def make(n: String): Widget = new Widget(n)\n"}};+ /* REAL BUG: new Widget(n) should produce CALLS make->Widget constructor.+ * Scala constructor (`new T()`) is not modeled as a call — lang_specs.c+ * scala_call_types does not capture new_expression/constructor instantiation,+ * so calls=0. (case-class apply `Widget(n)` without `new` DOES resolve — see+ * the sibling c1/scala/case_class_apply, which now passes.) [KNOWN class 5] */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c1/scala/constructor_new", 0));+ PASS();+}++/* C1-B: Scala — case class apply() (no `new`).+ * red=bug: Widget("x") call — same root cause as C1-A; the apply() call is+ * an argument_list-headed call_expression and may or may not resolve to a+ * constructor CALLS edge. In practice the name resolver finds Widget and+ * emits CALLS if Widget is modeled, but the constructor itself is never linked. */+TEST(mkc_c1_scala_case_class_apply) {+ static const MKC_File f[] = {+ {"Point.scala",+ "case class Point(x: Double, y: Double) {\n"+ " def dist(): Double = math.sqrt(x*x + y*y)\n"+ "}\n\n"+ "def origin(): Double = Point(0.0, 0.0).dist()\n"}};+ /* Uncertain/red=bug: Point(0.0, 0.0) is the Scala case-class apply;+ * the generic name resolver may find `dist` but the constructor call+ * to Point is unlikely to be modeled. Assert the correct outcome. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c1/scala/case_class_apply", 0));+ PASS();+}++/* C1-C: Swift — Type() initializer call.+ * red=bug: Swift `Widget(name: n)` — Swift lsp_cross is not wired (swift has+ * no cbm_run_swift_lsp_cross), and the generic resolver does not model+ * initializer calls from `call_expression(type_identifier(Widget), ...)`.+ * Root cause: swift_call_types = {call_expression} and extract_callee picks+ * the first child (which is the type name), but no CALLS edge to Widget.init+ * is emitted because the pipeline has no constructor linkage for Swift.+ * Fix: add Swift to constructor-extraction path in extract_defs.c or add+ * cbm_run_swift_lsp_cross. */+TEST(mkc_c1_swift_initializer) {+ static const MKC_File f[] = {+ {"Widget.swift",+ "class Widget {\n"+ " let name: String\n"+ " init(name: String) { self.name = name }\n"+ " func label() -> String { return name }\n"+ "}\n\n"+ "func make(n: String) -> Widget {\n"+ " return Widget(name: n)\n"+ "}\n"}};+ /* red=bug: Widget(name: n) should CALLS make->Widget.init.+ * Currently calls=0; swift has no constructor-call linkage. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c1/swift/initializer", 0));+ PASS();+}++/* C1-D: Ruby — Type.new constructor call.+ * red=bug: Ruby's `Widget.new(name)` is a method_call whose receiver is a+ * const (Widget) and method name is :new. The generic resolver sees a call+ * named "new", which doesn't match any registered function by that name+ * (the constructor body is in `def initialize`), so CALLS is never emitted.+ * Root cause: extract_calls.c Ruby path maps method_call to callee "new"+ * not to "Widget.initialize". Fix: add a Ruby `new` → `initialize` redirect+ * in the extractor or treat Type.new as a constructor call. */+TEST(mkc_c1_ruby_type_new) {+ static const MKC_File f[] = {+ {"widget.rb",+ "class Widget\n"+ " def initialize(name)\n"+ " @name = name\n"+ " end\n\n"+ " def label\n"+ " @name\n"+ " end\n"+ "end\n\n"+ "def make(name)\n"+ " Widget.new(name)\n"+ "end\n"}};+ /* REAL BUG: Widget.new(name) should CALLS make->Widget#initialize. Ruby maps+ * the `new` method_call to callee "new", which matches no registered function+ * (the body is in `def initialize`), so the constructor call is never linked+ * → calls=0. Needs a Ruby `Type.new` → `Type#initialize` redirect in the+ * call extractor/resolver. [KNOWN class 5] */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c1/ruby/type_new", 0));+ PASS();+}++/* C1-E: C++ — same-file constructor call (no cross-file complication).+ * green=guard: C++ `Counter c(0)` / `Counter c{0}` — lsp_cross (cpp_mode)+ * handles this when both definition and call site are in the same file.+ * This supplements lrp_cpp_s3_constructor (which uses two files) with a+ * single-file shape where forward-declaration ambiguity is absent. */+TEST(mkc_c1_cpp_constructor_samefile) {+ static const MKC_File f[] = {+ {"counter.cpp",+ "class Counter {\npublic:\n"+ " int n;\n"+ " Counter(int start) : n(start) {}\n"+ " int val() const { return n; }\n};\n\n"+ "int run(int start) {\n"+ " Counter c(start);\n"+ " return c.val();\n"+ "}\n"}};+ /* green=guard: constructor + method call both in one file; lsp_cross should+ * resolve both. If this fails it is a C++ same-file constructor regression. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c1/cpp/constructor_samefile", 1));+ PASS();+}++/* C1-F: Rust — struct literal T { field } in same file (avoids :: resolver bug).+ * The lrp_rust_s3_constructor fixture uses `point::Point::new(...)` which fails+ * due to the `::` split bug in cbm_registry_resolve. Here we test a plain+ * same-file struct + impl, where `Point::new(x, y)` has no module prefix,+ * so the resolver should find it.+ * green=guard: Rust same-file `StructName::new()` — the name "new" is a unique+ * function in the file; the generic resolver should link it. */+TEST(mkc_c1_rust_new_samefile) {+ static const MKC_File f[] = {+ {"point.rs",+ "pub struct Point { pub x: f64, pub y: f64 }\n\n"+ "impl Point {\n"+ " pub fn new(x: f64, y: f64) -> Self { Point { x, y } }\n"+ " pub fn dist(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() }\n"+ "}\n\n"+ "pub fn run() -> f64 {\n"+ " let p = Point::new(3.0, 4.0);\n"+ " p.dist()\n"+ "}\n"}};+ /* Uncertain/red=bug: Point::new inside the same file — the generic resolver+ * splits on '.' not '::' so "Point::new" never matches registered QN "new".+ * Root cause: registry.c cbm_registry_resolve doesn't handle Rust `::` paths.+ * Fix location: src/pipeline/registry.c — split on '::' for Rust as well as '.'. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c1/rust/new_samefile", 0));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C2: OPERATOR OVERLOADING ══════════════════════════════════════+ *+ * When a language desugars `a + b` → `a.operator+(b)` or `a.__add__(b)`,+ * the pipeline should emit a CALLS edge to that operator method.+ *+ * Languages: C++, Python, Rust (Add trait), Kotlin (operator fun),+ * C# (operator), Scala (symbolic def), Ruby (def +),+ * Swift (static func +)+ * ══════════════════════════════════════════════════════════════════════════ */++/* C2-A: C++ — operator+ overload.+ * red=bug: `a + b` where both are Vec2 objects is a binary_expression with+ * operator_name "+". C++ lsp_cross does not currently desugar operator+ * expressions into CALLS edges for overloaded operators.+ * Root cause: the C++ call_types list includes "call_expression" but not+ * "binary_expression" for operator-call desugaring.+ * Fix: extend extract_calls.c C++ path to emit a CALLS node for+ * binary_expression when both operands have a known overloaded type. */+TEST(mkc_c2_cpp_operator_plus) {+ static const MKC_File f[] = {+ {"vec.cpp",+ "struct Vec2 {\n float x, y;\n Vec2(float x, float y): x(x), y(y){}\n"+ " Vec2 operator+(const Vec2 &o) const { return Vec2(x+o.x, y+o.y); }\n"+ " float dot(const Vec2 &o) const { return x*o.x + y*o.y; }\n};\n\n"+ "float run(Vec2 a, Vec2 b) {\n"+ " Vec2 c = a + b;\n" /* operator+ call */+ " return c.dot(b);\n"+ "}\n"}};+ /* red=bug: `a + b` should CALLS run->Vec2::operator+.+ * c.dot(b) may pass via method-call resolution (it's a named call_expression).+ * We assert CALLS >= 2 (operator+ + dot); will fail until C++ operator desugaring+ * is implemented. Minimally assert >= 1 for now to capture the dot() shape. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 2, "c2/cpp/operator_plus", 0));+ PASS();+}++/* C2-B: C++ — operator[] subscript overload.+ * red=bug: `arr[0]` on a custom array type is a subscript_expression;+ * same root cause as C2-A — no desugaring to CALLS for subscript operators. */+TEST(mkc_c2_cpp_operator_subscript) {+ static const MKC_File f[] = {+ {"arr.cpp",+ "struct IntArr {\n int data[8];\n"+ " int& operator[](int i) { return data[i]; }\n"+ "};\n\n"+ "int run(IntArr &a) {\n"+ " return a[2];\n"+ "}\n"}};+ /* REAL BUG: a[2] should CALLS run->IntArr::operator[]. The subscript+ * operator desugaring is not modeled — C++ call extraction does not emit a+ * call for subscript_expression on an overloaded-operator type → 0 CALLS.+ * (Note: C++ binary operator+ desugaring now works — c2/cpp/operator_plus+ * passes — but subscript [] is still missing.) [KNOWN class 12] */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c2/cpp/operator_subscript", 0));+ PASS();+}++/* C2-C: Python — __add__ dunder method.+ * red=bug: `a + b` with Vector objects — Python grammar emits a+ * binary_operator node for `+`. Neither extract_calls.c nor the Python+ * lsp_cross pass maps binary_operator to a __add__ CALLS edge.+ * Root cause: py_call_types is {call, decorator} (lang_specs.c) — no+ * binary_operator entry. Fix: extend Python extractor to model dunder+ * operator expressions as calls to __add__ / __eq__ / etc. */+TEST(mkc_c2_python_dunder_add) {+ static const MKC_File f[] = {+ {"vec.py",+ "class Vec:\n"+ " def __init__(self, x, y):\n self.x, self.y = x, y\n\n"+ " def __add__(self, other):\n return Vec(self.x + other.x, self.y + other.y)\n\n"+ " def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n\n"+ "def run(a, b):\n"+ " return a + b\n"}};+ /* red=bug: `a + b` should CALLS run->Vec.__add__.+ * Currently binary_operator is not in Python call_types. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c2/python/dunder_add", 0));+ PASS();+}++/* C2-D: Python — __getitem__ dunder method.+ * red=bug: `a[0]` on a custom Seq emits a subscript node, not a call_expression.+ * Same root cause as C2-C — subscript desugaring to __getitem__ is missing. */+TEST(mkc_c2_python_dunder_getitem) {+ static const MKC_File f[] = {+ {"seq.py",+ "class Seq:\n"+ " def __init__(self, data):\n self._d = data\n\n"+ " def __getitem__(self, i):\n return self._d[i]\n\n"+ "def run(s):\n"+ " return s[0]\n"}};+ /* REAL BUG: s[0] should CALLS run->Seq.__getitem__. Python subscript+ * desugaring to __getitem__ is not modeled — the subscript node is not+ * mapped to a dunder call → 0 CALLS. (Note: Python binary `a + b` →+ * __add__ now works — c2/python/dunder_add passes — but subscript [] is+ * still missing.) [KNOWN class 12] */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c2/python/dunder_getitem", 0));+ PASS();+}++/* C2-E: Rust — Add trait operator overload (a + b).+ * red=bug: Rust `a + b` where T implements std::ops::Add is a binary_expression.+ * Rust's call_types do not include binary_expression, so `a + b` is never+ * extracted as a call to <T as Add>::add.+ * Root cause: lang_specs.c rust_call_types = {call_expression, macro_invocation}+ * — no binary_expression entry.+ * Note: Rust lsp_cross is also not wired (see lrp_rust_* suite), compounding the miss. */+TEST(mkc_c2_rust_add_trait) {+ static const MKC_File f[] = {+ {"vec.rs",+ "use std::ops::Add;\n\n"+ "#[derive(Clone, Copy)]\n"+ "pub struct Vec2 { pub x: f32, pub y: f32 }\n\n"+ "impl Add for Vec2 {\n"+ " type Output = Self;\n"+ " fn add(self, rhs: Self) -> Self {\n"+ " Vec2 { x: self.x + rhs.x, y: self.y + rhs.y }\n"+ " }\n"+ "}\n\n"+ "pub fn run(a: Vec2, b: Vec2) -> Vec2 {\n"+ " a + b\n"+ "}\n"}};+ /* REAL BUG: `a + b` should CALLS run->Vec2::add (via Add trait). Rust+ * binary_expression is not in lang_specs.c rust_call_types, so the operator+ * desugaring is never extracted as a call → 0 CALLS. (Rust also has no+ * cross-LSP, compounding the miss.) [KNOWN class 12] */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c2/rust/add_trait", 0));+ PASS();+}++/* C2-F: Kotlin — operator fun plus.+ * red=bug: Kotlin `a + b` with `operator fun plus` defined — the grammar+ * emits an additive_expression, not a call_expression. Kotlin's call_types+ * (lang_specs.c) do not include additive_expression.+ * Fix: extend Kotlin extractor to map operator expressions to CALLS. */+TEST(mkc_c2_kotlin_operator_plus) {+ static const MKC_File f[] = {+ {"vec.kt",+ "data class Vec2(val x: Float, val y: Float) {\n"+ " operator fun plus(other: Vec2): Vec2 =\n"+ " Vec2(x + other.x, y + other.y)\n"+ " operator fun get(i: Int): Float = if (i == 0) x else y\n"+ "}\n\n"+ "fun run(a: Vec2, b: Vec2): Vec2 = a + b\n"}};+ /* red=bug: `a + b` should CALLS run->Vec2.plus (operator fun). */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c2/kotlin/operator_plus", 0));+ PASS();+}++/* C2-G: C# — operator + overload.+ * red=bug: C# `a + b` for structs with operator+ is a binary_expression in+ * the grammar. cs_call_types = {invocation_expression} only — no+ * binary_expression, so the operator call is never extracted. */+TEST(mkc_c2_csharp_operator_plus) {+ static const MKC_File f[] = {+ {"Vec.cs",+ "namespace App {\n"+ " struct Vec2 {\n"+ " public float X, Y;\n"+ " public Vec2(float x, float y) { X = x; Y = y; }\n"+ " public static Vec2 operator+(Vec2 a, Vec2 b) {\n"+ " return new Vec2(a.X + b.X, a.Y + b.Y);\n"+ " }\n"+ " public float Dot(Vec2 o) { return X*o.X + Y*o.Y; }\n"+ " }\n"+ " class Math {\n"+ " public static float Run(Vec2 a, Vec2 b) {\n"+ " return (a + b).Dot(b);\n"+ " }\n"+ " }\n"+ "}\n"}};+ /* REAL BUG: `(a + b).Dot(b)` should CALLS both Vec2::op_Addition (the `+`)+ * AND Dot (>=2). Dot resolves (CALLS=1) but the operator `a + b` does not —+ * C# binary_expression operator desugaring is not modeled (cs_call_types omits+ * it), so the op_Addition call is missing → CALLS=1 < 2. [KNOWN class 12] */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 2, "c2/csharp/operator_plus", 0));+ PASS();+}++/* C2-H: Scala — symbolic method (operators are methods in Scala).+ * Uncertain/red=bug: in Scala `a + b` with a custom `def +(other: Vec2)` is+ * syntactic sugar for a method call `a.+(b)` — it IS a call_expression in the+ * tree-sitter-scala grammar. The generic resolver may find `+` if it maps to+ * a unique method name. Assert CALLS >= 1. */+TEST(mkc_c2_scala_symbolic_method) {+ static const MKC_File f[] = {+ {"vec.scala",+ "case class Vec2(x: Double, y: Double) {\n"+ " def +(other: Vec2): Vec2 = Vec2(x + other.x, y + other.y)\n"+ " def dot(other: Vec2): Double = x * other.x + y * other.y\n"+ "}\n\n"+ "def run(a: Vec2, b: Vec2): Double = (a + b).dot(b)\n"}};+ /* Uncertain: in Scala `a + b` is sugar for `a.+(b)`. The tree-sitter-scala+ * grammar may emit a call_expression whose callee is `+`. The generic+ * name resolver tries to match the method "+". If Scala call_types correctly+ * includes infix applications, this is GREEN; otherwise red=bug. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c2/scala/symbolic_method", 0));+ PASS();+}++/* C2-I: Ruby — operator method (def +).+ * Uncertain/red=bug: Ruby `a + b` is a binary method call. The tree-sitter-ruby+ * grammar emits a `binary` node for infix expressions. Ruby call_types+ * (extract_calls.c) handle `call` nodes but may not handle `binary`.+ * If binary is mapped to a method call, the resolver finds `+`; otherwise red. */+TEST(mkc_c2_ruby_operator_plus) {+ static const MKC_File f[] = {+ {"vec.rb",+ "class Vec2\n"+ " attr_reader :x, :y\n"+ " def initialize(x, y)\n @x, @y = x, y\n end\n\n"+ " def +(other)\n Vec2.new(@x + other.x, @y + other.y)\n end\n\n"+ " def dot(other)\n @x * other.x + @y * other.y\n end\n"+ "end\n\n"+ "def run(a, b)\n"+ " (a + b).dot(b)\n"+ "end\n"}};+ /* Uncertain/red=bug: `a + b` should CALLS run->Vec2#+.+ * Ruby binary node not in call_types. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c2/ruby/operator_plus", 0));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C3: DECORATES — annotations / attributes / macros ═════════════+ *+ * Languages / forms NOT yet covered by test_edge_structural.c:+ * - Rust #[derive(...)] and #[cfg(...)] macro attributes+ * - PHP 8 #[Attribute] syntax+ * - Swift @propertyWrapper / @available+ * - Scala @annotation.tailrec / @deprecated+ * - Ruby no native decorators (N/A — excluded)+ * - Python same-file already green in test_lang_contract.c; cross-file in+ * test_edge_structural.c. Add a class-level decorator here.+ *+ * Note: test_edge_structural.c already covers Java, Kotlin, C# annotations+ * (all expected RED). This section adds Rust/PHP/Swift/Scala.+ * ══════════════════════════════════════════════════════════════════════════ */++/* C3-A: Rust — #[derive(...)] attribute macro.+ * red=bug: Rust `#[derive(Debug, Clone)]` is an attribute_item node in the+ * grammar. The pipeline models decorators for Python/TS via `decorators[]`+ * in the def struct, but there is no Rust branch that maps attribute_item+ * to a DECORATES edge.+ * Root cause: extract_defs.c has no Rust attribute/decorator extraction.+ * Fix: add a Rust path in extract_defs.c that reads attribute_item children+ * and populates def.decorators[]. */+TEST(mkc_c3_rust_derive_attribute) {+ static const MKC_File f[] = {+ {"model.rs",+ "fn debug_marker() {}\n\n"+ "#[derive(Debug, Clone)]\n"+ "pub struct Point {\n"+ " pub x: f64,\n"+ " pub y: f64,\n"+ "}\n\n"+ "#[derive(Debug)]\n"+ "pub struct Color(pub u8, pub u8, pub u8);\n"}};+ /* REAL BUG: #[derive(Debug)] should produce a DECORATES edge. extract_defs.c+ * has no Rust attribute_item → decorators[] path, so Rust attribute/derive+ * macros are never modeled → DECORATES=0. [KNOWN class 13] */+ ASSERT_TRUE(mkc_edge(f, 1, "DECORATES", 1, "c3/rust/derive_attribute", 0));+ PASS();+}++/* C3-B: Rust — custom function attribute (locally defined proc-macro simulation).+ * red=bug: Even a simple fn-level attribute `#[my_attr]` applied to a function+ * where `my_attr` is defined in the same file is not modeled as DECORATES.+ * Same root cause as C3-A. */+TEST(mkc_c3_rust_fn_attribute) {+ static const MKC_File f[] = {+ {"service.rs",+ "/* hypothetical local marker — real proc-macros live in separate crates,\n"+ " * but we just want to check if ANY attribute is modeled as DECORATES */\n"+ "pub fn log_call() {}\n\n"+ "#[allow(dead_code)]\n"+ "pub fn helper(x: i32) -> i32 { x + 1 }\n\n"+ "#[allow(dead_code)]\n"+ "pub fn run(y: i32) -> i32 { helper(y) }\n"}};+ /* REAL BUG: #[allow(dead_code)] should produce a DECORATES edge. Same root+ * cause as c3/rust/derive_attribute — extract_defs.c has no Rust+ * attribute_item → decorators[] path → DECORATES=0. [KNOWN class 13] */+ ASSERT_TRUE(mkc_edge(f, 1, "DECORATES", 1, "c3/rust/fn_attribute", 0));+ PASS();+}++/* C3-C: PHP 8 — #[Attribute] syntax (modern PHP attributes).+ * red=bug: PHP 8 `#[Route("/users")]` attribute on a function is a new grammar+ * node (attribute_group / attribute) distinct from PHP docblock annotations.+ * The PHP extractor may not yet populate decorators[] for the new #[...] syntax.+ * Root cause: extract_defs.c PHP path handles @docblock annotations but may+ * not handle PHP 8 attribute_group nodes. */+TEST(mkc_c3_php8_attribute) {+ static const MKC_File f[] = {+ {"routes.php",+ "<?php\n"+ "function Route(string $path): callable {\n"+ " return function() use ($path) { return $path; };\n"+ "}\n\n"+ "#[Route('/users')]\n"+ "function listUsers(): array {\n"+ " return [];\n"+ "}\n\n"+ "#[Route('/items')]\n"+ "function listItems(): array {\n"+ " return [];\n"+ "}\n"}};+ /* REAL BUG: #[Route(...)] should DECORATES listUsers->Route. extract_defs.c+ * handles PHP @docblock annotations but not PHP 8 attribute_group / attribute+ * nodes → DECORATES=0. [KNOWN class 13] */+ ASSERT_TRUE(mkc_edge(f, 1, "DECORATES", 1, "c3/php8/attribute", 0));+ PASS();+}++/* C3-D: Swift — @available / @discardableResult attribute.+ * red=bug: Swift attributes like `@available(macOS 12, *)` and+ * `@discardableResult` are attribute nodes in the tree-sitter-swift grammar.+ * The pipeline has no Swift decorator extraction branch.+ * Root cause: extract_defs.c has no Swift attribute_item → decorators[] path. */+TEST(mkc_c3_swift_attribute) {+ static const MKC_File f[] = {+ {"service.swift",+ "func available() -> Bool { return true }\n\n"+ "@discardableResult\n"+ "func compute(x: Int) -> Int {\n"+ " return x * 2\n"+ "}\n\n"+ "@discardableResult\n"+ "func run(n: Int) -> Int {\n"+ " return compute(n)\n"+ "}\n"}};+ /* REAL BUG: @discardableResult should produce a DECORATES edge. extract_defs.c+ * has no Swift attribute → decorators[] path, so Swift attributes are never+ * modeled → DECORATES=0. [KNOWN class 13] */+ ASSERT_TRUE(mkc_edge(f, 1, "DECORATES", 1, "c3/swift/attribute", 0));+ PASS();+}++/* C3-E: Scala — @annotation on a method.+ * red=bug: Scala `@deprecated` / `@tailrec` annotations are annotation nodes.+ * The generic extractor may or may not capture them as DECORATES edges.+ * Root cause: extract_defs.c Scala path likely does not handle annotation nodes. */+TEST(mkc_c3_scala_annotation) {+ static const MKC_File f[] = {+ {"algo.scala",+ "import scala.annotation.tailrec\n\n"+ "@deprecated(\"use newHelper\", \"2.0\")\n"+ "def helper(x: Int): Int = x + 1\n\n"+ "@tailrec\n"+ "def loop(n: Int, acc: Int): Int =\n"+ " if (n <= 0) acc else loop(n - 1, acc + n)\n"}};+ /* REAL BUG: @deprecated should produce a DECORATES edge. extract_defs.c has+ * no Scala annotation → decorators[] path, so Scala annotations are never+ * modeled → DECORATES=0. [KNOWN class 13] */+ ASSERT_TRUE(mkc_edge(f, 1, "DECORATES", 1, "c3/scala/annotation", 0));+ PASS();+}++/* C3-F: Python — class-level decorator (not just function-level).+ * green=guard: test_lang_contract.c P6 covers function-level decorators.+ * This adds a CLASS-level decorator to confirm the extractor handles+ * decorated class definitions (not just functions). */+TEST(mkc_c3_python_class_decorator) {+ static const MKC_File f[] = {+ {"service.py",+ "def singleton(cls):\n"+ " instances = {}\n"+ " def get(*a, **kw):\n"+ " if cls not in instances:\n"+ " instances[cls] = cls(*a, **kw)\n"+ " return instances[cls]\n"+ " return get\n\n\n"+ "@singleton\n"+ "class Config:\n"+ " def __init__(self):\n self.debug = False\n\n\n"+ "@singleton\n"+ "class Cache:\n"+ " def __init__(self):\n self.data = {}\n"}};+ /* green=guard: @singleton on a class should DECORATES Config->singleton.+ * Python class-level decorator extraction should work the same as function-level+ * (both are `decorated_definition` nodes in tree-sitter-python). */+ ASSERT_TRUE(mkc_edge(f, 1, "DECORATES", 1, "c3/python/class_decorator", 1));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C4: ASYNC/AWAIT CALLS ═════════════════════════════════════════+ *+ * An `await expr` or async function call should still produce a CALLS edge+ * to the callee. The async/await syntax wraps the call but must not hide it+ * from the extractor.+ *+ * Languages: Python (async def / await), TypeScript (async/await),+ * C# (async Task / await), Rust (.await expr),+ * Kotlin (suspend fun / coroutine launch),+ * Swift (async/await — Swift 5.5+)+ * ══════════════════════════════════════════════════════════════════════════ */++/* C4-A: Python — async/await function call.+ * green=guard: Python `await fetch(url)` — the `await` expression wraps a+ * regular `call` node whose function field is `fetch`. Python's call_types+ * include `call`, so the `call` inside `await` is still extracted.+ * The extractor should find the inner call regardless of the await wrapper. */+TEST(mkc_c4_python_async_await) {+ static const MKC_File f[] = {+ {"client.py",+ "async def fetch(url: str) -> str:\n"+ " return url\n\n\n"+ "async def get_data(url: str) -> str:\n"+ " result = await fetch(url)\n"+ " return result\n\n\n"+ "async def run(urls):\n"+ " for url in urls:\n"+ " data = await get_data(url)\n"+ " print(data)\n"}};+ /* green=guard: await fetch(url) inner call should CALLS get_data->fetch.+ * await is transparent to the call extractor for Python. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c4/python/async_await", 1));+ PASS();+}++/* C4-B: TypeScript — async/await function call.+ * green=guard: TS `await fetch(url)` — the `await_expression` wraps a+ * `call_expression`. TS call_types include call_expression, so the inner+ * call is extracted regardless of the await wrapper. */+TEST(mkc_c4_typescript_async_await) {+ static const MKC_File f[] = {+ {"client.ts",+ "async function fetch(url: string): Promise<string> {\n"+ " return url;\n"+ "}\n\n"+ "async function getData(url: string): Promise<string> {\n"+ " return await fetch(url);\n"+ "}\n\n"+ "async function run(urls: string[]): Promise<void> {\n"+ " for (const url of urls) {\n"+ " const data = await getData(url);\n"+ " console.log(data);\n"+ " }\n"+ "}\n"}};+ /* green=guard: await fetch(url) should CALLS getData->fetch. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c4/typescript/async_await", 1));+ PASS();+}++/* C4-C: C# — async Task + await call.+ * Uncertain/red=bug: C# `await FetchAsync(url)` — the `await_expression` in+ * the C# grammar wraps an `invocation_expression`. cs_call_types includes+ * `invocation_expression`, so the inner call should be extracted.+ * However, the await wrapper may or may not be transparent; assert CALLS >= 1. */+TEST(mkc_c4_csharp_async_await) {+ static const MKC_File f[] = {+ {"Client.cs",+ "using System.Threading.Tasks;\n\n"+ "namespace App {\n"+ " class Client {\n"+ " public async Task<string> FetchAsync(string url) {\n"+ " return url;\n"+ " }\n\n"+ " public async Task<string> GetDataAsync(string url) {\n"+ " return await FetchAsync(url);\n"+ " }\n\n"+ " public async Task RunAsync() {\n"+ " string data = await GetDataAsync(\"http://example.com\");\n"+ " }\n"+ " }\n"+ "}\n"}};+ /* Uncertain: C# await_expression wraps invocation_expression.+ * If cs_call_types handles it, green=guard; otherwise red=bug. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c4/csharp/async_await", 0));+ PASS();+}++/* C4-D: Rust — .await expression.+ * red=bug: Rust `future.await` is an `await_expression` node where the+ * operand is a method-call-like expression. Rust call_types = {call_expression,+ * macro_invocation} — await_expression is not included.+ * Root cause: lang_specs.c rust_call_types does not include await_expression.+ * Fix: either add await_expression to rust_call_types, or teach extract_calls.c+ * to unwrap await_expression and process the inner expression. */+TEST(mkc_c4_rust_await) {+ static const MKC_File f[] = {+ {"client.rs",+ "async fn fetch(url: &str) -> String {\n"+ " url.to_string()\n"+ "}\n\n"+ "async fn get_data(url: &str) -> String {\n"+ " fetch(url).await\n"+ "}\n\n"+ "async fn run(urls: &[&str]) {\n"+ " for url in urls {\n"+ " let _data = get_data(url).await;\n"+ " }\n"+ "}\n"}};+ /* red=bug: fetch(url).await — the inner fetch(url) IS a call_expression,+ * but its CALLS attribution may be lost when wrapped in await.+ * Additionally, get_data(url).await has same issue.+ * Assert CALLS >= 1 (the correct outcome). */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c4/rust/await", 0));+ PASS();+}++/* C4-E: Kotlin — suspend function call (coroutines).+ * Uncertain: Kotlin `suspend fun` calls look like normal function calls at the+ * grammar level — the `suspend` keyword modifies the function signature but does+ * not change the call_expression shape. The generic resolver should find the+ * callee by name. Assert CALLS >= 1. */+TEST(mkc_c4_kotlin_suspend_call) {+ static const MKC_File f[] = {+ {"client.kt",+ "suspend fun fetchData(url: String): String {\n"+ " return url\n"+ "}\n\n"+ "suspend fun getData(url: String): String {\n"+ " return fetchData(url)\n"+ "}\n\n"+ "suspend fun run(urls: List<String>) {\n"+ " for (url in urls) {\n"+ " val data = getData(url)\n"+ " println(data)\n"+ " }\n"+ "}\n"}};+ /* green=guard (uncertain): suspend fun calls are regular function calls+ * at grammar level; the name resolver should find fetchData and getData. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c4/kotlin/suspend_call", 1));+ PASS();+}++/* C4-F: Swift — async/await (Swift 5.5+).+ * red=bug: Swift `await fetch(url)` — the grammar emits an `await_expression`+ * wrapping a `call_expression`. Swift call_types in lang_specs.c may or may+ * not include `call_expression`; even if it does, the extract_callee_name for+ * Swift's call_expression form needs to be validated.+ * Additionally, Swift lsp_cross is not wired. */+TEST(mkc_c4_swift_async_await) {+ static const MKC_File f[] = {+ {"client.swift",+ "func fetch(url: String) async -> String {\n"+ " return url\n"+ "}\n\n"+ "func getData(url: String) async -> String {\n"+ " return await fetch(url: url)\n"+ "}\n\n"+ "func run(urls: [String]) async {\n"+ " for url in urls {\n"+ " let data = await getData(url: url)\n"+ " print(data)\n"+ " }\n"+ "}\n"}};+ /* Uncertain: Swift `await fetch(url: url)` inner call_expression should+ * produce CALLS getData->fetch. Assert CALLS >= 1. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c4/swift/async_await", 0));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C5: GENERIC / TEMPLATED METHOD CALLS ═══════════════════════════+ *+ * Calling a method through a generic type parameter. The existing+ * lsp_resolution_probe.c covers S7 (generic call) for all 9 hybrid langs.+ *+ * Matrix-fill adds: Scala, Swift, Ruby (duck-typed, no generics per se).+ * ══════════════════════════════════════════════════════════════════════════ */++/* C5-A: Scala — generic function call.+ * Uncertain: Scala `def first[T](xs: List[T]): T` — the generic type parameter+ * does not affect the call_expression shape; the generic resolver should find+ * `first` by name regardless of the type argument. */+TEST(mkc_c5_scala_generic_call) {+ static const MKC_File f[] = {+ {"algo.scala",+ "def first[T](xs: List[T]): Option[T] =\n"+ " if (xs.isEmpty) None else Some(xs.head)\n\n"+ "def run(ns: List[Int]): Option[Int] = first(ns)\n"}};+ /* Uncertain: first is a top-level generic; the name resolver should find it.+ * Assert CALLS >= 1; red=bug if generic call is dropped. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c5/scala/generic_call", 0));+ PASS();+}++/* C5-B: Swift — generic function call.+ * Uncertain: Swift `func maxOf<T: Comparable>(_ a: T, _ b: T) -> T` — same as+ * Scala; the generic syntax does not change the call_expression structure. */+TEST(mkc_c5_swift_generic_call) {+ static const MKC_File f[] = {+ {"algo.swift",+ "func maxOf<T: Comparable>(_ a: T, _ b: T) -> T {\n"+ " return a > b ? a : b\n"+ "}\n\n"+ "func run(a: Int, b: Int) -> Int {\n"+ " return maxOf(a, b)\n"+ "}\n"}};+ /* Uncertain: maxOf is a top-level generic; assert CALLS >= 1. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c5/swift/generic_call", 0));+ PASS();+}++/* C5-C: Ruby — duck-typed "generic" (no static generics; method works on any type).+ * green=guard: Ruby method call is always dynamic; the name resolver treats it+ * like a regular method call. Confirms ordinary Ruby method resolution works+ * (orthogonal to generics but useful as a guard for Ruby CALLS coverage). */+TEST(mkc_c5_ruby_duck_typed_call) {+ static const MKC_File f[] = {+ {"algo.rb",+ "def first(collection)\n"+ " collection.empty? ? nil : collection.first\n"+ "end\n\n"+ "def run(items)\n"+ " first(items)\n"+ "end\n"}};+ /* green=guard: `first(items)` is a plain method call; CALLS run->first. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c5/ruby/duck_typed_call", 1));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C6: STATIC / CLASS-METHOD CALLS (grammar-only langs) ══════════+ *+ * The existing suites cover static calls for Go/C/C++/Python/TS/Java/Kotlin/+ * C#/PHP/Rust. Matrix-fill adds: Scala companion-object, Swift static/class+ * methods, Ruby self.method (class methods).+ * ══════════════════════════════════════════════════════════════════════════ */++/* C6-A: Scala — companion object method call.+ * Uncertain/red=bug: `Config.default()` where default() is in a companion+ * object. The Scala grammar may emit this as a call_expression whose+ * callee is a `field_expression` Config.default — the generic resolver should+ * strip the qualifier and find `default`. Assert CALLS >= 1. */+TEST(mkc_c6_scala_companion_object) {+ static const MKC_File f[] = {+ {"config.scala",+ "class Config(val debug: Boolean)\n\n"+ "object Config {\n"+ " def default(): Config = new Config(false)\n"+ " def debug(): Config = new Config(true)\n"+ "}\n\n"+ "def run(): Config = Config.default()\n"}};+ /* Uncertain: Config.default() — the generic resolver strips `Config.` prefix+ * and looks for `default`. May resolve if unique; otherwise red=bug. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c6/scala/companion_object", 0));+ PASS();+}++/* C6-B: Swift — static method call (class func / static func).+ * Uncertain: Swift `MathHelper.clamp(n, 0, 100)` where clamp is a `static func`.+ * The generic resolver should strip `MathHelper.` and find `clamp`. */+TEST(mkc_c6_swift_static_method) {+ static const MKC_File f[] = {+ {"mathhelper.swift",+ "class MathHelper {\n"+ " static func clamp(_ v: Int, _ lo: Int, _ hi: Int) -> Int {\n"+ " return v < lo ? lo : v > hi ? hi : v\n"+ " }\n"+ " static func square(_ x: Int) -> Int { return x * x }\n"+ "}\n\n"+ "func run(n: Int) -> Int {\n"+ " return MathHelper.clamp(n, 0, 100)\n"+ "}\n"}};+ /* Uncertain: MathHelper.clamp — resolver strips qualifier, finds clamp.+ * Assert CALLS >= 1; red=bug if Swift static method never resolves. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c6/swift/static_method", 0));+ PASS();+}++/* C6-C: Ruby — class method (self.method_name).+ * Uncertain: Ruby `Config.version` where `def self.version` is a class method.+ * The method is registered as a Function/Method with name `version` (the `self.`+ * prefix is the receiver, not part of the method name in the registry).+ * The generic resolver should find `version` by name. Assert CALLS >= 1. */+TEST(mkc_c6_ruby_class_method) {+ static const MKC_File f[] = {+ {"config.rb",+ "class Config\n"+ " def self.version\n"+ " '1.0'\n"+ " end\n\n"+ " def self.default\n"+ " new\n"+ " end\n"+ "end\n\n"+ "def run\n"+ " Config.version\n"+ "end\n"}};+ /* Uncertain: Config.version — the generic resolver strips `Config.` and+ * looks for `version`. Assert CALLS >= 1. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c6/ruby/class_method", 0));+ PASS();+}++/* C6-D: Scala — object method call (module-level singleton object).+ * green=guard: `Logger.log("msg")` where Logger is a singleton `object`.+ * In Scala, `object Logger` creates a singleton; `Logger.log(...)` is a+ * call_expression. The generic resolver should find `log` by name. */+TEST(mkc_c6_scala_singleton_object) {+ static const MKC_File f[] = {+ {"logger.scala",+ "object Logger {\n"+ " def log(msg: String): Unit = println(msg)\n"+ " def warn(msg: String): Unit = println(\"WARN: \" + msg)\n"+ "}\n\n"+ "def run(msg: String): Unit = Logger.log(msg)\n"}};+ /* green=guard: Logger.log(msg) should CALLS run->log.+ * The generic resolver strips the object prefix and resolves `log`. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c6/scala/singleton_object", 1));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C7: INHERITED-METHOD CALL (grammar-only langs) ════════════════+ *+ * Existing suites cover inherited-method calls for all 9 hybrid langs.+ * Matrix-fill adds: Scala, Swift, Ruby.+ * ══════════════════════════════════════════════════════════════════════════ */++/* C7-A: Scala — subclass calls inherited method.+ * Uncertain: `class Dog extends Animal` — Scala inheritance uses `extends`.+ * The extractor should produce INHERITS Dog->Animal, but this test focuses+ * on whether `dog.describe()` (an inherited method) produces a CALLS edge. */+TEST(mkc_c7_scala_inherited_method) {+ static const MKC_File f[] = {+ {"zoo.scala",+ "class Animal {\n"+ " def describe(): String = \"animal\"\n"+ " def speak(): String = \"...\"\n"+ "}\n\n"+ "class Dog extends Animal {\n"+ " override def speak(): String = \"woof\"\n"+ "}\n\n"+ "def run(d: Dog): String = d.describe()\n"}};+ /* Uncertain: d.describe() — the name resolver finds `describe` (it is in+ * Animal, which is in the same file). Assert CALLS >= 1 (correct outcome).+ * This may be GREEN if the generic resolver finds `describe` by name alone. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c7/scala/inherited_method", 0));+ PASS();+}++/* C7-B: Swift — subclass calls inherited method.+ * Uncertain: Swift `class Dog: Animal` — the subclass calls `describe()` from+ * the base class. Same reasoning as C7-A; assert CALLS >= 1. */+TEST(mkc_c7_swift_inherited_method) {+ static const MKC_File f[] = {+ {"zoo.swift",+ "class Animal {\n"+ " func describe() -> String { return \"animal\" }\n"+ " func speak() -> String { return \"...\" }\n"+ "}\n\n"+ "class Dog: Animal {\n"+ " override func speak() -> String { return \"woof\" }\n"+ "}\n\n"+ "func run(d: Dog) -> String {\n"+ " return d.describe()\n"+ "}\n"}};+ /* Uncertain: d.describe() should CALLS run->Animal.describe.+ * Assert CALLS >= 1; red=bug if inherited method call drops the edge. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c7/swift/inherited_method", 0));+ PASS();+}++/* C7-C: Ruby — subclass calls inherited method (via super or direct call).+ * green=guard: Ruby `def run; describe; end` in Dog where `describe` is defined+ * in Animal — the generic name resolver finds `describe` in the same project.+ * This is the same resolution path as the existing calls breadth cases. */+TEST(mkc_c7_ruby_inherited_method) {+ static const MKC_File f[] = {+ {"zoo.rb",+ "class Animal\n"+ " def describe\n 'animal'\n end\n\n"+ " def speak\n '...'\n end\n"+ "end\n\n"+ "class Dog < Animal\n"+ " def speak\n 'woof'\n end\n\n"+ " def run\n"+ " describe()\n" /* inherited method call — explicit () makes it a `call` node */+ " end\n"+ "end\n"}};+ /* FIXTURE FIX (was RED as a green guard): a bare `describe` (no parens, no+ * receiver) parses as an `identifier` in tree-sitter-ruby — indistinguishable+ * from a local-variable read — so it is NOT one of ruby_call_types+ * {call, command_call} and is never extracted as a call (calls=0). That is a+ * grammar reality, not an indexer bug. Writing `describe()` makes it a `call`+ * node; the name resolver then finds Animal#describe in the same file → CALLS+ * Dog#run->describe. (Sibling Ruby calls with args/receivers — c5 duck_typed,+ * c6 class_method, c2 operator — already pass.) green=guard. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c7/ruby/inherited_method", 1));+ PASS();+}++/* C7-D: Scala — super method call.+ * red=bug: `super.describe()` in a Scala subclass is a `super_expression` node+ * wrapping a field_expression / call. The extractor may or may not follow+ * the super dereference to find the callee `describe`. */+TEST(mkc_c7_scala_super_call) {+ static const MKC_File f[] = {+ {"zoo2.scala",+ "class Base {\n"+ " def describe(): String = \"base\"\n"+ "}\n\n"+ "class Child extends Base {\n"+ " override def describe(): String = \"child: \" + super.describe()\n"+ "}\n\n"+ "def run(c: Child): String = c.describe()\n"}};+ /* Uncertain/red=bug: `super.describe()` — the generic resolver may or may not+ * find `describe` through the `super` qualifier.+ * Also c.describe() should resolve (call to Child's override which calls super).+ * Assert CALLS >= 1 (the outer call c.describe at minimum). */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 1, "c7/scala/super_call", 0));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * ═══ CLASS C8: ADDITIONAL CONSTRUCTOR SHAPES (same-file cross-check) ════+ *+ * These cases probe constructor CALLS in languages where the cross-file+ * lsp_probe already documents failures, but we want a same-file variant to+ * determine if the failure is specifically cross-file (lsp_cross not wired)+ * or also same-file (call_types missing the construction expression).+ * ══════════════════════════════════════════════════════════════════════════ */++/* C8-A: Java — same-file constructor call (new T()).+ * red=bug: lrp_java_s3_constructor confirms the cross-file case fails.+ * The root cause is java_call_types = {method_invocation} only — no+ * object_creation_expression. This is a SAME-FILE reproduction to confirm+ * the bug is at the extraction layer (not a cross-file resolver issue). */+TEST(mkc_c8_java_constructor_samefile) {+ static const MKC_File f[] = {+ {"Factory.java",+ "package app;\n\n"+ "class Widget {\n"+ " private String name;\n"+ " public Widget(String name) { this.name = name; }\n"+ " public String label() { return name; }\n"+ "}\n\n"+ "class Factory {\n"+ " public Widget make(String name) { return new Widget(name); }\n"+ " public String run(String name) { return make(name).label(); }\n"+ "}\n"}};+ /* red=bug: new Widget(name) → CALLS make->Widget.<init> — missing.+ * Root cause: java_call_types does not include object_creation_expression.+ * Fix: lang_specs.c java_call_types — add "object_creation_expression". */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 2, "c8/java/constructor_samefile", 0));+ PASS();+}++/* C8-B: C# — same-file constructor call (new T()).+ * red=bug: same root cause as Java; cs_call_types = {invocation_expression}+ * only, no object_creation_expression. */+TEST(mkc_c8_csharp_constructor_samefile) {+ static const MKC_File f[] = {+ {"Service.cs",+ "namespace App {\n"+ " class Widget {\n"+ " public string Name;\n"+ " public Widget(string name) { Name = name; }\n"+ " public string Label() { return Name; }\n"+ " }\n\n"+ " class Service {\n"+ " public Widget Make(string name) { return new Widget(name); }\n"+ " public string Run(string name) { return Make(name).Label(); }\n"+ " }\n"+ "}\n"}};+ /* red=bug: new Widget(name) → CALLS Make->Widget..ctor — missing.+ * Root cause: cs_call_types missing object_creation_expression.+ * Fix: lang_specs.c cs_call_types — add "object_creation_expression". */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 2, "c8/csharp/constructor_samefile", 0));+ PASS();+}++/* C8-C: PHP — same-file constructor call (new T()).+ * red=bug: lrp_php_s3_constructor confirms this; same-file variant to isolate+ * extraction from resolution.+ * Root cause: php_call_types omits object_creation_expression. */+TEST(mkc_c8_php_constructor_samefile) {+ static const MKC_File f[] = {+ {"factory.php",+ "<?php\n"+ "class Widget {\n"+ " public $name;\n"+ " public function __construct($name) { $this->name = $name; }\n"+ " public function label() { return $this->name; }\n"+ "}\n\n"+ "class Factory {\n"+ " public function make($name) { return new Widget($name); }\n"+ " public function run($name) { return $this->make($name)->label(); }\n"+ "}\n"}};+ /* red=bug: new Widget($name) should CALLS make->Widget::__construct — missing.+ * Fix: lang_specs.c php_call_types — add "object_creation_expression". */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 2, "c8/php/constructor_samefile", 0));+ PASS();+}++/* C8-D: TypeScript — same-file constructor call (new T()).+ * red=bug: lrp_ts_s3_constructor confirms this is RED even with lsp_cross wired.+ * The TS resolver does not link new_expression to the class constructor node.+ * Same-file variant to confirm it is an extraction bug (not a cross-file gap). */+TEST(mkc_c8_typescript_constructor_samefile) {+ static const MKC_File f[] = {+ {"service.ts",+ "class Widget {\n"+ " constructor(public name: string) {}\n"+ " label(): string { return this.name; }\n"+ "}\n\n"+ "class Service {\n"+ " make(name: string): Widget { return new Widget(name); }\n"+ " run(name: string): string { return this.make(name).label(); }\n"+ "}\n"}};+ /* red=bug: new Widget(name) should CALLS make->Widget.constructor.+ * Root cause: TS ts_call_types includes new_expression (call_types in+ * lang_specs.c), but the extractor does not route new_expression to the+ * constructor CALLS path. Fix: handle new_expression callee extraction in+ * extract_calls.c TS/JS branch to emit CALLS to the class. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 2, "c8/typescript/constructor_samefile", 0));+ PASS();+}++/* C8-E: Kotlin — same-file constructor call.+ * red=bug: lrp_kotlin_s3_constructor confirms cross-file RED. Same-file variant+ * isolates whether the problem is extraction (Kotlin call_types missing+ * object_creation_expression) or Kotlin-specific cross-file resolution. */+TEST(mkc_c8_kotlin_constructor_samefile) {+ static const MKC_File f[] = {+ {"app.kt",+ "class Widget(val name: String) {\n"+ " fun label(): String = name\n"+ "}\n\n"+ "fun make(name: String): Widget = Widget(name)\n"+ "fun run(name: String): String = make(name).label()\n"}};+ /* red=bug: Widget(name) should CALLS make->Widget.<init>.+ * Root cause: Kotlin object creation `Widget(name)` is an+ * `call_expression` in tree-sitter-kotlin; but unlike Python's `call`+ * which routes to __init__, Kotlin has no constructor linkage.+ * The generic resolver finds `label` by name (from make(name).label())+ * but may not find the constructor because `Widget` the constructor+ * has no separate definition node in the registry.+ * Assert CALLS >= 2 (make->Widget + label chain); will be RED. */+ ASSERT_TRUE(mkc_edge(f, 1, "CALLS", 2, "c8/kotlin/constructor_samefile", 0));+ PASS();+}++/* ══════════════════════════════════════════════════════════════════════════+ * SUITE registration+ * ══════════════════════════════════════════════════════════════════════════ */++SUITE(matrix_known_classes) {++ /* ── CLASS C1: CONSTRUCTOR / INSTANTIATION ─────────────────────────── */+ /* C1-A/B: Scala new + case class apply — red=bug */+ RUN_TEST(mkc_c1_scala_constructor_new);+ RUN_TEST(mkc_c1_scala_case_class_apply);+ /* C1-C: Swift initializer — red=bug */+ RUN_TEST(mkc_c1_swift_initializer);+ /* C1-D: Ruby Type.new — red=bug */+ RUN_TEST(mkc_c1_ruby_type_new);+ /* C1-E: C++ same-file constructor — green=guard */+ RUN_TEST(mkc_c1_cpp_constructor_samefile);+ /* C1-F: Rust same-file Point::new — red=bug (:: resolver gap) */+ RUN_TEST(mkc_c1_rust_new_samefile);++ /* ── CLASS C2: OPERATOR OVERLOADING ────────────────────────────────── */+ /* C2-A/B: C++ operator+/[] — red=bug */+ RUN_TEST(mkc_c2_cpp_operator_plus);+ RUN_TEST(mkc_c2_cpp_operator_subscript);+ /* C2-C/D: Python __add__/__getitem__ — red=bug */+ RUN_TEST(mkc_c2_python_dunder_add);+ RUN_TEST(mkc_c2_python_dunder_getitem);+ /* C2-E: Rust Add trait — red=bug */+ RUN_TEST(mkc_c2_rust_add_trait);+ /* C2-F: Kotlin operator fun plus — red=bug */+ RUN_TEST(mkc_c2_kotlin_operator_plus);+ /* C2-G: C# operator+ — red=bug */+ RUN_TEST(mkc_c2_csharp_operator_plus);+ /* C2-H: Scala symbolic method — uncertain/red=bug */+ RUN_TEST(mkc_c2_scala_symbolic_method);+ /* C2-I: Ruby def + — uncertain/red=bug */+ RUN_TEST(mkc_c2_ruby_operator_plus);++ /* ── CLASS C3: DECORATES ─────────────────────────────────────────── */+ /* C3-A/B: Rust #[derive] / #[allow] — red=bug */+ RUN_TEST(mkc_c3_rust_derive_attribute);+ RUN_TEST(mkc_c3_rust_fn_attribute);+ /* C3-C: PHP 8 #[Attribute] — red=bug */+ RUN_TEST(mkc_c3_php8_attribute);+ /* C3-D: Swift @discardableResult — red=bug */+ RUN_TEST(mkc_c3_swift_attribute);+ /* C3-E: Scala @deprecated/@tailrec — red=bug */+ RUN_TEST(mkc_c3_scala_annotation);+ /* C3-F: Python class-level decorator — green=guard */+ RUN_TEST(mkc_c3_python_class_decorator);++ /* ── CLASS C4: ASYNC/AWAIT CALLS ─────────────────────────────────── */+ /* C4-A/B: Python / TypeScript async — green=guard */+ RUN_TEST(mkc_c4_python_async_await);+ RUN_TEST(mkc_c4_typescript_async_await);+ /* C4-C: C# async Task — uncertain/red=bug */+ RUN_TEST(mkc_c4_csharp_async_await);+ /* C4-D: Rust .await — red=bug */+ RUN_TEST(mkc_c4_rust_await);+ /* C4-E: Kotlin suspend — green=guard (uncertain) */+ RUN_TEST(mkc_c4_kotlin_suspend_call);+ /* C4-F: Swift async/await — uncertain/red=bug */+ RUN_TEST(mkc_c4_swift_async_await);++ /* ── CLASS C5: GENERIC / TEMPLATED CALLS ─────────────────────────── */+ /* C5-A/B: Scala + Swift generic — uncertain */+ RUN_TEST(mkc_c5_scala_generic_call);+ RUN_TEST(mkc_c5_swift_generic_call);+ /* C5-C: Ruby duck-typed — green=guard */+ RUN_TEST(mkc_c5_ruby_duck_typed_call);++ /* ── CLASS C6: STATIC / CLASS-METHOD CALLS ──────────────────────── */+ /* C6-A/B/C: Scala companion / Swift static / Ruby self.method */+ RUN_TEST(mkc_c6_scala_companion_object);+ RUN_TEST(mkc_c6_swift_static_method);+ RUN_TEST(mkc_c6_ruby_class_method);+ /* C6-D: Scala singleton object — green=guard */+ RUN_TEST(mkc_c6_scala_singleton_object);++ /* ── CLASS C7: INHERITED-METHOD CALLS ───────────────────────────── */+ /* C7-A: Scala inherited method — uncertain */+ RUN_TEST(mkc_c7_scala_inherited_method);+ /* C7-B: Swift inherited method — uncertain */+ RUN_TEST(mkc_c7_swift_inherited_method);+ /* C7-C: Ruby inherited method — green=guard */+ RUN_TEST(mkc_c7_ruby_inherited_method);+ /* C7-D: Scala super call — uncertain */+ RUN_TEST(mkc_c7_scala_super_call);++ /* ── CLASS C8: CONSTRUCTOR SAME-FILE CROSS-CHECK ────────────────── */+ /* All red=bug: isolates extraction-layer constructor gaps */+ RUN_TEST(mkc_c8_java_constructor_samefile);+ RUN_TEST(mkc_c8_csharp_constructor_samefile);+ RUN_TEST(mkc_c8_php_constructor_samefile);+ RUN_TEST(mkc_c8_typescript_constructor_samefile);+ RUN_TEST(mkc_c8_kotlin_constructor_samefile);+}diff --git a/tests/test_matrix_new_constructs.c b/tests/test_matrix_new_constructs.cnew file mode 100644index 000000000..116910b73--- /dev/null+++ b/tests/test_matrix_new_constructs.c@@ -0,0 +1,1567 @@+/*+ * test_matrix_new_constructs.c — New-constructs probe across languages.+ *+ * Green = guard (node/edge already produced correctly).+ * Red = bug found (node/edge not produced as expected; kept with a brief+ * comment naming the suspected root cause).+ *+ * Probed construct families (each spans multiple languages):+ * 1. Type aliases / typedefs / `type X = ...`+ * 2. Exception/error class hierarchies (INHERITS for error types)+ * 3. Multiple inheritance / mixins / multiple interfaces+ * 4. Extension methods / receiver functions+ * 5. Getters / setters / computed properties+ * 6. Records / data classes / structs-with-derive+ * 7. Default / named / variadic parameters+ * 8. Pattern matching / destructuring (calls inside match arms)+ * 9. Nested / local / inner functions calling enclosing scope+ * 10. Module / namespace nesting (module nodes + CONTAINS)+ *+ * Strategy: assert expected nodes or edges; RED means the pipeline is missing+ * something, not that the fixture is wrong. We use assertive floors (>= 1 for+ * the presence of a node class) so grammar refreshes don't flip green tests.+ *+ * Do NOT register in test_main.c — run via standalone suite_matrix_new_constructs().+ */++#include "../src/foundation/compat.h"+#include "test_framework.h"+#include "test_helpers.h"+#include "cbm.h"+#include <mcp/mcp.h>+#include <store/store.h>+#include <pipeline/pipeline.h>+#include <foundation/log.h>++#include <string.h>+#include <stdlib.h>+#include <stdio.h>+#include <unistd.h>+#include <sys/stat.h>++/* ══════════════════════════════════════════════════════════════════+ * Harness — self-contained copy following the pattern established in+ * test_node_creation_probe.c and test_edge_structural.c. Prefix: mn_+ * ══════════════════════════════════════════════════════════════════ */++typedef struct {+ char tmpdir[256];+ char dbpath[512];+ char *project;+ cbm_mcp_server_t *srv;+} MN_LangProj;++typedef struct {+ const char *name;+ const char *content;+} MN_LangFile;++static void mn_to_fwd_slashes(char *p) {+ for (; *p; p++) {+ if (*p == '\\') *p = '/';+ }+}++static cbm_store_t *mn_open_indexed(MN_LangProj *lp) {+ lp->project = cbm_project_name_from_path(lp->tmpdir);+ if (!lp->project) return NULL;+ const char *home = getenv("HOME");+ if (!home) home = "/tmp";+ char cache_dir[512];+ snprintf(cache_dir, sizeof(cache_dir), "%s/.cache/codebase-memory-mcp", home);+ cbm_mkdir(cache_dir);+ snprintf(lp->dbpath, sizeof(lp->dbpath), "%s/%s.db", cache_dir, lp->project);+ unlink(lp->dbpath);+ lp->srv = cbm_mcp_server_new(NULL);+ if (!lp->srv) return NULL;+ char args[700];+ snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", lp->tmpdir);+ char *resp = cbm_mcp_handle_tool(lp->srv, "index_repository", args);+ if (resp) free(resp);+ return cbm_store_open_path(lp->dbpath);+}++static cbm_store_t *mn_index_files(MN_LangProj *lp, const MN_LangFile *files, int nfiles) {+ memset(lp, 0, sizeof(*lp));+ snprintf(lp->tmpdir, sizeof(lp->tmpdir), "/tmp/cbm_mn_XXXXXX");+ if (!cbm_mkdtemp(lp->tmpdir)) return NULL;+ mn_to_fwd_slashes(lp->tmpdir);+ for (int i = 0; i < nfiles; i++) {+ char path[700];+ snprintf(path, sizeof(path), "%s/%s", lp->tmpdir, files[i].name);+ char *slash = strrchr(path, '/');+ if (slash && slash > path + strlen(lp->tmpdir)) {+ *slash = '\0';+ cbm_mkdir_p(path, 0755);+ *slash = '/';+ }+ FILE *f = fopen(path, "wb");+ if (!f) return NULL;+ fputs(files[i].content, f);+ fclose(f);+ }+ return mn_open_indexed(lp);+}++static void mn_cleanup(MN_LangProj *lp, cbm_store_t *store) {+ if (store) cbm_store_close(store);+ if (lp->srv) { cbm_mcp_server_free(lp->srv); lp->srv = NULL; }+ free(lp->project);+ lp->project = NULL;+ th_rmtree(lp->tmpdir);+ unlink(lp->dbpath);+ char wal[600], shm[600];+ snprintf(wal, sizeof(wal), "%s-wal", lp->dbpath);+ unlink(wal);+ snprintf(shm, sizeof(shm), "%s-shm", lp->dbpath);+ unlink(shm);+}++/* Count nodes with a given label; -1 on error. */+static int mn_count_label(cbm_store_t *store, const char *project, const char *label) {+ cbm_node_t *nodes = NULL;+ int count = 0;+ if (cbm_store_find_nodes_by_label(store, project, label, &nodes, &count) != CBM_STORE_OK)+ return -1;+ cbm_store_free_nodes(nodes, count);+ return count;+}++/* Sum type-like nodes (Class + Struct + Interface + Enum + Trait + Type). */+static int mn_type_nodes(cbm_store_t *store, const char *project) {+ static const char *labels[] = {"Class", "Struct", "Interface", "Enum", "Trait", "Type", NULL};+ int total = 0;+ for (int i = 0; labels[i]; i++) {+ int n = mn_count_label(store, project, labels[i]);+ if (n > 0) total += n;+ }+ return total;+}++/* Callable nodes (Function + Method) with >=1 outbound edge. */+static int mn_callables_with_outbound(cbm_store_t *store, const char *project) {+ static const char *callable_labels[] = {"Function", "Method", NULL};+ int total = 0;+ for (int i = 0; callable_labels[i]; i++) {+ cbm_search_params_t p = {0};+ p.project = project;+ p.label = callable_labels[i];+ p.min_degree = 1;+ p.max_degree = -1;+ p.limit = 100;+ cbm_search_output_t out = {0};+ if (cbm_store_search(store, &p, &out) == CBM_STORE_OK)+ total += out.count;+ cbm_store_search_free(&out);+ }+ return total;+}++/* Aggregate metrics for one index pass. */+typedef struct {+ int ok;+ int functions;+ int methods;+ int types; /* all type-like combined */+ int calls;+ int callers;+ int inherits;+ int implements;+ int defines_method;+} MN_Metrics;++static MN_Metrics mn_metrics_files(const MN_LangFile *files, int nfiles) {+ MN_LangProj lp;+ cbm_store_t *store = mn_index_files(&lp, files, nfiles);+ MN_Metrics m = {0};+ if (store) {+ m.ok = 1;+ m.functions = mn_count_label(store, lp.project, "Function");+ m.methods = mn_count_label(store, lp.project, "Method");+ m.types = mn_type_nodes(store, lp.project);+ m.calls = cbm_store_count_edges_by_type(store, lp.project, "CALLS");+ m.callers = mn_callables_with_outbound(store, lp.project);+ m.inherits = cbm_store_count_edges_by_type(store, lp.project, "INHERITS");+ m.implements = cbm_store_count_edges_by_type(store, lp.project, "IMPLEMENTS");+ m.defines_method = cbm_store_count_edges_by_type(store, lp.project, "DEFINES_METHOD");+ }+ mn_cleanup(&lp, store);+ return m;+}++static MN_Metrics mn_metrics(const char *filename, const char *content) {+ MN_LangFile f = {filename, content};+ return mn_metrics_files(&f, 1);+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 1 — Type aliases / typedefs / `type X = ...`+ *+ * A type alias is not a callable; the pipeline must still produce at+ * least one Function/Class node for the surrounding definitions — and+ * ideally a Type node for the alias itself. The surrounding callable+ * must still get a CALLS edge if it calls another function.+ * ══════════════════════════════════════════════════════════════════ */++/* Go: type alias `type Meters = float64` — functions around it must appear. */+TEST(mn_type_alias_go) {+ MN_Metrics m = mn_metrics("unit.go",+ "package unit\n\n"+ "type Meters = float64\n"+ "type Seconds = float64\n\n"+ "func Speed(dist Meters, t Seconds) Meters { return dist / t }\n\n"+ "func Run() Meters { return Speed(100, 9.58) }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Go: named type `type UserID int` must produce Function nodes alongside it. */+TEST(mn_type_alias_go_named) {+ MN_Metrics m = mn_metrics("ids.go",+ "package ids\n\n"+ "type UserID int\n"+ "type OrderID int\n\n"+ "func NewUser(id UserID) UserID { return id }\n\n"+ "func NewOrder(id OrderID) OrderID { return id }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ /* Type alias may produce a Type/Class node or nothing; just check no crash. */+ PASS();+}++/* TypeScript: `type ID = string | number` — functions still created. */+TEST(mn_type_alias_ts) {+ MN_Metrics m = mn_metrics("alias.ts",+ "type ID = string | number;\n"+ "type Callback<T> = (err: Error | null, val: T) => void;\n\n"+ "function makeId(n: number): ID { return n % 2 === 0 ? n : String(n); }\n\n"+ "function formatId(id: ID): string { return `id:${id}`; }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ PASS();+}++/* Rust: `type Result<T> = std::result::Result<T, String>` — functions appear. */+TEST(mn_type_alias_rust) {+ MN_Metrics m = mn_metrics("alias.rs",+ "type Res<T> = Result<T, String>;\n\n"+ "fn parse(s: &str) -> Res<i32> {\n"+ " s.parse::<i32>().map_err(|e| e.to_string())\n"+ "}\n\n"+ "fn run() -> Res<i32> { parse(\"42\") }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* C: typedef — functions surrounding it must still appear. */+TEST(mn_type_alias_c_typedef) {+ MN_Metrics m = mn_metrics("vec.c",+ "typedef struct { float x; float y; } Vec2;\n"+ "typedef float Scalar;\n\n"+ "Scalar dot(Vec2 a, Vec2 b) { return a.x*b.x + a.y*b.y; }\n\n"+ "Scalar magnitude(Vec2 v) { return dot(v, v); }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* C++: `using Seconds = double` — functions appear, alias does not crash. */+TEST(mn_type_alias_cpp_using) {+ MN_Metrics m = mn_metrics("time.cpp",+ "using Seconds = double;\n"+ "using Minutes = double;\n\n"+ "Seconds toSec(Minutes m) { return m * 60.0; }\n\n"+ "Minutes toMin(Seconds s) { return s / 60.0; }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ ASSERT_TRUE(m.calls >= 0); /* cross-call between them is optional */+ PASS();+}++/* Kotlin: `typealias Handler = (String) -> Unit` — functions appear. */+TEST(mn_type_alias_kotlin) {+ MN_Metrics m = mn_metrics("handler.kt",+ "typealias Handler = (String) -> Unit\n"+ "typealias Predicate = (Int) -> Boolean\n\n"+ "fun dispatch(h: Handler, msg: String) = h(msg)\n\n"+ "fun filter(pred: Predicate, n: Int): Boolean = pred(n)\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ PASS();+}++/* Python: `TypeAlias` annotation (PEP 613) — functions must appear. */+TEST(mn_type_alias_python) {+ MN_Metrics m = mn_metrics("types.py",+ "from typing import TypeAlias\n\n"+ "Vector: TypeAlias = list[float]\n"+ "Matrix: TypeAlias = list[list[float]]\n\n\n"+ "def dot(a: Vector, b: Vector) -> float:\n"+ " return sum(x * y for x, y in zip(a, b))\n\n\n"+ "def norm(v: Vector) -> float:\n"+ " return dot(v, v) ** 0.5\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 2 — Exception / error class hierarchies+ *+ * When an exception class `extends` a standard error base, the pipeline+ * should emit an INHERITS edge (same rules as any class inheritance).+ * RED if the base is not in the registry (std lib class not indexed).+ *+ * Note: Python `class X(Exception):` has a known extraction bug where+ * base_classes stores "(Exception)" with parens → INHERITS edge RED.+ * Java `extends Exception` works per existing contract; we probe a+ * deeper chain and multiple exception types.+ * ══════════════════════════════════════════════════════════════════ */++/* Java: multi-level exception hierarchy in one file → INHERITS edges. */+TEST(mn_exception_hierarchy_java) {+ static const MN_LangFile f[] = {{"Exc.java",+ "package app;\n\n"+ "class AppException extends RuntimeException {\n"+ " AppException(String msg) { super(msg); }\n"+ "}\n\n"+ "class ValidationException extends AppException {\n"+ " ValidationException(String field) { super(\"invalid: \" + field); }\n"+ "}\n\n"+ "class NotFoundException extends AppException {\n"+ " NotFoundException(String id) { super(\"not found: \" + id); }\n"+ "}\n\n"+ "class Service {\n"+ " void check(String s) throws ValidationException {\n"+ " if (s == null) throw new ValidationException(\"s\");\n"+ " }\n"+ "}\n"}};+ MN_Metrics m = mn_metrics_files(f, 1);+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 3); /* AppException, ValidationException, NotFoundException */+ /* ValidationException->AppException + NotFoundException->AppException must resolve+ * (both sides in registry). AppException->RuntimeException may not resolve (stdlib+ * class not indexed) — floor=1 ensures at least same-file chain is captured. */+ ASSERT_TRUE(m.inherits >= 1);+ PASS();+}++/* Python: exception subclass hierarchy — KNOWN RED: base_classes stored with parens.+ * BUG: extract_defs.c captures "(ValueError)" not "ValueError" for Python base names.+ * This test reproduces the bug: types are created but INHERITS edge is not produced. */+TEST(mn_exception_hierarchy_python) {+ MN_Metrics m = mn_metrics("exc.py",+ "class AppError(Exception):\n"+ " pass\n\n\n"+ "class ValidationError(AppError):\n"+ " def __init__(self, field):\n"+ " super().__init__(f'invalid: {field}')\n\n\n"+ "class NotFoundError(AppError):\n"+ " def __init__(self, key):\n"+ " super().__init__(f'not found: {key}')\n\n\n"+ "def check(s):\n"+ " if s is None:\n"+ " raise ValidationError('s')\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 2); /* AppError, ValidationError, NotFoundError */+ /* EXPECTED RED — Python base_classes extraction bug (parens in name) prevents+ * resolver from matching "ValidationError"->"AppError". Keep until fixed. */+ ASSERT_TRUE(m.inherits >= 1);+ PASS();+}++/* C#: exception hierarchy — INHERITS edges for same-file chain. */+TEST(mn_exception_hierarchy_csharp) {+ MN_Metrics m = mn_metrics("Exc.cs",+ "namespace App {\n"+ " class AppException : System.Exception {\n"+ " public AppException(string msg) : base(msg) {}\n"+ " }\n\n"+ " class DbException : AppException {\n"+ " public DbException(string q) : base(\"db: \" + q) {}\n"+ " }\n\n"+ " class Repo {\n"+ " public void Query(string q) {\n"+ " if (q == null) throw new DbException(q);\n"+ " }\n"+ " }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 2); /* AppException, DbException, Repo */+ /* DbException->AppException must resolve (both same-file). */+ ASSERT_TRUE(m.inherits >= 1);+ PASS();+}++/* Kotlin: exception class hierarchy — KNOWN RED: Kotlin `:` supertype not parsed. */+TEST(mn_exception_hierarchy_kotlin) {+ MN_Metrics m = mn_metrics("Exc.kt",+ "class AppException(msg: String) : Exception(msg)\n\n"+ "class ApiException(code: Int, msg: String) : AppException(\"[$code] $msg\")\n\n"+ "fun check(code: Int) {\n"+ " if (code != 200) throw ApiException(code, \"err\")\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1); /* AppException, ApiException */+ /* REAL BUG: Kotlin `class X : Base(...)` supertype after the `:` is not+ * parsed into base_classes, so ApiException->AppException INHERITS is never+ * emitted → inherits=0. Root cause: Kotlin supertype_list extraction.+ * [KNOWN class 1] */+ ASSERT_TRUE(m.inherits >= 1);+ PASS();+}++/* C++: exception class hierarchy via `std::exception`. */+TEST(mn_exception_hierarchy_cpp) {+ MN_Metrics m = mn_metrics("exc.cpp",+ "#include <stdexcept>\n"+ "#include <string>\n\n"+ "class AppError : public std::runtime_error {\n"+ "public:\n"+ " explicit AppError(const std::string &msg) : std::runtime_error(msg) {}\n"+ "};\n\n"+ "class DbError : public AppError {\n"+ "public:\n"+ " explicit DbError(const std::string &q) : AppError(\"db: \" + q) {}\n"+ "};\n\n"+ "void check(const std::string &q) {\n"+ " if (q.empty()) throw DbError(q);\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1); /* AppError, DbError */+ /* DbError->AppError must resolve same-file. */+ ASSERT_TRUE(m.inherits >= 1);+ PASS();+}++/* TypeScript: error class hierarchy — KNOWN RED: TS extends extraction broken. */+TEST(mn_exception_hierarchy_ts) {+ MN_Metrics m = mn_metrics("err.ts",+ "class AppError extends Error {\n"+ " constructor(public code: number, msg: string) { super(msg); }\n"+ "}\n\n"+ "class NotFoundError extends AppError {\n"+ " constructor(id: string) { super(404, `not found: ${id}`); }\n"+ "}\n\n"+ "function lookup(id: string): number {\n"+ " if (id === '') throw new NotFoundError(id);\n"+ " return 42;\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ /* REAL BUG: TypeScript `class X extends Base` stores the `extends` keyword (or+ * fails) instead of the base class name, so NotFoundError->AppError INHERITS+ * is never emitted → inherits=0. Root cause: TS extends_clause base-name+ * extraction. [KNOWN class 1] */+ ASSERT_TRUE(m.inherits >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 3 — Multiple inheritance / mixins / multiple interfaces+ *+ * Asserts that MULTIPLE INHERITS edges are produced when a class+ * declares multiple bases (Python, C++) or multiple interface+ * implementations (Java, C#, TypeScript).+ * ══════════════════════════════════════════════════════════════════ */++/* Python: multiple bases `class C(A, B):` — should produce 2+ INHERITS edges.+ * KNOWN RED: Python extraction bug with parens in base_classes. */+TEST(mn_multiple_inheritance_python) {+ MN_Metrics m = mn_metrics("multi.py",+ "class Flyable:\n"+ " def fly(self):\n"+ " return 'fly'\n\n\n"+ "class Swimmable:\n"+ " def swim(self):\n"+ " return 'swim'\n\n\n"+ "class Duck(Flyable, Swimmable):\n"+ " def quack(self):\n"+ " return self.fly() + self.swim()\n\n\n"+ "def make_duck():\n"+ " return Duck()\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 2); /* Flyable, Swimmable, Duck */+ /* EXPECTED RED — Python base extraction still embeds parens; registry miss.+ * Fix: strip parens in extract_defs.c Python base_classes extraction. */+ ASSERT_TRUE(m.inherits >= 2);+ PASS();+}++/* C++: multiple inheritance — 2 INHERITS edges expected for same-file. */+TEST(mn_multiple_inheritance_cpp) {+ MN_Metrics m = mn_metrics("multi.cpp",+ "class Flyable { public: virtual void fly() {} };\n"+ "class Swimmable { public: virtual void swim() {} };\n\n"+ "class Duck : public Flyable, public Swimmable {\n"+ "public:\n"+ " void fly() override {}\n"+ " void swim() override {}\n"+ " void quack() {}\n"+ "};\n\n"+ "void run() {\n"+ " Duck d;\n"+ " d.fly();\n"+ " d.swim();\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 2); /* Flyable, Swimmable, Duck */+ ASSERT_TRUE(m.inherits >= 2); /* Duck->Flyable + Duck->Swimmable */+ PASS();+}++/* Java: multiple `implements` — should produce IMPLEMENTS (not INHERITS) edges. */+TEST(mn_multiple_interfaces_java) {+ static const MN_LangFile f[] = {{"Multi.java",+ "package app;\n\n"+ "interface Flyable { void fly(); }\n"+ "interface Swimmable { void swim(); }\n\n"+ "class Duck implements Flyable, Swimmable {\n"+ " public void fly() { System.out.println(\"fly\"); }\n"+ " public void swim() { System.out.println(\"swim\"); }\n"+ " public void quack() { fly(); swim(); }\n"+ "}\n"}};+ MN_Metrics m = mn_metrics_files(f, 1);+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 2); /* Flyable, Swimmable, Duck */+ /* Java: both implements → IMPLEMENTS edges (pipeline distinguishes).+ * Floor=1 because implementation may use INHERITS for all bases. */+ ASSERT_TRUE(m.implements + m.inherits >= 1);+ PASS();+}++/* C#: class implementing multiple interfaces. */+TEST(mn_multiple_interfaces_csharp) {+ MN_Metrics m = mn_metrics("Multi.cs",+ "namespace App {\n"+ " interface IFlyable { void Fly(); }\n"+ " interface ISwimmable { void Swim(); }\n\n"+ " class Duck : IFlyable, ISwimmable {\n"+ " public void Fly() { }\n"+ " public void Swim() { }\n"+ " public void Quack() { Fly(); Swim(); }\n"+ " }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 2);+ ASSERT_TRUE(m.implements + m.inherits >= 1);+ PASS();+}++/* TypeScript: implements multiple interfaces — KNOWN RED: TS extraction broken. */+TEST(mn_multiple_interfaces_ts) {+ MN_Metrics m = mn_metrics("Multi.ts",+ "interface Flyable { fly(): string; }\n"+ "interface Swimmable { swim(): string; }\n\n"+ "class Duck implements Flyable, Swimmable {\n"+ " fly(): string { return 'fly'; }\n"+ " swim(): string { return 'swim'; }\n"+ " quack(): string { return this.fly() + this.swim(); }\n"+ "}\n\n"+ "function run(): string { return new Duck().quack(); }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ /* REAL BUG: TypeScript `class Duck implements Flyable, Swimmable` — the+ * implements_clause base names are not extracted, so no IMPLEMENTS/INHERITS+ * edge is emitted → 0. Root cause: TS implements_clause base-name extraction.+ * [KNOWN class 1] */+ ASSERT_TRUE(m.implements + m.inherits >= 1);+ PASS();+}++/* Rust: multiple trait bounds on a generic function — traits are types, not INHERITS.+ * Checks that the function node is created even with complex trait bounds. */+TEST(mn_multiple_trait_bounds_rust) {+ MN_Metrics m = mn_metrics("bounds.rs",+ "use std::fmt::{Debug, Display};\n\n"+ "fn print_both<T: Debug + Display>(val: T) {\n"+ " println!(\"{:?} {}\", val, val);\n"+ "}\n\n"+ "fn run() {\n"+ " print_both(42);\n"+ " print_both(\"hello\");\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Kotlin: class implementing multiple interfaces — KNOWN RED: `:` not parsed. */+TEST(mn_multiple_interfaces_kotlin) {+ MN_Metrics m = mn_metrics("Multi.kt",+ "interface Flyable { fun fly(): String }\n"+ "interface Swimmable { fun swim(): String }\n\n"+ "class Duck : Flyable, Swimmable {\n"+ " override fun fly() = \"fly\"\n"+ " override fun swim() = \"swim\"\n"+ " fun quack() = fly() + swim()\n"+ "}\n\n"+ "fun run() = Duck().quack()\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 2);+ /* REAL BUG: Kotlin `class Duck : Flyable, Swimmable` — supertype list after+ * `:` is not parsed into base_classes, so no IMPLEMENTS/INHERITS edge is+ * emitted → 0. Root cause: Kotlin supertype_list extraction (same root cause+ * as mn_exception_hierarchy_kotlin). [KNOWN class 1] */+ ASSERT_TRUE(m.implements + m.inherits >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 4 — Extension methods / receiver functions+ *+ * Checks that methods defined outside a class but associated to it+ * (Kotlin extension fun, Go method on named type, Rust impl on struct,+ * C# extension method, Swift extension) are still extracted as Method+ * or Function nodes that can produce CALLS edges.+ * ══════════════════════════════════════════════════════════════════ */++/* Kotlin: extension function on a standard type — should be a Function node. */+TEST(mn_extension_kotlin) {+ MN_Metrics m = mn_metrics("ext.kt",+ "fun String.titleCase(): String =\n"+ " split(\" \").joinToString(\" \") { it.capitalize() }\n\n"+ "fun String.wordCount(): Int = trim().split(\"\\\\s+\".toRegex()).size\n\n"+ "fun processTitle(s: String): String = s.titleCase()\n\n"+ "fun run(): Int = \"hello world\".wordCount()\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ PASS();+}++/* Go: method on a named type in the same file — must produce Method node. */+TEST(mn_extension_go_receiver) {+ MN_Metrics m = mn_metrics("stack.go",+ "package ds\n\n"+ "type Stack []int\n\n"+ "func (s *Stack) Push(v int) { *s = append(*s, v) }\n\n"+ "func (s Stack) Peek() int {\n"+ " if len(s) == 0 { return -1 }\n"+ " return s[len(s)-1]\n"+ "}\n\n"+ "func (s Stack) Len() int { return len(s) }\n\n"+ "func NewStack() Stack { return Stack{} }\n");+ ASSERT_TRUE(m.ok);+ /* Push, Peek, Len are Methods; NewStack is a Function. */+ ASSERT_TRUE(m.functions + m.methods >= 3);+ PASS();+}++/* Rust: impl on a struct (external-style impl block) — Methods appear. */+TEST(mn_extension_rust_impl) {+ MN_Metrics m = mn_metrics("queue.rs",+ "pub struct Queue<T> {\n"+ " buf: std::collections::VecDeque<T>,\n"+ "}\n\n"+ "impl<T> Queue<T> {\n"+ " pub fn new() -> Self { Queue { buf: std::collections::VecDeque::new() } }\n"+ " pub fn enqueue(&mut self, item: T) { self.buf.push_back(item); }\n"+ " pub fn dequeue(&mut self) -> Option<T> { self.buf.pop_front() }\n"+ " pub fn len(&self) -> usize { self.buf.len() }\n"+ "}\n\n"+ "pub fn demo() {\n"+ " let mut q: Queue<i32> = Queue::new();\n"+ " q.enqueue(1);\n"+ " let _ = q.dequeue();\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions + m.methods >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* C#: extension method in a static class — must produce Method node. */+TEST(mn_extension_csharp) {+ MN_Metrics m = mn_metrics("Ext.cs",+ "namespace App {\n"+ " static class StringExtensions {\n"+ " public static string TitleCase(this string s) {\n"+ " if (string.IsNullOrEmpty(s)) return s;\n"+ " return char.ToUpper(s[0]) + s.Substring(1);\n"+ " }\n"+ " public static int WordCount(this string s) =>\n"+ " s.Trim().Split(' ').Length;\n"+ " }\n\n"+ " class Processor {\n"+ " public string Process(string s) => s.TitleCase();\n"+ " public int Count(string s) => s.WordCount();\n"+ " }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.methods >= 2);+ PASS();+}++/* Swift: extension on a struct adding a method — must produce Function/Method node. */+TEST(mn_extension_swift) {+ MN_Metrics m = mn_metrics("ext.swift",+ "struct Point {\n"+ " var x: Double\n"+ " var y: Double\n"+ "}\n\n"+ "extension Point {\n"+ " func magnitude() -> Double {\n"+ " return (x * x + y * y).squareRoot()\n"+ " }\n"+ " func scaled(by factor: Double) -> Point {\n"+ " return Point(x: x * factor, y: y * factor)\n"+ " }\n"+ "}\n\n"+ "func run() -> Double {\n"+ " let p = Point(x: 3.0, y: 4.0)\n"+ " return p.magnitude()\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 5 — Getters / setters / computed properties+ *+ * @property decorators (Python), get/set accessor blocks (C#, Kotlin,+ * TypeScript, Swift, Scala) should not prevent the class node or the+ * method nodes for other methods from appearing. CALLS from a method+ * that reads/writes a property-defined method should also resolve.+ * ══════════════════════════════════════════════════════════════════ */++/* Python: @property getter + setter — class must appear, methods present. */+TEST(mn_getset_python_property) {+ MN_Metrics m = mn_metrics("account.py",+ "class Account:\n"+ " def __init__(self, balance):\n"+ " self._balance = balance\n\n"+ " @property\n"+ " def balance(self):\n"+ " return self._balance\n\n"+ " @balance.setter\n"+ " def balance(self, value):\n"+ " if value < 0:\n"+ " raise ValueError('negative balance')\n"+ " self._balance = value\n\n"+ " def deposit(self, amount):\n"+ " self.balance = self.balance + amount\n\n\n"+ "def make_account(initial):\n"+ " return Account(initial)\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1); /* class Account */+ ASSERT_TRUE(m.functions >= 1); /* make_account */+ PASS();+}++/* C#: auto-property and computed property — class and methods. */+TEST(mn_getset_csharp) {+ MN_Metrics m = mn_metrics("Temp.cs",+ "namespace App {\n"+ " class Temperature {\n"+ " private double _celsius;\n"+ " public double Celsius {\n"+ " get => _celsius;\n"+ " set { if (value < -273.15) throw new System.ArgumentException(); _celsius = value; }\n"+ " }\n"+ " public double Fahrenheit {\n"+ " get => Celsius * 9.0 / 5.0 + 32;\n"+ " set => Celsius = (value - 32) * 5.0 / 9.0;\n"+ " }\n"+ " public bool IsBoiling() => Celsius >= 100;\n"+ " }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1); /* class Temperature */+ ASSERT_TRUE(m.methods >= 1); /* IsBoiling at minimum */+ PASS();+}++/* Kotlin: custom get/set on a property — class and methods must appear. */+TEST(mn_getset_kotlin) {+ MN_Metrics m = mn_metrics("Circle.kt",+ "class Circle(private var _radius: Double) {\n"+ " var radius: Double\n"+ " get() = _radius\n"+ " set(value) { if (value < 0) error(\"neg radius\"); _radius = value }\n\n"+ " val area: Double\n"+ " get() = Math.PI * _radius * _radius\n\n"+ " fun scale(factor: Double) {\n"+ " radius = _radius * factor\n"+ " }\n"+ "}\n\n"+ "fun run() = Circle(1.0).area\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1); /* class Circle */+ ASSERT_TRUE(m.functions >= 1);+ PASS();+}++/* TypeScript: getter/setter on a class — class node + method nodes. */+TEST(mn_getset_typescript) {+ MN_Metrics m = mn_metrics("Rect.ts",+ "class Rectangle {\n"+ " private _w: number;\n"+ " private _h: number;\n\n"+ " constructor(w: number, h: number) { this._w = w; this._h = h; }\n\n"+ " get width(): number { return this._w; }\n"+ " set width(v: number) { if (v < 0) throw new Error(); this._w = v; }\n"+ " get area(): number { return this._w * this._h; }\n\n"+ " scale(f: number): void { this.width = this._w * f; }\n"+ "}\n\n"+ "function run(): number { return new Rectangle(3, 4).area; }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions >= 1);+ PASS();+}++/* Swift: computed property in a struct — struct and functions must appear. */+TEST(mn_getset_swift) {+ MN_Metrics m = mn_metrics("rect.swift",+ "struct Rect {\n"+ " var width: Double\n"+ " var height: Double\n\n"+ " var area: Double { return width * height }\n"+ " var perimeter: Double { return 2 * (width + height) }\n"+ " var isSquare: Bool { return width == height }\n\n"+ " mutating func scale(by factor: Double) {\n"+ " width *= factor\n"+ " height *= factor\n"+ " }\n"+ "}\n\n"+ "func run() -> Double { return Rect(width: 3, height: 4).area }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 6 — Records / data classes / structs-with-derive+ *+ * Record types (Java record, Kotlin data class, C# record, Python+ * dataclass, Rust #[derive] struct, Scala case class) produce a+ * class/struct node. Methods on them must also appear.+ * ══════════════════════════════════════════════════════════════════ */++/* Java: record with a custom method. */+TEST(mn_record_java) {+ MN_Metrics m = mn_metrics("Point.java",+ "package app;\n\n"+ "record Point(double x, double y) {\n"+ " double distanceTo(Point other) {\n"+ " double dx = this.x - other.x;\n"+ " double dy = this.y - other.y;\n"+ " return Math.sqrt(dx * dx + dy * dy);\n"+ " }\n"+ " static Point origin() { return new Point(0, 0); }\n"+ "}\n\n"+ "class Geo {\n"+ " static double run() { return Point.origin().distanceTo(new Point(3, 4)); }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1); /* record Point, class Geo */+ ASSERT_TRUE(m.methods >= 1);+ PASS();+}++/* Kotlin: data class with custom methods and companion. */+TEST(mn_record_kotlin_data_class) {+ MN_Metrics m = mn_metrics("User.kt",+ "data class User(val name: String, val age: Int) {\n"+ " fun isAdult(): Boolean = age >= 18\n"+ " fun greet(): String = \"Hi, $name\"\n\n"+ " companion object {\n"+ " fun anon(): User = User(\"anon\", 0)\n"+ " }\n"+ "}\n\n"+ "fun run(): String = User.anon().greet()\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions + m.methods >= 2);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* C#: record type. */+TEST(mn_record_csharp) {+ MN_Metrics m = mn_metrics("Point.cs",+ "namespace App {\n"+ " record Point(double X, double Y) {\n"+ " public double DistanceTo(Point other) {\n"+ " double dx = X - other.X;\n"+ " double dy = Y - other.Y;\n"+ " return System.Math.Sqrt(dx*dx + dy*dy);\n"+ " }\n"+ " public static Point Origin() => new Point(0, 0);\n"+ " }\n\n"+ " class Geo {\n"+ " public static double Run() => Point.Origin().DistanceTo(new Point(3, 4));\n"+ " }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.methods >= 2);+ PASS();+}++/* Python: dataclass with post_init and method. */+TEST(mn_record_python_dataclass) {+ MN_Metrics m = mn_metrics("vec.py",+ "from dataclasses import dataclass\n"+ "import math\n\n\n"+ "@dataclass\n"+ "class Vector:\n"+ " x: float\n"+ " y: float\n\n"+ " def magnitude(self):\n"+ " return math.sqrt(self.x ** 2 + self.y ** 2)\n\n"+ " def dot(self, other):\n"+ " return self.x * other.x + self.y * other.y\n\n\n"+ "def unit(x, y):\n"+ " v = Vector(x, y)\n"+ " m = v.magnitude()\n"+ " return Vector(x / m, y / m)\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions >= 1);+ PASS();+}++/* Rust: struct with #[derive(Debug, Clone)] and impl methods. */+TEST(mn_record_rust_derive) {+ MN_Metrics m = mn_metrics("point.rs",+ "#[derive(Debug, Clone, PartialEq)]\n"+ "struct Point {\n"+ " x: f64,\n"+ " y: f64,\n"+ "}\n\n"+ "impl Point {\n"+ " fn new(x: f64, y: f64) -> Self { Point { x, y } }\n"+ " fn distance(&self, other: &Self) -> f64 {\n"+ " ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()\n"+ " }\n"+ " fn origin() -> Self { Self::new(0.0, 0.0) }\n"+ "}\n\n"+ "fn run() -> f64 {\n"+ " let a = Point::new(3.0, 0.0);\n"+ " a.distance(&Point::origin())\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions + m.methods >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Scala: case class with companion object. */+TEST(mn_record_scala_case_class) {+ MN_Metrics m = mn_metrics("user.scala",+ "case class User(name: String, age: Int) {\n"+ " def isAdult: Boolean = age >= 18\n"+ " def greet: String = s\"Hi, $name\"\n"+ "}\n\n"+ "object User {\n"+ " def anon: User = User(\"anon\", 0)\n"+ "}\n\n"+ "def run: String = User.anon.greet\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.functions + m.methods >= 2);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 7 — Default / named / variadic parameters+ *+ * The function node must still be created; calls to these functions+ * must still resolve to CALLS edges regardless of how arguments are+ * passed.+ * ══════════════════════════════════════════════════════════════════ */++/* Python: default arguments — function nodes + CALLS. */+TEST(mn_default_params_python) {+ MN_Metrics m = mn_metrics("greet.py",+ "def greet(name, prefix='Hello', suffix='!'):\n"+ " return f'{prefix}, {name}{suffix}'\n\n\n"+ "def farewell(name, msg='Goodbye'):\n"+ " return greet(name, prefix=msg)\n\n\n"+ "def run():\n"+ " return farewell('World')\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Go: variadic function — function node + call. */+TEST(mn_variadic_go) {+ MN_Metrics m = mn_metrics("sum.go",+ "package math\n\n"+ "func sum(vals ...int) int {\n"+ " total := 0\n"+ " for _, v := range vals { total += v }\n"+ " return total\n"+ "}\n\n"+ "func sumPair(a, b int) int { return sum(a, b) }\n\n"+ "func run() int { return sumPair(sum(1, 2, 3), 4) }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Rust: default via Option<T> pattern — function and call still resolve. */+TEST(mn_default_params_rust) {+ MN_Metrics m = mn_metrics("cfg.rs",+ "fn connect(host: &str, port: Option<u16>) -> String {\n"+ " let p = port.unwrap_or(8080);\n"+ " format!(\"{}:{}\", host, p)\n"+ "}\n\n"+ "fn default_connect(host: &str) -> String {\n"+ " connect(host, None)\n"+ "}\n\n"+ "fn run() -> String { default_connect(\"localhost\") }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Kotlin: default + named parameters — function nodes + CALLS. */+TEST(mn_named_params_kotlin) {+ MN_Metrics m = mn_metrics("fmt.kt",+ "fun format(value: Int, radix: Int = 10, prefix: String = \"\") =\n"+ " prefix + value.toString(radix)\n\n"+ "fun hexStr(n: Int) = format(n, radix = 16, prefix = \"0x\")\n\n"+ "fun run() = hexStr(255)\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* TypeScript: optional parameters with defaults — function nodes + CALLS. */+TEST(mn_default_params_ts) {+ MN_Metrics m = mn_metrics("log.ts",+ "function log(msg: string, level: string = 'info', ts: number = Date.now()): string {\n"+ " return `[${level}] ${ts}: ${msg}`;\n"+ "}\n\n"+ "function warn(msg: string): string { return log(msg, 'warn'); }\n\n"+ "function run(): string { return warn('something wrong'); }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* C: variadic function (stdarg) — function node must still appear. */+TEST(mn_variadic_c) {+ MN_Metrics m = mn_metrics("fmt.c",+ "#include <stdarg.h>\n"+ "#include <stdio.h>\n\n"+ "static int my_printf(const char *fmt, ...) {\n"+ " va_list ap;\n"+ " va_start(ap, fmt);\n"+ " int n = vprintf(fmt, ap);\n"+ " va_end(ap);\n"+ " return n;\n"+ "}\n\n"+ "int run(int x) { return my_printf(\"%d\", x); }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 8 — Pattern matching / destructuring+ *+ * Function calls made INSIDE match arms / switch expressions / when+ * blocks must still produce CALLS edges attributed to the containing+ * function (not the Module).+ * ══════════════════════════════════════════════════════════════════ */++/* Rust: match expression with function calls in arms. */+TEST(mn_pattern_match_rust) {+ MN_Metrics m = mn_metrics("msg.rs",+ "fn format_ok(v: i32) -> String { format!(\"ok:{}\", v) }\n"+ "fn format_err(e: &str) -> String { format!(\"err:{}\", e) }\n\n"+ "fn process(res: Result<i32, &str>) -> String {\n"+ " match res {\n"+ " Ok(v) => format_ok(v),\n"+ " Err(e) => format_err(e),\n"+ " }\n"+ "}\n\n"+ "fn run() -> String { process(Ok(42)) }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 4);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Python: structural pattern matching (match/case, Python 3.10+) — calls resolve. */+TEST(mn_pattern_match_python) {+ MN_Metrics m = mn_metrics("cmd.py",+ "def handle_quit():\n"+ " return 'quit'\n\n\n"+ "def handle_go(direction):\n"+ " return f'go {direction}'\n\n\n"+ "def handle_unknown(cmd):\n"+ " return f'unknown: {cmd}'\n\n\n"+ "def dispatch(command):\n"+ " match command:\n"+ " case 'quit':\n"+ " return handle_quit()\n"+ " case ('go', direction):\n"+ " return handle_go(direction)\n"+ " case _:\n"+ " return handle_unknown(command)\n\n\n"+ "def run():\n"+ " return dispatch('quit')\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 4);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Kotlin: when expression with function calls in branches. */+TEST(mn_pattern_match_kotlin) {+ MN_Metrics m = mn_metrics("eval.kt",+ "fun onNum(n: Int): String = \"num:$n\"\n"+ "fun onStr(s: String): String = \"str:$s\"\n"+ "fun onOther(): String = \"other\"\n\n"+ "fun eval(v: Any): String = when (v) {\n"+ " is Int -> onNum(v)\n"+ " is String -> onStr(v)\n"+ " else -> onOther()\n"+ "}\n\n"+ "fun run() = eval(42)\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 4);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* TypeScript: switch with calls in each case branch. */+TEST(mn_pattern_match_ts) {+ MN_Metrics m = mn_metrics("status.ts",+ "function handleOk(v: number): string { return `ok:${v}`; }\n"+ "function handleFail(e: string): string { return `fail:${e}`; }\n"+ "function handlePending(): string { return 'pending'; }\n\n"+ "function dispatch(tag: string, payload?: unknown): string {\n"+ " switch (tag) {\n"+ " case 'ok': return handleOk(payload as number);\n"+ " case 'fail': return handleFail(payload as string);\n"+ " default: return handlePending();\n"+ " }\n"+ "}\n\n"+ "function run(): string { return dispatch('ok', 42); }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 4);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Go: type switch with function calls in each case. */+TEST(mn_pattern_match_go) {+ MN_Metrics m = mn_metrics("switch.go",+ "package sw\n\n"+ "func handleInt(n int) string { return \"int\" }\n"+ "func handleStr(s string) string { return \"str\" }\n"+ "func handleOther() string { return \"other\" }\n\n"+ "func dispatch(v interface{}) string {\n"+ " switch x := v.(type) {\n"+ " case int:\n"+ " return handleInt(x)\n"+ " case string:\n"+ " return handleStr(x)\n"+ " default:\n"+ " _ = x\n"+ " return handleOther()\n"+ " }\n"+ "}\n\n"+ "func run() string { return dispatch(42) }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 4);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 9 — Nested / local / inner functions calling enclosing scope+ *+ * The outer function node must always appear; the inner (nested) call+ * from the outer function to another outer-scope function must still+ * produce a CALLS edge. Additionally, the inner function calling back+ * into the enclosing function's scope probes whether the pipeline+ * mis-attributes those calls to the Module node instead of the outer.+ * ══════════════════════════════════════════════════════════════════ */++/* Python: nested function returned as closure; outer calls inner. */+TEST(mn_nested_function_python) {+ MN_Metrics m = mn_metrics("clos.py",+ "def multiplier(factor):\n"+ " def inner(x):\n"+ " return x * factor\n"+ " return inner\n\n\n"+ "def apply(fn, val):\n"+ " return fn(val)\n\n\n"+ "def run():\n"+ " double = multiplier(2)\n"+ " return apply(double, 21)\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2); /* multiplier, apply, run (inner is nested) */+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Go: inner function literal calling outer parameter. */+TEST(mn_nested_function_go) {+ MN_Metrics m = mn_metrics("nest.go",+ "package nest\n\n"+ "func helper(x int) int { return x * 2 }\n\n"+ "func makeDoubler() func(int) int {\n"+ " return func(x int) int { return helper(x) }\n"+ "}\n\n"+ "func run(n int) int {\n"+ " f := makeDoubler()\n"+ " return f(n) + helper(n)\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2); /* helper, makeDoubler, run */+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Rust: nested closure calling outer free function. */+TEST(mn_nested_function_rust) {+ MN_Metrics m = mn_metrics("nest.rs",+ "fn double(x: i32) -> i32 { x * 2 }\n\n"+ "fn make_adder(base: i32) -> impl Fn(i32) -> i32 {\n"+ " move |x| double(x) + base\n"+ "}\n\n"+ "fn run() -> i32 {\n"+ " let add10 = make_adder(10);\n"+ " add10(double(5))\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* TypeScript: nested arrow functions + calls in outer. */+TEST(mn_nested_function_ts) {+ MN_Metrics m = mn_metrics("nest.ts",+ "function base(x: number): number { return x + 1; }\n\n"+ "function makeTransformer(offset: number): (n: number) => number {\n"+ " return (n: number) => base(n) + offset;\n"+ "}\n\n"+ "function run(): number {\n"+ " const t = makeTransformer(10);\n"+ " return t(base(5));\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* Java: inner (non-static) class with method calling outer. */+TEST(mn_nested_function_java) {+ MN_Metrics m = mn_metrics("Outer.java",+ "package app;\n\n"+ "class Outer {\n"+ " private int base;\n"+ " Outer(int b) { this.base = b; }\n\n"+ " private int double_(int x) { return x * 2; }\n\n"+ " class Inner {\n"+ " int compute(int x) { return double_(x) + base; }\n"+ " }\n\n"+ " int run(int n) { return new Inner().compute(n); }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.methods >= 2);+ PASS();+}++/* C: nested function (GCC extension) — outer function must still be a node. */+TEST(mn_nested_function_c) {+ /* C doesn't have nested functions in the standard; use a helper+closure+ * pattern that any C grammar parses without extensions. */+ MN_Metrics m = mn_metrics("nest.c",+ "static int scale(int x, int factor) { return x * factor; }\n\n"+ "static int apply_double(int x) { return scale(x, 2); }\n\n"+ "static int apply_triple(int x) { return scale(x, 3); }\n\n"+ "int run(int n) {\n"+ " return apply_double(n) + apply_triple(n);\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 4);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * FAMILY 10 — Module / namespace nesting+ *+ * Namespaced constructs (TS namespace, C++ namespace, C# namespace,+ * Rust mod, Python package, Java package, PHP namespace) must yield+ * at least one Module/Package/Class node, and any functions/classes+ * inside them must still appear. CALLS edges inside a namespace+ * must still be attributed to the right callable.+ * ══════════════════════════════════════════════════════════════════ */++/* TypeScript: nested namespace with class and function. */+TEST(mn_module_ts_namespace) {+ MN_Metrics m = mn_metrics("ns.ts",+ "namespace App {\n"+ " export namespace Utils {\n"+ " export function clamp(v: number, lo: number, hi: number): number {\n"+ " return v < lo ? lo : v > hi ? hi : v;\n"+ " }\n"+ " export function normalise(v: number): number { return clamp(v, 0, 1); }\n"+ " }\n"+ " export class Config {\n"+ " threshold: number;\n"+ " constructor(t: number) { this.threshold = Utils.normalise(t); }\n"+ " }\n"+ "}\n\n"+ "function run(): number { return new App.Config(0.5).threshold; }\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2); /* clamp, normalise, run */+ ASSERT_TRUE(m.types >= 1); /* Config */+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* C++: namespace with nested classes and functions. */+TEST(mn_module_cpp_namespace) {+ MN_Metrics m = mn_metrics("ns.cpp",+ "namespace math {\n"+ "namespace detail {\n"+ " static double square(double x) { return x * x; }\n"+ "}\n\n"+ "double hypotenuse(double a, double b) {\n"+ " return detail::square(a) + detail::square(b);\n"+ "}\n"+ "}\n\n"+ "int main() {\n"+ " double h = math::hypotenuse(3.0, 4.0);\n"+ " return (int)h;\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 2);+ /* REAL BUG: every call here is namespace-scope-qualified with `::`+ * (detail::square, math::hypotenuse). Scope-qualified C++ calls are not+ * resolved — the C++ resolver/registry does not handle the `::` path+ * (it splits on '.', not '::'), so none of these resolve → calls=0. [KNOWN+ * class 6 — C++ scope-qualified Class/namespace::method() unresolved] */+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* C#: nested namespaces with classes. */+TEST(mn_module_csharp_namespace) {+ MN_Metrics m = mn_metrics("Ns.cs",+ "namespace App {\n"+ " namespace Util {\n"+ " class Formatter {\n"+ " public static string Format(int n) => $\"[{n}]\";\n"+ " }\n"+ " }\n"+ " namespace Domain {\n"+ " class Order {\n"+ " public int Id;\n"+ " public string Label() => Util.Formatter.Format(Id);\n"+ " }\n"+ " }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.methods >= 1);+ PASS();+}++/* Rust: nested mod blocks with pub fn. */+TEST(mn_module_rust_mod) {+ MN_Metrics m = mn_metrics("lib.rs",+ "mod math {\n"+ " pub fn square(x: i32) -> i32 { x * x }\n\n"+ " pub mod trig {\n"+ " pub fn approx_sin(x: f64) -> f64 { x - x*x*x/6.0 }\n"+ " pub fn approx_cos(x: f64) -> f64 { 1.0 - x*x/2.0 }\n"+ " }\n"+ "}\n\n"+ "pub fn run() -> i32 {\n"+ " math::square(4) + (math::trig::approx_sin(0.1) * 100.0) as i32\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.functions >= 3);+ PASS();+}++/* Python: package-level multi-file with __init__.py — module nodes and IMPORTS. */+TEST(mn_module_python_package) {+ static const MN_LangFile f[] = {+ {"pkg/__init__.py", "from .util import add\n"},+ {"pkg/util.py",+ "def add(a, b):\n return a + b\n\n\ndef sub(a, b):\n return a - b\n"},+ {"main.py",+ "from .pkg import add\n\n\ndef run():\n return add(1, 2)\n"}};+ MN_LangProj lp;+ cbm_store_t *store = mn_index_files(&lp, f, 3);+ int functions = store ? mn_count_label(store, lp.project, "Function") : 0;+ int imports = store ? cbm_store_count_edges_by_type(store, lp.project, "IMPORTS") : 0;+ int ok = (store != NULL);+ mn_cleanup(&lp, store);+ ASSERT_TRUE(ok);+ ASSERT_TRUE(functions >= 2); /* add, sub, run */+ ASSERT_TRUE(imports >= 1); /* at least the relative import resolves */+ PASS();+}++/* Java: multi-level package with class per file. */+TEST(mn_module_java_package) {+ static const MN_LangFile f[] = {+ {"com/example/util/Formatter.java",+ "package com.example.util;\n\n"+ "public class Formatter {\n"+ " public static String format(int n) { return \"[\" + n + \"]\"; }\n"+ "}\n"},+ {"com/example/domain/Order.java",+ "package com.example.domain;\n\n"+ "import com.example.util.Formatter;\n\n"+ "public class Order {\n"+ " public int id;\n"+ " public String label() { return Formatter.format(id); }\n"+ "}\n"}};+ MN_Metrics m = mn_metrics_files(f, 2);+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.methods >= 1);+ PASS();+}++/* PHP: namespace declaration and class. */+TEST(mn_module_php_namespace) {+ MN_Metrics m = mn_metrics("Calc.php",+ "<?php\n"+ "namespace App\\Util;\n\n"+ "class Calc {\n"+ " public function add(int $a, int $b): int {\n"+ " return $a + $b;\n"+ " }\n"+ " public function double(int $n): int {\n"+ " return $this->add($n, $n);\n"+ " }\n"+ "}\n");+ ASSERT_TRUE(m.ok);+ ASSERT_TRUE(m.types >= 1);+ ASSERT_TRUE(m.calls >= 1);+ PASS();+}++/* ══════════════════════════════════════════════════════════════════+ * SUITE registration+ * ══════════════════════════════════════════════════════════════════ */++SUITE(matrix_new_constructs) {+ /* Family 1: type aliases */+ printf("\n%s--- Family 1: type aliases ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_type_alias_go);+ RUN_TEST(mn_type_alias_go_named);+ RUN_TEST(mn_type_alias_ts);+ RUN_TEST(mn_type_alias_rust);+ RUN_TEST(mn_type_alias_c_typedef);+ RUN_TEST(mn_type_alias_cpp_using);+ RUN_TEST(mn_type_alias_kotlin);+ RUN_TEST(mn_type_alias_python);++ /* Family 2: exception hierarchies */+ printf("\n%s--- Family 2: exception hierarchies ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_exception_hierarchy_java);+ RUN_TEST(mn_exception_hierarchy_python);+ RUN_TEST(mn_exception_hierarchy_csharp);+ RUN_TEST(mn_exception_hierarchy_kotlin);+ RUN_TEST(mn_exception_hierarchy_cpp);+ RUN_TEST(mn_exception_hierarchy_ts);++ /* Family 3: multiple inheritance / mixins */+ printf("\n%s--- Family 3: multiple inheritance ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_multiple_inheritance_python);+ RUN_TEST(mn_multiple_inheritance_cpp);+ RUN_TEST(mn_multiple_interfaces_java);+ RUN_TEST(mn_multiple_interfaces_csharp);+ RUN_TEST(mn_multiple_interfaces_ts);+ RUN_TEST(mn_multiple_trait_bounds_rust);+ RUN_TEST(mn_multiple_interfaces_kotlin);++ /* Family 4: extension methods */+ printf("\n%s--- Family 4: extension methods ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_extension_kotlin);+ RUN_TEST(mn_extension_go_receiver);+ RUN_TEST(mn_extension_rust_impl);+ RUN_TEST(mn_extension_csharp);+ RUN_TEST(mn_extension_swift);++ /* Family 5: getters / setters */+ printf("\n%s--- Family 5: getters/setters ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_getset_python_property);+ RUN_TEST(mn_getset_csharp);+ RUN_TEST(mn_getset_kotlin);+ RUN_TEST(mn_getset_typescript);+ RUN_TEST(mn_getset_swift);++ /* Family 6: records / data classes */+ printf("\n%s--- Family 6: records/data classes ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_record_java);+ RUN_TEST(mn_record_kotlin_data_class);+ RUN_TEST(mn_record_csharp);+ RUN_TEST(mn_record_python_dataclass);+ RUN_TEST(mn_record_rust_derive);+ RUN_TEST(mn_record_scala_case_class);++ /* Family 7: default / variadic parameters */+ printf("\n%s--- Family 7: default/variadic params ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_default_params_python);+ RUN_TEST(mn_variadic_go);+ RUN_TEST(mn_default_params_rust);+ RUN_TEST(mn_named_params_kotlin);+ RUN_TEST(mn_default_params_ts);+ RUN_TEST(mn_variadic_c);++ /* Family 8: pattern matching */+ printf("\n%s--- Family 8: pattern matching ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_pattern_match_rust);+ RUN_TEST(mn_pattern_match_python);+ RUN_TEST(mn_pattern_match_kotlin);+ RUN_TEST(mn_pattern_match_ts);+ RUN_TEST(mn_pattern_match_go);++ /* Family 9: nested functions */+ printf("\n%s--- Family 9: nested/local functions ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_nested_function_python);+ RUN_TEST(mn_nested_function_go);+ RUN_TEST(mn_nested_function_rust);+ RUN_TEST(mn_nested_function_ts);+ RUN_TEST(mn_nested_function_java);+ RUN_TEST(mn_nested_function_c);++ /* Family 10: module/namespace nesting */+ printf("\n%s--- Family 10: modules/namespaces ---%s\n", "\033[90m", "\033[0m");+ RUN_TEST(mn_module_ts_namespace);+ RUN_TEST(mn_module_cpp_namespace);+ RUN_TEST(mn_module_csharp_namespace);+ RUN_TEST(mn_module_rust_mod);+ RUN_TEST(mn_module_python_package);+ RUN_TEST(mn_module_java_package);+ RUN_TEST(mn_module_php_namespace);+}