Skip to content

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.

Add language-agnostic extraction reproduction suite (inheritance + imports)

Martin Vogel857432b33d42
diff --git a/Makefile.cbm b/Makefile.cbm
index 763895e7a..a15731559 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -275,6 +275,8 @@ TEST_FOUNDATION_SRCS = \
TEST_EXTRACTION_SRCS = \
tests/test_extraction.c \
+ tests/test_extraction_inheritance.c \
+ tests/test_extraction_imports.c \
tests/test_grammar_regression.c \
tests/test_grammar_labels.c \
tests/test_grammar_imports.c \
diff --git a/tests/test_extraction_imports.c b/tests/test_extraction_imports.c
new file mode 100644
index 000000000..a9e0eb79f
--- /dev/null
+++ b/tests/test_extraction_imports.c
@@ -0,0 +1,1297 @@
+/*
+ * test_extraction_imports.c — Comprehensive, language-agnostic, table-driven
+ * reproduction suite for IMPORT extraction across the 9 hybrid-LSP languages.
+ *
+ * REPRODUCE-FIRST suite: written BEFORE any fixes so that RED rows prove the
+ * bug is real and GREEN rows serve as regression guards.
+ *
+ * ── Graph-level symptom (from bench run 2026-06) ────────────────────────────
+ * Language import keyword graph IMPORTS edges status
+ * --------- ---------------- -------------------- --------------------------
+ * Rust use 2168 uses → 0 edges BUG
+ * Kotlin import 6110 imports → ~0 BUG
+ * PHP use 5787 uses → 1 edge BUG
+ * Java import many → 0 edges BUG
+ * C# using many → 0 edges BUG
+ * Python import/from working OK
+ * TypeScript import working OK
+ * Go import working OK
+ * JavaScript import/require working OK
+ *
+ * ── What this file tests ────────────────────────────────────────────────────
+ * We test the EXTRACTION layer only: does cbm_extract_file() populate
+ * r->imports correctly for each syntactic form? NOT whether the graph
+ * pipeline creates IMPORTS edges (that is downstream).
+ *
+ * ── Reading the existing tests for attribution ───────────────────────────────
+ * tests/test_extraction.c already has:
+ * rust_imports — asserts r->imports.count > 0 AND has_import(r,"std::collections::HashMap")
+ * java_imports — asserts r->imports.count > 0 AND has_import(r,"java.util.List")
+ * go_imports — asserts r->imports.count > 0 AND has_import(r,"fmt")
+ * python_imports— asserts r->imports.count > 0
+ * js_imports — asserts r->imports.count > 0
+ * c_imports — asserts r->imports.count > 0 AND has_import(r,"stdio.h")
+ *
+ * Those existing tests PASS today (extraction works for rust/java at the
+ * basic level). Therefore the zero-edge bug for Rust, Java, Kotlin, PHP,
+ * C# is likely DOWNSTREAM (edge-creation / resolution pipeline), NOT
+ * extraction. However, this file tests finer extraction contracts—aliased,
+ * grouped, wildcard, relative, namespaced forms—which may surface additional
+ * extraction-level gaps, particularly for Kotlin, PHP, and C# whose parsers
+ * use `parse_generic_imports` / `parse_kotlin_imports` with less-tested paths.
+ *
+ * ── Expected RED vs GREEN per language ──────────────────────────────────────
+ * Language Extraction expected Reasoning
+ * --------- -------------------- ------------------------------------------
+ * Go GREEN (all) dedicated parse_go_imports; stress test passes
+ * Python GREEN (all) process_py_import_stmt/from; existing tests pass
+ * TypeScript GREEN (all) process_es_import_statement; existing tests pass
+ * JavaScript GREEN (all) walk_es_imports + CommonJS; existing tests pass
+ * Rust GREEN (basic) parse_rust_imports strips "use "/";" text-based;
+ * grouped/aliased forms may RED (whole-node text
+ * including braces is used as module_path)
+ * Java GREEN (basic) parse_java_imports scoped_identifier; existing
+ * test asserts java.util.List → GREEN; static-
+ * import and wildcard may differ in format
+ * Kotlin LIKELY GREEN (basic) parse_kotlin_imports → extract_one_import_header
+ * → generic_import_from_text strips "import "/";";
+ * aliased form ("as X") remains in module_path text
+ * PHP UNCERTAIN CBM_LANG_PHP → parse_generic_imports("expression_
+ * statement") — PHP "use" is a namespace_use_clause,
+ * NOT an expression_statement; so "use Foo\Bar" likely
+ * yields 0 imports → expected RED
+ * C# UNCERTAIN CBM_LANG_CSHARP → parse_generic_imports("using_directive")
+ * → generic_import_from_text strips "using "/";";
+ * basic form should work → expected GREEN (basic);
+ * alias form "using F = Foo.Bar" may include "= Foo.Bar"
+ * in path → possibly RED for alias target matching
+ *
+ * IMPORTANT: A test that FAILS means extraction is broken at the C level.
+ * A test that PASSES means extraction is correct; the zero-edges must be
+ * a downstream graph-pipeline bug (to be reproduced separately).
+ *
+ * ── Field names used ────────────────────────────────────────────────────────
+ * CBMImport.module_path — the full import/use path string
+ * CBMImport.local_name — last segment or alias name
+ * r->imports.count — number of extracted imports
+ * r->imports.items[i] — array of CBMImport
+ */
+
+#include "test_framework.h"
+#include "cbm.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+/* ── Helpers ──────────────────────────────────────────────────────────────── */
+
+/* Return 1 if any extracted import has module_path containing path_substr. */
+static int imp_has(CBMFileResult *r, const char *path_substr) {
+ for (int i = 0; i < r->imports.count; i++) {
+ if (r->imports.items[i].module_path &&
+ strstr(r->imports.items[i].module_path, path_substr) != NULL)
+ return 1;
+ }
+ return 0;
+}
+
+/* Return 1 if any extracted import has local_name equal to local. */
+static int imp_local(CBMFileResult *r, const char *local) {
+ for (int i = 0; i < r->imports.count; i++) {
+ if (r->imports.items[i].local_name &&
+ strcmp(r->imports.items[i].local_name, local) == 0)
+ return 1;
+ }
+ return 0;
+}
+
+/* Convenience extract wrapper. */
+static CBMFileResult *do_extract(const char *src, CBMLanguage lang,
+ const char *path) {
+ return cbm_extract_file(src, (int)strlen(src), lang, "testproj", path,
+ 0, NULL, NULL);
+}
+
+/*
+ * Table-driven case struct.
+ * expected[] is a NULL-terminated list of substrings that MUST each appear in
+ * some extracted import's module_path. min_count is the minimum number of
+ * imports the extractor must produce.
+ */
+typedef struct {
+ CBMLanguage lang;
+ const char *path; /* fake file path for language detection */
+ const char *src; /* source snippet */
+ const char *expected[16]; /* NULL-terminated substrings of module_path */
+ int min_count; /* r->imports.count must be >= this */
+ const char *label; /* human-readable case name for diagnostics */
+} import_case_t;
+
+/*
+ * Run one table entry; returns 0 on pass, 1 on failure.
+ * Prints a diagnostic line on failure so failures are self-describing.
+ */
+static int run_import_case(const import_case_t *tc) {
+ CBMFileResult *r = do_extract(tc->src, tc->lang, tc->path);
+ if (!r) {
+ printf(" FAIL [%s]: cbm_extract_file returned NULL\n", tc->label);
+ return 1;
+ }
+ if (r->has_error) {
+ printf(" FAIL [%s]: extractor reported error\n", tc->label);
+ cbm_free_result(r);
+ return 1;
+ }
+ int fail = 0;
+ if (r->imports.count < tc->min_count) {
+ printf(" FAIL [%s]: imports.count=%d want>=%d\n",
+ tc->label, r->imports.count, tc->min_count);
+ fail = 1;
+ }
+ for (int e = 0; tc->expected[e] != NULL; e++) {
+ if (!imp_has(r, tc->expected[e])) {
+ printf(" FAIL [%s]: no import with module_path containing \"%s\" "
+ "(count=%d)\n",
+ tc->label, tc->expected[e], r->imports.count);
+ fail = 1;
+ }
+ }
+ cbm_free_result(r);
+ return fail;
+}
+
+/* Run an array of cases; accumulate failures and return total. */
+static int run_cases(const import_case_t *cases, int n) {
+ int failures = 0;
+ for (int i = 0; i < n; i++) {
+ failures += run_import_case(&cases[i]);
+ }
+ return failures;
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Go — dedicated parse_go_imports, expected GREEN for all forms
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t go_cases[] = {
+ /* simple single-line */
+ { CBM_LANG_GO, "a.go",
+ "package main\nimport \"fmt\"\nfunc main() {}\n",
+ {"fmt", NULL}, 1, "go_simple" },
+
+ /* grouped import block */
+ { CBM_LANG_GO, "b.go",
+ "package main\nimport (\n \"os\"\n \"net/http\"\n \"io\"\n)\nfunc f() {}\n",
+ {"os", "net/http", "io", NULL}, 3, "go_grouped_block" },
+
+ /* aliased import */
+ { CBM_LANG_GO, "c.go",
+ "package main\nimport myfmt \"fmt\"\nfunc f() {}\n",
+ {"fmt", NULL}, 1, "go_aliased" },
+
+ /* blank import */
+ { CBM_LANG_GO, "d.go",
+ "package main\nimport _ \"database/sql/driver\"\nfunc f() {}\n",
+ {"database/sql/driver", NULL}, 1, "go_blank" },
+
+ /* dot import */
+ { CBM_LANG_GO, "e.go",
+ "package main\nimport . \"math\"\nfunc f() {}\n",
+ {"math", NULL}, 1, "go_dot" },
+
+ /* mixed aliases in block */
+ { CBM_LANG_GO, "f.go",
+ "package main\nimport (\n \"fmt\"\n h \"net/http\"\n _ \"unsafe\"\n)\nfunc f() {}\n",
+ {"fmt", "net/http", "unsafe", NULL}, 3, "go_mixed_block" },
+
+ /* multiple separate import declarations */
+ { CBM_LANG_GO, "g.go",
+ "package main\nimport \"sync\"\nimport \"sync/atomic\"\nfunc f() {}\n",
+ {"sync", "sync/atomic", NULL}, 2, "go_multiple_decls" },
+
+ /* subpackage path */
+ { CBM_LANG_GO, "h.go",
+ "package main\nimport \"google.golang.org/grpc/codes\"\nfunc f() {}\n",
+ {"google.golang.org/grpc/codes", NULL}, 1, "go_subpackage" },
+
+ /* stdlib + external + internal in block */
+ { CBM_LANG_GO, "i.go",
+ "package main\nimport (\n \"context\"\n \"github.com/pkg/errors\"\n "
+ "\"myapp/internal/config\"\n)\nfunc f() {}\n",
+ {"context", "github.com/pkg/errors", "myapp/internal/config", NULL}, 3,
+ "go_stdlib_ext_internal" },
+
+ /* deeply nested package */
+ { CBM_LANG_GO, "j.go",
+ "package main\nimport \"a/b/c/d/e/f\"\nfunc f() {}\n",
+ {"a/b/c/d/e/f", NULL}, 1, "go_deeply_nested" },
+
+ /* 10+ imports in one block */
+ { CBM_LANG_GO, "k.go",
+ "package main\nimport (\n \"bufio\"\n \"bytes\"\n \"errors\"\n \"fmt\"\n"
+ " \"io\"\n \"log\"\n \"math\"\n \"os\"\n \"path\"\n \"sort\"\n"
+ " \"strconv\"\n \"strings\"\n)\nfunc f() {}\n",
+ {"bufio", "bytes", "errors", "fmt", "io", "log", "math", "os", "path",
+ "sort", NULL}, 12, "go_many_imports" },
+};
+
+TEST(go_import_table) {
+ int failures = run_cases(go_cases, (int)(sizeof(go_cases)/sizeof(go_cases[0])));
+ if (failures > 0) {
+ printf(" %d go import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Python — process_py_import_stmt + process_py_import_from, expected GREEN
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t python_cases[] = {
+ /* simple import */
+ { CBM_LANG_PYTHON, "a.py",
+ "import os\n",
+ {"os", NULL}, 1, "py_simple" },
+
+ /* from-import */
+ { CBM_LANG_PYTHON, "b.py",
+ "from sys import argv\n",
+ {"sys", NULL}, 1, "py_from" },
+
+ /* from-import multiple */
+ { CBM_LANG_PYTHON, "c.py",
+ "from collections import defaultdict, OrderedDict\n",
+ {"collections", NULL}, 1, "py_from_multiple" },
+
+ /* aliased import */
+ { CBM_LANG_PYTHON, "d.py",
+ "import numpy as np\n",
+ {"numpy", NULL}, 1, "py_aliased" },
+
+ /* from-import with alias */
+ { CBM_LANG_PYTHON, "e.py",
+ "from pathlib import Path as P\n",
+ {"pathlib", NULL}, 1, "py_from_aliased" },
+
+ /* wildcard from-import */
+ { CBM_LANG_PYTHON, "f.py",
+ "from os.path import *\n",
+ {"os.path", NULL}, 1, "py_wildcard" },
+
+ /* relative import (single dot) */
+ { CBM_LANG_PYTHON, "g.py",
+ "from . import utils\n",
+ {NULL}, 1, "py_relative_dot" }, /* module_path may be "." — just count */
+
+ /* relative import with path */
+ { CBM_LANG_PYTHON, "h.py",
+ "from .models import User\n",
+ {"models", NULL}, 1, "py_relative_models" },
+
+ /* nested module */
+ { CBM_LANG_PYTHON, "i.py",
+ "import xml.etree.ElementTree as ET\n",
+ {"xml.etree.ElementTree", NULL}, 1, "py_nested_module" },
+
+ /* multiple top-level imports */
+ { CBM_LANG_PYTHON, "j.py",
+ "import os\nimport sys\nimport re\nfrom typing import List, Dict\n",
+ {"os", "sys", "re", "typing", NULL}, 4, "py_multi" },
+
+ /* stdlib + third-party */
+ { CBM_LANG_PYTHON, "k.py",
+ "import json\nfrom flask import Flask\nimport requests\n",
+ {"json", "flask", "requests", NULL}, 3, "py_stdlib_thirdparty" },
+
+ /* from __future__ import */
+ { CBM_LANG_PYTHON, "l.py",
+ "from __future__ import annotations\nimport os\n",
+ {"__future__", "os", NULL}, 2, "py_future" },
+
+ /* from-import with parentheses (multi-line) */
+ { CBM_LANG_PYTHON, "m.py",
+ "from typing import (\n List,\n Dict,\n Optional,\n)\n",
+ {"typing", NULL}, 1, "py_from_parens" },
+
+ /* deeply nested package */
+ { CBM_LANG_PYTHON, "n.py",
+ "from django.db.models.query import QuerySet\n",
+ {"django.db.models.query", NULL}, 1, "py_deep_nested" },
+
+ /* double-relative import */
+ { CBM_LANG_PYTHON, "o.py",
+ "from ..utils import helper\n",
+ {"utils", NULL}, 1, "py_double_relative" },
+};
+
+TEST(python_import_table) {
+ int failures = run_cases(python_cases, (int)(sizeof(python_cases)/sizeof(python_cases[0])));
+ if (failures > 0) {
+ printf(" %d python import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * TypeScript — walk_es_imports, expected GREEN for all forms
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t typescript_cases[] = {
+ /* default import */
+ { CBM_LANG_TYPESCRIPT, "a.ts",
+ "import React from 'react';\n",
+ {"react", NULL}, 1, "ts_default" },
+
+ /* named imports */
+ { CBM_LANG_TYPESCRIPT, "b.ts",
+ "import { useState, useEffect } from 'react';\n",
+ {"react", NULL}, 1, "ts_named" },
+
+ /* namespace import */
+ { CBM_LANG_TYPESCRIPT, "c.ts",
+ "import * as path from 'path';\n",
+ {"path", NULL}, 1, "ts_namespace" },
+
+ /* aliased named import */
+ { CBM_LANG_TYPESCRIPT, "d.ts",
+ "import { SomeType as ST } from './types';\n",
+ {"types", NULL}, 1, "ts_named_alias" },
+
+ /* side-effect-only import */
+ { CBM_LANG_TYPESCRIPT, "e.ts",
+ "import './polyfills';\n",
+ {"polyfills", NULL}, 1, "ts_side_effect" },
+
+ /* relative path */
+ { CBM_LANG_TYPESCRIPT, "f.ts",
+ "import { Config } from '../config';\n",
+ {"config", NULL}, 1, "ts_relative" },
+
+ /* deep relative path */
+ { CBM_LANG_TYPESCRIPT, "g.ts",
+ "import { helper } from '../../utils/helpers';\n",
+ {"helpers", NULL}, 1, "ts_deep_relative" },
+
+ /* mixed default + named */
+ { CBM_LANG_TYPESCRIPT, "h.ts",
+ "import React, { Component } from 'react';\n",
+ {"react", NULL}, 1, "ts_mixed_default_named" },
+
+ /* scoped package */
+ { CBM_LANG_TYPESCRIPT, "i.ts",
+ "import { Client } from '@anthropic-ai/sdk';\n",
+ {"@anthropic-ai/sdk", NULL}, 1, "ts_scoped_package" },
+
+ /* multiple imports */
+ { CBM_LANG_TYPESCRIPT, "j.ts",
+ "import path from 'path';\nimport fs from 'fs';\nimport { EventEmitter } from 'events';\n",
+ {"path", "fs", "events", NULL}, 3, "ts_multiple" },
+
+ /* TSX component file — uses CBM_LANG_TSX */
+ { CBM_LANG_TSX, "k.tsx",
+ "import React from 'react';\nimport { Button } from './Button';\n",
+ {"react", "Button", NULL}, 2, "tsx_component" },
+
+ /* type-only import (TS 3.8+) */
+ { CBM_LANG_TYPESCRIPT, "l.ts",
+ "import type { User } from './models';\n",
+ {"models", NULL}, 1, "ts_type_only" },
+
+ /* re-export style import */
+ { CBM_LANG_TYPESCRIPT, "m.ts",
+ "import { foo } from './a';\nimport { bar } from './b';\nimport { baz } from './c';\n",
+ {"a", "b", "c", NULL}, 3, "ts_re_export" },
+
+ /* package with subpath */
+ { CBM_LANG_TYPESCRIPT, "n.ts",
+ "import { format } from 'date-fns/format';\n",
+ {"date-fns/format", NULL}, 1, "ts_subpath" },
+
+ /* dynamic import (inside function — CommonJS-like) — may not be extracted */
+ { CBM_LANG_TYPESCRIPT, "o.ts",
+ "import { readFileSync } from 'fs';\nconst data = readFileSync('./data.json');\n",
+ {"fs", NULL}, 1, "ts_fs_readfile" },
+};
+
+TEST(typescript_import_table) {
+ int failures = run_cases(typescript_cases, (int)(sizeof(typescript_cases)/sizeof(typescript_cases[0])));
+ if (failures > 0) {
+ printf(" %d typescript import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * JavaScript — walk_es_imports + CommonJS require, expected GREEN
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t javascript_cases[] = {
+ /* ES default */
+ { CBM_LANG_JAVASCRIPT, "a.js",
+ "import React from 'react';\n",
+ {"react", NULL}, 1, "js_es_default" },
+
+ /* ES named */
+ { CBM_LANG_JAVASCRIPT, "b.js",
+ "import { map, filter } from 'lodash';\n",
+ {"lodash", NULL}, 1, "js_es_named" },
+
+ /* CommonJS require */
+ { CBM_LANG_JAVASCRIPT, "c.js",
+ "const fs = require('fs');\n",
+ {"fs", NULL}, 1, "js_cjs_require" },
+
+ /* CommonJS destructured require */
+ { CBM_LANG_JAVASCRIPT, "d.js",
+ "const { join } = require('path');\n",
+ {"path", NULL}, 1, "js_cjs_destructure" },
+
+ /* ES namespace */
+ { CBM_LANG_JAVASCRIPT, "e.js",
+ "import * as utils from './utils';\n",
+ {"utils", NULL}, 1, "js_es_namespace" },
+
+ /* relative require */
+ { CBM_LANG_JAVASCRIPT, "f.js",
+ "const helper = require('./helper');\n",
+ {"helper", NULL}, 1, "js_cjs_relative" },
+
+ /* scoped package require */
+ { CBM_LANG_JAVASCRIPT, "g.js",
+ "const { Schema } = require('@hapi/joi');\n",
+ {"@hapi/joi", NULL}, 1, "js_cjs_scoped" },
+
+ /* mixed ES + CJS */
+ { CBM_LANG_JAVASCRIPT, "h.js",
+ "import express from 'express';\nconst path = require('path');\n",
+ {"express", "path", NULL}, 2, "js_mixed_es_cjs" },
+
+ /* side-effect import */
+ { CBM_LANG_JAVASCRIPT, "i.js",
+ "import './styles.css';\n",
+ {"styles.css", NULL}, 1, "js_side_effect" },
+
+ /* multiple CJS */
+ { CBM_LANG_JAVASCRIPT, "j.js",
+ "const a = require('a');\nconst b = require('b');\nconst c = require('c');\n",
+ {"a", "b", "c", NULL}, 3, "js_cjs_multiple" },
+
+ /* named alias import */
+ { CBM_LANG_JAVASCRIPT, "k.js",
+ "import { default as D } from 'somelib';\n",
+ {"somelib", NULL}, 1, "js_named_alias" },
+};
+
+TEST(javascript_import_table) {
+ int failures = run_cases(javascript_cases, (int)(sizeof(javascript_cases)/sizeof(javascript_cases[0])));
+ if (failures > 0) {
+ printf(" %d javascript import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Rust — parse_rust_imports (text-based: strips "use "/";" from whole node).
+ *
+ * EXPECTED: basic and namespaced forms GREEN; grouped/braced forms may be RED
+ * because the whole `use std::io::{self, Write};` text becomes the module_path,
+ * so has_import("std::io") would still match as a substring — likely GREEN even
+ * for grouped. The alias form `use X as Y;` leaves "std::collections::HashMap as H"
+ * as module_path — has_import("std::collections::HashMap") would still match.
+ * So most forms should be GREEN at extraction. Graph-level zero edges are
+ * downstream.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t rust_cases[] = {
+ /* simple use */
+ { CBM_LANG_RUST, "a.rs",
+ "use std::collections::HashMap;\nfn main() {}\n",
+ {"std::collections::HashMap", NULL}, 1, "rust_simple" },
+
+ /* crate-root use */
+ { CBM_LANG_RUST, "b.rs",
+ "use crate::config::Config;\nfn main() {}\n",
+ {"crate::config::Config", NULL}, 1, "rust_crate_root" },
+
+ /* self-reference in braces */
+ { CBM_LANG_RUST, "c.rs",
+ "use std::io::{self, Write};\nfn main() {}\n",
+ {"std::io", NULL}, 1, "rust_grouped_self_write" },
+
+ /* braced multi-item */
+ { CBM_LANG_RUST, "d.rs",
+ "use std::sync::{Arc, Mutex, RwLock};\nfn main() {}\n",
+ {"std::sync", NULL}, 1, "rust_grouped_3" },
+
+ /* wildcard glob */
+ { CBM_LANG_RUST, "e.rs",
+ "use std::prelude::v1::*;\nfn main() {}\n",
+ {"std::prelude", NULL}, 1, "rust_glob" },
+
+ /* alias rename */
+ { CBM_LANG_RUST, "f.rs",
+ "use std::collections::HashMap as Map;\nfn main() {}\n",
+ {"std::collections::HashMap", NULL}, 1, "rust_alias" },
+
+ /* external crate */
+ { CBM_LANG_RUST, "g.rs",
+ "use serde::{Serialize, Deserialize};\nfn main() {}\n",
+ {"serde", NULL}, 1, "rust_serde_grouped" },
+
+ /* super:: relative */
+ { CBM_LANG_RUST, "h.rs",
+ "use super::utils::helper;\nfn main() {}\n",
+ {"super::utils::helper", NULL}, 1, "rust_super" },
+
+ /* multiple use statements */
+ { CBM_LANG_RUST, "i.rs",
+ "use std::fs;\nuse std::io::Read;\nuse std::path::PathBuf;\nfn main() {}\n",
+ {"std::fs", "std::io::Read", "std::path::PathBuf", NULL}, 3, "rust_multi" },
+
+ /* nested braces */
+ { CBM_LANG_RUST, "j.rs",
+ "use std::{collections::HashMap, io::{BufRead, BufReader}};\nfn main() {}\n",
+ {"std::", NULL}, 1, "rust_nested_braces" },
+
+ /* tokio async */
+ { CBM_LANG_RUST, "k.rs",
+ "use tokio::runtime::Runtime;\nuse tokio::sync::mpsc;\nfn main() {}\n",
+ {"tokio::runtime::Runtime", "tokio::sync::mpsc", NULL}, 2, "rust_tokio" },
+
+ /* pub use (re-export) */
+ { CBM_LANG_RUST, "l.rs",
+ "pub use crate::error::Error;\nfn main() {}\n",
+ {"crate::error::Error", NULL}, 1, "rust_pub_use" },
+
+ /* std + external + crate mix */
+ { CBM_LANG_RUST, "m.rs",
+ "use std::fmt;\nuse log::info;\nuse crate::db::Database;\nfn main() {}\n",
+ {"std::fmt", "log::info", "crate::db::Database", NULL}, 3, "rust_mixed" },
+
+ /* deeply nested path */
+ { CBM_LANG_RUST, "n.rs",
+ "use actix_web::web::{Data, Json, Path};\nfn main() {}\n",
+ {"actix_web::web", NULL}, 1, "rust_actix" },
+
+ /* use inside function body — may not be at root cursor level */
+ { CBM_LANG_RUST, "o.rs",
+ "fn main() {\n use std::collections::BTreeMap;\n let _ = BTreeMap::<i32,i32>::new();\n}\n",
+ {NULL}, 0, "rust_use_in_fn" }, /* count may be 0 (root-only scan) — no assert */
+};
+
+TEST(rust_import_table) {
+ int failures = run_cases(rust_cases, (int)(sizeof(rust_cases)/sizeof(rust_cases[0])));
+ if (failures > 0) {
+ printf(" %d rust import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Java — parse_java_imports (scoped_identifier / identifier child of
+ * import_declaration). Existing test asserts java.util.List → GREEN.
+ * Graph zero-edges are likely downstream resolution/edge-creation.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t java_cases[] = {
+ /* single type import */
+ { CBM_LANG_JAVA, "A.java",
+ "import java.util.List;\npublic class A {}\n",
+ {"java.util.List", NULL}, 1, "java_single" },
+
+ /* multiple type imports */
+ { CBM_LANG_JAVA, "B.java",
+ "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Map;\n"
+ "public class B {}\n",
+ {"java.util.List", "java.util.ArrayList", "java.util.Map", NULL}, 3, "java_multi" },
+
+ /* static import */
+ { CBM_LANG_JAVA, "C.java",
+ "import static java.lang.Math.PI;\npublic class C {}\n",
+ {"java.lang.Math", NULL}, 1, "java_static" },
+
+ /* on-demand wildcard */
+ { CBM_LANG_JAVA, "D.java",
+ "import java.io.*;\npublic class D {}\n",
+ {"java.io", NULL}, 1, "java_wildcard" },
+
+ /* static on-demand */
+ { CBM_LANG_JAVA, "E.java",
+ "import static org.junit.Assert.*;\npublic class E {}\n",
+ {"org.junit.Assert", NULL}, 1, "java_static_wildcard" },
+
+ /* deeply nested package */
+ { CBM_LANG_JAVA, "F.java",
+ "import com.google.common.collect.ImmutableList;\npublic class F {}\n",
+ {"com.google.common.collect.ImmutableList", NULL}, 1, "java_deep_nested" },
+
+ /* multiple mixed */
+ { CBM_LANG_JAVA, "G.java",
+ "import java.util.List;\nimport java.io.*;\nimport static java.lang.System.out;\n"
+ "public class G {}\n",
+ {"java.util.List", "java.io", "java.lang.System", NULL}, 3, "java_mixed" },
+
+ /* android / androidx */
+ { CBM_LANG_JAVA, "H.java",
+ "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\n"
+ "public class H {}\n",
+ {"androidx.appcompat.app.AppCompatActivity", "android.os.Bundle", NULL}, 2,
+ "java_android" },
+
+ /* javax imports */
+ { CBM_LANG_JAVA, "I.java",
+ "import javax.servlet.http.HttpServletRequest;\npublic class I {}\n",
+ {"javax.servlet.http.HttpServletRequest", NULL}, 1, "java_javax" },
+
+ /* lombok annotation */
+ { CBM_LANG_JAVA, "J.java",
+ "import lombok.Data;\nimport lombok.Builder;\npublic class J {}\n",
+ {"lombok.Data", "lombok.Builder", NULL}, 2, "java_lombok" },
+
+ /* spring framework */
+ { CBM_LANG_JAVA, "K.java",
+ "import org.springframework.web.bind.annotation.RestController;\n"
+ "import org.springframework.web.bind.annotation.GetMapping;\n"
+ "public class K {}\n",
+ {"org.springframework.web.bind.annotation.RestController",
+ "org.springframework.web.bind.annotation.GetMapping", NULL}, 2, "java_spring" },
+
+ /* interface file */
+ { CBM_LANG_JAVA, "L.java",
+ "import java.util.function.Function;\nimport java.util.function.Predicate;\n"
+ "public interface L {}\n",
+ {"java.util.function.Function", "java.util.function.Predicate", NULL}, 2,
+ "java_interface_imports" },
+
+ /* enum file */
+ { CBM_LANG_JAVA, "M.java",
+ "import java.util.Arrays;\nimport java.util.Collections;\npublic enum M { A, B }\n",
+ {"java.util.Arrays", "java.util.Collections", NULL}, 2, "java_enum_imports" },
+};
+
+TEST(java_import_table) {
+ int failures = run_cases(java_cases, (int)(sizeof(java_cases)/sizeof(java_cases[0])));
+ if (failures > 0) {
+ printf(" %d java import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Kotlin — parse_kotlin_imports → extract_one_import_header →
+ * generic_import_from_text (strips "import "/";").
+ *
+ * tree-sitter-kotlin wraps imports in import_list → import_header.
+ * generic_import_from_text strips the first word ("import") and trailing ";",
+ * so "import kotlin.collections.HashMap" → module_path="kotlin.collections.HashMap".
+ * Alias form "import X as Y" → module_path="X as Y" (includes " as Y").
+ * Wildcard "import X.*" → module_path="X.*".
+ *
+ * EXPECTED: basic, wildcard GREEN; alias substring check on original name GREEN
+ * (since "kotlin.collections.HashMap" is a substring of "kotlin.collections.HashMap as Map").
+ * Graph zero-edges are likely downstream.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t kotlin_cases[] = {
+ /* simple import */
+ { CBM_LANG_KOTLIN, "A.kt",
+ "import kotlin.collections.HashMap\nfun main() {}\n",
+ {"kotlin.collections.HashMap", NULL}, 1, "kotlin_simple" },
+
+ /* import with alias */
+ { CBM_LANG_KOTLIN, "B.kt",
+ "import kotlin.collections.HashMap as Map\nfun main() {}\n",
+ {"kotlin.collections.HashMap", NULL}, 1, "kotlin_alias" },
+
+ /* wildcard import */
+ { CBM_LANG_KOTLIN, "C.kt",
+ "import kotlin.math.*\nfun main() {}\n",
+ {"kotlin.math", NULL}, 1, "kotlin_wildcard" },
+
+ /* multiple imports */
+ { CBM_LANG_KOTLIN, "D.kt",
+ "import java.util.Date\nimport java.io.File\nimport kotlin.text.Regex\nfun main() {}\n",
+ {"java.util.Date", "java.io.File", "kotlin.text.Regex", NULL}, 3, "kotlin_multi" },
+
+ /* Android imports */
+ { CBM_LANG_KOTLIN, "E.kt",
+ "import android.app.Activity\nimport android.os.Bundle\nclass E : Activity() {}\n",
+ {"android.app.Activity", "android.os.Bundle", NULL}, 2, "kotlin_android" },
+
+ /* coroutines */
+ { CBM_LANG_KOTLIN, "F.kt",
+ "import kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.launch\n"
+ "fun main() {}\n",
+ {"kotlinx.coroutines.Dispatchers", "kotlinx.coroutines.launch", NULL}, 2,
+ "kotlin_coroutines" },
+
+ /* stdlib + external */
+ { CBM_LANG_KOTLIN, "G.kt",
+ "import kotlin.io.println\nimport com.example.MyClass\nfun main() {}\n",
+ {"kotlin.io.println", "com.example.MyClass", NULL}, 2, "kotlin_mixed" },
+
+ /* deeply nested */
+ { CBM_LANG_KOTLIN, "H.kt",
+ "import org.springframework.web.bind.annotation.RestController\nfun main() {}\n",
+ {"org.springframework.web.bind.annotation.RestController", NULL}, 1,
+ "kotlin_deep_nested" },
+
+ /* companion object pattern */
+ { CBM_LANG_KOTLIN, "I.kt",
+ "import kotlin.jvm.JvmStatic\nclass I { companion object {} }\n",
+ {"kotlin.jvm.JvmStatic", NULL}, 1, "kotlin_jvm_static" },
+
+ /* many imports */
+ { CBM_LANG_KOTLIN, "J.kt",
+ "import java.util.Date\nimport java.util.Calendar\nimport java.util.TimeZone\n"
+ "import java.text.SimpleDateFormat\nimport java.text.DateFormat\n"
+ "fun main() {}\n",
+ {"java.util.Date", "java.util.Calendar", "java.util.TimeZone",
+ "java.text.SimpleDateFormat", NULL}, 5, "kotlin_many" },
+
+ /* Ktor imports */
+ { CBM_LANG_KOTLIN, "K.kt",
+ "import io.ktor.application.*\nimport io.ktor.response.*\nimport io.ktor.routing.*\n"
+ "fun main() {}\n",
+ {"io.ktor.application", "io.ktor.response", "io.ktor.routing", NULL}, 3,
+ "kotlin_ktor" },
+
+ /* sealed class import */
+ { CBM_LANG_KOTLIN, "L.kt",
+ "import com.myapp.Result\nimport com.myapp.Result.Success\nimport com.myapp.Result.Error\n"
+ "fun main() {}\n",
+ {"com.myapp.Result", NULL}, 3, "kotlin_sealed_class" },
+
+ /* interface/extension imports */
+ { CBM_LANG_KOTLIN, "M.kt",
+ "import kotlin.collections.MutableList\nimport kotlin.collections.mutableListOf\n"
+ "fun main() {}\n",
+ {"kotlin.collections.MutableList", "kotlin.collections.mutableListOf", NULL}, 2,
+ "kotlin_extensions" },
+
+ /* enum + annotation imports */
+ { CBM_LANG_KOTLIN, "N.kt",
+ "import kotlin.annotation.AnnotationRetention\nimport kotlin.annotation.Retention\n"
+ "fun main() {}\n",
+ {"kotlin.annotation.AnnotationRetention", "kotlin.annotation.Retention", NULL}, 2,
+ "kotlin_annotation" },
+
+ /* object declaration */
+ { CBM_LANG_KOTLIN, "O.kt",
+ "import kotlin.properties.Delegates\nobject O {}\n",
+ {"kotlin.properties.Delegates", NULL}, 1, "kotlin_object" },
+};
+
+TEST(kotlin_import_table) {
+ int failures = run_cases(kotlin_cases, (int)(sizeof(kotlin_cases)/sizeof(kotlin_cases[0])));
+ if (failures > 0) {
+ printf(" %d kotlin import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * PHP — parse_generic_imports("expression_statement").
+ *
+ * PHP's "use" keyword appears as a `namespace_use_declaration` node, NOT an
+ * `expression_statement`. So "use Foo\Bar;" will yield 0 extracted imports
+ * (the dispatcher looks for expression_statement, finds none).
+ *
+ * "require"/"include" ARE expression_statements, so require/include should
+ * be extracted IF the generic text-stripper catches them.
+ *
+ * EXPECTED:
+ * - PHP "use Namespace\Class" → LIKELY RED (0 imports; wrong node type)
+ * - PHP require/include → MAY be GREEN (expression_statement nodes)
+ *
+ * We write both forms so RED rows expose the namespace-use gap.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t php_cases[] = {
+ /* use statement — basic (expected RED if node-type mismatch) */
+ { CBM_LANG_PHP, "a.php",
+ "<?php\nuse App\\Http\\Controllers\\Controller;\nclass A extends Controller {}\n",
+ {"App\\Http\\Controllers\\Controller", NULL}, 1, "php_use_basic" },
+
+ /* use with alias */
+ { CBM_LANG_PHP, "b.php",
+ "<?php\nuse Illuminate\\Support\\Facades\\DB as Database;\nclass B {}\n",
+ {"Illuminate\\Support\\Facades\\DB", NULL}, 1, "php_use_alias" },
+
+ /* multiple use statements */
+ { CBM_LANG_PHP, "c.php",
+ "<?php\nuse App\\Models\\User;\nuse App\\Models\\Post;\nuse App\\Models\\Comment;\n"
+ "class C {}\n",
+ {"App\\Models\\User", "App\\Models\\Post", "App\\Models\\Comment", NULL}, 3,
+ "php_use_multi" },
+
+ /* use function */
+ { CBM_LANG_PHP, "d.php",
+ "<?php\nuse function App\\Helpers\\format_date;\nclass D {}\n",
+ {"App\\Helpers\\format_date", NULL}, 1, "php_use_function" },
+
+ /* use const */
+ { CBM_LANG_PHP, "e.php",
+ "<?php\nuse const App\\Constants\\MAX_SIZE;\nclass E {}\n",
+ {"App\\Constants\\MAX_SIZE", NULL}, 1, "php_use_const" },
+
+ /* grouped use (PHP 7+) */
+ { CBM_LANG_PHP, "f.php",
+ "<?php\nuse App\\Http\\{Request, Response, Middleware};\nclass F {}\n",
+ {"App\\Http", NULL}, 1, "php_grouped_use" },
+
+ /* trait use (inside class — not namespace use) */
+ { CBM_LANG_PHP, "g.php",
+ "<?php\nuse App\\Traits\\HasTimestamps;\nclass G { use HasTimestamps; }\n",
+ {"App\\Traits\\HasTimestamps", NULL}, 1, "php_trait_use" },
+
+ /* require expression */
+ { CBM_LANG_PHP, "h.php",
+ "<?php\nrequire 'vendor/autoload.php';\nclass H {}\n",
+ {"vendor/autoload.php", NULL}, 1, "php_require" },
+
+ /* require_once */
+ { CBM_LANG_PHP, "i.php",
+ "<?php\nrequire_once 'config.php';\nclass I {}\n",
+ {"config.php", NULL}, 1, "php_require_once" },
+
+ /* include */
+ { CBM_LANG_PHP, "j.php",
+ "<?php\ninclude 'header.php';\nclass J {}\n",
+ {"header.php", NULL}, 1, "php_include" },
+
+ /* Laravel facade import */
+ { CBM_LANG_PHP, "k.php",
+ "<?php\nuse Illuminate\\Support\\Facades\\Auth;\nuse Illuminate\\Support\\Facades\\Cache;\n"
+ "class K {}\n",
+ {"Illuminate\\Support\\Facades\\Auth", "Illuminate\\Support\\Facades\\Cache", NULL}, 2,
+ "php_laravel_facades" },
+
+ /* Symfony component */
+ { CBM_LANG_PHP, "l.php",
+ "<?php\nuse Symfony\\Component\\HttpFoundation\\Request;\n"
+ "use Symfony\\Component\\HttpFoundation\\Response;\nclass L {}\n",
+ {"Symfony\\Component\\HttpFoundation\\Request",
+ "Symfony\\Component\\HttpFoundation\\Response", NULL}, 2, "php_symfony" },
+
+ /* interface implementation */
+ { CBM_LANG_PHP, "m.php",
+ "<?php\nuse Psr\\Log\\LoggerInterface;\nuse Psr\\Log\\AbstractLogger;\n"
+ "class M implements LoggerInterface {}\n",
+ {"Psr\\Log\\LoggerInterface", "Psr\\Log\\AbstractLogger", NULL}, 2, "php_psr" },
+};
+
+TEST(php_import_table) {
+ int failures = run_cases(php_cases, (int)(sizeof(php_cases)/sizeof(php_cases[0])));
+ if (failures > 0) {
+ printf(" %d php import case(s) failed (use-statement forms likely RED: "
+ "wrong node_type 'expression_statement' vs actual 'namespace_use_declaration')\n",
+ failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * C# — parse_generic_imports("using_directive") → generic_import_from_text.
+ *
+ * generic_import_from_text strips the first word ("using") and trailing ";".
+ * So "using System.Collections.Generic;" → module_path="System.Collections.Generic".
+ * Alias form "using F = System.IO.File;" → module_path="F = System.IO.File"
+ * (includes "F = " prefix — has_import("System.IO.File") STILL matches as
+ * substring, so alias cases may be GREEN at the module_path level).
+ * Static using "using static System.Math;" → module_path="static System.Math"
+ * — has_import("System.Math") matches as substring → GREEN.
+ *
+ * EXPECTED: most forms GREEN (substring match works despite extra tokens).
+ * Graph zero-edges are likely downstream.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+static const import_case_t csharp_cases[] = {
+ /* simple namespace */
+ { CBM_LANG_CSHARP, "A.cs",
+ "using System;\npublic class A {}\n",
+ {"System", NULL}, 1, "cs_simple" },
+
+ /* nested namespace */
+ { CBM_LANG_CSHARP, "B.cs",
+ "using System.Collections.Generic;\npublic class B {}\n",
+ {"System.Collections.Generic", NULL}, 1, "cs_nested" },
+
+ /* static using */
+ { CBM_LANG_CSHARP, "C.cs",
+ "using static System.Math;\npublic class C {}\n",
+ {"System.Math", NULL}, 1, "cs_static" },
+
+ /* alias using */
+ { CBM_LANG_CSHARP, "D.cs",
+ "using F = System.IO.File;\npublic class D {}\n",
+ {"System.IO.File", NULL}, 1, "cs_alias" },
+
+ /* multiple usings */
+ { CBM_LANG_CSHARP, "E.cs",
+ "using System;\nusing System.IO;\nusing System.Text;\nusing System.Linq;\n"
+ "public class E {}\n",
+ {"System", "System.IO", "System.Text", "System.Linq", NULL}, 4, "cs_multi" },
+
+ /* LINQ */
+ { CBM_LANG_CSHARP, "F.cs",
+ "using System.Linq;\nusing System.Collections.Generic;\npublic class F {}\n",
+ {"System.Linq", "System.Collections.Generic", NULL}, 2, "cs_linq" },
+
+ /* ASP.NET Core */
+ { CBM_LANG_CSHARP, "G.cs",
+ "using Microsoft.AspNetCore.Mvc;\nusing Microsoft.AspNetCore.Http;\n"
+ "public class G : ControllerBase {}\n",
+ {"Microsoft.AspNetCore.Mvc", "Microsoft.AspNetCore.Http", NULL}, 2, "cs_aspnet" },
+
+ /* Entity Framework */
+ { CBM_LANG_CSHARP, "H.cs",
+ "using Microsoft.EntityFrameworkCore;\nusing System.ComponentModel.DataAnnotations;\n"
+ "public class H {}\n",
+ {"Microsoft.EntityFrameworkCore", "System.ComponentModel.DataAnnotations", NULL}, 2,
+ "cs_ef" },
+
+ /* Newtonsoft.Json */
+ { CBM_LANG_CSHARP, "I.cs",
+ "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\npublic class I {}\n",
+ {"Newtonsoft.Json", NULL}, 2, "cs_json" },
+
+ /* multiple aliases */
+ { CBM_LANG_CSHARP, "J.cs",
+ "using Dict = System.Collections.Generic.Dictionary<string, int>;\n"
+ "using Str = System.String;\npublic class J {}\n",
+ {"System.Collections.Generic.Dictionary", "System.String", NULL}, 2, "cs_multi_alias" },
+
+ /* Xunit test */
+ { CBM_LANG_CSHARP, "K.cs",
+ "using Xunit;\nusing FluentAssertions;\npublic class K {}\n",
+ {"Xunit", "FluentAssertions", NULL}, 2, "cs_xunit" },
+
+ /* global using (C# 10+) — may or may not be a using_directive */
+ { CBM_LANG_CSHARP, "L.cs",
+ "global using System;\nglobal using System.Threading.Tasks;\npublic class L {}\n",
+ {"System", "System.Threading.Tasks", NULL}, 2, "cs_global_using" },
+
+ /* mixed: regular, static, alias */
+ { CBM_LANG_CSHARP, "M.cs",
+ "using System;\nusing static System.Console;\nusing Path = System.IO.Path;\n"
+ "public class M {}\n",
+ {"System", "System.Console", "System.IO.Path", NULL}, 3, "cs_mixed" },
+
+ /* threading */
+ { CBM_LANG_CSHARP, "N.cs",
+ "using System.Threading;\nusing System.Threading.Tasks;\nusing System.Threading.Channels;\n"
+ "public class N {}\n",
+ {"System.Threading", "System.Threading.Tasks", "System.Threading.Channels", NULL}, 3,
+ "cs_threading" },
+
+ /* Azure SDK */
+ { CBM_LANG_CSHARP, "O.cs",
+ "using Azure.Storage.Blobs;\nusing Azure.Identity;\npublic class O {}\n",
+ {"Azure.Storage.Blobs", "Azure.Identity", NULL}, 2, "cs_azure" },
+};
+
+TEST(csharp_import_table) {
+ int failures = run_cases(csharp_cases, (int)(sizeof(csharp_cases)/sizeof(csharp_cases[0])));
+ if (failures > 0) {
+ printf(" %d csharp import case(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Cross-language: zero-import guard.
+ *
+ * Files with NO import statements should produce imports.count == 0.
+ * This ensures the extractors don't fabricate phantom imports.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+typedef struct {
+ CBMLanguage lang;
+ const char *path;
+ const char *src;
+ const char *label;
+} zero_import_case_t;
+
+static const zero_import_case_t zero_cases[] = {
+ { CBM_LANG_RUST, "a.rs", "fn main() { println!(\"hello\"); }\n",
+ "rust_no_imports" },
+ { CBM_LANG_JAVA, "A.java", "public class A { public static void main(String[] a) {} }\n",
+ "java_no_imports" },
+ { CBM_LANG_KOTLIN, "A.kt", "fun main() { println(\"hello\") }\n",
+ "kotlin_no_imports" },
+ { CBM_LANG_CSHARP, "A.cs", "public class A { static void Main() {} }\n",
+ "cs_no_imports" },
+ { CBM_LANG_PHP, "a.php", "<?php\necho 'hello';\n",
+ "php_no_imports" },
+ { CBM_LANG_GO, "a.go", "package main\nfunc main() {}\n",
+ "go_no_imports" },
+ { CBM_LANG_PYTHON, "a.py", "def main(): pass\n",
+ "py_no_imports" },
+ { CBM_LANG_TYPESCRIPT, "a.ts", "function hello(): void { console.log('hi'); }\n",
+ "ts_no_imports" },
+ { CBM_LANG_JAVASCRIPT, "a.js", "function hello() { return 42; }\n",
+ "js_no_imports" },
+};
+
+TEST(zero_imports_guard) {
+ int failures = 0;
+ int n = (int)(sizeof(zero_cases)/sizeof(zero_cases[0]));
+ for (int i = 0; i < n; i++) {
+ const zero_import_case_t *tc = &zero_cases[i];
+ CBMFileResult *r = do_extract(tc->src, tc->lang, tc->path);
+ if (!r) {
+ printf(" FAIL [%s]: NULL result\n", tc->label);
+ failures++;
+ continue;
+ }
+ if (r->imports.count != 0) {
+ printf(" FAIL [%s]: expected 0 imports, got %d\n",
+ tc->label, r->imports.count);
+ failures++;
+ }
+ cbm_free_result(r);
+ }
+ if (failures > 0) {
+ printf(" %d zero-import guard(s) failed\n", failures);
+ return 1;
+ }
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Per-language: import count exactness spot-checks.
+ *
+ * For each language we write a snippet with a KNOWN number of imports and
+ * assert imports.count equals exactly that number. This catches over-
+ * or under-counting bugs that substring presence alone won't catch.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+TEST(import_count_go_exact) {
+ /* 3 imports in a block */
+ CBMFileResult *r = do_extract(
+ "package main\nimport (\n \"fmt\"\n \"os\"\n \"io\"\n)\nfunc main() {}\n",
+ CBM_LANG_GO, "a.go");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(r->imports.count, 3);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(import_count_python_exact) {
+ CBMFileResult *r = do_extract(
+ "import os\nimport sys\nfrom typing import List\nfrom collections import defaultdict\n",
+ CBM_LANG_PYTHON, "a.py");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(r->imports.count, 4);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(import_count_ts_exact) {
+ CBMFileResult *r = do_extract(
+ "import React from 'react';\nimport { useState } from 'react';\nimport * as _ from 'lodash';\n",
+ CBM_LANG_TYPESCRIPT, "a.ts");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ /* 3 import statements; named imports produce one entry per name or one per source */
+ ASSERT_GTE(r->imports.count, 2);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(import_count_rust_exact) {
+ /* 3 use declarations at module root */
+ CBMFileResult *r = do_extract(
+ "use std::fs;\nuse std::io::Read;\nuse std::path::PathBuf;\nfn main() {}\n",
+ CBM_LANG_RUST, "a.rs");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(r->imports.count, 3);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(import_count_java_exact) {
+ /* 2 import_declarations */
+ CBMFileResult *r = do_extract(
+ "import java.util.List;\nimport java.util.Map;\npublic class A {}\n",
+ CBM_LANG_JAVA, "A.java");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(r->imports.count, 2);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(import_count_kotlin_exact) {
+ /* 2 import_headers */
+ CBMFileResult *r = do_extract(
+ "import java.util.Date\nimport java.io.File\nfun main() {}\n",
+ CBM_LANG_KOTLIN, "A.kt");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(r->imports.count, 2);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(import_count_csharp_exact) {
+ /* 2 using_directives */
+ CBMFileResult *r = do_extract(
+ "using System;\nusing System.IO;\npublic class A {}\n",
+ CBM_LANG_CSHARP, "A.cs");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(r->imports.count, 2);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * PHP edge-case: only require/include forms (no "use") should be extractable
+ * even given the expression_statement dispatch.
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+TEST(php_require_only_extracted) {
+ /* Only require — no namespace use. Should produce at least 1 import. */
+ CBMFileResult *r = do_extract(
+ "<?php\nrequire_once 'vendor/autoload.php';\n$x = 1;\n",
+ CBM_LANG_PHP, "a.php");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ /* require_once is an expression_statement — may be extracted by generic */
+ if (r->imports.count == 0) {
+ printf(" INFO [php_require_only]: 0 imports — expression_statement path "
+ "does not catch require_once\n");
+ }
+ cbm_free_result(r);
+ PASS(); /* informational — count assertion relaxed; table test carries RED */
+}
+
+TEST(php_namespace_use_zero) {
+ /* "use" namespace declaration — expected count 0 given wrong node_type dispatch */
+ CBMFileResult *r = do_extract(
+ "<?php\nuse App\\Http\\Controllers\\Controller;\nclass A extends Controller {}\n",
+ CBM_LANG_PHP, "a.php");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ /*
+ * REPRODUCTION of bug: PHP namespace use yields 0 imports because
+ * parse_generic_imports("expression_statement") matches the wrong node type.
+ * If this assertion fails the bug is FIXED — remove it and update the table tests.
+ * If it passes (count==0) the bug is confirmed at extraction level.
+ */
+ if (r->imports.count > 0) {
+ /* Bug unexpectedly fixed — print info and pass */
+ printf(" INFO [php_namespace_use_zero]: got %d import(s) — extractor "
+ "apparently handles namespace_use_declaration now\n",
+ r->imports.count);
+ }
+ cbm_free_result(r);
+ PASS(); /* non-fatal; table test php_use_basic carries the RED assertion */
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Rust: local_name field spot-checks (last segment of path)
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+TEST(rust_local_name_last_segment) {
+ CBMFileResult *r = do_extract(
+ "use std::collections::HashMap;\nfn main() {}\n",
+ CBM_LANG_RUST, "a.rs");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_GT(r->imports.count, 0);
+ /* local_name should be "HashMap" (last segment after "::") */
+ ASSERT(imp_local(r, "HashMap"));
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * Java: local_name field spot-check (last dot-component)
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+TEST(java_local_name_last_segment) {
+ CBMFileResult *r = do_extract(
+ "import java.util.ArrayList;\npublic class A {}\n",
+ CBM_LANG_JAVA, "A.java");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_GT(r->imports.count, 0);
+ /* local_name should be "ArrayList" */
+ ASSERT(imp_local(r, "ArrayList"));
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * C#: local_name field spot-check
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+TEST(csharp_local_name_last_segment) {
+ CBMFileResult *r = do_extract(
+ "using System.Collections.Generic;\npublic class A {}\n",
+ CBM_LANG_CSHARP, "A.cs");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_GT(r->imports.count, 0);
+ /* local_name should be "Generic" (last dot-segment) */
+ ASSERT(imp_local(r, "Generic"));
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════════════
+ * SUITE declaration — do NOT register in test_main.c; the main workstream will
+ * ═══════════════════════════════════════════════════════════════════════════ */
+
+SUITE(extraction_imports) {
+ cbm_init();
+
+ /* Working languages — all expected GREEN (regression guards) */
+ RUN_TEST(go_import_table);
+ RUN_TEST(python_import_table);
+ RUN_TEST(typescript_import_table);
+ RUN_TEST(javascript_import_table);
+
+ /* Extraction-level spot-checks for languages with graph-level zero-edges */
+ RUN_TEST(rust_import_table); /* extraction likely GREEN; graph edges RED downstream */
+ RUN_TEST(java_import_table); /* extraction likely GREEN; graph edges RED downstream */
+ RUN_TEST(kotlin_import_table); /* extraction likely GREEN; graph edges RED downstream */
+ RUN_TEST(csharp_import_table); /* extraction likely GREEN; graph edges RED downstream */
+ RUN_TEST(php_import_table); /* use-forms likely RED at extraction; require forms TBD */
+
+ /* Zero-import guards */
+ RUN_TEST(zero_imports_guard);
+
+ /* Exact count spot-checks */
+ RUN_TEST(import_count_go_exact);
+ RUN_TEST(import_count_python_exact);
+ RUN_TEST(import_count_ts_exact);
+ RUN_TEST(import_count_rust_exact);
+ RUN_TEST(import_count_java_exact);
+ RUN_TEST(import_count_kotlin_exact);
+ RUN_TEST(import_count_csharp_exact);
+
+ /* PHP diagnostic tests */
+ RUN_TEST(php_require_only_extracted);
+ RUN_TEST(php_namespace_use_zero);
+
+ /* Local-name field spot-checks */
+ RUN_TEST(rust_local_name_last_segment);
+ RUN_TEST(java_local_name_last_segment);
+ RUN_TEST(csharp_local_name_last_segment);
+}
diff --git a/tests/test_extraction_inheritance.c b/tests/test_extraction_inheritance.c
new file mode 100644
index 000000000..23a311dd3
--- /dev/null
+++ b/tests/test_extraction_inheritance.c
@@ -0,0 +1,1818 @@
+/*
+ * test_extraction_inheritance.c — Reproduce-first suite for class-inheritance
+ * base-class extraction across the 9 hybrid-LSP languages.
+ *
+ * DESIGN INTENT
+ * ─────────────
+ * Every row asserts the CORRECT behaviour: that `CBMDefinition.base_classes`
+ * contains real type names, not keywords or punctuation. For the three broken
+ * languages the rows are EXPECTED RED until the extractors are fixed:
+ *
+ * RED (broken extractors — rows FAIL until fixed):
+ * TypeScript / TSX — extractor stores the keyword "extends" / "implements"
+ * instead of the following type name.
+ * PHP — base_classes is never populated (always NULL / empty).
+ * Kotlin — `:` supertype syntax is not parsed → base_classes empty.
+ *
+ * GREEN (correct extractors — rows PASS as regression guards):
+ * Python — NOTE: the simple `class Dog(Animal):` case is ALSO red because
+ * collect_bases_from_field does not yet match the plain `identifier`
+ * node used by tree-sitter-python (it grabs the argument_list text
+ * "(Animal)" with parens). The reproduction for that root-cause is
+ * already in test_extraction.c (python_class_base_extracted_bare).
+ * This suite adds multi-base, generic-base, and qualified-base
+ * variants that share the same root bug — they are all RED until the
+ * identifier-node fix lands. Python cases that use
+ * `type_identifier` nodes (not yet confirmed) are tentatively
+ * labelled RED.
+ * Java — single-base and multi-interface extraction is correct (regression
+ * guard for the fix landed with #279).
+ * C# — extraction is correct (regression guards).
+ * C++ — extraction is correct (regression guards).
+ * Rust — impl_traits array (not base_classes) is the capture point; Rust
+ * rows verify impl_traits entries for `impl Trait for Struct`.
+ *
+ * STRUCTURE
+ * ─────────
+ * inherit_case_t — one test row.
+ * run_inherit_case — generic runner: extract → find def → check base_classes
+ * (or impl_traits for Rust).
+ * One TEST() per language group so failures are readable at the suite level.
+ * SUITE(extraction_inheritance) wires them together via RUN_TEST().
+ *
+ * HOW TO ADD TO THE RUNNER
+ * ─────────────────────────
+ * In test_main.c add:
+ * extern void suite_extraction_inheritance(void);
+ * RUN_SUITE(extraction_inheritance);
+ * (Do NOT do this here — another workstream owns test_main.c.)
+ */
+
+#include "test_framework.h"
+#include "cbm.h"
+#include <string.h>
+#include <stdbool.h>
+#include <stdio.h>
+
+/* ── Shared helpers ─────────────────────────────────────────────── */
+
+/* Find a definition by label+name; returns NULL if not found. */
+static CBMDefinition *find_def(CBMFileResult *r, const char *label, const char *name) {
+ for (int i = 0; i < r->defs.count; i++) {
+ CBMDefinition *d = &r->defs.items[i];
+ if (d->label && strcmp(d->label, label) == 0 &&
+ d->name && strcmp(d->name, name) == 0)
+ return d;
+ }
+ return NULL;
+}
+
+/* Find a definition by name alone (any label). */
+static CBMDefinition *find_def_any(CBMFileResult *r, const char *name) {
+ for (int i = 0; i < r->defs.count; i++) {
+ CBMDefinition *d = &r->defs.items[i];
+ if (d->name && strcmp(d->name, name) == 0)
+ return d;
+ }
+ return NULL;
+}
+
+/* Return 1 if base_classes contains `want` exactly. */
+static int bases_contain(CBMDefinition *d, const char *want) {
+ if (!d->base_classes) return 0;
+ for (const char **b = d->base_classes; *b; b++) {
+ if (strcmp(*b, want) == 0) return 1;
+ }
+ return 0;
+}
+
+/* Return 1 if ANY base_classes entry contains `substr` as a substring.
+ * Used to assert that keywords like "extends" / "implements" / ":" do NOT
+ * appear inside any captured base name. */
+static int bases_contain_substr(CBMDefinition *d, const char *substr) {
+ if (!d->base_classes) return 0;
+ for (const char **b = d->base_classes; *b; b++) {
+ if (strstr(*b, substr)) return 1;
+ }
+ return 0;
+}
+
+/* Count entries in a NULL-terminated base_classes array. */
+static int bases_count(CBMDefinition *d) {
+ if (!d->base_classes) return 0;
+ int n = 0;
+ for (const char **b = d->base_classes; *b; b++) n++;
+ return n;
+}
+
+/* ── Table-driven case type ─────────────────────────────────────── */
+
+/* Labels used to look up the class definition in the extraction result.
+ * The extractor uses "Class", "Interface", "Struct" — we try all three in
+ * find_def_flex() below. */
+typedef struct {
+ CBMLanguage lang;
+ const char *path; /* file path hint (sets language via extension too) */
+ const char *src; /* source snippet */
+ const char *class_name; /* name to look up */
+ const char *expected_bases[8]; /* NULL-terminated list of real type names to find */
+ /* bad_strings: substrings that must NOT appear inside any base_classes entry.
+ * Used to catch keyword-capture bugs. NULL-terminated, or {NULL} if unused. */
+ const char *bad_strings[6];
+ int min_base_count; /* >= this many entries expected (0 = don't check count) */
+} inherit_case_t;
+
+/* Find def trying Class / Interface / Struct / any-label fallback. */
+static CBMDefinition *find_def_flex(CBMFileResult *r, const char *name) {
+ CBMDefinition *d;
+ if ((d = find_def(r, "Class", name))) return d;
+ if ((d = find_def(r, "Interface", name))) return d;
+ if ((d = find_def(r, "Struct", name))) return d;
+ /* Fallback: any label — covers languages where the extractor uses custom labels */
+ return find_def_any(r, name);
+}
+
+/*
+ * Generic runner for one inherit_case_t row.
+ * Returns 0 on pass, 1 on failure (sets FAIL path via printf + return).
+ * Cannot use ASSERT macros directly here because they do `return 1` — which
+ * is fine since this helper also returns int. We use manual checks so we
+ * can include the case description in the failure message.
+ */
+static int run_inherit_case(const inherit_case_t *tc) {
+ CBMFileResult *r = cbm_extract_file(tc->src, (int)strlen(tc->src),
+ tc->lang, "t", tc->path,
+ 0, NULL, NULL);
+ if (!r) {
+ printf(" FAIL [%s] cbm_extract_file returned NULL\n", tc->class_name);
+ return 1;
+ }
+
+ CBMDefinition *cls = find_def_flex(r, tc->class_name);
+ if (!cls) {
+ printf(" FAIL [%s] definition not found in extraction result\n", tc->class_name);
+ cbm_free_result(r);
+ return 1;
+ }
+
+ /* When no bases are expected and no min count is set, this is a
+ * no-crash / sanity row — skip the rest of the checks. */
+ if (!tc->expected_bases[0] && tc->min_base_count == 0) {
+ cbm_free_result(r);
+ return 0;
+ }
+
+ /* Assert base_classes is non-NULL (at least one base expected). */
+ if (!cls->base_classes) {
+ printf(" FAIL [%s] base_classes is NULL (expected non-empty)\n", tc->class_name);
+ cbm_free_result(r);
+ return 1;
+ }
+
+ /* Assert each expected base name is present. */
+ int ok = 1;
+ for (int i = 0; tc->expected_bases[i]; i++) {
+ if (!bases_contain(cls, tc->expected_bases[i])) {
+ printf(" FAIL [%s] expected base \"%s\" not found in base_classes\n",
+ tc->class_name, tc->expected_bases[i]);
+ ok = 0;
+ }
+ }
+
+ /* Assert no bad keyword strings appear inside any base name. */
+ for (int i = 0; tc->bad_strings[i]; i++) {
+ if (bases_contain_substr(cls, tc->bad_strings[i])) {
+ printf(" FAIL [%s] bad string \"%s\" found inside a base_classes entry\n",
+ tc->class_name, tc->bad_strings[i]);
+ ok = 0;
+ }
+ }
+
+ /* Assert minimum count. */
+ if (tc->min_base_count > 0) {
+ int cnt = bases_count(cls);
+ if (cnt < tc->min_base_count) {
+ printf(" FAIL [%s] base_classes has %d entries, expected >= %d\n",
+ tc->class_name, cnt, tc->min_base_count);
+ ok = 0;
+ }
+ }
+
+ cbm_free_result(r);
+ return ok ? 0 : 1;
+}
+
+/* Convenience macro: run a table of cases, accumulate failures. */
+#define RUN_CASES(table) \
+ do { \
+ int _fail = 0; \
+ int _n = (int)(sizeof(table) / sizeof(table[0])); \
+ for (int _i = 0; _i < _n; _i++) { \
+ if (run_inherit_case(&table[_i]) != 0) _fail++; \
+ } \
+ if (_fail > 0) { \
+ printf(" FAIL %d / %d cases above failed\n", _fail, _n); \
+ return 1; \
+ } \
+ } while (0)
+
+/* ═══════════════════════════════════════════════════════════════════
+ * PYTHON (expected: RED until identifier-node fix in extract_defs.c)
+ *
+ * Root cause: collect_bases_from_field() does not match the plain
+ * `identifier` node used by tree-sitter-python for unqualified base
+ * names → raw argument_list text "(Base)" (with parens) is stored
+ * instead of "Base". Fix: accept `identifier` as a valid child type.
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t python_cases[] = {
+ /* ── single base (bare identifier) ────────────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "class Animal:\n pass\n\nclass Dog(Animal):\n pass\n",
+ "Dog",
+ {"Animal", NULL},
+ {"(", ")", NULL},
+ 1
+ },
+ /* ── multiple bases ─────────────────────────────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "class A: pass\nclass B: pass\nclass C(A, B): pass\n",
+ "C",
+ {"A", "B", NULL},
+ {"(", ")", NULL},
+ 2
+ },
+ /* ── base + mixin ───────────────────────────────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "class Base: pass\nclass Mixin: pass\nclass Service(Base, Mixin): pass\n",
+ "Service",
+ {"Base", "Mixin", NULL},
+ {"(", ")", NULL},
+ 2
+ },
+ /* ── generic base (subscript, e.g. Generic[T]) ──────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "from typing import Generic, TypeVar\nT = TypeVar('T')\n"
+ "class Stack(Generic[T]):\n pass\n",
+ "Stack",
+ {"Generic", NULL},
+ {"(", ")", NULL},
+ 1
+ },
+ /* ── qualified base (dotted: module.Base) ───────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "import django.db\nclass MyModel(django.db.Model):\n pass\n",
+ "MyModel",
+ {"django.db.Model", NULL},
+ {"(", ")", NULL},
+ 1
+ },
+ /* ── abstract base (abc.ABC) ────────────────────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "from abc import ABC, abstractmethod\nclass Shape(ABC):\n @abstractmethod\n def area(self): pass\n",
+ "Shape",
+ {"ABC", NULL},
+ {"(", ")", NULL},
+ 1
+ },
+ /* ── dataclass with base ────────────────────────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "from dataclasses import dataclass\n@dataclass\nclass Point:\n x: float\n\n"
+ "@dataclass\nclass Point3D(Point):\n z: float\n",
+ "Point3D",
+ {"Point", NULL},
+ {"(", ")", NULL},
+ 1
+ },
+ /* ── exception subclass ─────────────────────────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "class AppError(Exception): pass\n",
+ "AppError",
+ {"Exception", NULL},
+ {"(", ")", NULL},
+ 1
+ },
+ /* ── three bases ────────────────────────────────────────────── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "class X: pass\nclass Y: pass\nclass Z: pass\nclass Multi(X, Y, Z): pass\n",
+ "Multi",
+ {"X", "Y", "Z", NULL},
+ {"(", ")", NULL},
+ 3
+ },
+ /* ── base with keyword argument (metaclass=) should not bleed ── */
+ {
+ CBM_LANG_PYTHON, "m.py",
+ "class Meta: pass\nclass MyClass(object, metaclass=Meta): pass\n",
+ "MyClass",
+ {"object", NULL},
+ {"(", ")", "metaclass", NULL},
+ 1
+ },
+};
+
+TEST(inherit_python) {
+ RUN_CASES(python_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * JAVA (expected: GREEN — regression guards for #279 fix)
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t java_cases[] = {
+ /* ── extends only ───────────────────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Dog extends Animal { }",
+ "Dog",
+ {"Animal", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── implements single interface ─────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class ConcreteList implements List { }",
+ "ConcreteList",
+ {"List", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── extends + implements one ────────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class MyThread extends Thread implements Runnable { }",
+ "MyThread",
+ {"Thread", "Runnable", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── extends + implements two (regression for #279) ─────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class DefaultLinkTool extends DefaultDiagramTool implements ILinkTool, Closeable { }",
+ "DefaultLinkTool",
+ {"DefaultDiagramTool", "ILinkTool", "Closeable", NULL},
+ {"extends", "implements", NULL},
+ 3
+ },
+ /* ── implements three interfaces ─────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Svc implements A, B, C { }",
+ "Svc",
+ {"A", "B", "C", NULL},
+ {"extends", "implements", NULL},
+ 3
+ },
+ /* ── generic base (extends List<String>) ─────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "import java.util.*; public class MyList extends ArrayList<String> { }",
+ "MyList",
+ {"ArrayList", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── generic implements (Comparable<T>) ──────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Box<T> implements Comparable<Box<T>> { public int compareTo(Box<T> o) { return 0; } }",
+ "Box",
+ {"Comparable", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── abstract class extends ──────────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public abstract class AbstractSvc extends BaseService { protected abstract void run(); }",
+ "AbstractSvc",
+ {"BaseService", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── interface extends interface ─────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public interface ReadWriteRepo extends ReadRepo, WriteRepo { }",
+ "ReadWriteRepo",
+ {"ReadRepo", "WriteRepo", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── enum implements interface ───────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public enum Status implements Displayable { OPEN, CLOSED; public String display() { return name(); } }",
+ "Status",
+ {"Displayable", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── qualified (imported) type name ─────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Handler extends java.net.ServerSocket { }",
+ "Handler",
+ {"java.net.ServerSocket", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── extends + implements four ───────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Mega extends Base implements A, B, C, D { }",
+ "Mega",
+ {"Base", "A", "B", "C", "D", NULL},
+ {"extends", "implements", NULL},
+ 5
+ },
+ /* ── nested class with base ──────────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Outer { public static class Inner extends Outer { } }",
+ "Inner",
+ {"Outer", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── record implements interface (Java 16+) ──────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public record Point(int x, int y) implements Comparable<Point> { "
+ "public int compareTo(Point o) { return Integer.compare(x, o.x); } }",
+ "Point",
+ {"Comparable", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── sealed class (Java 17+) ─────────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public sealed class Shape permits Circle, Rectangle { }",
+ "Shape",
+ {NULL}, /* permitted-types are not base_classes of Shape; no bases to assert */
+ {NULL},
+ 0
+ },
+ /* ── class implements Serializable ──────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "import java.io.*; public class Data extends BaseData implements Serializable, Cloneable { }",
+ "Data",
+ {"BaseData", "Serializable", "Cloneable", NULL},
+ {"extends", "implements", NULL},
+ 3
+ },
+ /* ── generic class extends generic base ──────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Pair<A, B> extends AbstractPair<A, B> implements Iterable<A> { "
+ "public java.util.Iterator<A> iterator() { return null; } }",
+ "Pair",
+ {"AbstractPair", "Iterable", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── class extending Exception ───────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class AppException extends RuntimeException { "
+ "public AppException(String msg) { super(msg); } }",
+ "AppException",
+ {"RuntimeException", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── multiple interfaces no extends ──────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "public class Codec implements Encoder, Decoder, Closeable { }",
+ "Codec",
+ {"Encoder", "Decoder", "Closeable", NULL},
+ {"extends", "implements", NULL},
+ 3
+ },
+ /* ── annotated class with base ───────────────────────────────── */
+ {
+ CBM_LANG_JAVA, "Svc.java",
+ "@Override public class AnnotatedSvc extends BaseSvc { }",
+ "AnnotatedSvc",
+ {"BaseSvc", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+};
+
+TEST(inherit_java) {
+ RUN_CASES(java_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * C# (expected: GREEN — regression guards)
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t csharp_cases[] = {
+ /* ── single base class ──────────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Dog : Animal { }",
+ "Dog",
+ {"Animal", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── implements single interface ─────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Repo : IRepository { }",
+ "Repo",
+ {"IRepository", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── base + interface ────────────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Service : BaseService, IService { }",
+ "Service",
+ {"BaseService", "IService", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── base + two interfaces ───────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Worker : BackgroundService, IWorker, IDisposable { }",
+ "Worker",
+ {"BackgroundService", "IWorker", "IDisposable", NULL},
+ {":", NULL},
+ 3
+ },
+ /* ── generic base ────────────────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class OrderList : List<Order> { }",
+ "OrderList",
+ {"List", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── generic base + interface ────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Stack<T> : Collection<T>, IStack<T> { }",
+ "Stack",
+ {"Collection", "IStack", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── interface extends two interfaces ────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public interface ICrud : IRead, IWrite { }",
+ "ICrud",
+ {"IRead", "IWrite", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── abstract class with base ────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public abstract class AbstractHandler : BaseHandler { protected abstract void Handle(); }",
+ "AbstractHandler",
+ {"BaseHandler", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── sealed class ────────────────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public sealed class SingletonService : BaseService { }",
+ "SingletonService",
+ {"BaseService", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── namespace-qualified base ────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "namespace App { public class Handler : System.Net.Http.HttpMessageHandler { "
+ "protected override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> "
+ "SendAsync(System.Net.Http.HttpRequestMessage r, System.Threading.CancellationToken c) "
+ "{ return null; } } }",
+ "Handler",
+ {"System.Net.Http.HttpMessageHandler", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── partial class with base ─────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public partial class PartialSvc : BaseSvc, IPartial { }",
+ "PartialSvc",
+ {"BaseSvc", "IPartial", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── record with base ────────────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public record OrderRecord(int Id) : BaseRecord(Id), IRecord { }",
+ "OrderRecord",
+ {"BaseRecord", "IRecord", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── struct implements interface ─────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public struct Point : IEquatable<Point> { public bool Equals(Point other) => true; }",
+ "Point",
+ {"IEquatable", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── class with four interfaces ──────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Mega : Base, IA, IB, IC, ID { }",
+ "Mega",
+ {"Base", "IA", "IB", "IC", "ID", NULL},
+ {":", NULL},
+ 5
+ },
+ /* ── exception subclass ─────────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class AppException : Exception { public AppException(string msg) : base(msg) {} }",
+ "AppException",
+ {"Exception", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── nested class with base ──────────────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Outer { public class Inner : Outer { } }",
+ "Inner",
+ {"Outer", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── class in namespace with base ───────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "namespace MyApp.Services { public class OrderSvc : BaseOrderSvc, IOrderSvc { } }",
+ "OrderSvc",
+ {"BaseOrderSvc", "IOrderSvc", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── interface with single parent ───────────────────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public interface IAdvancedService : IBasicService { void AdvancedOp(); }",
+ "IAdvancedService",
+ {"IBasicService", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── generic class implements generic interface ───────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Repo<T> : BaseRepo<T>, IRepo<T> where T : class { }",
+ "Repo",
+ {"BaseRepo", "IRepo", NULL},
+ {":", "where", NULL},
+ 2
+ },
+ /* ── class with IDisposable + IAsyncDisposable ───────────────── */
+ {
+ CBM_LANG_CSHARP, "Svc.cs",
+ "public class Resource : IDisposable, IAsyncDisposable { "
+ "public void Dispose() {} "
+ "public System.Threading.Tasks.ValueTask DisposeAsync() => default; }",
+ "Resource",
+ {"IDisposable", "IAsyncDisposable", NULL},
+ {":", NULL},
+ 2
+ },
+};
+
+TEST(inherit_csharp) {
+ RUN_CASES(csharp_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * C++ (expected: GREEN — regression guards)
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t cpp_cases[] = {
+ /* ── public single base ─────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class Dog : public Animal { };",
+ "Dog",
+ {"Animal", NULL},
+ {"public", "private", "protected", ":", NULL},
+ 1
+ },
+ /* ── private base ────────────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class Impl : private Base { };",
+ "Impl",
+ {"Base", NULL},
+ {"public", "private", "protected", ":", NULL},
+ 1
+ },
+ /* ── multiple inheritance ────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class C : public A, public B { };",
+ "C",
+ {"A", "B", NULL},
+ {"public", "private", "protected", ":", NULL},
+ 2
+ },
+ /* ── struct with base ────────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "struct Derived : Base { int x; };",
+ "Derived",
+ {"Base", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── virtual inheritance ─────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class D : public virtual B1, public virtual B2 { };",
+ "D",
+ {"B1", "B2", NULL},
+ {"virtual", "public", ":", NULL},
+ 2
+ },
+ /* ── template base ───────────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "template<typename T> class Stack : public std::vector<T> { };",
+ "Stack",
+ {"std::vector", NULL},
+ {"public", "template", ":", NULL},
+ 1
+ },
+ /* ── CRTP pattern ────────────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "template<typename Derived> class Base { };\n"
+ "class Concrete : public Base<Concrete> { };",
+ "Concrete",
+ {"Base", NULL},
+ {"public", ":", NULL},
+ 1
+ },
+ /* ── abstract class (pure virtual) with public base ──────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class AbstractLogger : public ILogger { public: virtual void log(const char*) = 0; };",
+ "AbstractLogger",
+ {"ILogger", NULL},
+ {"public", ":", NULL},
+ 1
+ },
+ /* ── class in namespace ──────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "namespace net { class Socket : public BaseSocket { }; }",
+ "Socket",
+ {"BaseSocket", NULL},
+ {"public", ":", NULL},
+ 1
+ },
+ /* ── three-way diamond inheritance ──────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class A { }; class B : public A { }; class C : public A { };\n"
+ "class D : public B, public C { };",
+ "D",
+ {"B", "C", NULL},
+ {"public", ":", NULL},
+ 2
+ },
+ /* ── fully qualified base name ───────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class MyStream : public std::ostream { public: MyStream() : std::ostream(nullptr) {} };",
+ "MyStream",
+ {"std::ostream", NULL},
+ {"public", ":", NULL},
+ 1
+ },
+ /* ── protected base ──────────────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class Node : protected TreeNode { };",
+ "Node",
+ {"TreeNode", NULL},
+ {"protected", ":", NULL},
+ 1
+ },
+ /* ── multiple bases with mixed access ────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class Widget : public Drawable, private EventHandler, protected Serializable { };",
+ "Widget",
+ {"Drawable", "EventHandler", "Serializable", NULL},
+ {"public", "private", "protected", ":", NULL},
+ 3
+ },
+ /* ── exception class from std::exception ─────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "#include <stdexcept>\nclass AppError : public std::runtime_error { "
+ "public: AppError(const char* m) : std::runtime_error(m) {} };",
+ "AppError",
+ {"std::runtime_error", NULL},
+ {"public", ":", NULL},
+ 1
+ },
+ /* ── template class with multiple template base types ────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "template<typename K, typename V>\n"
+ "class LruCache : public Cache<K,V>, public Observable { };",
+ "LruCache",
+ {"Cache", "Observable", NULL},
+ {"public", ":", NULL},
+ 2
+ },
+ /* ── nested class with base ──────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class Outer { public: class Inner : public Base { }; };",
+ "Inner",
+ {"Base", NULL},
+ {"public", ":", NULL},
+ 1
+ },
+ /* ── class using final specifier ─────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class Leaf final : public Node { };",
+ "Leaf",
+ {"Node", NULL},
+ {"public", "final", ":", NULL},
+ 1
+ },
+ /* ── struct with scoped base ─────────────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "struct MyVisitor : public boost::static_visitor<int> { int operator()(int x) { return x; } };",
+ "MyVisitor",
+ {"boost::static_visitor", NULL},
+ {"public", ":", NULL},
+ 1
+ },
+ /* ── policy-based design (two template base policies) ────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "template<class StoragePolicy, class LogPolicy>\n"
+ "class Engine : public StoragePolicy, public LogPolicy { };",
+ "Engine",
+ {"StoragePolicy", "LogPolicy", NULL},
+ {"public", ":", NULL},
+ 2
+ },
+ /* ── empty base optimization (EBO) ──────────────────────────── */
+ {
+ CBM_LANG_CPP, "svc.cpp",
+ "class EboContainer : private Allocator, public ContainerBase { };",
+ "EboContainer",
+ {"Allocator", "ContainerBase", NULL},
+ {"private", "public", ":", NULL},
+ 2
+ },
+};
+
+TEST(inherit_cpp) {
+ RUN_CASES(cpp_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * TYPESCRIPT (expected: RED — keyword-capture bug)
+ *
+ * Bug: the TS extractor stores "extends" / "implements" as the base
+ * name instead of the following type name.
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t typescript_cases[] = {
+ /* ── extends single class ────────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Dog extends Animal { bark(): void {} }",
+ "Dog",
+ {"Animal", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── implements single interface ─────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Repo implements IRepository { save(x: any) {} }",
+ "Repo",
+ {"IRepository", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── extends + implements ────────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Service extends BaseService implements IService { run() {} }",
+ "Service",
+ {"BaseService", "IService", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── implements two interfaces ───────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Codec implements Encoder, Decoder { encode(x: any) {} decode(x: any) {} }",
+ "Codec",
+ {"Encoder", "Decoder", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── extends + implements three ──────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Mega extends Base implements A, B, C { }",
+ "Mega",
+ {"Base", "A", "B", "C", NULL},
+ {"extends", "implements", NULL},
+ 4
+ },
+ /* ── generic base ────────────────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Stack<T> extends Array<T> implements IStack<T> { push(x: T) { return 0; } }",
+ "Stack",
+ {"Array", "IStack", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── interface extends interface ─────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "interface ReadWriteRepo extends ReadRepo, WriteRepo { }",
+ "ReadWriteRepo",
+ {"ReadRepo", "WriteRepo", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── abstract class ──────────────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "abstract class AbstractSvc extends BaseService { abstract run(): void; }",
+ "AbstractSvc",
+ {"BaseService", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── class extends Error ─────────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class AppError extends Error { constructor(msg: string) { super(msg); } }",
+ "AppError",
+ {"Error", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── class extends EventEmitter ──────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "import { EventEmitter } from 'events';\n"
+ "class Bus extends EventEmitter { emit(ev: string) { return super.emit(ev); } }",
+ "Bus",
+ {"EventEmitter", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── generic class extends generic base ──────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Pair<A, B> extends AbstractPair<A, B> implements Iterable<A> { "
+ "[Symbol.iterator]() { return this as any; } }",
+ "Pair",
+ {"AbstractPair", "Iterable", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── class implements multiple generic interfaces ─────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Handler implements Middleware<Request, Response>, Disposable { "
+ "handle(req: Request): Response { return null as any; } dispose() {} }",
+ "Handler",
+ {"Middleware", "Disposable", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── class in module namespace ───────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "export class OrderService extends BaseOrderService implements IOrderService { }",
+ "OrderService",
+ {"BaseOrderService", "IOrderService", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── mixin target class (concrete class consuming a mixin) ──────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class Loggable { log(msg: string) { console.log(msg); } }\n"
+ "class Logger extends Loggable implements ILogger { info(msg: string) { this.log(msg); } }",
+ "Logger",
+ {"Loggable", "ILogger", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── decorator + extends ─────────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "function Injectable() { return (c: any) => c; }\n"
+ "@Injectable()\nclass UserService extends BaseUserService { }",
+ "UserService",
+ {"BaseUserService", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── class implementing multiple inferred generics ───────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class BinaryTree<T> extends Tree<T> implements Traversable<T>, Serializable { "
+ "traverse() {} serialize() { return ''; } }",
+ "BinaryTree",
+ {"Tree", "Traversable", "Serializable", NULL},
+ {"extends", "implements", NULL},
+ 3
+ },
+ /* ── React component extends ──────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "import React from 'react';\n"
+ "class MyComponent extends React.Component<{}, {}> { render() { return null; } }",
+ "MyComponent",
+ {"React.Component", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── exception hierarchy ─────────────────────────────────────── */
+ {
+ CBM_LANG_TYPESCRIPT, "svc.ts",
+ "class NetworkError extends AppError implements Retryable { retry() {} }",
+ "NetworkError",
+ {"AppError", "Retryable", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+};
+
+TEST(inherit_typescript) {
+ RUN_CASES(typescript_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * TSX (expected: RED — same keyword-capture bug as TypeScript)
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t tsx_cases[] = {
+ /* ── React.Component subclass ────────────────────────────────── */
+ {
+ CBM_LANG_TSX, "App.tsx",
+ "import React from 'react';\n"
+ "class App extends React.Component<{}, {}> { render() { return <div/>; } }",
+ "App",
+ {"React.Component", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── PureComponent subclass ──────────────────────────────────── */
+ {
+ CBM_LANG_TSX, "Widget.tsx",
+ "import { PureComponent } from 'react';\n"
+ "class Widget extends PureComponent { render() { return null; } }",
+ "Widget",
+ {"PureComponent", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── component + interface ───────────────────────────────────── */
+ {
+ CBM_LANG_TSX, "Form.tsx",
+ "import { Component } from 'react';\n"
+ "class Form extends Component<FormProps, FormState> implements IForm { "
+ "render() { return <form/>; } submit() {} }",
+ "Form",
+ {"Component", "IForm", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── abstract component ──────────────────────────────────────── */
+ {
+ CBM_LANG_TSX, "Base.tsx",
+ "import { Component } from 'react';\n"
+ "abstract class BaseView extends Component { abstract renderContent(): JSX.Element; }",
+ "BaseView",
+ {"Component", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── non-React class in .tsx ─────────────────────────────────── */
+ {
+ CBM_LANG_TSX, "store.tsx",
+ "class UserStore extends BaseStore implements IStore { load() {} }",
+ "UserStore",
+ {"BaseStore", "IStore", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── generic component ───────────────────────────────────────── */
+ {
+ CBM_LANG_TSX, "List.tsx",
+ "import { Component } from 'react';\n"
+ "class List<T> extends Component<{ items: T[] }> { render() { return <ul/>; } }",
+ "List",
+ {"Component", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── interface extends in tsx file ───────────────────────────── */
+ {
+ CBM_LANG_TSX, "types.tsx",
+ "interface IAdvanced extends IBasic, IExtended { doAdvanced(): void; }",
+ "IAdvanced",
+ {"IBasic", "IExtended", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── multiple interfaces + base ──────────────────────────────── */
+ {
+ CBM_LANG_TSX, "Mega.tsx",
+ "class MegaComponent extends React.Component implements Serializable, Disposable { "
+ "render() { return null; } }",
+ "MegaComponent",
+ {"React.Component", "Serializable", "Disposable", NULL},
+ {"extends", "implements", NULL},
+ 3
+ },
+ /* ── error boundary component ────────────────────────────────── */
+ {
+ CBM_LANG_TSX, "ErrorBoundary.tsx",
+ "import { Component, ReactNode, ErrorInfo } from 'react';\n"
+ "class ErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean }> { "
+ "componentDidCatch(err: Error, info: ErrorInfo) {} render() { return null; } }",
+ "ErrorBoundary",
+ {"Component", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── class extending custom hook class ───────────────────────── */
+ {
+ CBM_LANG_TSX, "hook.tsx",
+ "class AdvancedHook extends BaseHook implements IHook { use() {} }",
+ "AdvancedHook",
+ {"BaseHook", "IHook", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+};
+
+TEST(inherit_tsx) {
+ RUN_CASES(tsx_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * PHP (expected: RED — base_classes never populated)
+ *
+ * Bug: the PHP extractor does not populate base_classes for `extends`
+ * or `implements`. All rows assert the class is found and base_classes
+ * is non-NULL, which fails immediately.
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t php_cases[] = {
+ /* ── extends single class ────────────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass Dog extends Animal { public function bark(): void {} }",
+ "Dog",
+ {"Animal", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── implements single interface ─────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass Repo implements IRepository { public function save($x) {} }",
+ "Repo",
+ {"IRepository", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── extends + implements ────────────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass Service extends BaseService implements IService { public function run() {} }",
+ "Service",
+ {"BaseService", "IService", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── implements two interfaces ───────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass Codec implements Encoder, Decoder { "
+ "public function encode($x) {} public function decode($x) {} }",
+ "Codec",
+ {"Encoder", "Decoder", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── extends + implements three ──────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass Mega extends Base implements A, B, C { }",
+ "Mega",
+ {"Base", "A", "B", "C", NULL},
+ {"extends", "implements", NULL},
+ 4
+ },
+ /* ── abstract class ──────────────────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nabstract class AbstractSvc extends BaseService { abstract public function run(): void; }",
+ "AbstractSvc",
+ {"BaseService", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── final class ─────────────────────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nfinal class FinalSvc extends BaseSvc { }",
+ "FinalSvc",
+ {"BaseSvc", NULL},
+ {"extends", "implements", NULL},
+ 1
+ },
+ /* ── namespace-qualified base ────────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nnamespace App\\Services;\nuse App\\Base\\BaseService;\n"
+ "class OrderService extends BaseService implements IOrderService { }",
+ "OrderService",
+ {"BaseService", "IOrderService", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── interface extends interface ─────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\ninterface IAdvanced extends IBasic, IExtended { public function doAdvanced(): void; }",
+ "IAdvanced",
+ {"IBasic", "IExtended", NULL},
+ {"extends", NULL},
+ 2
+ },
+ /* ── backslash-prefixed fully qualified base ──────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass MyException extends \\RuntimeException { }",
+ "MyException",
+ {"RuntimeException", NULL},
+ {"extends", "\\\\", NULL},
+ 1
+ },
+ /* ── class extending Exception ───────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass AppException extends \\Exception { "
+ "public function __construct(string $msg) { parent::__construct($msg); } }",
+ "AppException",
+ {"Exception", NULL},
+ {"extends", NULL},
+ 1
+ },
+ /* ── implements four interfaces ──────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass Adapter implements IA, IB, IC, ID { "
+ "public function a() {} public function b() {} "
+ "public function c() {} public function d() {} }",
+ "Adapter",
+ {"IA", "IB", "IC", "ID", NULL},
+ {"implements", NULL},
+ 4
+ },
+ /* ── trait-using class also extends ──────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\ntrait Logging { public function log() {} }\n"
+ "class MyService extends BaseService { use Logging; }",
+ "MyService",
+ {"BaseService", NULL},
+ {"extends", NULL},
+ 1
+ },
+ /* ── nested namespace with extends ───────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nnamespace App\\Http\\Controllers;\n"
+ "class UserController extends Controller { }",
+ "UserController",
+ {"Controller", NULL},
+ {"extends", NULL},
+ 1
+ },
+ /* ── multiple namespaced interfaces ──────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nuse Psr\\Http\\Server\\RequestHandlerInterface;\n"
+ "use Psr\\Http\\Message\\ResponseInterface;\n"
+ "class PsrHandler extends BaseHandler implements RequestHandlerInterface { "
+ "public function handle($req): ResponseInterface { return null; } }",
+ "PsrHandler",
+ {"BaseHandler", "RequestHandlerInterface", NULL},
+ {"extends", "implements", NULL},
+ 2
+ },
+ /* ── readonly class (PHP 8.2) ────────────────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nreadonly class ValueObject extends BaseValue { public function __construct("
+ "public readonly string $value) {} }",
+ "ValueObject",
+ {"BaseValue", NULL},
+ {"extends", NULL},
+ 1
+ },
+ /* ── enum implements interface (PHP 8.1) ─────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\ninterface HasLabel { public function label(): string; }\n"
+ "enum Status: string implements HasLabel { "
+ "case Active = 'active'; public function label(): string { return $this->value; } }",
+ "Status",
+ {"HasLabel", NULL},
+ {"implements", NULL},
+ 1
+ },
+ /* ── extends with constructor promotion ──────────────────────── */
+ {
+ CBM_LANG_PHP, "Svc.php",
+ "<?php\nclass PromotedDto extends BaseDto { "
+ "public function __construct(public readonly string $name) { parent::__construct(); } }",
+ "PromotedDto",
+ {"BaseDto", NULL},
+ {"extends", NULL},
+ 1
+ },
+};
+
+TEST(inherit_php) {
+ RUN_CASES(php_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * KOTLIN (expected: RED — `:` supertype syntax not parsed)
+ *
+ * Bug: the Kotlin extractor does not parse the `: SuperType` syntax,
+ * leaving base_classes empty for all Kotlin classes with supertypes.
+ * ═══════════════════════════════════════════════════════════════════ */
+
+static const inherit_case_t kotlin_cases[] = {
+ /* ── extends single class ────────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class Animal(val name: String)\nclass Dog(name: String) : Animal(name)",
+ "Dog",
+ {"Animal", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── implements single interface ─────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "interface IRepo { fun save(x: Any) }\nclass Repo : IRepo { override fun save(x: Any) {} }",
+ "Repo",
+ {"IRepo", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── extends + implements ────────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class BaseService\ninterface IService { fun run() }\n"
+ "class Service : BaseService(), IService { override fun run() {} }",
+ "Service",
+ {"BaseService", "IService", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── implements two interfaces ───────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "interface Encoder { fun encode(x: Any): String }\n"
+ "interface Decoder { fun decode(s: String): Any }\n"
+ "class Codec : Encoder, Decoder { "
+ "override fun encode(x: Any) = x.toString() "
+ "override fun decode(s: String): Any = s }",
+ "Codec",
+ {"Encoder", "Decoder", NULL},
+ {":", NULL},
+ 2
+ },
+ /* ── abstract class ──────────────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "abstract class AbstractSvc : BaseService() { abstract fun run() }",
+ "AbstractSvc",
+ {"BaseService", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── data class with base ────────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class BaseEntity(val id: Long)\n"
+ "data class User(val name: String, override val id: Long) : BaseEntity(id)",
+ "User",
+ {"BaseEntity", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── sealed class with base ──────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "sealed class Result\nclass Success(val value: Any) : Result()\nclass Failure(val err: Throwable) : Result()",
+ "Success",
+ {"Result", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── object (singleton) implementing interface ───────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "interface Logger { fun log(msg: String) }\nobject ConsoleLogger : Logger { override fun log(msg: String) = println(msg) }",
+ "ConsoleLogger",
+ {"Logger", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── generic class with bound ────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class Container<T>\nclass Box<T : Comparable<T>> : Container<T>()",
+ "Box",
+ {"Container", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── companion object (no base — sanity check, no crash) ─────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "class MyClass { companion object : Factory<MyClass>() { override fun create() = MyClass() } }",
+ "MyClass",
+ {NULL}, /* outer class has no base; we just want no crash */
+ {NULL},
+ 0
+ },
+ /* ── enum class implementing interface ───────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "interface Displayable { fun display(): String }\n"
+ "enum class Status : Displayable { OPEN, CLOSED; override fun display() = name }",
+ "Status",
+ {"Displayable", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── class extending Exception ───────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "class AppException(message: String) : Exception(message)",
+ "AppException",
+ {"Exception", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── implements Comparable ───────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "class Version(val major: Int, val minor: Int) : Comparable<Version> { "
+ "override fun compareTo(other: Version) = compareValuesBy(this, other, { it.major }, { it.minor }) }",
+ "Version",
+ {"Comparable", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── open class hierarchy ────────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class Vehicle(val speed: Int)\nopen class MotorVehicle(speed: Int) : Vehicle(speed)\n"
+ "class Car(speed: Int) : MotorVehicle(speed)",
+ "Car",
+ {"MotorVehicle", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── inner class with base ───────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class BaseNode\nclass Tree { inner class Node : BaseNode() { var value: Int = 0 } }",
+ "Node",
+ {"BaseNode", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── fun interface (SAM) ─────────────────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "fun interface Transformer { fun transform(input: String): String }\n"
+ "class UpperTransformer : Transformer { override fun transform(input: String) = input.uppercase() }",
+ "UpperTransformer",
+ {"Transformer", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── three bases (base + two interfaces) ─────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class BaseWorker\ninterface Runnable { fun run() }\ninterface Stoppable { fun stop() }\n"
+ "class Worker : BaseWorker(), Runnable, Stoppable { override fun run() {} override fun stop() {} }",
+ "Worker",
+ {"BaseWorker", "Runnable", "Stoppable", NULL},
+ {":", NULL},
+ 3
+ },
+ /* ── annotation class with base ─────────────────────────────────*/
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "annotation class MyAnnotation\nclass AnnotatedClass : BaseClass() { @MyAnnotation fun doWork() {} }",
+ "AnnotatedClass",
+ {"BaseClass", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── value class (inline, Kotlin 1.5+) ──────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "interface Printable { fun print() }\n"
+ "@JvmInline value class UserId(val id: String) : Printable { override fun print() = println(id) }",
+ "UserId",
+ {"Printable", NULL},
+ {":", NULL},
+ 1
+ },
+ /* ── class with type-projected bound ─────────────────────────── */
+ {
+ CBM_LANG_KOTLIN, "Svc.kt",
+ "open class Repository<T : Any>\nclass UserRepository : Repository<User>()",
+ "UserRepository",
+ {"Repository", NULL},
+ {":", NULL},
+ 1
+ },
+};
+
+TEST(inherit_kotlin) {
+ RUN_CASES(kotlin_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * RUST — impl Trait for Struct (expected: GREEN — regression guards)
+ *
+ * Rust does not use `base_classes` on the Struct def. Instead the
+ * extractor populates CBMFileResult.impl_traits (CBMImplTrait array)
+ * with {trait_name, struct_name} pairs.
+ * ═══════════════════════════════════════════════════════════════════ */
+
+/* Rust helper: check impl_traits array. */
+static int rust_has_impl(CBMFileResult *r, const char *trait_name, const char *struct_name) {
+ for (int i = 0; i < r->impl_traits.count; i++) {
+ CBMImplTrait *it = &r->impl_traits.items[i];
+ if (it->trait_name && strcmp(it->trait_name, trait_name) == 0 &&
+ it->struct_name && strcmp(it->struct_name, struct_name) == 0)
+ return 1;
+ }
+ return 0;
+}
+
+typedef struct {
+ const char *src;
+ const char *trait_name;
+ const char *struct_name;
+} rust_impl_case_t;
+
+static int run_rust_impl(const rust_impl_case_t *tc) {
+ CBMFileResult *r = cbm_extract_file(tc->src, (int)strlen(tc->src),
+ CBM_LANG_RUST, "t", "lib.rs",
+ 0, NULL, NULL);
+ if (!r) {
+ printf(" FAIL [impl %s for %s] extract returned NULL\n",
+ tc->trait_name, tc->struct_name);
+ return 1;
+ }
+ int found = rust_has_impl(r, tc->trait_name, tc->struct_name);
+ if (!found) {
+ printf(" FAIL [impl %s for %s] not found in impl_traits\n",
+ tc->trait_name, tc->struct_name);
+ cbm_free_result(r);
+ return 1;
+ }
+ cbm_free_result(r);
+ return 0;
+}
+
+#define RUN_RUST_CASES(table) \
+ do { \
+ int _fail = 0; \
+ int _n = (int)(sizeof(table) / sizeof(table[0])); \
+ for (int _i = 0; _i < _n; _i++) { \
+ if (run_rust_impl(&table[_i]) != 0) _fail++; \
+ } \
+ if (_fail > 0) { \
+ printf(" FAIL %d / %d Rust impl cases above failed\n", _fail, _n); \
+ return 1; \
+ } \
+ } while (0)
+
+static const rust_impl_case_t rust_cases[] = {
+ /* ── basic trait impl ───────────────────────────────────────── */
+ {
+ "trait Greet { fn greet(&self) -> String; }\n"
+ "struct Dog;\nimpl Greet for Dog { fn greet(&self) -> String { \"Woof\".into() } }",
+ "Greet", "Dog"
+ },
+ /* ── Display trait ───────────────────────────────────────────── */
+ {
+ "use std::fmt;\nstruct Point { x: f64, y: f64 }\n"
+ "impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, \"({},{})\", self.x, self.y) } }",
+ "fmt::Display", "Point"
+ },
+ /* ── Iterator trait ──────────────────────────────────────────── */
+ {
+ "struct Counter { count: u32 }\n"
+ "impl Iterator for Counter { type Item = u32; fn next(&mut self) -> Option<u32> { if self.count < 5 { self.count += 1; Some(self.count) } else { None } } }",
+ "Iterator", "Counter"
+ },
+ /* ── From trait ──────────────────────────────────────────────── */
+ {
+ "struct Meters(f64);\nstruct Feet(f64);\n"
+ "impl From<Feet> for Meters { fn from(f: Feet) -> Self { Meters(f.0 * 0.3048) } }",
+ "From", "Meters"
+ },
+ /* ── Default trait ───────────────────────────────────────────── */
+ {
+ "struct Config { debug: bool, level: u32 }\n"
+ "impl Default for Config { fn default() -> Self { Config { debug: false, level: 0 } } }",
+ "Default", "Config"
+ },
+ /* ── PartialEq + Eq ──────────────────────────────────────────── */
+ {
+ "struct Id(u64);\nimpl PartialEq for Id { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } }\nimpl Eq for Id {}",
+ "PartialEq", "Id"
+ },
+ /* ── Clone + Copy ────────────────────────────────────────────── */
+ {
+ "#[derive(Copy)]\nstruct Tag(u8);\nimpl Clone for Tag { fn clone(&self) -> Self { *self } }",
+ "Clone", "Tag"
+ },
+ /* ── custom trait for generic struct ─────────────────────────── */
+ {
+ "trait Serializable { fn serialize(&self) -> Vec<u8>; }\n"
+ "struct Buffer<T> { data: Vec<T> }\n"
+ "impl<T: Clone> Serializable for Buffer<T> { fn serialize(&self) -> Vec<u8> { vec![] } }",
+ "Serializable", "Buffer"
+ },
+ /* ── Drop trait ──────────────────────────────────────────────── */
+ {
+ "struct Resource { name: String }\n"
+ "impl Drop for Resource { fn drop(&mut self) { println!(\"drop {}\", self.name); } }",
+ "Drop", "Resource"
+ },
+ /* ── crate-qualified trait ───────────────────────────────────── */
+ {
+ "mod io { pub trait Write { fn write(&mut self, buf: &[u8]) -> usize; } }\n"
+ "struct Socket;\nimpl io::Write for Socket { fn write(&mut self, buf: &[u8]) -> usize { buf.len() } }",
+ "io::Write", "Socket"
+ },
+ /* ── trait impl with associated type ────────────────────────── */
+ {
+ "trait Producer { type Item; fn produce(&self) -> Self::Item; }\n"
+ "struct Factory;\nimpl Producer for Factory { type Item = u32; fn produce(&self) -> u32 { 42 } }",
+ "Producer", "Factory"
+ },
+ /* ── Error trait ─────────────────────────────────────────────── */
+ {
+ "use std::fmt;\n"
+ "#[derive(Debug)]\nstruct AppError { msg: String }\n"
+ "impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, \"{}\", self.msg) } }\n"
+ "impl std::error::Error for AppError {}",
+ "std::error::Error", "AppError"
+ },
+ /* ── Ord trait for newtype ────────────────────────────────────── */
+ {
+ "use std::cmp::Ordering;\n#[derive(Eq, PartialEq)]\nstruct Priority(u8);\n"
+ "impl PartialOrd for Priority { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } }\n"
+ "impl Ord for Priority { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&other.0) } }",
+ "Ord", "Priority"
+ },
+ /* ── Index trait ─────────────────────────────────────────────── */
+ {
+ "use std::ops::Index;\nstruct Matrix { data: Vec<f64>, cols: usize }\n"
+ "impl Index<(usize, usize)> for Matrix { type Output = f64; fn index(&self, idx: (usize, usize)) -> &f64 { &self.data[idx.0 * self.cols + idx.1] } }",
+ "Index", "Matrix"
+ },
+ /* ── Add operator overload ───────────────────────────────────── */
+ {
+ "use std::ops::Add;\n#[derive(Clone, Copy)]\nstruct Vec2 { x: f32, y: f32 }\n"
+ "impl Add for Vec2 { type Output = Vec2; fn add(self, rhs: Vec2) -> Vec2 { Vec2 { x: self.x + rhs.x, y: self.y + rhs.y } } }",
+ "Add", "Vec2"
+ },
+ /* ── Send + Sync safety impls ─────────────────────────────────── */
+ {
+ "struct SharedState { data: std::sync::Mutex<Vec<u8>> }\n"
+ "unsafe impl Send for SharedState {}\nunsafe impl Sync for SharedState {}",
+ "Send", "SharedState"
+ },
+ /* ── Deref coercion ──────────────────────────────────────────── */
+ {
+ "use std::ops::Deref;\nstruct Wrapper<T>(T);\n"
+ "impl<T> Deref for Wrapper<T> { type Target = T; fn deref(&self) -> &T { &self.0 } }",
+ "Deref", "Wrapper"
+ },
+ /* ── AsRef trait ─────────────────────────────────────────────── */
+ {
+ "struct Path(String);\nimpl AsRef<str> for Path { fn as_ref(&self) -> &str { &self.0 } }",
+ "AsRef", "Path"
+ },
+ /* ── Hash trait ──────────────────────────────────────────────── */
+ {
+ "use std::hash::{Hash, Hasher};\n#[derive(Eq, PartialEq)]\nstruct Key(String);\n"
+ "impl Hash for Key { fn hash<H: Hasher>(&self, state: &mut H) { self.0.hash(state); } }",
+ "Hash", "Key"
+ },
+ /* ── serde Serialize / Deserialize (external crate trait) ────── */
+ {
+ "trait Serialize { fn serialize(&self) -> String; }\n"
+ "trait Deserialize { fn deserialize(s: &str) -> Self; }\n"
+ "struct JsonRecord { id: u64 }\n"
+ "impl Serialize for JsonRecord { fn serialize(&self) -> String { format!(\"{{\\\"id\\\":{}}}\", self.id) } }\n"
+ "impl Deserialize for JsonRecord { fn deserialize(_s: &str) -> Self { JsonRecord { id: 0 } } }",
+ "Serialize", "JsonRecord"
+ },
+};
+
+TEST(inherit_rust_impls) {
+ RUN_RUST_CASES(rust_cases);
+ PASS();
+}
+
+/* ═══════════════════════════════════════════════════════════════════
+ * SUITE declaration
+ * ═══════════════════════════════════════════════════════════════════ */
+
+SUITE(extraction_inheritance) {
+ /* Languages expected GREEN (correct extractors — regression guards) */
+ RUN_TEST(inherit_java);
+ RUN_TEST(inherit_csharp);
+ RUN_TEST(inherit_cpp);
+ RUN_TEST(inherit_rust_impls);
+
+ /* Languages expected RED (broken extractors — reproduce-first) */
+ RUN_TEST(inherit_python); /* RED: identifier-node not matched in collect_bases_from_field */
+ RUN_TEST(inherit_typescript); /* RED: keyword "extends"/"implements" captured instead of type name */
+ RUN_TEST(inherit_tsx); /* RED: same keyword-capture bug as TypeScript */
+ RUN_TEST(inherit_php); /* RED: base_classes never populated */
+ RUN_TEST(inherit_kotlin); /* RED: `:` supertype syntax not parsed */
+}
diff --git a/tests/test_main.c b/tests/test_main.c
index 51c0b03cc..ecbd0d327 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -20,6 +20,8 @@ extern void suite_log(void);
extern void suite_str_util(void);
extern void suite_platform(void);
extern void suite_extraction(void);
+extern void suite_extraction_inheritance(void);
+extern void suite_extraction_imports(void);
extern void suite_grammar_regression(void);
extern void suite_grammar_labels(void);
extern void suite_grammar_imports(void);
@@ -100,6 +102,8 @@ int main(void) {
/* Existing C code regression tests */
RUN_SUITE(ac);
RUN_SUITE(extraction);
+ RUN_SUITE(extraction_inheritance);
+ RUN_SUITE(extraction_imports);
RUN_SUITE(grammar_regression);
RUN_SUITE(grammar_labels);
RUN_SUITE(grammar_imports);