Skip to content

feat(dart): replace regex extractor with tree-sitter-dart - #3651

Open
derekpitts wants to merge 1 commit into
Graphify-Labs:v8from
derekpitts:feat/dart-tree-sitter-extractor
Open

derekpitts wants to merge 1 commit into
Graphify-Labs:v8from
derekpitts:feat/dart-tree-sitter-extractor

Conversation

@derekpitts

Copy link
Copy Markdown

Summary

  • Replace the regex-based Dart extractor with a tree-sitter AST walker using PyPI tree-sitter-dart (UserNobody14 grammar, efrenbl Python packaging).
  • Class/mixin/extension members are now defines-linked from their containing type (not only the file), and a call-graph second pass emits in-file calls edges.
  • Keep Flutter-oriented body heuristics (Bloc / Riverpod / GoRouter-style navigation) with the same context= tags so existing architecture graphs stay rich.
  • Add tree-sitter-dart as a core dependency, tests/fixtures/sample.dart, and tests for class scoping, calls, and missing-grammar errors. Existing tests/test_dart.py cases still pass (invalid # “comments” in the advanced fixture updated to //).

Test plan

  • uv run python -m pytest tests/test_dart.py tests/test_extract.py::test_dart_child_node_ids_are_stem_based -q
  • uv run graphify extract <dir-with-sample.dart> --code-only --no-cluster
  • Reviewers: spot-check a small Flutter app for Bloc/Riverpod edges and class→method defines

Upgrade .dart extraction to an AST walker for class-scoped members and
in-file call edges, while retaining Flutter Bloc/Riverpod/navigation
heuristics. Add tree-sitter-dart as a core dependency with fixtures and tests.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 5 advisory finding(s) below merit a look before merge.

Formal verification. No changes could be formally verified in this run.


Graphify review — findings

Rewrites the Dart extractor to walk the tree-sitter AST instead of scanning with regex, emitting class/mixin/function/import nodes and extends/implements/with heritage edges with source locations on the edges themselves. Adds _apply_flutter_heuristics to layer Bloc, Riverpod, and navigation edges (on<Event>, emit, context.read().add, ref.watch, BlocBuilder<...>, route pushes) parsed from method-body text, plus preserved generic type-lookup references for backward compatibility. Introduces helper support for qualified type names via _collect_top_type_names and _qualified_type_before, and filters out Dart builtin types so heuristic edges point only at user-defined symbols.

Worth a look

  • extract_dart now hard-requires tree-sitter-dart for any extraction — graphify/extractors/dart.py · Escalate · high
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Call resolution conflates duplicate method labels — graphify/extractors/dart.py · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Flutter heuristics emit edges from comments and string literals — graphify/extractors/dart.py:176 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Generic type lookup scans comments and strings — graphify/extractors/dart.py · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Nested local function bodies are attributed to the enclosing function — graphify/extractors/dart.py · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 68 functions depend on the 67 functions this change touches.

Health — this change adds coupling hotspots:

  • new: extract_dart() — 13 callers, 14 callees
  • new: emit_annotation_edges() — 4 callers, 5 callees
  • new: handle_type_decl() — 1 callers, 10 callees
  • new: handle_class_body() — 1 callers, 9 callees
  • new: handle_top_level_vars() — 1 callers, 8 callees
  • new: handle_top_function() — 1 callers, 7 callees

Verification — 68 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 68 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

286 of 286 test file(s) selected (100%) via static blast radius.

Escalated to a full run for safety — the selection is not trustworthy on its own (see below). CI should run the whole suite.

  • tests/test_affected_cli.py — full-run-safety
  • tests/test_affected_member_seed.py — full-run-safety
  • tests/test_agents_platform.py — full-run-safety
  • tests/test_analyze.py — full-run-safety
  • tests/test_anthropic_custom_endpoint.py — full-run-safety
  • tests/test_antigravity_install.py — full-run-safety
  • tests/test_apm_fallback_version.py — full-run-safety
  • tests/test_architecture_doc.py — full-run-safety
  • tests/test_astro_extraction.py — full-run-safety
  • tests/test_astro_import_ids.py — full-run-safety
  • tests/test_atomic_canvas_export.py — full-run-safety
  • tests/test_atomic_version_stamp.py — full-run-safety
  • tests/test_atomic_writes.py — full-run-safety
  • tests/test_backend_env_isolation.py — full-run-safety
  • tests/test_backend_extras.py — full-run-safety
  • tests/test_benchmark.py — full-run-safety
  • tests/test_benchmark_raw_graph.py — full-run-safety
  • tests/test_build.py — full-run-safety
  • tests/test_build_merge_dedup_scope.py — full-run-safety
  • tests/test_build_merge_hyperedges_and_prune.py — full-run-safety
  • tests/test_build_merge_shrink_guard.py — full-run-safety
  • tests/test_builtin_global_type_refs.py — full-run-safety
  • tests/test_cache.py — full-run-safety
  • tests/test_callflow_html.py — full-run-safety
  • tests/test_cargo_introspect.py — full-run-safety
  • tests/test_carried_hyperedge_remap.py — full-run-safety
  • tests/test_case_sensitive_resolution.py — full-run-safety
  • tests/test_charmap_encoding.py — full-run-safety
  • tests/test_chunking.py — full-run-safety
  • tests/test_cjs_module_extension.py — full-run-safety
  • tests/test_claude_cli_backend.py — full-run-safety
  • tests/test_claude_md.py — full-run-safety
  • tests/test_cli_broken_pipe.py — full-run-safety
  • tests/test_cli_export.py — full-run-safety
  • tests/test_cli_help.py — full-run-safety
  • tests/test_cluster.py — full-run-safety
  • tests/test_codebuddy.py — full-run-safety
  • tests/test_community_hub_labels.py — full-run-safety
  • tests/test_community_labels_skill.py — full-run-safety
  • tests/test_confidence.py — full-run-safety
  • tests/test_corrupt_graph_json.py — full-run-safety
  • tests/test_cpp_nested_and_cli.py — full-run-safety
  • tests/test_cpp_objc_cross_file_calls.py — full-run-safety
  • tests/test_cpp_preprocess.py — full-run-safety
  • tests/test_cross_extension_reexport_self_cycle.py — full-run-safety
  • tests/test_cross_language_call_resolution.py — full-run-safety
  • tests/test_cross_repo_external_call_guards.py — full-run-safety
  • tests/test_cross_repo_member_calls.py — full-run-safety
  • tests/test_cross_repo_shared_types.py — full-run-safety
  • tests/test_csharp_call_site_generic_args.py — full-run-safety
  • … and 236 more

non-code file(s) changed (pyproject.toml, uv.lock) → running the full suite for safety (a code graph can't see config/fixture/data deps)

changed code file(s) with no mapped test (pyproject.toml, tests/fixtures/sample.dart) — a coverage gap or a missing link — running the full suite rather than only the selected tests

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Formal verification

Could not verify: Could not verify extract\_dart.

The verifier did not have enough to check extract\_dart, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: parameter `path` is annotated `Path` — outside the synthesizable primitive/collection set

· 6 grounded finding(s) anchored inline below.

)


def extract_dart(path: Path) -> dict:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — extract_dart()

fans out to 14 callees (efferent coupling); 13 callers depend on it (afferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

if not is_part:
add_node(file_nid, path.name, source_file=str_path, line=None)

def emit_annotation_edges(ann_node, target_nid: str, target_name: str, target_kind: str) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — emit_annotation_edges()

high coupling complexity (Ca·Ce = 20).

Grounded coupling-delta finding (deterministic), not an LLM guess.

base_nid = ensure_external(base)
add_edge(type_nid, base_nid, "inherits", line=line)

def handle_class_body(body_node, class_nid: str, class_name: str) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — handle_class_body()

fans out to 9 callees (efferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

attribute_generic_lookups_to=file_nid,
)

def handle_type_decl(node) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — handle_type_decl()

fans out to 10 callees (efferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

add_edge(type_nid, tid, "extends", line=line)
break

def handle_top_function(sig_node, body_node, pending_annotations: list) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — handle_top_function()

fans out to 7 callees (efferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

break
add_edge(file_nid, tgt, "exports" if is_export else "imports", line=line)

def handle_top_level_vars(program) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — handle_top_level_vars()

fans out to 8 callees (efferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

@bounty1342

Copy link
Copy Markdown

Thanks for this. Moving Dart to tree-sitter is worth doing, and the numbers below back that up. I ran the branch (1ec3e0b) against current v8 and against a real Flutter app: flutter_bloc, go_router and freezed, 321 .dart files including 89 generated part of files. I also checked the bot's five advisory findings by running small cases. Line numbers are from graphify/extractors/dart.py at 1ec3e0b.

What works

  • tree-sitter-dart==0.1.0 loads as ABI 15 with the pinned tree-sitter==0.25.2. All 321 files parse with 0 ERROR/MISSING nodes, and so do Dart 3 samples: class modifiers, extension types, patterns, dot shorthands, null-aware elements and digit separators.
  • In-file calls edges go from 10 to 570.
  • Class-scoped membership works.
  • The regex junk that v8 produces from generated freezed code is gone. Nodes labelled identical, operator, orElse, null, _ and class came to roughly 400 occurrences.
  • Runtime is on par: 1.44 s vs 1.32 s for the whole app.
  • The PR's own tests/test_dart.py passes 11 of 11.

Rebase blockers

With the PR's dart.py dropped onto current v8, 6 of 14 v8 tests in tests/test_dart.py fail:

Failing v8 test Cause, confirmed with a minimal case
test_anonymous_extension_is_detected extension on Widget { void foo() {} } yields nothing, not even foo: handle_type_decl returns when there is no identifier (L664)
test_conditional_uris_emit_every_branch import 'a_stub.dart' if (dart.library.io) 'a_io.dart' drops the a_io.dart / conditional_uri edge (find_uri, L738-753)
test_mixin_on_clause_with_multiple_superclass_constraints mixin M on A, B gives only M → A. The grammar emits two sibling type_identifiers and L480 reads only the first
test_part_file_keeps_its_own_node, test_roadmap_bug_fixes part files get no own node, includes or contains edges (L387). On the app this removes 4,868 contains and 89 includes edges
test_advanced_dart_features only because v8's fixture still has the invalid # comments, which this PR changes to //. Keep that fixture fix when rebasing

Also for the rebase:

  • read the file with _read_source_bytes instead of path.read_bytes() (L290);
  • bump _AST_CACHE_SCHEMA (currently 40) with a "so cached Dart extractions re-run" note;
  • regenerate uv.lock.

Other regressions found on the app

  • Abstract/interface members are dropped. In a class body, Future<bool> openX(); parses as declaration(function_signature). The declaration branch (L504-582) only handles constructors and initialized_identifier_list, so it skips these. Clean-architecture apps put repository and navigator interfaces exactly here.
  • static const / static final class fields are dropped. They parse as declaration(const_builtin, type_identifier, static_final_declaration_list), and the class-body branch never looks at static_final_declaration_list. One icon-constants class lost 72 symbols. Across the app, 104 files have fewer local symbols than on v8.
  • The legacy function typedef is inverted. typedef int Cmp(Object a, Object b); creates a node named int and an edge int --references--> Cmp. In handle_type_decl (L660), the first type_identifier is the return type, not the alias name. The typedef F = R Function(int) form is handled correctly.
  • implements is inflated: 46 → 802 edges from 424 implements lines. _collect_top_type_names also returns the names inside a type's type_arguments (L104-106). So implements $FooCopyWith<$Res> emits implements $Res as well. with is likely affected the same way.
  • Top-level getters are dropped (int get answer => 42;). The main loop only handles function_signature (L926).
  • Heuristics now fire in comments. // TODO: emit(Loading()) creates an emit_state edge, while v8 scanned comment-stripped text. String literals already leak on v8 too ("context.push('/x')" creates a route on both), so blanking comment and string_literal byte ranges before matching would fix both.
  • type_lookup is emitted up to 3× per site. The per-method pass, the class-body pass and the whole-file pass (L966) all emit it: 545 → 1,460 on the app. Each Bloc/Riverpod edge appearing as both method → X and class → X matches v8, so that part is not new.
  • configures goes 287 → 2,131. Most of it comes from annotations on generated-code members (@optionalTypeArgs, @pragma, @useResult, @JsonKey). Consider adding these to _ANNOTATION_SKIP, or skipping annotations on generated files.

The bot's advisory findings, checked by running

  1. Call resolution conflates duplicate labels. Confirmed. label_to_nid keeps the last node per label (L982-986). In
    class A { build() {…} }
    class B { build() {…} }
    main() { A().build(); }
    the call is resolved to B.build, as EXTRACTED with confidence 1.0. On the app, 116 of 321 files have duplicate local labels, and 151 of the 552 new call edges target a duplicated label. Elsewhere in the repo (Go, C#, Kotlin, Solidity), resolution fails closed on ambiguity. Resolving only unique labels, or preferring the caller's own class, and otherwise emitting a raw_call, would fit that.
  2. Heuristics run on comments and strings. Confirmed for comments, as described above.
  3. The generic lookup scans comments and strings. Confirmed: the whole-file pass reads raw source, and the comment at L964 says so.
  4. Nested and closure bodies. Confirmed, and wider than the bot reported:
    • in void f() { void inner() { outerDep(); } inner(); }, the call to outerDep is credited to f;
    • calls inside closures are lost: run(() { doThing(); }) gives f → run but not f → doThing, because function_expression is skipped at L1050;
    • calls are found only under expression_statement and return_statement (L1029), so arrow bodies (greet() => helper()), initializers (final x = load()) and conditions (if (check())) produce no edge.
  5. Hard requirement on tree-sitter-dart. Confirmed (L283-287). The grammar works fine today. Still:

Smaller points

  • Members get defines from both the class and the file (L569-571, L623-625). That is why defines rises from 9.8k to 16.5k on the app. Other extractors (C#, Elixir, Apex, DM, CommonLisp) link a type to its members with method.
  • Two loops search the whole node list to fix a label (L759, L974). A nid → node dict avoids that.
  • test_missing_grammar_reports_error swaps out builtins.__import__. mock.patch.dict(sys.modules, {"tree_sitter_dart": None}) is simpler.

I'm happy to help port the missing v8 behaviours and fix the regressions above in a PR against your branch, or to share the comparison harness. Let me know which you'd prefer.

@bounty1342

Copy link
Copy Markdown

I opened derekpitts#1 against your branch. It merges current v8 (conflicts resolved, your dart.py kept as-is in the merge commit). A second commit ports the six v8 Dart fixes and fixes the regressions from my review above, with a regression test for each. If you merge it, this PR becomes mergeable again. The review is easiest commit by commit, since Files changed includes the whole v8 merge. Happy to change anything.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants