feat(graph): full Dart support via tree-sitter AST (#71)

Dart previously fell through to the regex symbol fallback, which cannot
match type-first signatures (void foo(), Future<int> baz() async), so
classes, methods, and calls were invisible to codebase_symbol,
codebase_flow, and codebase_impact, and files were chunked by line
count instead of declaration boundaries.

- Register @ast-grep/lang-dart as a dynamic grammar (per-grammar
  failure isolation keeps missing prebuilds on the regex fallback).
- Add extractFromDart: classes, mixins (trait), enums, extensions,
  typedefs, type-first top-level functions, getters/setters, and
  constructors including named and factory forms. Scope ranges are
  stitched from Dart's sibling function_signature/function_body pairs.
  Calls are recovered from argument_part nodes: method calls, bare
  calls, constructor invocations, prefixed calls, and cascades.
- Add dart to TOP_LEVEL_KINDS so chunking follows declaration
  boundaries; signature and body kinds are both listed so the
  overlap-merge fuses each pair into one region.
- Add dart main() to ENTRY_POINT_NAMES for entry-point detection.
- Move Dart to Full Support in the README language matrix.
This commit is contained in:
Giancarlo Erra
2026-06-11 12:12:18 +01:00
parent ec97746373
commit 7bd9eb5308
10 changed files with 414 additions and 15 deletions
+4 -2
View File
@@ -959,13 +959,15 @@ SocratiCode supports languages at three levels:
### Full Support (indexing + code graph + AST chunking)
JavaScript, TypeScript, TSX, Python, Java, Kotlin, Scala, C, C++, C#, Go, Rust, Ruby, PHP, Swift, Bash/Shell, HTML, CSS/SCSS, Svelte, Vue
JavaScript, TypeScript, TSX, Python, Java, Kotlin, Scala, C, C++, C#, Go, Rust, Ruby, PHP, Swift, Dart, Bash/Shell, HTML, CSS/SCSS, Svelte, Vue
Svelte and Vue: imports extracted from `<script>` blocks (re-parsed as TypeScript) and CSS `@import`/`@require` from `<style>` blocks (any combination of `lang`, `scoped`, `module`, `global` attributes). Path aliases from `tsconfig.json`/`jsconfig.json` `compilerOptions.paths` are resolved (including `extends` chains). SCSS partial resolution (`_` prefix convention) is supported.
Dart: symbols (classes, mixins, enums, extensions, typedefs, functions, getters/setters, constructors including named and factory), call sites (method calls, cascades, constructor invocations), `main()` entry-point detection, and AST chunking are all tree-sitter based; import/export/part edges are extracted via regex.
### Code Graph via Regex + Indexing
Dart (import/export/part), Lua (require/dofile/loadfile), SASS, LESS (CSS `@import` extraction)
Lua (require/dofile/loadfile), SASS, LESS (CSS `@import` extraction)
### Indexing Only (hybrid search, line-based chunking)
+19
View File
@@ -13,6 +13,7 @@
"@ast-grep/lang-c": "^0.0.5",
"@ast-grep/lang-cpp": "^0.0.5",
"@ast-grep/lang-csharp": "^0.0.5",
"@ast-grep/lang-dart": "^0.0.7",
"@ast-grep/lang-go": "^0.0.5",
"@ast-grep/lang-java": "^0.0.6",
"@ast-grep/lang-kotlin": "^0.0.6",
@@ -126,6 +127,24 @@
}
}
},
"node_modules/@ast-grep/lang-dart": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/@ast-grep/lang-dart/-/lang-dart-0.0.7.tgz",
"integrity": "sha512-9tTkOnw10g+/cgt8jw1XqZ0AKLDXoKYP1HoY3reZPQLhk4IWs8mNAu4Yd6E80CdQ2sJ10+L7wv1C16jTt4Yirw==",
"hasInstallScript": true,
"license": "ISC",
"dependencies": {
"@ast-grep/setup-lang": "0.0.6"
},
"peerDependencies": {
"tree-sitter-cli": "0.25.8"
},
"peerDependenciesMeta": {
"tree-sitter-cli": {
"optional": true
}
}
},
"node_modules/@ast-grep/lang-go": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/@ast-grep/lang-go/-/lang-go-0.0.5.tgz",
+1
View File
@@ -67,6 +67,7 @@
"@ast-grep/lang-c": "^0.0.5",
"@ast-grep/lang-cpp": "^0.0.5",
"@ast-grep/lang-csharp": "^0.0.5",
"@ast-grep/lang-dart": "^0.0.7",
"@ast-grep/lang-go": "^0.0.5",
"@ast-grep/lang-java": "^0.0.6",
"@ast-grep/lang-kotlin": "^0.0.6",
+1
View File
@@ -163,6 +163,7 @@ export const ENTRY_POINT_NAMES: Record<string, Set<string>> = {
swift: new Set(["main"]),
ruby: new Set(["main"]),
php: new Set(["main"]),
dart: new Set(["main"]),
};
// ── Path normalization ──────────────────────────────────────────────────
+1
View File
@@ -493,6 +493,7 @@ export function ensureDynamicLanguages(): void {
["bash", "@ast-grep/lang-bash"],
["php", "@ast-grep/lang-php"],
["lua", "@ast-grep/lang-lua"],
["dart", "@ast-grep/lang-dart"],
];
for (const [name, pkg] of langPackages) {
+209 -1
View File
@@ -145,7 +145,10 @@ export function extractSymbolsAndCalls(
if (langKey === "lua") {
return extractFromLua(source, relativePath, language, moduleSymbol);
}
// Dart, Svelte, Vue and others fall through to the regex fallback.
if (langKey === "dart") {
return extractFromDart(source, relativePath, language, moduleSymbol);
}
// Svelte, Vue and others fall through to the regex fallback.
return extractFromRegex(source, relativePath, language, moduleSymbol);
} catch (err) {
if (!symbolExtractionWarned.has(langKey)) {
@@ -276,6 +279,211 @@ function extractFromLua(
return { symbols, rawCalls };
}
// ── Dart (type-first signatures, sibling signature/body pairs, selector calls) ──
/**
* Dart previously fell through to the regex fallback, which cannot match
* type-first signatures (`void foo()`, `Future<int> baz() async`), so
* classes, methods, and call sites were invisible to the symbol graph.
* This walks the ast-grep Dart tree instead. Grammar quirks handled here:
* class/mixin/enum/extension nodes span their bodies, but a function is a
* `function_signature` followed by a SIBLING `function_body`, so scope
* ranges are stitched from each pair; plain constructors live inside a
* generic `declaration` wrapper; and there is no call_expression kind, so
* calls are recovered from `argument_part` nodes (callee = the preceding
* identifier or selector chain, or the `cascade_selector` for `..` calls).
*/
function extractFromDart(
source: string,
file: string,
language: string,
moduleSym: SymbolNode,
): ExtractedSymbols {
const root = parse("dart" as unknown as Lang, source).root();
const symbols: SymbolNode[] = [moduleSym];
const scopes: ScopeFrame[] = [];
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const kidsOf = (n: any): any[] => {
try {
return n.children();
} catch {
return [];
}
};
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const childOfKind = (n: any, kind: string): any | null =>
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
kidsOf(n).find((c: any) => c.kind() === kind) ?? null;
// Direct identifier children only — the name slot. Type annotations are
// `type_identifier`/`void_type` and parameter names are nested deeper, so
// they never appear here.
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const idChildren = (n: any): any[] =>
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
kidsOf(n).filter((c: any) => c.kind() === "identifier");
const addSym = (
name: string,
qualifiedName: string,
kind: SymbolKind,
startLine: number,
endLine: number,
): void => {
const sym: SymbolNode = {
id: makeId(file, qualifiedName, startLine),
name,
qualifiedName,
kind,
file,
line: startLine,
endLine,
language,
};
symbols.push(sym);
scopes.push({ name: qualifiedName, startLine, endLine, symbolId: sym.id });
};
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const lineOf = (n: any): number => n.range().start.line + 1;
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const endLineOf = (n: any): number => n.range().end.line + 1;
/**
* Emit the member symbols of a class-like body. Members come in ordered
* sibling pairs: a `method_signature` (wrapping function/getter/setter/
* factory signatures) or a `declaration` (fields and plain constructors),
* optionally followed by its `function_body`.
*/
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const walkMembers = (bodyNode: any, owner: string): void => {
const members = kidsOf(bodyNode);
for (let i = 0; i < members.length; i++) {
const member = members[i];
const memberKind = member.kind();
const next = members[i + 1];
const scopeEnd = next && next.kind() === "function_body" ? endLineOf(next) : endLineOf(member);
if (memberKind === "method_signature") {
const inner = kidsOf(member)[0];
if (!inner) continue;
const innerKind = inner.kind();
if (innerKind === "factory_constructor_signature") {
const ids = idChildren(inner);
if (ids.length === 0) continue;
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const qn = ids.map((c: any) => c.text()).join(".");
addSym(ids[ids.length - 1].text(), qn, "constructor", lineOf(member), scopeEnd);
} else if (
innerKind === "function_signature" ||
innerKind === "getter_signature" ||
innerKind === "setter_signature"
) {
const ids = idChildren(inner);
if (ids.length === 0) continue;
const name = ids[ids.length - 1].text();
addSym(name, `${owner}.${name}`, "method", lineOf(member), scopeEnd);
}
} else if (memberKind === "declaration") {
// Plain (possibly named) constructors: `Foo(this.c);` / `Foo.named(...)`.
// Field declarations have no constructor_signature child and are skipped.
const ctor = childOfKind(member, "constructor_signature");
if (!ctor) continue;
const ids = idChildren(ctor);
if (ids.length === 0) continue;
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
const qn = ids.map((c: any) => c.text()).join(".");
addSym(ids[ids.length - 1].text(), qn, "constructor", lineOf(member), scopeEnd);
}
}
};
// ── Top-level declarations (ordered walk so signature/body pairs line up) ──
const topLevel = kidsOf(root);
for (let i = 0; i < topLevel.length; i++) {
const node = topLevel[i];
const nodeKind = node.kind();
if (nodeKind === "class_definition" || nodeKind === "mixin_declaration" || nodeKind === "extension_declaration") {
const nameNode = childOfKind(node, "identifier");
if (!nameNode) continue;
const name = nameNode.text();
const kind: SymbolKind = nodeKind === "mixin_declaration" ? "trait" : "class";
addSym(name, name, kind, lineOf(node), endLineOf(node));
const body = childOfKind(node, "class_body") ?? childOfKind(node, "extension_body");
if (body) walkMembers(body, name);
} else if (nodeKind === "enum_declaration") {
const nameNode = childOfKind(node, "identifier");
if (nameNode) addSym(nameNode.text(), nameNode.text(), "enum", lineOf(node), endLineOf(node));
} else if (nodeKind === "type_alias") {
const nameNode = childOfKind(node, "type_identifier");
if (nameNode) addSym(nameNode.text(), nameNode.text(), "interface", lineOf(node), endLineOf(node));
} else if (nodeKind === "function_signature" || nodeKind === "getter_signature" || nodeKind === "setter_signature") {
const ids = idChildren(node);
if (ids.length === 0) continue;
const name = ids[ids.length - 1].text();
const next = topLevel[i + 1];
const scopeEnd = next && next.kind() === "function_body" ? endLineOf(next) : endLineOf(node);
addSym(name, name, "function", lineOf(node), scopeEnd);
}
}
// ── Calls — every invocation wraps an `argument_part` node ──────────────
const rawCalls: ExtractedSymbols["rawCalls"] = [];
for (const ap of safeFindAll(root, "argument_part")) {
const holder = ap.parent();
if (!holder) continue;
const holderKind = holder.kind();
let callee: string | null = null;
if (holderKind === "cascade_section") {
// `obj..method(args)` — the callee lives in the cascade_selector.
const cs = childOfKind(holder, "cascade_selector");
const id = cs ? childOfKind(cs, "identifier") : null;
callee = id ? id.text() : null;
} else if (holderKind === "selector") {
// `name(args)` / `expr.name(args)` — the callee is the previous
// sibling: a bare identifier, or a selector whose trailing identifier
// is the method name (`f.bar(…)`, `mat.runApp(…)`, `Foo.create(…)`).
const parent = holder.parent();
if (!parent) continue;
const siblings = kidsOf(parent);
const hr = holder.range();
const idx = siblings.findIndex(
// biome-ignore lint/suspicious/noExplicitAny: ast-grep node type leaks through
(c: any) => {
if (c.kind() !== "selector") return false;
const r = c.range();
return (
r.start.line === hr.start.line &&
r.start.column === hr.start.column &&
r.end.line === hr.end.line &&
r.end.column === hr.end.column
);
},
);
if (idx <= 0) continue;
const prev = siblings[idx - 1];
if (prev.kind() === "identifier") {
callee = prev.text();
} else if (prev.kind() === "selector") {
const ids = safeFindAll(prev, "identifier");
callee = ids.length > 0 ? ids[ids.length - 1].text() : null;
}
}
if (!callee) continue;
const line = ap.range().start.line + 1;
rawCalls.push({
callerId: findCallerId(scopes, line, moduleSym.id),
calleeName: callee,
callSite: { file, line },
});
}
return { symbols, rawCalls };
}
// ── JS / TS / TSX ────────────────────────────────────────────────────────
function extractFromTsLike(
+5
View File
@@ -272,6 +272,11 @@ const TOP_LEVEL_KINDS: Record<string, string[]> = {
php: ["function_definition", "class_declaration", "method_declaration", "trait_declaration"],
swift: ["function_declaration", "class_declaration", "struct_declaration", "protocol_declaration", "extension_declaration"],
bash: ["function_definition"],
// Dart: class/mixin/enum/extension nodes span their bodies, but a top-level
// function is a `function_signature` followed by a SIBLING `function_body`
// starting on the same line. Both kinds are listed so the overlap-merge in
// findAstBoundaries fuses each signature/body pair into one region.
dart: ["class_definition", "mixin_declaration", "enum_declaration", "extension_declaration", "type_alias", "function_signature", "function_body"],
};
/** Minimum lines for a chunk to stand on its own (otherwise merge with neighbors) */
+22
View File
@@ -96,6 +96,28 @@ describe("graph-entrypoints", () => {
expect(entries.some((e) => e.name === "main")).toBe(true);
});
it("detects Dart main() as a conventional entry point", () => {
const graph: CodeGraph = {
nodes: [
{
relativePath: "lib/main.dart",
imports: [],
exports: [],
dependencies: [],
dependents: ["lib/app.dart"], // not an orphan — name heuristic must fire
},
],
edges: [],
};
const payloads: SymbolGraphFilePayload[] = [
{ ...mkPayload("lib/main.dart", [{ name: "main", line: 3 }]), language: "dart" },
];
const entries = detectEntryPoints(graph, payloads);
const main = entries.find((e) => e.name === "main");
expect(main).toBeDefined();
expect(main?.reason).toBe("well-known-name:main");
});
it("returns empty array when nothing matches", () => {
const graph: CodeGraph = { nodes: [], edges: [] };
const entries = detectEntryPoints(graph, []);
+110 -12
View File
@@ -472,25 +472,123 @@ end
});
});
describe("Regex fallback (Dart, Svelte, Vue, unknown)", () => {
it("handles Dart via regex fallback", () => {
describe("Dart", () => {
it("extracts type-first declarations the regex fallback could never match", () => {
const src = `
String greet(String name) {
return 'Hi $name';
class Foo {
Foo(int c);
Foo.named(int c);
factory Foo.create() => Foo(1);
void bar(int x) {
helper(x);
}
String get name => 'foo';
set name(String v) {}
}
class Foo {
int bar() => 1;
mixin Loggable {
void log(String msg) {}
}
enum Color { red, green }
extension StrExt on String {
int len() => length;
}
typedef Callback = void Function(int);
Future<int> fetchCount() async {
return 1;
}
`;
const out = extractSymbolsAndCalls(src, "dart" as unknown as Lang, ".dart", "main.dart");
// regex fallback should at least produce <module> and not throw
expect(out.symbols.some((s) => s.name === "<module>")).toBe(true);
const names = out.symbols.map((s) => s.name);
// best-effort detection: should find at least one named symbol
expect(names.length).toBeGreaterThanOrEqual(1);
const out = extractSymbolsAndCalls(src, "dart" as unknown as Lang, ".dart", "lib/foo.dart");
const has = (qn: string, kind: string) =>
out.symbols.some((s) => s.qualifiedName === qn && s.kind === kind);
expect(has("Foo", "class")).toBe(true);
// Constructors: plain, named, and factory all resolve as constructors
// with dotted qualified names — the regex fallback saw none of these.
// The plain constructor deliberately shares the class's qualified name
// (that is how call sites reference it); they differ by kind and line.
expect(has("Foo", "constructor")).toBe(true);
expect(has("Foo.named", "constructor")).toBe(true);
expect(has("Foo.create", "constructor")).toBe(true);
expect(has("Foo.bar", "method")).toBe(true);
// Getter and setter share a name but live on different lines (distinct ids)
const nameSyms = out.symbols.filter((s) => s.qualifiedName === "Foo.name");
expect(nameSyms).toHaveLength(2);
expect(has("Loggable", "trait")).toBe(true);
expect(has("Loggable.log", "method")).toBe(true);
expect(has("Color", "enum")).toBe(true);
expect(has("StrExt.len", "method")).toBe(true);
expect(has("Callback", "interface")).toBe(true);
// Type-first top-level signature (`Future<int> fetchCount()`)
expect(has("fetchCount", "function")).toBe(true);
});
it("stitches a top-level function's scope from its sibling signature and body", () => {
const src = `
void helper(int x) {
print(x);
print(x + 1);
}
`;
const out = extractSymbolsAndCalls(src, "dart" as unknown as Lang, ".dart", "lib/h.dart");
const helper = out.symbols.find((s) => s.qualifiedName === "helper");
// The signature node alone ends on line 2; the scope must reach the
// body's closing brace, otherwise calls inside attribute to <module>.
expect(helper?.line).toBe(2);
expect(helper?.endLine).toBe(5);
const printCall = out.rawCalls.find((c) => c.calleeName === "print");
expect(printCall?.callerId).toContain("::helper#");
});
it("attributes method calls, cascades, and constructor invocations to the enclosing scope", () => {
const src = `
class Foo {
void bar(int x) {}
Future<void> load() async {}
}
void main() {
final f = Foo(1);
f.bar(2);
f..bar(3)..load();
mat.runApp();
helper(5);
}
`;
const out = extractSymbolsAndCalls(src, "dart" as unknown as Lang, ".dart", "lib/main.dart");
const fromMain = out.rawCalls.filter((c) => c.callerId.includes("::main#"));
const callees = fromMain.map((c) => c.calleeName);
// Constructor invocation (`Foo(1)`, no `new` keyword in modern Dart)
expect(callees).toContain("Foo");
// Plain method call `f.bar(2)`
expect(callees).toContain("bar");
// Cascade `..load()` — a Dart-only form with its own grammar shape
expect(callees).toContain("load");
// Prefixed call `mat.runApp()` resolves to the trailing identifier
expect(callees).toContain("runApp");
// Bare call
expect(callees).toContain("helper");
});
it("detects main() so Dart apps get a conventional entry point", () => {
const src = `
void main() {
runApp();
}
`;
const out = extractSymbolsAndCalls(src, "dart" as unknown as Lang, ".dart", "bin/app.dart");
const main = out.symbols.find((s) => s.name === "main");
expect(main).toBeDefined();
expect(main?.kind).toBe("function");
});
});
describe("Regex fallback (Svelte, Vue, unknown)", () => {
it("handles unknown language without throwing", () => {
const src = "some random text\nwith no recognizable structure";
const out = extractSymbolsAndCalls(
+42
View File
@@ -188,6 +188,48 @@ describe("indexer utilities", () => {
}
});
it("uses AST-aware chunking for Dart files (class and signature/body boundaries)", () => {
// Two large Dart classes plus a top-level function, exceeding CHUNK_SIZE
// lines. Dart splits a top-level function into sibling signature and
// body nodes; if the two were not merged into one region, the function
// body would be severed from its signature.
const method = (name: string) => {
const body = Array.from({ length: 12 }, (_, j) => ` final v${j} = ${j};`).join("\n");
return ` void ${name}() {\n${body}\n }`;
};
// Six 14-line methods per class (~86 lines each): two classes exceed the
// 150-line merge cap, so the chunker must flush them as separate chunks
// instead of grouping them (small adjacent declarations merge by design).
const classOf = (name: string) =>
`class ${name} {\n${Array.from({ length: 6 }, (_, i) => method(`m${i}`)).join("\n")}\n}`;
const topFn = `Future<int> compute() async {\n${Array.from({ length: 12 }, (_, j) => ` final t${j} = ${j};`).join("\n")}\n return 1;\n}`;
const content = `import 'package:foo/bar.dart';\n\n${classOf("Alpha")}\n\n${classOf("Beta")}\n\n${topFn}\n`;
const chunks = chunkFileContent("/test/app.dart", "app.dart", content);
expect(chunks.length).toBeGreaterThan(1);
for (const chunk of chunks) {
expect(chunk.language).toBe("dart");
}
// AST-aware (not line-based): each class lives in a single chunk whose
// content begins at the declaration. Beta spans lines ~90-175, so a
// fixed 100-line window would split it mid-body.
const lines = content.split("\n");
const alphaLine = lines.findIndex((l) => l.startsWith("class Alpha")) + 1;
expect(chunks.some((c) => c.startLine === alphaLine)).toBe(true);
const betaLine = lines.findIndex((l) => l.startsWith("class Beta")) + 1;
const betaClassLines = classOf("Beta").split("\n").length;
const betaChunk = chunks.find((c) => c.startLine <= betaLine && c.endLine >= betaLine);
expect(betaChunk).toBeDefined();
expect(betaChunk?.content.trim().startsWith("class Beta")).toBe(true);
expect(betaChunk?.endLine).toBeGreaterThanOrEqual(betaLine + betaClassLines - 1);
// The top-level function's signature and body stay in the same chunk.
const computeLine = lines.findIndex((l) => l.startsWith("Future<int> compute")) + 1;
const computeChunk = chunks.find((c) => c.startLine <= computeLine && c.endLine >= computeLine);
expect(computeChunk).toBeDefined();
expect(computeChunk?.content).toContain("return 1;");
});
it("sets correct language for Python files", () => {
const content = "def hello():\n print('hello')";
const chunks = chunkFileContent("/test/app.py", "app.py", content);