mirror of
https://github.com/elicpeter/nyx.git
synced 2026-07-21 21:31:03 +02:00
Prerelease cleanup (#46)
* feat: Add const_bound_vars tracking to prevent false positives in ownership checks
* feat: Introduce field interner and typed bounded vars for enhanced type tracking
* feat: Add typed_call_receivers and typed_bounded_dto_fields for enhanced type tracking
* feat: Centralize method name extraction with bare_method_name helper
* feat: Implement Phase-6 hierarchy fan-out for runtime virtual dispatch
* feat: Enhance C++ taint tracking with additional container operations and inline method resolution
* feat: Introduce field-sensitive points-to analysis for enhanced resource tracking
* feat: Implement Pointer-Phase 6 subscript handling for enhanced container analysis
* test: Add comprehensive tests for JavaScript control flow constructs and lattice operations
* docs: Update advanced analysis documentation with field-sensitive points-to and hierarchy fan-out details
* test: Add comprehensive tests for lattice algebra laws and SSA edge cases
* feat: Add destructured session user handling and safe user ID access patterns
* feat: Implement row-population reverse-walk for enhanced authorization checks
* feat: Enhance authorization checks with local alias chain for self-actor types
* feat: Introduce ActiveRecord query safety checks and enhance snippet extraction
* feat: Implement chained method call inner-gate rebinding for SSRF prevention
* feat: Add observability and error modules, enhance debug functionality, and implement theme context
* feat: Remove Auth Analysis page and update navigation to redirect to Explorer
* feat: Optimize SSA lowering by sharing results between taint engine and artifact extractor
* feat: Optimize SSA lowering by sharing results between taint engine and artifact extractor
* feat: Reset path-safe-suppressed spans before lowering to maintain analysis integrity
* fix(ssa): ungate debug_assert_bfs_ordering for release-tests build
The helper at src/ssa/lower.rs was gated `#[cfg(debug_assertions)]` while
the unit test at the bottom of the file was gated only `#[cfg(test)]`.
Since `cfg(test)` is set in release builds with `--tests` but
`cfg(debug_assertions)` is not, `cargo build --release --tests` failed
with E0425. Removing the gate fixes the build; the body is `debug_assert!`
only, so the helper is free in release. Also drop the gate at the call
site to avoid a `dead_code` warning when the lib is built without
`--tests`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(closure-capture): flip JS/TS fixtures to required-finding
The JS and TS closure-capture fixtures pinned the old broken behaviour
via `forbidden_findings: [{ "id_prefix": "taint-" }]`. The engine now
correctly traces taint through the closure boundary (env source captured
by an arrow function, sunk via `child_process.exec` inside the body), so
the formerly-forbidden finding is a true positive.
Match the Python sibling's shape — `required_findings` with
`id_prefix` + `min_count` plus a small `noise_budget` — and rewrite the
companion READMEs and the phase8_fragility_tests doc-comments from
"known gap" to "regression guard".
Verified:
- cargo test --release --test phase8_fragility_tests → 8/8 pass
- cargo test --release --lib bfs_assertion → pass
- corpus benchmark F1 = 0.9976 (TP=205, FP=1, FN=0) — unchanged
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: Add OWASP mapping and baseline mutation hooks for enhanced security analysis
* feat: Introduce health module and enhance health score computation with calibration tests
* feat: Add expectations configuration and cleanup .gitignore for log files
* feat: Implement theme selection and enhance settings panel for triage sync
* feat: Suppress false positives for strcpy calls with literal sources in AST
* feat: Update analyse_function_ssa to return body CFG for accurate analysis
* feat: Add bug report and feature request templates for improved issue tracking
* feat: removed dev scripts
* feat: update README.md for clarity and consistency in fixture descriptions
* feat: removed dev docs
* feat: clean up error handling and UI elements for improved user experience
* feat: adjust button sizes in HeaderBar for better UI consistency
* feat: enhance taint analysis with additional context for sanitizer and taint findings
* cargo fmt
* prettier
* refactor: simplify conditional checks and improve code readability in AST and screenshot capture scripts
* feat: add script to frame PNG screenshots with brand gradient
* feat: add fuzzing support with new targets and CI workflows
* refactor: streamline match expressions and improve formatting in CLI and output handling
* feat: enhance configuration display with detailed output options
* feat: stage demo configuration for improved CLI screenshot output
* feat: expose merge_configs function for user-configurable settings
* refactor: simplify code structure and improve readability in config handling
* refactor: improve descriptions for vulnerability patterns in various languages
* feat: update MIT License section with additional usage details and copyright information
* feat: update screenshots
* refactor: update build process and paths for frontend assets
* feat: add cross-file taint fuzzing target and supporting dictionary
* refactor: clean up formatting and comments in fuzz configuration and example files
* refactor: remove outdated comments and clean up CI configuration files
* chore: update changelog dates and improve formatting in documentation
* refactor: update Cargo.toml and CI configuration for improved packaging and build process
* refactor: enhance quote-stripping logic to prevent panics and add regression tests
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
79c29b394d
commit
82f18184b1
348 changed files with 48731 additions and 2925 deletions
|
|
@ -1107,6 +1107,7 @@ fn clone_preserves_all_sub_structs() {
|
|||
kind: StmtKind::Call,
|
||||
call: CallMeta {
|
||||
callee: Some("foo".into()),
|
||||
callee_text: Some("obj.foo".into()),
|
||||
outer_callee: Some("bar".into()),
|
||||
callee_span: Some((7, 17)),
|
||||
call_ordinal: 5,
|
||||
|
|
@ -2041,3 +2042,857 @@ fn numeric_length_access_ignores_method_calls_with_args() {
|
|||
"is_numeric_length_access must stay false for arg-bearing calls"
|
||||
);
|
||||
}
|
||||
|
||||
// ── Pointer-Phase 6 / W5: subscript lowering tests ────────────────────────
|
||||
|
||||
/// Scope for tests that flip `NYX_POINTER_ANALYSIS=1` so the CFG-side
|
||||
/// subscript synthesis activates. The env-var is restored afterwards
|
||||
/// so the rest of the test suite stays bit-identical to the unset
|
||||
/// state. Mirrors the env-var serialisation pattern used elsewhere in
|
||||
/// the test suite (see `tests/pointer_disabled_bit_identity.rs`).
|
||||
use std::sync::Mutex;
|
||||
static POINTER_ENV_GUARD: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn with_pointer_env<R>(value: Option<&str>, f: impl FnOnce() -> R) -> R {
|
||||
let _lock = POINTER_ENV_GUARD.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let prev = std::env::var("NYX_POINTER_ANALYSIS").ok();
|
||||
unsafe {
|
||||
match value {
|
||||
Some(v) => std::env::set_var("NYX_POINTER_ANALYSIS", v),
|
||||
None => std::env::remove_var("NYX_POINTER_ANALYSIS"),
|
||||
}
|
||||
}
|
||||
let r = f();
|
||||
unsafe {
|
||||
match prev {
|
||||
Some(v) => std::env::set_var("NYX_POINTER_ANALYSIS", v),
|
||||
None => std::env::remove_var("NYX_POINTER_ANALYSIS"),
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn with_pointer_on<R>(f: impl FnOnce() -> R) -> R {
|
||||
with_pointer_env(Some("1"), f)
|
||||
}
|
||||
|
||||
fn count_nodes_with_callee(cfg: &Cfg, callee: &str) -> usize {
|
||||
cfg.node_indices()
|
||||
.filter(|i| cfg[*i].call.callee.as_deref() == Some(callee))
|
||||
.count()
|
||||
}
|
||||
|
||||
fn find_node_with_callee<'a>(cfg: &'a Cfg, callee: &str) -> Option<&'a NodeInfo> {
|
||||
cfg.node_indices()
|
||||
.map(|i| &cfg[i])
|
||||
.find(|n| n.call.callee.as_deref() == Some(callee))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_subscript_read_lowers_to_index_get_call() {
|
||||
with_pointer_on(|| {
|
||||
// `arr[0]` as a sink call argument should be pre-emitted as a
|
||||
// synth `__index_get__` call before the consuming sink.
|
||||
let src = br#"function f(arr) {
|
||||
sink(arr[0]);
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
let node = find_node_with_callee(&cfg, "__index_get__")
|
||||
.expect("__index_get__ node should be present");
|
||||
assert_eq!(node.call.receiver.as_deref(), Some("arr"));
|
||||
assert_eq!(node.call.arg_uses.len(), 1, "expect one arg group (index)");
|
||||
assert_eq!(node.call.arg_uses[0], vec!["0"]);
|
||||
assert!(
|
||||
node.taint
|
||||
.defines
|
||||
.as_deref()
|
||||
.is_some_and(|d| d.starts_with("__nyx_idxget_")),
|
||||
"synth defines should use the __nyx_idxget_ prefix"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_subscript_write_lowers_to_index_set_call() {
|
||||
with_pointer_on(|| {
|
||||
let src = br#"function f(arr, v) {
|
||||
arr[0] = v;
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
let node = find_node_with_callee(&cfg, "__index_set__")
|
||||
.expect("__index_set__ node should be present");
|
||||
assert_eq!(node.call.receiver.as_deref(), Some("arr"));
|
||||
assert_eq!(
|
||||
node.call.arg_uses.len(),
|
||||
2,
|
||||
"expect arg_uses [[idx], [val]]"
|
||||
);
|
||||
assert_eq!(node.call.arg_uses[0], vec!["0"]);
|
||||
assert_eq!(node.call.arg_uses[1], vec!["v"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn py_subscript_read_lowers_to_index_get_call() {
|
||||
with_pointer_on(|| {
|
||||
let src = br#"def f(arr):
|
||||
sink(arr[0])
|
||||
"#;
|
||||
let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "python", ts_lang);
|
||||
let node = find_node_with_callee(&cfg, "__index_get__")
|
||||
.expect("python: __index_get__ node should be present");
|
||||
assert_eq!(node.call.receiver.as_deref(), Some("arr"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn py_subscript_write_lowers_to_index_set_call() {
|
||||
with_pointer_on(|| {
|
||||
let src = br#"def f(arr, v):
|
||||
arr[0] = v
|
||||
"#;
|
||||
let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "python", ts_lang);
|
||||
let node = find_node_with_callee(&cfg, "__index_set__")
|
||||
.expect("python: __index_set__ node should be present");
|
||||
assert_eq!(node.call.receiver.as_deref(), Some("arr"));
|
||||
assert_eq!(node.call.arg_uses.len(), 2);
|
||||
assert_eq!(node.call.arg_uses[1], vec!["v"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_index_expr_read_lowers_to_index_get_call() {
|
||||
with_pointer_on(|| {
|
||||
let src = br#"package main
|
||||
func f(arr []string) {
|
||||
sink(arr[0])
|
||||
}
|
||||
"#;
|
||||
let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "go", ts_lang);
|
||||
let node = find_node_with_callee(&cfg, "__index_get__")
|
||||
.expect("go: __index_get__ node should be present");
|
||||
assert_eq!(node.call.receiver.as_deref(), Some("arr"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_index_expr_write_lowers_to_index_set_call() {
|
||||
with_pointer_on(|| {
|
||||
let src = br#"package main
|
||||
func f(m map[string]int, k string, v int) {
|
||||
m[k] = v
|
||||
}
|
||||
"#;
|
||||
let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "go", ts_lang);
|
||||
let node = find_node_with_callee(&cfg, "__index_set__")
|
||||
.expect("go: __index_set__ node should be present");
|
||||
assert_eq!(node.call.receiver.as_deref(), Some("m"));
|
||||
assert_eq!(node.call.arg_uses.len(), 2);
|
||||
assert_eq!(node.call.arg_uses[0], vec!["k"]);
|
||||
assert_eq!(node.call.arg_uses[1], vec!["v"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_disabled_skips_subscript_synthesis() {
|
||||
// Strict-additive contract: when NYX_POINTER_ANALYSIS=0 the CFG
|
||||
// must contain zero __index_get__/__index_set__ nodes regardless
|
||||
// of the source shape. This is the off-by-default invariant the
|
||||
// bit-identity gate relies on.
|
||||
with_pointer_env(Some("0"), || {
|
||||
let src = br#"function f(arr, v) {
|
||||
sink(arr[0]);
|
||||
arr[1] = v;
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
assert_eq!(count_nodes_with_callee(&cfg, "__index_get__"), 0);
|
||||
assert_eq!(count_nodes_with_callee(&cfg, "__index_set__"), 0);
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
// Gap-filling: switch / for / do-while / nested loops / re-throw
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// JS `switch` should produce one synthetic dispatch `If` node per
|
||||
/// case (default excluded when at the tail), plus True edges into
|
||||
/// each case body. Verifies the discriminant cascade is wired.
|
||||
#[test]
|
||||
fn js_switch_cascade_has_one_if_per_case() {
|
||||
let src = br#"function f(x) {
|
||||
switch (x) {
|
||||
case 1: a(); break;
|
||||
case 2: b(); break;
|
||||
default: c();
|
||||
}
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
// Two non-default cases => 2 dispatch If nodes (the tail default
|
||||
// is wired via the previous header's False edge, not its own If).
|
||||
assert_eq!(
|
||||
if_nodes(&cfg).len(),
|
||||
2,
|
||||
"switch with 2 explicit cases + default should emit 2 dispatch If nodes"
|
||||
);
|
||||
|
||||
// Each dispatch If must have at least one True and one False edge
|
||||
// (True → case body, False → next case / default).
|
||||
for i in if_nodes(&cfg) {
|
||||
let trues = cfg
|
||||
.edges(i)
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::True))
|
||||
.count();
|
||||
let falses = cfg
|
||||
.edges(i)
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::False))
|
||||
.count();
|
||||
assert!(
|
||||
trues >= 1,
|
||||
"case dispatch should have at least one True edge"
|
||||
);
|
||||
assert!(
|
||||
falses >= 1,
|
||||
"case dispatch should have at least one False edge"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Default case in the *middle* of a switch must be reordered to the
|
||||
/// tail so the dispatch cascade stays a clean True/False chain. The
|
||||
/// observable CFG shape (number of If nodes, presence of True/False
|
||||
/// edges per dispatch) should match the all-default-at-tail case.
|
||||
#[test]
|
||||
fn js_switch_default_in_middle_reorders_to_tail() {
|
||||
let src = br#"function f(x) {
|
||||
switch (x) {
|
||||
case 1: a(); break;
|
||||
default: c(); break;
|
||||
case 2: b(); break;
|
||||
}
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
// 2 non-default cases ⇒ 2 If dispatch nodes (default reordered to tail).
|
||||
assert_eq!(
|
||||
if_nodes(&cfg).len(),
|
||||
2,
|
||||
"default-in-middle should still produce one If per non-default case"
|
||||
);
|
||||
}
|
||||
|
||||
/// JS switch fall-through (`case 1: a(); case 2: b();`) — case 1's
|
||||
/// exit should flow into case 2's body so taint from `first()`
|
||||
/// reaches `second()`'s sinks.
|
||||
///
|
||||
/// We assert two things:
|
||||
/// (a) Reachability: `second()` is reachable from `first()` over
|
||||
/// forward edges. This is the semantic property taint analysis
|
||||
/// depends on; checking it directly avoids over-fitting to the
|
||||
/// structural shape.
|
||||
/// (b) `first()` has a non-Back forward out-edge that lands inside
|
||||
/// the case-2 sub-graph (the actual fall-through wire), so we
|
||||
/// prove there *is* a fall-through edge — not just an
|
||||
/// Entry→…→Exit path that happens to walk through both calls
|
||||
/// via the dispatch chain.
|
||||
///
|
||||
/// Note on the structural shape: case bodies are wrapped in synthetic
|
||||
/// Seq passthrough nodes (one per surrounding scope), so the
|
||||
/// fall-through edge from `first()` lands on the *first wrapper
|
||||
/// Seq node* of case 2, not on `second()` itself. Asserting that
|
||||
/// `second()` has ≥2 in-edges would therefore be wrong — the True
|
||||
/// edge from the case-2 dispatch If targets the wrapper node, and
|
||||
/// only a single Seq chain leads from there to `second()`.
|
||||
#[test]
|
||||
fn js_switch_fallthrough_no_break() {
|
||||
use std::collections::HashSet;
|
||||
let src = br#"function f(x) {
|
||||
switch (x) {
|
||||
case 1: first();
|
||||
case 2: second(); break;
|
||||
}
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
let first = cfg
|
||||
.node_indices()
|
||||
.find(|&n| cfg[n].call.callee.as_deref() == Some("first"))
|
||||
.expect("expected a Call node for `first`");
|
||||
let second = cfg
|
||||
.node_indices()
|
||||
.find(|&n| cfg[n].call.callee.as_deref() == Some("second"))
|
||||
.expect("expected a Call node for `second`");
|
||||
|
||||
// (a) Reachability from first → second over forward (non-Back) edges.
|
||||
let mut seen: HashSet<NodeIndex> = HashSet::new();
|
||||
let mut stack = vec![first];
|
||||
while let Some(n) = stack.pop() {
|
||||
if !seen.insert(n) {
|
||||
continue;
|
||||
}
|
||||
for e in cfg.edges(n) {
|
||||
if matches!(e.weight(), EdgeKind::Seq | EdgeKind::True | EdgeKind::False) {
|
||||
stack.push(e.target());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
seen.contains(&second),
|
||||
"fall-through: `second` must be reachable from `first` over forward edges"
|
||||
);
|
||||
|
||||
// (b) Prove the fall-through edge exists: `first()` must have at
|
||||
// least one outgoing forward edge whose target is *not*
|
||||
// reachable from the function entry without first going
|
||||
// through `first()`. The straightforward check: `first()`
|
||||
// itself must have at least one outgoing Seq edge (the
|
||||
// fall-through wire is always Seq).
|
||||
let first_seq_outs = cfg
|
||||
.edges(first)
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::Seq))
|
||||
.count();
|
||||
assert!(
|
||||
first_seq_outs >= 1,
|
||||
"fall-through: `first()` must have a Seq out-edge (the fall-through wire)"
|
||||
);
|
||||
}
|
||||
|
||||
/// `for (i = 0; i < 10; i++) { body(); }` should produce a Loop node
|
||||
/// with at least one Back edge from the body back to the loop header.
|
||||
#[test]
|
||||
fn js_for_loop_has_back_edge() {
|
||||
let src = br#"function f() { for (let i = 0; i < 10; i++) { body(); } }"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
let loop_nodes: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&n| cfg[n].kind == StmtKind::Loop)
|
||||
.collect();
|
||||
assert_eq!(loop_nodes.len(), 1, "expected exactly one Loop node");
|
||||
|
||||
let back_edges = cfg
|
||||
.edge_references()
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::Back))
|
||||
.count();
|
||||
assert!(
|
||||
back_edges >= 1,
|
||||
"for loop must have at least one Back edge to its header"
|
||||
);
|
||||
}
|
||||
|
||||
/// `do { ... } while (cond);` is mapped to `Kind::While` for many
|
||||
/// languages but the grammar puts the body *before* the condition.
|
||||
/// The CFG must still produce a Loop node and at least one Back edge.
|
||||
#[test]
|
||||
fn js_do_while_has_loop_node_and_back_edge() {
|
||||
let src = br#"function f() { do { body(); } while (cond); }"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
let loop_count = cfg
|
||||
.node_indices()
|
||||
.filter(|&n| cfg[n].kind == StmtKind::Loop)
|
||||
.count();
|
||||
assert_eq!(loop_count, 1, "do-while should produce one Loop node");
|
||||
assert!(
|
||||
cfg.edge_references()
|
||||
.any(|e| matches!(e.weight(), EdgeKind::Back)),
|
||||
"do-while must have at least one Back edge"
|
||||
);
|
||||
}
|
||||
|
||||
/// In `outer: while (a) { while (b) { break; } }`, the `break`
|
||||
/// terminates only the *inner* loop. Equivalent for our CFG: the
|
||||
/// break's predecessors should reach the inner loop's exit frontier
|
||||
/// without crossing the outer loop's body again. We can verify this
|
||||
/// structurally: there must be exactly two Loop nodes and at least
|
||||
/// one Break node whose forward (Seq) successor is *not* the outer
|
||||
/// header.
|
||||
#[test]
|
||||
fn js_nested_while_break_targets_inner_loop() {
|
||||
let src = br#"function f() {
|
||||
while (a) {
|
||||
while (b) { break; }
|
||||
inner_after();
|
||||
}
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
let loops: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&n| cfg[n].kind == StmtKind::Loop)
|
||||
.collect();
|
||||
assert_eq!(loops.len(), 2, "expected two Loop nodes");
|
||||
|
||||
let breaks: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&n| cfg[n].kind == StmtKind::Break)
|
||||
.collect();
|
||||
assert_eq!(breaks.len(), 1, "expected exactly one Break node");
|
||||
|
||||
// The inner loop body's break should NOT close back via Back edge
|
||||
// onto the outer header (outer header is loops[0] in source order).
|
||||
let outer_header = loops[0];
|
||||
let brk = breaks[0];
|
||||
let crosses_outer = cfg
|
||||
.edges(brk)
|
||||
.any(|e| e.target() == outer_header && matches!(e.weight(), EdgeKind::Back));
|
||||
assert!(
|
||||
!crosses_outer,
|
||||
"inner break must not back-edge onto the outer loop header"
|
||||
);
|
||||
}
|
||||
|
||||
/// `continue` in the inner loop must back-edge onto the *inner*
|
||||
/// header, not the outer. With nested while loops we expect exactly
|
||||
/// one Continue node and at least one Back edge originating at it
|
||||
/// going to the inner (second-emitted) Loop header.
|
||||
#[test]
|
||||
fn js_nested_while_continue_targets_inner_loop() {
|
||||
let src = br#"function f() {
|
||||
while (a) {
|
||||
while (b) { continue; }
|
||||
}
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
let loops: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&n| cfg[n].kind == StmtKind::Loop)
|
||||
.collect();
|
||||
assert_eq!(loops.len(), 2, "expected two Loop nodes");
|
||||
let outer_header = loops[0];
|
||||
let inner_header = loops[1];
|
||||
|
||||
let cont = cfg
|
||||
.node_indices()
|
||||
.find(|&n| cfg[n].kind == StmtKind::Continue)
|
||||
.expect("expected Continue node");
|
||||
|
||||
let back_edges_from_cont: Vec<_> = cfg
|
||||
.edges(cont)
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::Back))
|
||||
.collect();
|
||||
assert!(
|
||||
!back_edges_from_cont.is_empty(),
|
||||
"continue must originate at least one Back edge"
|
||||
);
|
||||
assert!(
|
||||
back_edges_from_cont
|
||||
.iter()
|
||||
.any(|e| e.target() == inner_header),
|
||||
"continue's Back edge must target the inner loop header"
|
||||
);
|
||||
assert!(
|
||||
!back_edges_from_cont
|
||||
.iter()
|
||||
.any(|e| e.target() == outer_header),
|
||||
"continue must not back-edge onto the outer loop header"
|
||||
);
|
||||
}
|
||||
|
||||
/// `throw` inside a `catch` block should still register a throw
|
||||
/// target so a surrounding outer try (or function-level exit) can
|
||||
/// receive it. We verify here that the throw produces a Throw node
|
||||
/// even when it is reached only via an Exception edge from the inner
|
||||
/// try body (i.e. the re-throw path is preserved structurally).
|
||||
#[test]
|
||||
fn js_throw_inside_catch_emits_throw_node() {
|
||||
let src = br#"function f() {
|
||||
try {
|
||||
try { foo(); } catch (e) { throw e; }
|
||||
} catch (e2) {
|
||||
handle();
|
||||
}
|
||||
}"#;
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
let throws: Vec<_> = cfg
|
||||
.node_indices()
|
||||
.filter(|&n| cfg[n].kind == StmtKind::Throw)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
throws.len(),
|
||||
1,
|
||||
"expected exactly one Throw node for the inner re-throw"
|
||||
);
|
||||
|
||||
// The outer `catch (e2)` body must be reachable. Check that the
|
||||
// `handle()` call exists and has at least one incoming edge.
|
||||
let handle = cfg
|
||||
.node_indices()
|
||||
.find(|&n| cfg[n].call.callee.as_deref() == Some("handle"))
|
||||
.expect("expected `handle()` call node");
|
||||
let in_edges = cfg
|
||||
.edges_directed(handle, petgraph::Direction::Incoming)
|
||||
.count();
|
||||
assert!(in_edges >= 1, "outer catch body must be reachable");
|
||||
}
|
||||
|
||||
/// Empty if/else branches (e.g., `if (a) {} else {}`) must not panic
|
||||
/// and the resulting CFG must still have a single If node with both
|
||||
/// True and False edges going somewhere reachable. This guards
|
||||
/// against off-by-one bugs in `then_first_node`/exits handling.
|
||||
#[test]
|
||||
fn js_if_with_empty_branches_does_not_panic() {
|
||||
let src = b"function f() { if (a) {} else {} return; }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _entry) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
let ifs = if_nodes(&cfg);
|
||||
assert_eq!(ifs.len(), 1, "expected one If node");
|
||||
let i = ifs[0];
|
||||
|
||||
let trues: Vec<_> = cfg
|
||||
.edges(i)
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::True))
|
||||
.collect();
|
||||
let falses: Vec<_> = cfg
|
||||
.edges(i)
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::False))
|
||||
.collect();
|
||||
assert!(!trues.is_empty(), "empty-then If must still emit True edge");
|
||||
assert!(
|
||||
!falses.is_empty(),
|
||||
"empty-else If must still emit False edge"
|
||||
);
|
||||
}
|
||||
|
||||
/// A function body with no statements should still produce a
|
||||
/// well-formed CFG (entry/exit only); no panic, no orphan nodes from
|
||||
/// `build_sub` returning an empty exit set.
|
||||
#[test]
|
||||
fn js_empty_function_body_well_formed() {
|
||||
let src = b"function f() {}";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let file_cfg = parse_to_file_cfg(src, "javascript", ts_lang);
|
||||
// We expect 2 bodies: top-level + the function body. Both must be
|
||||
// valid graphs with at least an entry node.
|
||||
assert!(
|
||||
file_cfg.bodies.len() >= 2,
|
||||
"expected at least 2 bodies (top-level + function)"
|
||||
);
|
||||
for body in &file_cfg.bodies {
|
||||
assert!(
|
||||
body.graph.node_count() >= 1,
|
||||
"every body must have at least one node"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Loop CFG structure: every loop variant must produce a Loop header
|
||||
// with at least one Back edge that targets that header. Without these
|
||||
// invariants the SSA loop-induction-variable phi placement is wrong
|
||||
// and the abstract-interp widening points are missed.
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn loop_headers(cfg: &Cfg) -> Vec<NodeIndex> {
|
||||
cfg.node_indices()
|
||||
.filter(|&n| cfg[n].kind == StmtKind::Loop)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn back_edges(cfg: &Cfg) -> Vec<(NodeIndex, NodeIndex)> {
|
||||
cfg.edge_references()
|
||||
.filter(|e| matches!(e.weight(), EdgeKind::Back))
|
||||
.map(|e| (e.source(), e.target()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn assert_loop_with_back_edge(cfg: &Cfg, label: &str) {
|
||||
let headers = loop_headers(cfg);
|
||||
assert!(
|
||||
!headers.is_empty(),
|
||||
"{label}: expected at least one Loop header, found none"
|
||||
);
|
||||
let backs = back_edges(cfg);
|
||||
assert!(
|
||||
!backs.is_empty(),
|
||||
"{label}: expected at least one Back edge"
|
||||
);
|
||||
for (_, dst) in &backs {
|
||||
assert!(
|
||||
headers.contains(dst),
|
||||
"{label}: Back edge target {:?} is not a Loop header (headers={:?})",
|
||||
dst,
|
||||
headers
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_for_loop_back_edge() {
|
||||
let src = b"function f() { for (let i = 0; i < 10; i++) { body(i); } }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "js classic for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_do_while_back_edge() {
|
||||
let src = b"function f() { do { body(); } while (cond()); }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "js do-while");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_for_in_back_edge() {
|
||||
let src = b"function f() { for (let k in obj) { use(k); } }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "js for-in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn js_for_of_back_edge() {
|
||||
let src = b"function f() { for (const x of items) { use(x); } }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
// for-of is usually classified the same as for-in / for via
|
||||
// for_in_statement. Still, body-with-back-edge invariant must hold.
|
||||
assert_loop_with_back_edge(&cfg, "js for-of");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_for_loop_back_edge() {
|
||||
let src = b"def f():\n for x in items:\n use(x)\n";
|
||||
let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "python", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "python for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_while_loop_back_edge() {
|
||||
let src = b"def f():\n while cond():\n use(x)\n";
|
||||
let ts_lang = Language::from(tree_sitter_python::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "python", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "python while");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_enhanced_for_back_edge() {
|
||||
let src = b"class A { void f(int[] xs) { for (int x : xs) { use(x); } } }";
|
||||
let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "java", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "java enhanced-for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_do_while_back_edge() {
|
||||
let src = b"class A { void f() { do { body(); } while (cond()); } }";
|
||||
let ts_lang = Language::from(tree_sitter_java::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "java", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "java do-while");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpp_range_for_back_edge() {
|
||||
let src = b"void f(int* xs) { for (int x : range) { use(x); } }";
|
||||
let ts_lang = Language::from(tree_sitter_cpp::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "cpp", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "cpp range-for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_do_while_back_edge() {
|
||||
let src = b"void f() { do { body(); } while (cond()); }";
|
||||
let ts_lang = Language::from(tree_sitter_c::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "c", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "c do-while");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_for_loop_back_edge() {
|
||||
let src = b"package p\nfunc f() { for i := 0; i < 10; i++ { body(i) } }";
|
||||
let ts_lang = Language::from(tree_sitter_go::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "go", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "go for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_while_back_edge() {
|
||||
let src = b"def f\n while cond\n body\n end\nend\n";
|
||||
let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "ruby", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "ruby while");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_until_back_edge() {
|
||||
// `until cond` is `while not cond`; should still produce a loop.
|
||||
let src = b"def f\n until done\n body\n end\nend\n";
|
||||
let ts_lang = Language::from(tree_sitter_ruby::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "ruby", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "ruby until");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn php_foreach_back_edge() {
|
||||
let src = b"<?php function f($items) { foreach ($items as $x) { use($x); } }";
|
||||
let ts_lang = Language::from(tree_sitter_php::LANGUAGE_PHP);
|
||||
let (cfg, _) = parse_and_build(src, "php", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "php foreach");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_for_loop_back_edge() {
|
||||
let src = b"fn f() { for x in 0..10 { use_fn(x); } }";
|
||||
let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "rust", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "rust for");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_while_loop_back_edge() {
|
||||
let src = b"fn f() { while cond() { body(); } }";
|
||||
let ts_lang = Language::from(tree_sitter_rust::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "rust", ts_lang);
|
||||
assert_loop_with_back_edge(&cfg, "rust while");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_loops_two_headers_two_back_edges() {
|
||||
// Nested loops must produce two distinct loop headers and a back
|
||||
// edge for each. This guards against headers being collapsed and
|
||||
// back edges being mis-routed to the outer header.
|
||||
let src = b"function f() { for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { use(i, j); } } }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
let headers = loop_headers(&cfg);
|
||||
assert_eq!(headers.len(), 2, "expected 2 loop headers in nested loops");
|
||||
let backs = back_edges(&cfg);
|
||||
assert!(
|
||||
backs.len() >= 2,
|
||||
"expected ≥2 back edges in nested loops, got {}",
|
||||
backs.len()
|
||||
);
|
||||
// Every back edge must target one of the two headers.
|
||||
for (_, dst) in &backs {
|
||||
assert!(headers.contains(dst), "back edge target not a loop header");
|
||||
}
|
||||
// Each header should be the target of at least one back edge.
|
||||
let mut hit = std::collections::HashSet::new();
|
||||
for (_, dst) in &backs {
|
||||
hit.insert(*dst);
|
||||
}
|
||||
assert_eq!(
|
||||
hit.len(),
|
||||
2,
|
||||
"each header must receive at least one back edge"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_with_break_no_back_edge_from_break() {
|
||||
// A `break` short-circuits the loop body — its edge must NOT be a
|
||||
// back edge to the header (it leaves the loop entirely).
|
||||
let src = b"function f() { while (cond()) { if (done()) break; body(); } }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
let headers = loop_headers(&cfg);
|
||||
assert_eq!(headers.len(), 1, "expected 1 loop header");
|
||||
let header = headers[0];
|
||||
|
||||
// Find any Break node and verify none of its outgoing edges are
|
||||
// Back edges to the header.
|
||||
for n in cfg.node_indices() {
|
||||
if cfg[n].kind != StmtKind::Break {
|
||||
continue;
|
||||
}
|
||||
for e in cfg.edges(n) {
|
||||
assert!(
|
||||
!(matches!(e.weight(), EdgeKind::Back) && e.target() == header),
|
||||
"break must not produce a back edge to the loop header"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_with_continue_back_edge_to_header() {
|
||||
// `continue` must produce a Back edge to the loop header.
|
||||
let src = b"function f() { while (cond()) { if (skip()) continue; body(); } }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
let headers = loop_headers(&cfg);
|
||||
assert_eq!(headers.len(), 1);
|
||||
let header = headers[0];
|
||||
|
||||
let mut found = false;
|
||||
for n in cfg.node_indices() {
|
||||
if cfg[n].kind != StmtKind::Continue {
|
||||
continue;
|
||||
}
|
||||
for e in cfg.edges(n) {
|
||||
if matches!(e.weight(), EdgeKind::Back) && e.target() == header {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
found,
|
||||
"expected at least one Back edge from a Continue node to the loop header"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression guard for the 2026-04-27 chained-method-call inner-gate
|
||||
/// rebinding (CVE-2025-64430 hunt session). Without the fix, the outer
|
||||
/// `.on('error', cb)` call swallows classification of the inner
|
||||
/// `http.get(uri, cb)` so neither the gate label nor `sink_payload_args`
|
||||
/// are populated for this CFG node.
|
||||
#[test]
|
||||
fn chained_method_call_rebinds_to_inner_gated_sink() {
|
||||
// Use `https.get` (a gated SSRF sink) so the gate fires only when
|
||||
// the inner-call rebinding works. The outer `.on(...)` is a plain
|
||||
// method call that does not classify on its own.
|
||||
let src = b"function f(uri) { https.get(uri, r => {}).on('error', e => {}); }";
|
||||
let ts_lang = Language::from(tree_sitter_javascript::LANGUAGE);
|
||||
let (cfg, _) = parse_and_build(src, "javascript", ts_lang);
|
||||
|
||||
// Find a Call node whose `text` was rebound to the inner gated callee.
|
||||
let mut found = false;
|
||||
for n in cfg.node_indices() {
|
||||
let info = &cfg[n];
|
||||
if info.kind != StmtKind::Call {
|
||||
continue;
|
||||
}
|
||||
let Some(callee) = info.call.callee.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
// The inner callee is `https.get`; the outer chained `.on` should
|
||||
// no longer be the recorded callee for this node.
|
||||
if callee.ends_with("https.get") {
|
||||
// The inner-gate path must have populated sink_payload_args
|
||||
// (the gate's payload arg is position 0 — the URL string).
|
||||
assert!(
|
||||
info.call.sink_payload_args.is_some(),
|
||||
"expected sink_payload_args to be populated for chained \
|
||||
inner-gate https.get; got None on call node with callee {callee:?}"
|
||||
);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
found,
|
||||
"expected at least one Call node whose callee was rebound from \
|
||||
the outer `.on(...)` to the inner `https.get` after the chained- \
|
||||
call inner-gate rebinding fired"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
450
src/cfg/dto.rs
Normal file
450
src/cfg/dto.rs
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
//! Phase 6.1: per-language DTO definition collectors.
|
||||
//!
|
||||
//! Walks a parsed file's AST and emits `(class_name, DtoFields)` pairs
|
||||
//! for class / interface / struct / Pydantic-model declarations whose
|
||||
//! field types resolve to a recognised [`TypeKind`].
|
||||
//!
|
||||
//! Strictly additive: classes whose fields cannot be classified produce
|
||||
//! a `DtoFields` with an empty `fields` map — the caller must decide
|
||||
//! whether to use that as a "Dto with no inferred fields" or fall back
|
||||
//! to the pre-Phase-6 Object/Unknown classification.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::helpers::text_of;
|
||||
use super::params::{java_type_to_kind, python_primitive_to_kind, ts_type_to_kind};
|
||||
use crate::ssa::type_facts::{DtoFields, TypeKind};
|
||||
|
||||
/// Collect all DTO-shaped class definitions in a parsed file.
|
||||
///
|
||||
/// Dispatches per-language; returns an empty map for languages without
|
||||
/// a Phase 6 collector (Go, Ruby, PHP, C/C++ — DTOs in those ecosystems
|
||||
/// either don't follow framework conventions Nyx tracks today, or are
|
||||
/// already covered by other type-inference paths).
|
||||
pub(super) fn collect_dto_classes(
|
||||
root: Node<'_>,
|
||||
lang: &str,
|
||||
code: &[u8],
|
||||
) -> HashMap<String, DtoFields> {
|
||||
let mut out: HashMap<String, DtoFields> = HashMap::new();
|
||||
match lang {
|
||||
"java" => collect_java(root, code, &mut out),
|
||||
"typescript" | "ts" | "javascript" | "js" => collect_ts(root, code, &mut out),
|
||||
"rust" | "rs" => collect_rust(root, code, &mut out),
|
||||
"python" | "py" => collect_python(root, code, &mut out),
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Java
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Walk the AST for `class_declaration` nodes whose body contains
|
||||
/// `field_declaration`s with classifiable types. Only class-level
|
||||
/// fields are collected; method-local declarations are ignored.
|
||||
fn collect_java(root: Node<'_>, code: &[u8], out: &mut HashMap<String, DtoFields>) {
|
||||
walk(root, &mut |node| {
|
||||
if node.kind() != "class_declaration" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(class_name) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
let Some(body) = node.child_by_field_name("body") else {
|
||||
return;
|
||||
};
|
||||
let mut fields = DtoFields::new(class_name.clone());
|
||||
let mut cursor = body.walk();
|
||||
for child in body.named_children(&mut cursor) {
|
||||
if child.kind() != "field_declaration" {
|
||||
continue;
|
||||
}
|
||||
let Some(type_node) = child.child_by_field_name("type") else {
|
||||
continue;
|
||||
};
|
||||
let Some(type_text) = text_of(type_node, code) else {
|
||||
continue;
|
||||
};
|
||||
let Some(kind) = java_type_to_kind(&type_text) else {
|
||||
continue;
|
||||
};
|
||||
// The declarator field carries the variable name(s).
|
||||
let Some(declarator) = child.child_by_field_name("declarator") else {
|
||||
continue;
|
||||
};
|
||||
// `variable_declarator` has a `name` field for the simple case.
|
||||
let Some(name_inner) = declarator.child_by_field_name("name") else {
|
||||
continue;
|
||||
};
|
||||
if let Some(field_name) = text_of(name_inner, code) {
|
||||
fields.insert(field_name, kind.clone());
|
||||
}
|
||||
}
|
||||
if !fields.fields.is_empty() {
|
||||
out.insert(class_name, fields);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// TypeScript / JavaScript
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Walk for `interface_declaration` and `class_declaration` nodes.
|
||||
/// Interfaces with `property_signature` children and classes with
|
||||
/// `public_field_definition` children produce DTO entries.
|
||||
fn collect_ts(root: Node<'_>, code: &[u8], out: &mut HashMap<String, DtoFields>) {
|
||||
walk(root, &mut |node| match node.kind() {
|
||||
"interface_declaration" => {
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(class_name) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
let Some(body) = node.child_by_field_name("body") else {
|
||||
return;
|
||||
};
|
||||
let mut fields = DtoFields::new(class_name.clone());
|
||||
let mut cursor = body.walk();
|
||||
for child in body.named_children(&mut cursor) {
|
||||
if child.kind() != "property_signature" {
|
||||
continue;
|
||||
}
|
||||
let Some((field_name, kind)) = extract_ts_property(child, code) else {
|
||||
continue;
|
||||
};
|
||||
fields.insert(field_name, kind);
|
||||
}
|
||||
if !fields.fields.is_empty() {
|
||||
out.insert(class_name, fields);
|
||||
}
|
||||
}
|
||||
"class_declaration" => {
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(class_name) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
let Some(body) = node.child_by_field_name("body") else {
|
||||
return;
|
||||
};
|
||||
let mut fields = DtoFields::new(class_name.clone());
|
||||
let mut cursor = body.walk();
|
||||
for child in body.named_children(&mut cursor) {
|
||||
if child.kind() != "public_field_definition" && child.kind() != "field_definition" {
|
||||
continue;
|
||||
}
|
||||
let Some((field_name, kind)) = extract_ts_property(child, code) else {
|
||||
continue;
|
||||
};
|
||||
fields.insert(field_name, kind);
|
||||
}
|
||||
if !fields.fields.is_empty() {
|
||||
out.insert(class_name, fields);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Extract `(field_name, TypeKind)` from a TS `property_signature` /
|
||||
/// `public_field_definition`. Returns None when either piece is absent
|
||||
/// or the type doesn't classify.
|
||||
fn extract_ts_property<'a>(node: Node<'a>, code: &'a [u8]) -> Option<(String, TypeKind)> {
|
||||
let name_node = node.child_by_field_name("name")?;
|
||||
let field_name = text_of(name_node, code)?;
|
||||
let type_anno = node.child_by_field_name("type")?;
|
||||
// type_annotation node text is `: T` — walk to the inner type.
|
||||
let type_text = type_anno
|
||||
.named_child(0)
|
||||
.and_then(|t| text_of(t, code))
|
||||
.or_else(|| text_of(type_anno, code))?;
|
||||
let stripped = type_text.trim().trim_start_matches(':').trim();
|
||||
let kind = ts_type_to_kind(stripped)?;
|
||||
Some((field_name, kind))
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Rust
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Walk for `struct_item` nodes whose body lists named fields.
|
||||
fn collect_rust(root: Node<'_>, code: &[u8], out: &mut HashMap<String, DtoFields>) {
|
||||
walk(root, &mut |node| {
|
||||
if node.kind() != "struct_item" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(class_name) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
let Some(body) = node.child_by_field_name("body") else {
|
||||
return;
|
||||
};
|
||||
if body.kind() != "field_declaration_list" {
|
||||
// Tuple struct or unit struct — no named fields.
|
||||
return;
|
||||
}
|
||||
let mut fields = DtoFields::new(class_name.clone());
|
||||
let mut cursor = body.walk();
|
||||
for child in body.named_children(&mut cursor) {
|
||||
if child.kind() != "field_declaration" {
|
||||
continue;
|
||||
}
|
||||
let Some(name_inner) = child.child_by_field_name("name") else {
|
||||
continue;
|
||||
};
|
||||
let Some(type_inner) = child.child_by_field_name("type") else {
|
||||
continue;
|
||||
};
|
||||
let Some(field_name) = text_of(name_inner, code) else {
|
||||
continue;
|
||||
};
|
||||
let Some(type_text) = text_of(type_inner, code) else {
|
||||
continue;
|
||||
};
|
||||
let Some(kind) = super::params::rust_primitive_to_kind(type_text.trim()) else {
|
||||
continue;
|
||||
};
|
||||
fields.insert(field_name, kind);
|
||||
}
|
||||
if !fields.fields.is_empty() {
|
||||
out.insert(class_name, fields);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Python (Pydantic)
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Walk for `class_definition` nodes whose superclass list contains
|
||||
/// `BaseModel` / `pydantic.BaseModel`. Each `expression_statement` in
|
||||
/// the class body that is a typed assignment (`name: type`) produces a
|
||||
/// field entry.
|
||||
fn collect_python(root: Node<'_>, code: &[u8], out: &mut HashMap<String, DtoFields>) {
|
||||
walk(root, &mut |node| {
|
||||
if node.kind() != "class_definition" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(class_name) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
if !python_inherits_basemodel(node, code) {
|
||||
return;
|
||||
}
|
||||
let Some(body) = node.child_by_field_name("body") else {
|
||||
return;
|
||||
};
|
||||
let mut fields = DtoFields::new(class_name.clone());
|
||||
let mut cursor = body.walk();
|
||||
for stmt in body.named_children(&mut cursor) {
|
||||
// Field declarations show up as `expression_statement` wrapping
|
||||
// either an `assignment` (`name: type = default`) or a bare
|
||||
// typed assignment.
|
||||
if stmt.kind() != "expression_statement" {
|
||||
continue;
|
||||
}
|
||||
let Some(inner) = stmt.named_child(0) else {
|
||||
continue;
|
||||
};
|
||||
if inner.kind() != "assignment" {
|
||||
continue;
|
||||
}
|
||||
let Some(left) = inner.child_by_field_name("left") else {
|
||||
continue;
|
||||
};
|
||||
let Some(field_name) = text_of(left, code) else {
|
||||
continue;
|
||||
};
|
||||
let Some(type_node) = inner.child_by_field_name("type") else {
|
||||
continue;
|
||||
};
|
||||
let Some(type_text) = text_of(type_node, code) else {
|
||||
continue;
|
||||
};
|
||||
let Some(kind) = python_primitive_to_kind(type_text.trim()) else {
|
||||
continue;
|
||||
};
|
||||
fields.insert(field_name, kind);
|
||||
}
|
||||
if !fields.fields.is_empty() {
|
||||
out.insert(class_name, fields);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Conservative supertype scan: returns true when the class definition
|
||||
/// has a superclass list whose text mentions `BaseModel` (covers both
|
||||
/// `BaseModel` and `pydantic.BaseModel`). No false positives on
|
||||
/// non-Pydantic classes named `BaseModel`-something — match is on the
|
||||
/// full token, not a substring.
|
||||
fn python_inherits_basemodel<'a>(class_node: Node<'a>, code: &'a [u8]) -> bool {
|
||||
let Some(supers) = class_node.child_by_field_name("superclasses") else {
|
||||
return false;
|
||||
};
|
||||
let mut cursor = supers.walk();
|
||||
for child in supers.named_children(&mut cursor) {
|
||||
if let Some(text) = text_of(child, code) {
|
||||
let head = text.trim();
|
||||
if head == "BaseModel" || head == "pydantic.BaseModel" {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Walk helper
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn walk<'a, F: FnMut(Node<'a>)>(node: Node<'a>, f: &mut F) {
|
||||
f(node);
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
walk(child, f);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn collect(lang: &str, src: &str) -> HashMap<String, DtoFields> {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let language = match lang {
|
||||
"java" => tree_sitter_java::LANGUAGE.into(),
|
||||
"typescript" => tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
|
||||
"rust" => tree_sitter_rust::LANGUAGE.into(),
|
||||
"python" => tree_sitter_python::LANGUAGE.into(),
|
||||
other => panic!("unsupported lang: {other}"),
|
||||
};
|
||||
parser.set_language(&language).unwrap();
|
||||
let tree = parser.parse(src, None).unwrap();
|
||||
collect_dto_classes(tree.root_node(), lang, src.as_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_class_with_long_and_string_fields() {
|
||||
let src = r#"
|
||||
public class CreateUser {
|
||||
private Long age;
|
||||
private String email;
|
||||
}
|
||||
"#;
|
||||
let dtos = collect("java", src);
|
||||
let dto = dtos.get("CreateUser").expect("CreateUser DTO recorded");
|
||||
assert_eq!(dto.get("age"), Some(&TypeKind::Int));
|
||||
assert_eq!(dto.get("email"), Some(&TypeKind::String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_unclassifiable_field_dropped() {
|
||||
let src = r#"
|
||||
public class HoldsList {
|
||||
private List<String> items;
|
||||
private Long count;
|
||||
}
|
||||
"#;
|
||||
let dtos = collect("java", src);
|
||||
let dto = dtos.get("HoldsList").expect("class recorded");
|
||||
// Only the Long field qualifies; List<String> is not currently
|
||||
// recognised by `java_type_to_kind`.
|
||||
assert_eq!(dto.get("count"), Some(&TypeKind::Int));
|
||||
assert!(dto.get("items").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts_interface_with_number_and_string_fields() {
|
||||
let src = r#"
|
||||
export interface CreateUser {
|
||||
age: number;
|
||||
email: string;
|
||||
}
|
||||
"#;
|
||||
let dtos = collect("typescript", src);
|
||||
let dto = dtos.get("CreateUser").expect("CreateUser interface");
|
||||
assert_eq!(dto.get("age"), Some(&TypeKind::Int));
|
||||
assert_eq!(dto.get("email"), Some(&TypeKind::String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts_class_with_typed_field_definitions() {
|
||||
let src = r#"
|
||||
export class CreateUser {
|
||||
age!: number;
|
||||
email!: string;
|
||||
}
|
||||
"#;
|
||||
let dtos = collect("typescript", src);
|
||||
let dto = dtos.get("CreateUser").expect("CreateUser class");
|
||||
assert_eq!(dto.get("age"), Some(&TypeKind::Int));
|
||||
assert_eq!(dto.get("email"), Some(&TypeKind::String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_struct_with_int_and_string_fields() {
|
||||
let src = r#"
|
||||
pub struct CreateUser {
|
||||
pub age: i64,
|
||||
pub email: String,
|
||||
}
|
||||
"#;
|
||||
let dtos = collect("rust", src);
|
||||
let dto = dtos.get("CreateUser").expect("CreateUser struct");
|
||||
assert_eq!(dto.get("age"), Some(&TypeKind::Int));
|
||||
assert_eq!(dto.get("email"), Some(&TypeKind::String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_tuple_struct_skipped() {
|
||||
let src = r#"
|
||||
pub struct Wrap(i64, String);
|
||||
"#;
|
||||
let dtos = collect("rust", src);
|
||||
// Tuple structs have no named fields and must NOT produce a
|
||||
// DtoFields entry — Phase 6 only handles named-field DTOs.
|
||||
assert!(!dtos.contains_key("Wrap"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_pydantic_basemodel_with_int_and_str() {
|
||||
let src = r#"
|
||||
class CreateUser(BaseModel):
|
||||
age: int
|
||||
email: str
|
||||
"#;
|
||||
let dtos = collect("python", src);
|
||||
let dto = dtos.get("CreateUser").expect("CreateUser model");
|
||||
assert_eq!(dto.get("age"), Some(&TypeKind::Int));
|
||||
assert_eq!(dto.get("email"), Some(&TypeKind::String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_class_without_basemodel_is_skipped() {
|
||||
// Hard Rule 3 spirit: only Pydantic models should be lifted as
|
||||
// DTOs. Plain classes with typed attributes don't qualify.
|
||||
let src = r#"
|
||||
class NotADto:
|
||||
age: int
|
||||
email: str
|
||||
"#;
|
||||
let dtos = collect("python", src);
|
||||
assert!(!dtos.contains_key("NotADto"));
|
||||
}
|
||||
}
|
||||
|
|
@ -328,13 +328,21 @@ pub(crate) fn member_expr_text(n: Node, code: &[u8]) -> Option<String> {
|
|||
pub(crate) fn member_expr_text_inner(n: Node, code: &[u8]) -> Option<String> {
|
||||
match n.kind() {
|
||||
"member_expression" | "attribute" | "selector_expression" => {
|
||||
// Tree-sitter exposes the receiver under `object` (JS/TS, Python),
|
||||
// `value` (Rust field_expression — handled in the matching arm
|
||||
// above), or `operand` (Go selector_expression). Without the
|
||||
// `operand` fallback, Go member access like `r.Body` collapsed to
|
||||
// just the trailing field (`Body`), so source rules keyed on the
|
||||
// dotted form (e.g. Go's `r.Body`) would never match.
|
||||
let obj = n
|
||||
.child_by_field_name("object")
|
||||
.or_else(|| n.child_by_field_name("value"))
|
||||
.or_else(|| n.child_by_field_name("operand"))
|
||||
.and_then(|o| member_expr_text_inner(o, code))
|
||||
.or_else(|| {
|
||||
n.child_by_field_name("object")
|
||||
.or_else(|| n.child_by_field_name("value"))
|
||||
.or_else(|| n.child_by_field_name("operand"))
|
||||
.and_then(|o| text_of(o, code))
|
||||
});
|
||||
let prop = n
|
||||
|
|
@ -700,3 +708,79 @@ pub(crate) fn collect_idents(n: Node, code: &[u8], out: &mut Vec<String>) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pointer-Phase 6 / W5: AST kind names for subscript / index expressions
|
||||
/// across the languages whose container-element flow we model.
|
||||
///
|
||||
/// JS/TS use `subscript_expression`; Python uses `subscript`; Go uses
|
||||
/// `index_expression`. Other languages either lower indexing through
|
||||
/// method calls (Rust slice indexing) or are out of scope for the
|
||||
/// initial W5 rollout (Java/Ruby/PHP/C/C++).
|
||||
#[inline]
|
||||
pub(crate) fn is_subscript_kind(kind: &str) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
"subscript_expression" | "subscript" | "index_expression"
|
||||
)
|
||||
}
|
||||
|
||||
/// Pointer-Phase 6 / W5: when the LHS of an assignment statement is a
|
||||
/// subscript / index expression (or a single-element wrapper around
|
||||
/// one), return that node. Returns `None` for multi-target Go
|
||||
/// `expression_list`s, identifier LHSs, member-expression LHSs, etc.
|
||||
pub(crate) fn subscript_lhs_node<'a>(lhs: Node<'a>, lang: &str) -> Option<Node<'a>> {
|
||||
if is_subscript_kind(lhs.kind()) {
|
||||
return Some(lhs);
|
||||
}
|
||||
// Go: `assignment_statement.left` is an `expression_list`; for
|
||||
// single-target subscript writes (`m[k] = v`) it has exactly one
|
||||
// named child which is `index_expression`.
|
||||
if lang == "go" && lhs.kind() == "expression_list" {
|
||||
let mut cursor = lhs.walk();
|
||||
let named: Vec<Node> = lhs.named_children(&mut cursor).collect();
|
||||
if named.len() == 1 && is_subscript_kind(named[0].kind()) {
|
||||
return Some(named[0]);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Pointer-Phase 6 / W5: extract `(array_text, index_text)` from a
|
||||
/// subscript / index AST node.
|
||||
///
|
||||
/// Returns `None` when the array operand is not a plain identifier — we
|
||||
/// only synthesise `__index_get__` / `__index_set__` calls when the
|
||||
/// receiver resolves cleanly to a SSA-renamed local, since the W2/W4
|
||||
/// container hooks need a stable receiver var_name to drive
|
||||
/// `pt(receiver)`.
|
||||
pub(crate) fn subscript_components<'a>(n: Node<'a>, code: &'a [u8]) -> Option<(String, String)> {
|
||||
if !is_subscript_kind(n.kind()) {
|
||||
return None;
|
||||
}
|
||||
let arr = n
|
||||
.child_by_field_name("object")
|
||||
.or_else(|| n.child_by_field_name("operand"))
|
||||
.or_else(|| n.child_by_field_name("value"))
|
||||
.or_else(|| n.child(0))?;
|
||||
let idx = n
|
||||
.child_by_field_name("index")
|
||||
.or_else(|| n.child_by_field_name("subscript"))
|
||||
.or_else(|| {
|
||||
// Fallback: take the second named child after the array.
|
||||
let mut cur = n.walk();
|
||||
n.named_children(&mut cur).nth(1)
|
||||
})?;
|
||||
let arr_kind = arr.kind();
|
||||
// Only proceed when the array is a plain identifier — otherwise
|
||||
// we can't bind a stable receiver name for the synth Call.
|
||||
if !matches!(
|
||||
arr_kind,
|
||||
"identifier" | "variable_name" | "simple_identifier"
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
let arr_text = text_of(arr, code)?;
|
||||
// PHP-style `$x` strip not needed here — Go/JS/Python don't use it.
|
||||
let idx_text = text_of(idx, code)?;
|
||||
Some((arr_text, idx_text))
|
||||
}
|
||||
|
|
|
|||
547
src/cfg/hierarchy.rs
Normal file
547
src/cfg/hierarchy.rs
Normal file
|
|
@ -0,0 +1,547 @@
|
|||
//! Phase 6: per-language class / trait / interface hierarchy extraction.
|
||||
//!
|
||||
//! Walks a parsed file's AST and emits `(sub_container, super_container)`
|
||||
//! pairs for every declared inheritance / impl / implements relationship.
|
||||
//! The result is consumed by [`crate::callgraph::TypeHierarchyIndex`] to
|
||||
//! fan out method-call edges to every concrete implementer when a
|
||||
//! receiver's static type is a super-class / trait / interface.
|
||||
//!
|
||||
//! Strictly additive: a language without an extractor (Go, C) returns
|
||||
//! the empty vector and the resolver falls back to today's
|
||||
//! single-container behaviour.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::helpers::text_of;
|
||||
|
||||
/// Collect `(sub_container, super_container)` edges for a parsed file.
|
||||
///
|
||||
/// The returned vector is **deduplicated within the file** but may
|
||||
/// contain duplicates across files (each file emits its own edges).
|
||||
/// The downstream [`crate::callgraph::TypeHierarchyIndex::build`]
|
||||
/// dedups across files.
|
||||
pub(crate) fn collect_hierarchy_edges(
|
||||
root: Node<'_>,
|
||||
lang: &str,
|
||||
code: &[u8],
|
||||
) -> Vec<(String, String)> {
|
||||
let mut acc: Vec<(String, String)> = Vec::new();
|
||||
let mut seen: HashSet<(String, String)> = HashSet::new();
|
||||
let mut push = |sub: String, sup: String| {
|
||||
if sub.is_empty() || sup.is_empty() {
|
||||
return;
|
||||
}
|
||||
if seen.insert((sub.clone(), sup.clone())) {
|
||||
acc.push((sub, sup));
|
||||
}
|
||||
};
|
||||
|
||||
match lang {
|
||||
"java" => collect_java(root, code, &mut push),
|
||||
"rust" | "rs" => collect_rust(root, code, &mut push),
|
||||
"typescript" | "ts" | "tsx" | "javascript" | "js" => collect_ts(root, code, &mut push),
|
||||
"python" | "py" => collect_python(root, code, &mut push),
|
||||
"ruby" | "rb" => collect_ruby(root, code, &mut push),
|
||||
"php" => collect_php(root, code, &mut push),
|
||||
"cpp" | "c++" => collect_cpp(root, code, &mut push),
|
||||
// Go: structural / implicit interface satisfaction is intractable
|
||||
// per-file; Phase 6 deliberately skips it.
|
||||
// C: no inheritance.
|
||||
_ => {}
|
||||
}
|
||||
acc
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Java
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn collect_java<F: FnMut(String, String)>(root: Node<'_>, code: &[u8], push: &mut F) {
|
||||
walk(root, &mut |node| {
|
||||
let kind = node.kind();
|
||||
if kind != "class_declaration" && kind != "interface_declaration" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(sub) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
// `superclass` field on class_declaration — singular `extends Y`.
|
||||
if let Some(superclass) = node.child_by_field_name("superclass") {
|
||||
let mut cursor = superclass.walk();
|
||||
for c in superclass.named_children(&mut cursor) {
|
||||
if let Some(t) = type_identifier_text(c, code) {
|
||||
push(sub.clone(), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// `interfaces` field on class_declaration — `implements I, J`
|
||||
// wraps a `super_interfaces` → `type_list`.
|
||||
if let Some(ifaces) = node.child_by_field_name("interfaces") {
|
||||
collect_java_type_list(ifaces, code, &sub, push);
|
||||
}
|
||||
// `extends_interfaces` is an unnamed child on
|
||||
// interface_declaration — `extends Foo, Bar` for an
|
||||
// interface. Walk children directly since it's not a field.
|
||||
let mut cursor = node.walk();
|
||||
for c in node.named_children(&mut cursor) {
|
||||
if c.kind() == "extends_interfaces" {
|
||||
collect_java_type_list(c, code, &sub, push);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn collect_java_type_list<F: FnMut(String, String)>(
|
||||
n: Node<'_>,
|
||||
code: &[u8],
|
||||
sub: &str,
|
||||
push: &mut F,
|
||||
) {
|
||||
let mut cursor = n.walk();
|
||||
for child in n.named_children(&mut cursor) {
|
||||
match child.kind() {
|
||||
"type_list" | "interface_type_list" => {
|
||||
collect_java_type_list(child, code, sub, push);
|
||||
}
|
||||
_ => {
|
||||
if let Some(t) = type_identifier_text(child, code) {
|
||||
push(sub.to_string(), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip generic / nested `type_arguments` from a type-reference node
|
||||
/// down to the bare identifier.
|
||||
fn type_identifier_text(n: Node<'_>, code: &[u8]) -> Option<String> {
|
||||
match n.kind() {
|
||||
"type_identifier" | "identifier" => text_of(n, code),
|
||||
"generic_type" => {
|
||||
// `Foo<T>` — the leading child is the bare type identifier.
|
||||
let mut cursor = n.walk();
|
||||
for c in n.named_children(&mut cursor) {
|
||||
if matches!(
|
||||
c.kind(),
|
||||
"type_identifier" | "identifier" | "scoped_type_identifier"
|
||||
) {
|
||||
return text_of(c, code);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
"scoped_type_identifier" => {
|
||||
// `pkg.Foo` — return last segment.
|
||||
text_of(n, code).map(|s| {
|
||||
let last = s.rsplit('.').next().unwrap_or(&s);
|
||||
last.to_string()
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Rust
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Walk for `impl_item` nodes and emit edges from the concrete type to
|
||||
/// the trait being implemented. Inherent impls (`impl Foo {}`) emit
|
||||
/// no edge — there is no super-trait relationship to record.
|
||||
fn collect_rust<F: FnMut(String, String)>(root: Node<'_>, code: &[u8], push: &mut F) {
|
||||
walk(root, &mut |node| {
|
||||
if node.kind() != "impl_item" {
|
||||
return;
|
||||
}
|
||||
// tree-sitter-rust uses `trait` and `type` field names.
|
||||
let Some(trait_node) = node.child_by_field_name("trait") else {
|
||||
return; // inherent impl
|
||||
};
|
||||
let Some(type_node) = node.child_by_field_name("type") else {
|
||||
return;
|
||||
};
|
||||
let Some(trait_name) = rust_path_leaf(trait_node, code) else {
|
||||
return;
|
||||
};
|
||||
let Some(type_name) = rust_path_leaf(type_node, code) else {
|
||||
return;
|
||||
};
|
||||
push(type_name, trait_name);
|
||||
});
|
||||
}
|
||||
|
||||
fn rust_path_leaf(n: Node<'_>, code: &[u8]) -> Option<String> {
|
||||
match n.kind() {
|
||||
"type_identifier" | "identifier" => text_of(n, code),
|
||||
"scoped_type_identifier" | "scoped_identifier" => {
|
||||
// `crate::foo::Bar` — last segment.
|
||||
let s = text_of(n, code)?;
|
||||
Some(s.rsplit("::").next().unwrap_or(&s).to_string())
|
||||
}
|
||||
"generic_type" => {
|
||||
let mut cursor = n.walk();
|
||||
for c in n.named_children(&mut cursor) {
|
||||
if matches!(
|
||||
c.kind(),
|
||||
"type_identifier" | "scoped_type_identifier" | "identifier"
|
||||
) {
|
||||
return rust_path_leaf(c, code);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// TypeScript / JavaScript
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn collect_ts<F: FnMut(String, String)>(root: Node<'_>, code: &[u8], push: &mut F) {
|
||||
walk(root, &mut |node| {
|
||||
let kind = node.kind();
|
||||
if kind != "class_declaration" && kind != "interface_declaration" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(sub) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
match child.kind() {
|
||||
"class_heritage" => {
|
||||
let mut h = child.walk();
|
||||
for c in child.named_children(&mut h) {
|
||||
match c.kind() {
|
||||
"extends_clause" => collect_ts_heritage(c, code, &sub, push),
|
||||
"implements_clause" => collect_ts_heritage(c, code, &sub, push),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
"extends_clause" => collect_ts_heritage(child, code, &sub, push),
|
||||
"extends_type_clause" => collect_ts_heritage(child, code, &sub, push),
|
||||
"implements_clause" => collect_ts_heritage(child, code, &sub, push),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn collect_ts_heritage<F: FnMut(String, String)>(
|
||||
clause: Node<'_>,
|
||||
code: &[u8],
|
||||
sub: &str,
|
||||
push: &mut F,
|
||||
) {
|
||||
let mut cursor = clause.walk();
|
||||
for c in clause.named_children(&mut cursor) {
|
||||
match c.kind() {
|
||||
"identifier" | "type_identifier" => {
|
||||
if let Some(t) = text_of(c, code) {
|
||||
push(sub.to_string(), t);
|
||||
}
|
||||
}
|
||||
"generic_type" | "type_arguments" | "type_query" => {
|
||||
let mut cursor2 = c.walk();
|
||||
for inner in c.named_children(&mut cursor2) {
|
||||
if matches!(inner.kind(), "identifier" | "type_identifier")
|
||||
&& let Some(t) = text_of(inner, code)
|
||||
{
|
||||
push(sub.to_string(), t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Python
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn collect_python<F: FnMut(String, String)>(root: Node<'_>, code: &[u8], push: &mut F) {
|
||||
walk(root, &mut |node| {
|
||||
if node.kind() != "class_definition" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(sub) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
let Some(superclasses) = node.child_by_field_name("superclasses") else {
|
||||
return; // no parents
|
||||
};
|
||||
// `superclasses` is an `argument_list` — each non-keyword
|
||||
// argument is a base class.
|
||||
let mut cursor = superclasses.walk();
|
||||
for arg in superclasses.named_children(&mut cursor) {
|
||||
if let Some(t) = python_base_text(arg, code) {
|
||||
// Skip Python `object` — not informative.
|
||||
if t != "object" {
|
||||
push(sub.clone(), t);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn python_base_text(n: Node<'_>, code: &[u8]) -> Option<String> {
|
||||
match n.kind() {
|
||||
"identifier" => text_of(n, code),
|
||||
"attribute" => {
|
||||
// `pkg.Base` — last segment.
|
||||
let s = text_of(n, code)?;
|
||||
Some(s.rsplit('.').next().unwrap_or(&s).to_string())
|
||||
}
|
||||
// Skip keyword arguments like `metaclass=...`.
|
||||
"keyword_argument" => None,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Ruby
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn collect_ruby<F: FnMut(String, String)>(root: Node<'_>, code: &[u8], push: &mut F) {
|
||||
walk(root, &mut |node| {
|
||||
if node.kind() != "class" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(sub) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
if let Some(superclass) = node.child_by_field_name("superclass") {
|
||||
// `superclass` wraps the parent identifier.
|
||||
let mut cursor = superclass.walk();
|
||||
for c in superclass.named_children(&mut cursor) {
|
||||
if matches!(c.kind(), "constant" | "scope_resolution")
|
||||
&& let Some(t) = text_of(c, code)
|
||||
{
|
||||
let leaf = t.rsplit("::").next().unwrap_or(&t).to_string();
|
||||
push(sub.clone(), leaf);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// PHP
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn collect_php<F: FnMut(String, String)>(root: Node<'_>, code: &[u8], push: &mut F) {
|
||||
walk(root, &mut |node| {
|
||||
let kind = node.kind();
|
||||
if kind != "class_declaration" && kind != "interface_declaration" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(sub) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
// PHP class_declaration may have base_clause and class_interface_clause.
|
||||
let mut cursor = node.walk();
|
||||
for c in node.named_children(&mut cursor) {
|
||||
match c.kind() {
|
||||
"base_clause" | "class_interface_clause" => {
|
||||
let mut cc = c.walk();
|
||||
for inner in c.named_children(&mut cc) {
|
||||
if matches!(inner.kind(), "name" | "qualified_name")
|
||||
&& let Some(t) = text_of(inner, code)
|
||||
{
|
||||
let leaf = t.rsplit('\\').next().unwrap_or(&t).to_string();
|
||||
push(sub.clone(), leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// C++
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn collect_cpp<F: FnMut(String, String)>(root: Node<'_>, code: &[u8], push: &mut F) {
|
||||
walk(root, &mut |node| {
|
||||
let kind = node.kind();
|
||||
if kind != "class_specifier" && kind != "struct_specifier" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else {
|
||||
return;
|
||||
};
|
||||
let Some(sub) = text_of(name_node, code) else {
|
||||
return;
|
||||
};
|
||||
// tree-sitter-cpp uses `base_class_clause` for the `: public Y` part.
|
||||
let mut cursor = node.walk();
|
||||
for c in node.named_children(&mut cursor) {
|
||||
if c.kind() == "base_class_clause" {
|
||||
let mut cc = c.walk();
|
||||
for inner in c.named_children(&mut cc) {
|
||||
if matches!(
|
||||
inner.kind(),
|
||||
"type_identifier" | "qualified_identifier" | "template_type"
|
||||
) {
|
||||
if let Some(t) = text_of(inner, code) {
|
||||
let leaf = t.rsplit("::").next().unwrap_or(&t).to_string();
|
||||
push(sub.clone(), leaf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn walk<'a, F: FnMut(Node<'a>)>(node: Node<'a>, f: &mut F) {
|
||||
f(node);
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
walk(child, f);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn collect(lang: &str, src: &str) -> Vec<(String, String)> {
|
||||
let mut parser = tree_sitter::Parser::new();
|
||||
let ts_lang = match lang {
|
||||
"java" => tree_sitter::Language::from(tree_sitter_java::LANGUAGE),
|
||||
"rust" => tree_sitter::Language::from(tree_sitter_rust::LANGUAGE),
|
||||
"python" => tree_sitter::Language::from(tree_sitter_python::LANGUAGE),
|
||||
"typescript" => {
|
||||
tree_sitter::Language::from(tree_sitter_typescript::LANGUAGE_TYPESCRIPT)
|
||||
}
|
||||
"ruby" => tree_sitter::Language::from(tree_sitter_ruby::LANGUAGE),
|
||||
"php" => tree_sitter::Language::from(tree_sitter_php::LANGUAGE_PHP),
|
||||
"cpp" => tree_sitter::Language::from(tree_sitter_cpp::LANGUAGE),
|
||||
_ => panic!("unsupported test lang: {lang}"),
|
||||
};
|
||||
parser.set_language(&ts_lang).unwrap();
|
||||
let tree = parser.parse(src.as_bytes(), None).unwrap();
|
||||
collect_hierarchy_edges(tree.root_node(), lang, src.as_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_class_extends_emits_edge() {
|
||||
let src = "class Derived extends Base {}";
|
||||
let edges = collect("java", src);
|
||||
assert!(edges.contains(&("Derived".into(), "Base".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_class_implements_emits_per_interface_edge() {
|
||||
let src = "class UserRepo implements Repository, Cache {}";
|
||||
let edges = collect("java", src);
|
||||
assert!(edges.contains(&("UserRepo".into(), "Repository".into())));
|
||||
assert!(edges.contains(&("UserRepo".into(), "Cache".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_interface_extends_emits_edges() {
|
||||
let src = "interface Mine extends Foo, Bar {}";
|
||||
let edges = collect("java", src);
|
||||
// tree-sitter-java models `extends` on interface as `extends_interfaces`
|
||||
// rooted at the same node — at least one of the parents should land.
|
||||
assert!(
|
||||
edges.iter().any(|(s, _)| s == "Mine"),
|
||||
"interface extends should emit at least one edge; got {edges:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_impl_trait_for_type_emits_edge() {
|
||||
let src = "impl Repository for UserRepo {}";
|
||||
let edges = collect("rust", src);
|
||||
assert!(edges.contains(&("UserRepo".into(), "Repository".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_inherent_impl_emits_no_edge() {
|
||||
let src = "impl UserRepo { fn new() {} }";
|
||||
let edges = collect("rust", src);
|
||||
assert!(
|
||||
edges.is_empty(),
|
||||
"inherent impl must not emit; got {edges:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ts_class_extends_implements_emits_edges() {
|
||||
let src = "class UserRepo extends BaseRepo implements Repository {}";
|
||||
let edges = collect("typescript", src);
|
||||
assert!(edges.contains(&("UserRepo".into(), "BaseRepo".into())));
|
||||
assert!(edges.contains(&("UserRepo".into(), "Repository".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_class_inherits_from_bases() {
|
||||
let src = "class Derived(Base, Mixin):\n pass\n";
|
||||
let edges = collect("python", src);
|
||||
assert!(edges.contains(&("Derived".into(), "Base".into())));
|
||||
assert!(edges.contains(&("Derived".into(), "Mixin".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_class_object_base_skipped() {
|
||||
// Inheriting from `object` is not informative — Python's
|
||||
// implicit root. Phase 6 omits these edges to keep the
|
||||
// hierarchy index focused on user-defined relationships.
|
||||
let src = "class Plain(object):\n pass\n";
|
||||
let edges = collect("python", src);
|
||||
assert!(
|
||||
!edges.contains(&("Plain".into(), "object".into())),
|
||||
"object base must be filtered; got {edges:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruby_class_lt_super_emits_edge() {
|
||||
let src = "class Derived < Base\nend\n";
|
||||
let edges = collect("ruby", src);
|
||||
assert!(edges.contains(&("Derived".into(), "Base".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedup_within_file() {
|
||||
let src = r#"
|
||||
class A extends B {}
|
||||
class A extends B {}
|
||||
"#;
|
||||
let edges = collect("java", src);
|
||||
let count = edges.iter().filter(|(s, p)| s == "A" && p == "B").count();
|
||||
assert_eq!(count, 1, "duplicates within a file must be deduped");
|
||||
}
|
||||
}
|
||||
|
|
@ -244,6 +244,214 @@ pub(super) fn has_keyword_arg(call_node: Node, keyword_name: &str, code: &[u8])
|
|||
false
|
||||
}
|
||||
|
||||
/// Inspect the first positional argument of a call node and return its
|
||||
/// tree-sitter `kind()` plus a flag indicating whether any descendant is an
|
||||
/// `interpolation` node. Skips parenthesisation (`(arg0)` is treated as
|
||||
/// `arg0`). Returns `None` when the call has no arguments.
|
||||
///
|
||||
/// Used by per-language shape-aware sink suppression — for example, Ruby
|
||||
/// ActiveRecord query methods (`where`, `order`, `pluck`, …) are intrinsically
|
||||
/// parameterised when arg 0 is a hash/symbol/array/non-interpolated string,
|
||||
/// regardless of taint reaching that argument.
|
||||
pub(super) fn arg0_kind_and_interpolation(call_node: Node) -> Option<(String, bool)> {
|
||||
let args = call_node.child_by_field_name("arguments")?;
|
||||
let mut cursor = args.walk();
|
||||
let arg0 = args.named_children(&mut cursor).next()?;
|
||||
let arg0 = unwrap_parens(arg0);
|
||||
let kind = arg0.kind().to_string();
|
||||
let has_interp = subtree_has_interpolation(arg0);
|
||||
Some((kind, has_interp))
|
||||
}
|
||||
|
||||
/// Walk a Java method-chain receiver looking for an inner `method_invocation`
|
||||
/// whose method name matches one of `target_methods` (e.g. `createQuery`,
|
||||
/// `prepareStatement`). Returns the kind of that inner call's arg 0 — used
|
||||
/// to verify the SQL-bearing call up-chain was given a string literal rather
|
||||
/// than a concatenation / method call.
|
||||
///
|
||||
/// Conservative: returns `None` when no matching call is found in the chain.
|
||||
/// Stops drilling into args of an unrelated call, so the chain walk is
|
||||
/// strictly down the receiver spine.
|
||||
pub(super) fn java_chain_arg0_kind_for_method(
|
||||
expr: Node,
|
||||
target_methods: &[&str],
|
||||
code: &[u8],
|
||||
) -> Option<String> {
|
||||
let n = unwrap_parens(expr);
|
||||
if n.kind() == "method_invocation"
|
||||
&& let Some(name_node) = n.child_by_field_name("name")
|
||||
&& let Some(name) = text_of(name_node, code)
|
||||
&& target_methods.iter().any(|m| *m == name)
|
||||
{
|
||||
let args = n.child_by_field_name("arguments")?;
|
||||
let mut cursor = args.walk();
|
||||
let arg0 = args.named_children(&mut cursor).next()?;
|
||||
let arg0 = unwrap_parens(arg0);
|
||||
return Some(arg0.kind().to_string());
|
||||
}
|
||||
// Drill down the receiver spine. Java grammar uses `object` for the
|
||||
// receiver of a `method_invocation`.
|
||||
if n.kind() == "method_invocation"
|
||||
&& let Some(recv) = n.child_by_field_name("object")
|
||||
&& let Some(found) = java_chain_arg0_kind_for_method(recv, target_methods, code)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Walk a Ruby method-chain receiver-side looking for the inner call whose
|
||||
/// method identifier matches one of `target_methods`, then return that
|
||||
/// inner call's [`arg0_kind_and_interpolation`]. Used when the CFG node
|
||||
/// represents a chained expression like `Model.where(...).preload(...).to_a`
|
||||
/// — the outermost call (`to_a`) has no arguments, so the shape suppressor
|
||||
/// must reach down the chain to inspect `where`'s arg 0.
|
||||
///
|
||||
/// Conservative: returns `None` if the chain doesn't contain a matching
|
||||
/// method, so callers fall through to the no-suppression path.
|
||||
pub(super) fn ruby_chain_arg0_for_method(
|
||||
expr: Node,
|
||||
target_methods: &[&str],
|
||||
code: &[u8],
|
||||
) -> Option<(String, bool)> {
|
||||
let n = unwrap_parens(expr);
|
||||
if n.kind() == "call"
|
||||
&& let Some(method) = n.child_by_field_name("method")
|
||||
&& let Some(name) = text_of(method, code)
|
||||
&& target_methods.iter().any(|m| *m == name)
|
||||
{
|
||||
return arg0_kind_and_interpolation(n);
|
||||
}
|
||||
// Recurse into the receiver chain (`call.receiver` → next call up).
|
||||
if n.kind() == "call"
|
||||
&& let Some(recv) = n
|
||||
.child_by_field_name("receiver")
|
||||
.or_else(|| n.child_by_field_name("object"))
|
||||
&& let Some(found) = ruby_chain_arg0_for_method(recv, target_methods, code)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
// Also descend into named children to handle wrapping (assignment RHS,
|
||||
// begin-end blocks, parenthesised expressions, etc.).
|
||||
let mut cursor = n.walk();
|
||||
for c in n.named_children(&mut cursor) {
|
||||
if let Some(found) = ruby_chain_arg0_for_method(c, target_methods, code) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn subtree_has_interpolation(n: Node) -> bool {
|
||||
if n.kind() == "interpolation" || n.kind() == "string_interpolation" {
|
||||
return true;
|
||||
}
|
||||
let mut cursor = n.walk();
|
||||
n.named_children(&mut cursor).any(subtree_has_interpolation)
|
||||
}
|
||||
|
||||
/// For a chained method call (`a.b().c().d()`), walk down the receiver
|
||||
/// chain (`function.object`) and return the innermost call_expression
|
||||
/// alongside its callee text (e.g. `"http.get"`).
|
||||
///
|
||||
/// Returns `None` when:
|
||||
/// * `outer` is not itself a CallFn / CallMethod node, or
|
||||
/// * its `function`/`method` field is not a member-style expression whose
|
||||
/// `object` field is itself a call (i.e. there is no chained receiver).
|
||||
///
|
||||
/// Motivated by CVE-2025-64430 (Parse Server SSRF via
|
||||
/// `http.get(uri, cb).on('error', e => ...)`). Without this, the outer
|
||||
/// `.on(...)` call swallows classification of the inner gated sink.
|
||||
pub(super) fn find_chained_inner_call<'a>(
|
||||
outer: Node<'a>,
|
||||
lang: &str,
|
||||
code: &[u8],
|
||||
) -> Option<(Node<'a>, String)> {
|
||||
if !matches!(lookup(lang, outer.kind()), Kind::CallFn | Kind::CallMethod) {
|
||||
return None;
|
||||
}
|
||||
let function = outer
|
||||
.child_by_field_name("function")
|
||||
.or_else(|| outer.child_by_field_name("method"))?;
|
||||
// The function/method field for a chained call is a member_expression
|
||||
// (JS/TS) or attribute (Python) etc.; its `object` field is the
|
||||
// receiver expression. Only proceed when that receiver is itself a
|
||||
// call.
|
||||
let object = function.child_by_field_name("object")?;
|
||||
if !matches!(lookup(lang, object.kind()), Kind::CallFn | Kind::CallMethod) {
|
||||
return None;
|
||||
}
|
||||
// Recurse: the inner call may itself be chained
|
||||
// (`axios.get(u).then(h).catch(h)` — innermost is `axios.get`).
|
||||
if let Some(inner) = find_chained_inner_call(object, lang, code) {
|
||||
return Some(inner);
|
||||
}
|
||||
// `object` is the innermost call_expression in the chain. Extract
|
||||
// its callee identifier the same way `first_call_ident_with_span`
|
||||
// does for a CallFn (member_expression text → "http.get").
|
||||
let inner_func = object
|
||||
.child_by_field_name("function")
|
||||
.or_else(|| object.child_by_field_name("method"))
|
||||
.or_else(|| object.child_by_field_name("name"))?;
|
||||
// Multi-line dotted member expressions (`http\n .get`) include
|
||||
// formatting whitespace in the source-text slice. The labels map
|
||||
// keys are literal `"http.get"` etc. — strip whitespace so the
|
||||
// chained-call inner-gate rebinding fires for both single-line and
|
||||
// multi-line chain styles. Also strips `\r` for CRLF sources.
|
||||
// Motivated by upstream Parse Server CVE-2025-64430 which uses the
|
||||
// multi-line `http\n .get(uri, ...)\n .on(...)` form.
|
||||
let raw = text_of(inner_func, code)?;
|
||||
let inner_text: String = raw.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
Some((object, inner_text))
|
||||
}
|
||||
|
||||
/// Recursively walk the receiver chain of `outer` (a CallFn / CallMethod
|
||||
/// node) and yield each *named argument* of every inner call along the
|
||||
/// way. Outer's own arguments are NOT included — the caller already
|
||||
/// handles those via the standard `pre_emit_arg_source_nodes` pass over
|
||||
/// `outer.arguments`.
|
||||
///
|
||||
/// For `json.NewDecoder(r.Body).Decode(emoji)`:
|
||||
/// outer = `.Decode(emoji)` — caller iterates `emoji`
|
||||
/// inner = `json.NewDecoder(r.Body)` — yielded arg: `r.Body`
|
||||
///
|
||||
/// We only pull from each inner call's `arguments` field, never from its
|
||||
/// `function`/`method`/receiver expressions. That distinction matters
|
||||
/// because chained source-receivers like `r.URL.Query()` expose a
|
||||
/// member-text path that classifies as a Source — but it's the OUTER
|
||||
/// chain text (`r.URL.Query.Get`) that already classifies, so emitting
|
||||
/// a synth source for the inner-call's own callee would double-count.
|
||||
///
|
||||
/// Used by Go (where chain shapes like `json.NewDecoder(r.Body).Decode`
|
||||
/// hide source-labeled args inside parens between dots, leaving the
|
||||
/// outer callee text un-classifiable). The helper itself is
|
||||
/// language-neutral, but callers should gate per-language until each
|
||||
/// language's regression coverage catches up.
|
||||
pub(super) fn walk_chain_inner_call_args<'a>(outer: Node<'a>, lang: &str, out: &mut Vec<Node<'a>>) {
|
||||
if !matches!(lookup(lang, outer.kind()), Kind::CallFn | Kind::CallMethod) {
|
||||
return;
|
||||
}
|
||||
let function = outer
|
||||
.child_by_field_name("function")
|
||||
.or_else(|| outer.child_by_field_name("method"));
|
||||
let Some(function) = function else { return };
|
||||
let object = function
|
||||
.child_by_field_name("object")
|
||||
.or_else(|| function.child_by_field_name("operand"))
|
||||
.or_else(|| function.child_by_field_name("value"));
|
||||
let Some(inner) = object else { return };
|
||||
if !matches!(lookup(lang, inner.kind()), Kind::CallFn | Kind::CallMethod) {
|
||||
return;
|
||||
}
|
||||
if let Some(args) = inner.child_by_field_name("arguments") {
|
||||
let mut cursor = args.walk();
|
||||
for arg in args.named_children(&mut cursor) {
|
||||
out.push(arg);
|
||||
}
|
||||
}
|
||||
walk_chain_inner_call_args(inner, lang, out);
|
||||
}
|
||||
|
||||
/// Recursively find a call-expression node within an AST subtree (up to
|
||||
/// 4 levels deep). Unlike `find_call_node` which only checks 2 levels,
|
||||
/// this handles `await`-wrapped calls inside declarations.
|
||||
|
|
|
|||
826
src/cfg/mod.rs
826
src/cfg/mod.rs
File diff suppressed because it is too large
Load diff
|
|
@ -1,23 +1,36 @@
|
|||
use super::{
|
||||
AstMeta, Cfg, EdgeKind, NodeInfo, StmtKind, TaintMeta, collect_idents, connect_all,
|
||||
is_anon_fn_name, text_of,
|
||||
AstMeta, Cfg, DTO_CLASSES, EdgeKind, NodeInfo, StmtKind, TaintMeta, collect_idents,
|
||||
connect_all, is_anon_fn_name, text_of,
|
||||
};
|
||||
use crate::labels::{DataLabel, LangAnalysisRules, classify, param_config};
|
||||
use crate::ssa::type_facts::TypeKind;
|
||||
use petgraph::graph::NodeIndex;
|
||||
use smallvec::smallvec;
|
||||
use tree_sitter::Node;
|
||||
|
||||
/// Extract parameter names from a function AST node.
|
||||
///
|
||||
/// Uses the language's `ParamConfig` to find the parameter list field
|
||||
/// and extract identifiers from each parameter child.
|
||||
pub(super) fn extract_param_names<'a>(
|
||||
/// Phase 6.2 — resolve a syntactic class / struct / interface / model
|
||||
/// name against the per-file [`DTO_CLASSES`] map populated at the top
|
||||
/// of `build_cfg`. Returns the [`TypeKind::Dto`] carrying the
|
||||
/// per-field type map when the class is declared in the same file;
|
||||
/// returns `None` otherwise so callers can fall through to the
|
||||
/// pre-Phase-6 behaviour (Object / Unknown).
|
||||
fn lookup_dto_class(class_name: &str) -> Option<TypeKind> {
|
||||
DTO_CLASSES.with(|cell| cell.borrow().get(class_name).cloned().map(TypeKind::Dto))
|
||||
}
|
||||
|
||||
/// Extract parameter names + per-position [`TypeKind`] from a function
|
||||
/// AST node. Each entry's second slot is `Some(TypeKind)` when the
|
||||
/// parameter's decorator, attribute, or static type annotation maps to
|
||||
/// a known kind, and `None` otherwise. Strictly additive — when no
|
||||
/// type info is recoverable, behaviour is identical to the names-only
|
||||
/// path.
|
||||
pub(super) fn extract_param_meta<'a>(
|
||||
func_node: Node<'a>,
|
||||
lang: &str,
|
||||
code: &'a [u8],
|
||||
) -> Vec<String> {
|
||||
) -> Vec<(String, Option<TypeKind>)> {
|
||||
let cfg = param_config(lang);
|
||||
let mut names = Vec::new();
|
||||
let mut out: Vec<(String, Option<TypeKind>)> = Vec::new();
|
||||
// Try the params_field directly on the function node first.
|
||||
// For C/C++, the parameter list is nested inside the declarator
|
||||
// (function_definition > declarator:function_declarator > parameters:parameter_list),
|
||||
|
|
@ -28,13 +41,28 @@ pub(super) fn extract_param_names<'a>(
|
|||
.and_then(|d| d.child_by_field_name(cfg.params_field))
|
||||
});
|
||||
let Some(params) = params else {
|
||||
return names;
|
||||
// Single-param arrow shorthand (`uri => ...` in JS/TS): tree-sitter
|
||||
// exposes the lone identifier under the singular `parameter` field
|
||||
// rather than wrapping it in `formal_parameters`. Without this
|
||||
// fallback the function appears parameterless to the SSA pipeline,
|
||||
// breaking cross-function param_to_sink resolution for any
|
||||
// single-arg arrow helper. Motivated by CVE-2025-64430.
|
||||
if func_node.kind() == "arrow_function" {
|
||||
if let Some(p) = func_node.child_by_field_name("parameter") {
|
||||
if p.kind() == "identifier" {
|
||||
if let Some(name) = text_of(p, code) {
|
||||
out.push((name, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
let mut cursor = params.walk();
|
||||
for child in params.children(&mut cursor) {
|
||||
// Self/this parameter (e.g. Rust's `self_parameter`)
|
||||
if cfg.self_param_kinds.contains(&child.kind()) {
|
||||
names.push("self".into());
|
||||
out.push(("self".into(), None));
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -52,7 +80,8 @@ pub(super) fn extract_param_names<'a>(
|
|||
tmp.into_iter().next()
|
||||
};
|
||||
if let Some(name) = candidate {
|
||||
names.push(name);
|
||||
let ty = classify_param_type(child, lang, code);
|
||||
out.push((name, ty));
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
|
|
@ -63,7 +92,7 @@ pub(super) fn extract_param_names<'a>(
|
|||
&& child.kind() == "identifier"
|
||||
&& let Some(txt) = text_of(child, code)
|
||||
{
|
||||
names.push(txt);
|
||||
out.push((txt, None));
|
||||
found = true;
|
||||
}
|
||||
// Fallback for C/C++: look for nested declarator → identifier
|
||||
|
|
@ -71,7 +100,8 @@ pub(super) fn extract_param_names<'a>(
|
|||
let mut tmp = Vec::new();
|
||||
collect_idents(child, code, &mut tmp);
|
||||
if let Some(last) = tmp.pop() {
|
||||
names.push(last);
|
||||
let ty = classify_param_type(child, lang, code);
|
||||
out.push((last, ty));
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -86,7 +116,8 @@ pub(super) fn extract_param_names<'a>(
|
|||
let mut tmp = Vec::new();
|
||||
collect_idents(child, code, &mut tmp);
|
||||
if let Some(first) = tmp.into_iter().next() {
|
||||
names.push(first);
|
||||
let ty = classify_param_type(child, lang, code);
|
||||
out.push((first, ty));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
|
|
@ -96,11 +127,11 @@ pub(super) fn extract_param_names<'a>(
|
|||
// where the child is an `identifier` node, not a `parameter` wrapper.
|
||||
if child.kind() == "identifier" {
|
||||
if let Some(txt) = text_of(child, code) {
|
||||
names.push(txt);
|
||||
out.push((txt, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
names
|
||||
out
|
||||
}
|
||||
|
||||
/// Walk up from a function definition node and build a container path.
|
||||
|
|
@ -392,6 +423,369 @@ pub(super) fn inject_framework_param_sources(
|
|||
preds
|
||||
}
|
||||
|
||||
/// Classify a parameter AST node to a [`TypeKind`] using per-language
|
||||
/// decorator / attribute / annotation matchers. Strictly additive: when
|
||||
/// no recognised pattern matches, returns `None` and the engine
|
||||
/// behaves exactly as before.
|
||||
///
|
||||
/// Recognised patterns (Phase 2):
|
||||
/// * Java (Spring) — `@PathVariable`/`@RequestParam Long X` →
|
||||
/// [`TypeKind::Int`]; `@RequestBody T` → object (no kind today).
|
||||
/// * TypeScript (NestJS) — `@Param('id') id: number` →
|
||||
/// [`TypeKind::Int`]; `@Body() dto: T` / `@Query('q') q: string`.
|
||||
/// * Rust (Axum / Rocket / Actix) — `Path<i64>` / `Path<u32>` /
|
||||
/// `web::Path<i64>` → [`TypeKind::Int`]; `Path<String>` →
|
||||
/// [`TypeKind::String`].
|
||||
/// * Python (FastAPI) — `def h(x: int)` → [`TypeKind::Int`];
|
||||
/// `Annotated[int, Path()]` → [`TypeKind::Int`].
|
||||
pub(super) fn classify_param_type<'a>(
|
||||
param: Node<'a>,
|
||||
lang: &str,
|
||||
code: &'a [u8],
|
||||
) -> Option<TypeKind> {
|
||||
match lang {
|
||||
"java" => classify_param_type_java(param, code),
|
||||
"typescript" | "ts" => classify_param_type_ts(param, code),
|
||||
"javascript" | "js" => classify_param_type_ts(param, code),
|
||||
"rust" | "rs" => classify_param_type_rust(param, code),
|
||||
"python" | "py" => classify_param_type_python(param, code),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Java (Spring) — recognise typed-extractor parameters via the
|
||||
/// surrounding annotation. Per Hard Rule 3, plain `Long X` without a
|
||||
/// known framework annotation is **not** treated as a typed extractor —
|
||||
/// the parameter could be a regular function argument that the
|
||||
/// framework never validates. Recognised annotations:
|
||||
/// `@PathVariable`, `@RequestParam`, `@RequestBody`, `@RequestHeader`,
|
||||
/// `@CookieValue`, `@MatrixVariable`. When an annotation matches, the
|
||||
/// parameter's static type is consulted via [`java_type_to_kind`].
|
||||
fn classify_param_type_java<'a>(param: Node<'a>, code: &'a [u8]) -> Option<TypeKind> {
|
||||
if param.kind() != "formal_parameter" && param.kind() != "spread_parameter" {
|
||||
return None;
|
||||
}
|
||||
if !has_java_framework_annotation(param, code) {
|
||||
return None;
|
||||
}
|
||||
let type_node = param.child_by_field_name("type")?;
|
||||
let type_text = text_of(type_node, code)?;
|
||||
if let Some(k) = java_type_to_kind(&type_text) {
|
||||
return Some(k);
|
||||
}
|
||||
// Phase 6.2: when the static type is a class name we don't classify
|
||||
// as a primitive (e.g. `@RequestBody CreateUser dto`), look up the
|
||||
// class in the same-file DTO map. Strip any generics for the
|
||||
// leading type so `Foo<Bar>` still resolves on `Foo`.
|
||||
let bare = type_text.split('<').next().unwrap_or(&type_text).trim();
|
||||
let last = bare.rsplit('.').next().unwrap_or(bare);
|
||||
lookup_dto_class(last)
|
||||
}
|
||||
|
||||
/// Walk the parameter's modifiers (annotations) and check if any of
|
||||
/// them are a recognised Spring web binding annotation. Spring's
|
||||
/// annotation grammar exposes annotations as `marker_annotation` /
|
||||
/// `annotation` siblings inside the formal_parameter's `modifiers`
|
||||
/// child.
|
||||
fn has_java_framework_annotation(param: Node<'_>, code: &[u8]) -> bool {
|
||||
const KNOWN: &[&str] = &[
|
||||
"@PathVariable",
|
||||
"@RequestParam",
|
||||
"@RequestBody",
|
||||
"@RequestHeader",
|
||||
"@CookieValue",
|
||||
"@MatrixVariable",
|
||||
"@ModelAttribute",
|
||||
];
|
||||
// Inspect modifiers child first.
|
||||
if let Some(modifiers) = param.child_by_field_name("modifiers") {
|
||||
if let Some(text) = text_of(modifiers, code) {
|
||||
for k in KNOWN {
|
||||
if text.contains(k) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fall back to scanning all named children: tree-sitter-java emits
|
||||
// annotations as direct children of formal_parameter in some grammar
|
||||
// versions.
|
||||
let mut cursor = param.walk();
|
||||
for child in param.children(&mut cursor) {
|
||||
let kind = child.kind();
|
||||
if matches!(kind, "marker_annotation" | "annotation" | "modifiers")
|
||||
&& let Some(text) = text_of(child, code)
|
||||
{
|
||||
for k in KNOWN {
|
||||
if text.contains(k) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Map a Java type-text fragment to a [`TypeKind`]. Public to the
|
||||
/// `cfg` module so the Phase 6 DTO collector can reuse the same
|
||||
/// classifier for class fields.
|
||||
pub(super) fn java_type_to_kind(t: &str) -> Option<TypeKind> {
|
||||
let bare = t.trim().trim_start_matches('@').trim();
|
||||
// Drop generic args for the leading type.
|
||||
let bare = bare.split('<').next().unwrap_or(bare).trim();
|
||||
let last = bare.rsplit('.').next().unwrap_or(bare);
|
||||
match last {
|
||||
"int" | "long" | "short" | "byte" | "Integer" | "Long" | "Short" | "Byte"
|
||||
| "BigInteger" => Some(TypeKind::Int),
|
||||
"boolean" | "Boolean" => Some(TypeKind::Bool),
|
||||
"double" | "float" | "Double" | "Float" | "BigDecimal" => Some(TypeKind::Int),
|
||||
"String" | "CharSequence" => Some(TypeKind::String),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a TypeScript type-text fragment (already stripped of leading
|
||||
/// `:` / whitespace) to a primitive [`TypeKind`]. Used by both the
|
||||
/// per-parameter classifier and the Phase 6 DTO collector.
|
||||
pub(super) fn ts_type_to_kind(t: &str) -> Option<TypeKind> {
|
||||
let head = t.split('<').next().unwrap_or(t).trim();
|
||||
match head {
|
||||
"number" | "bigint" => Some(TypeKind::Int),
|
||||
"boolean" => Some(TypeKind::Bool),
|
||||
"string" => Some(TypeKind::String),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// TypeScript (NestJS) — recognise typed-extractor parameters via a
|
||||
/// known NestJS decorator (`@Param`, `@Body`, `@Query`, `@Headers`,
|
||||
/// `@Req`, `@Res`). Per Hard Rule 3, a bare `function h(id: number)`
|
||||
/// is not a framework extractor — without a NestJS decorator no
|
||||
/// runtime gate is implied. Pipe coercions (`ParseIntPipe` /
|
||||
/// `ParseBoolPipe`) override the static type.
|
||||
fn classify_param_type_ts<'a>(param: Node<'a>, code: &'a [u8]) -> Option<TypeKind> {
|
||||
if !has_ts_decorator_argument(
|
||||
param,
|
||||
code,
|
||||
&[
|
||||
"@Param",
|
||||
"@Body",
|
||||
"@Query",
|
||||
"@Headers",
|
||||
"@Header",
|
||||
"@Cookie",
|
||||
"@UploadedFile",
|
||||
],
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
// Decorator-based pipe coercion overrides the static type.
|
||||
if has_ts_decorator_argument(param, code, &["ParseIntPipe"]) {
|
||||
return Some(TypeKind::Int);
|
||||
}
|
||||
if has_ts_decorator_argument(param, code, &["ParseBoolPipe"]) {
|
||||
return Some(TypeKind::Bool);
|
||||
}
|
||||
let t = param
|
||||
.child_by_field_name("type")
|
||||
.and_then(|n| inner_ts_type_text(n, code))?;
|
||||
let stripped = t.trim().trim_start_matches(':').trim();
|
||||
if let Some(k) = ts_type_to_kind(stripped) {
|
||||
return Some(k);
|
||||
}
|
||||
// Phase 6.2: NestJS `@Body() dto: CreateUser` — when the static
|
||||
// type is a class / interface name declared in the same file,
|
||||
// resolve via the DTO map. Generic args dropped for the leading
|
||||
// type so `Foo<Bar>` matches on `Foo`.
|
||||
let head = stripped.split('<').next().unwrap_or(stripped).trim();
|
||||
lookup_dto_class(head)
|
||||
}
|
||||
|
||||
fn inner_ts_type_text<'a>(type_anno: Node<'a>, code: &'a [u8]) -> Option<String> {
|
||||
// type_annotation node text is `: T` — unwrap to T.
|
||||
if let Some(child) = type_anno.named_child(0) {
|
||||
return text_of(child, code);
|
||||
}
|
||||
text_of(type_anno, code)
|
||||
}
|
||||
|
||||
/// Walk through a TypeScript / NestJS parameter's decorators looking
|
||||
/// for an identifier matching `wanted` anywhere in the decorator
|
||||
/// argument list (e.g. `@Query('id', ParseIntPipe)`). Conservative
|
||||
/// substring match; all decorator nodes precede the parameter.
|
||||
fn has_ts_decorator_argument(param: Node<'_>, code: &[u8], wanted: &[&str]) -> bool {
|
||||
let mut cur = param.prev_sibling();
|
||||
while let Some(node) = cur {
|
||||
if node.kind() == "decorator" {
|
||||
if let Some(text) = text_of(node, code) {
|
||||
for w in wanted {
|
||||
if text.contains(w) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Some grammars attach decorators as children of the param.
|
||||
cur = node.prev_sibling();
|
||||
}
|
||||
let mut cursor = param.walk();
|
||||
for child in param.children(&mut cursor) {
|
||||
if child.kind() == "decorator" {
|
||||
if let Some(text) = text_of(child, code) {
|
||||
for w in wanted {
|
||||
if text.contains(w) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Rust (Axum / Rocket / Actix) — read the parameter's type text and
|
||||
/// look for `Path<i64>` / `Json<T>` / `Form<T>` / `Query<T>` shapes.
|
||||
/// Per Hard Rule 3, bare primitives (`fn h(id: i64)` without an
|
||||
/// extractor wrapper) are **not** treated as typed extractors — only
|
||||
/// framework-wrapped types qualify.
|
||||
fn classify_param_type_rust<'a>(param: Node<'a>, code: &'a [u8]) -> Option<TypeKind> {
|
||||
if param.kind() != "parameter" {
|
||||
return None;
|
||||
}
|
||||
let type_node = param.child_by_field_name("type")?;
|
||||
let type_text = text_of(type_node, code)?;
|
||||
rust_type_to_kind(&type_text)
|
||||
}
|
||||
|
||||
fn rust_type_to_kind(t: &str) -> Option<TypeKind> {
|
||||
let stripped = t.trim();
|
||||
// Reject reference / mutability noise so `&Path<i64>` still matches
|
||||
// the wrapper detection below.
|
||||
let stripped = stripped
|
||||
.trim_start_matches('&')
|
||||
.trim_start_matches('&')
|
||||
.trim_start_matches("mut ")
|
||||
.trim();
|
||||
// Only framework wrapper extractors qualify — bare primitives like
|
||||
// `i64` could be regular function parameters with no framework
|
||||
// validation gate.
|
||||
for wrap in [
|
||||
"Path",
|
||||
"Json",
|
||||
"Form",
|
||||
"Query",
|
||||
"web::Path",
|
||||
"web::Json",
|
||||
"web::Form",
|
||||
"web::Query",
|
||||
"rocket::http::uri::Origin",
|
||||
] {
|
||||
let prefix = format!("{wrap}<");
|
||||
if let Some(rest) = stripped.strip_prefix(&prefix) {
|
||||
if let Some(inner) = rest.strip_suffix('>') {
|
||||
let inner = inner.trim();
|
||||
// Tuple extractor `Path<(i64, String)>` — first element wins.
|
||||
if inner.starts_with('(') {
|
||||
let inside = inner.trim_start_matches('(').trim_end_matches(')');
|
||||
let first = inside.split(',').next().unwrap_or("").trim();
|
||||
if let Some(k) = rust_primitive_to_kind(first) {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
// Bare path generic `Path<i64>`.
|
||||
if let Some(k) = rust_primitive_to_kind(inner) {
|
||||
return Some(k);
|
||||
}
|
||||
// Phase 6.2: `Json<T>` / `Form<T>` / `Query<T>` /
|
||||
// `Path<T>` with a same-file struct type — resolve via
|
||||
// the DTO map. Strip nested generics so `Json<Foo<i64>>`
|
||||
// matches on `Foo`.
|
||||
let head = inner.split('<').next().unwrap_or(inner).trim();
|
||||
if let Some(k) = lookup_dto_class(head) {
|
||||
return Some(k);
|
||||
}
|
||||
// Custom struct outside the same file — leave None
|
||||
// (cross-file resolution is Phase 6.4).
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Map a Rust primitive / `String` / `&str` to a [`TypeKind`]. Public
|
||||
/// to the `cfg` module so the Phase 6 DTO collector can reuse it for
|
||||
/// `struct` field types.
|
||||
pub(super) fn rust_primitive_to_kind(t: &str) -> Option<TypeKind> {
|
||||
let t = t.trim();
|
||||
match t {
|
||||
"i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" | "u128"
|
||||
| "usize" => Some(TypeKind::Int),
|
||||
"f32" | "f64" => Some(TypeKind::Int),
|
||||
"bool" => Some(TypeKind::Bool),
|
||||
"String" | "&str" | "str" => Some(TypeKind::String),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Python (FastAPI) — recognise typed-extractor parameters via the
|
||||
/// `Annotated[X, Path()/Query()/Body()/Header()/Cookie()]` shape. Per
|
||||
/// Hard Rule 3, a bare `def h(id: int)` is **not** a framework
|
||||
/// extractor — the function may be a plain Python function and the
|
||||
/// type annotation provides no runtime gate.
|
||||
fn classify_param_type_python<'a>(param: Node<'a>, code: &'a [u8]) -> Option<TypeKind> {
|
||||
let type_node = param.child_by_field_name("type")?;
|
||||
let type_text = text_of(type_node, code)?;
|
||||
python_type_to_kind(&type_text)
|
||||
}
|
||||
|
||||
fn python_type_to_kind(t: &str) -> Option<TypeKind> {
|
||||
let stripped = t.trim();
|
||||
// `Annotated[int, Path()]` — only matches when one of the generic
|
||||
// args names a recognised FastAPI binding marker. Otherwise no
|
||||
// framework gate is implied.
|
||||
if let Some(inner) = stripped
|
||||
.strip_prefix("Annotated[")
|
||||
.or_else(|| stripped.strip_prefix("typing.Annotated["))
|
||||
{
|
||||
let inside = inner.trim_end_matches(']');
|
||||
if !contains_fastapi_marker(inside) {
|
||||
return None;
|
||||
}
|
||||
let first = inside.split(',').next().unwrap_or("").trim();
|
||||
if let Some(k) = python_primitive_to_kind(first) {
|
||||
return Some(k);
|
||||
}
|
||||
// Phase 6.2: `Annotated[CreateUser, Body()]` with a same-file
|
||||
// Pydantic model — resolve via the DTO map. Generic args are
|
||||
// dropped via the same head-split as `python_primitive_to_kind`.
|
||||
let head = first.split('[').next().unwrap_or(first).trim();
|
||||
return lookup_dto_class(head);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn contains_fastapi_marker(s: &str) -> bool {
|
||||
const MARKERS: &[&str] = &[
|
||||
"Path(", "Query(", "Body(", "Header(", "Cookie(", "Form(", "File(",
|
||||
];
|
||||
MARKERS.iter().any(|m| s.contains(m))
|
||||
}
|
||||
|
||||
/// Map a Python type expression to a primitive [`TypeKind`]. Used by
|
||||
/// both the per-parameter classifier and the Phase 6 Pydantic-model
|
||||
/// field collector.
|
||||
pub(super) fn python_primitive_to_kind(t: &str) -> Option<TypeKind> {
|
||||
let head = t.trim().split('[').next().unwrap_or(t).trim();
|
||||
match head {
|
||||
"int" => Some(TypeKind::Int),
|
||||
"bool" => Some(TypeKind::Bool),
|
||||
"float" => Some(TypeKind::Int),
|
||||
"str" => Some(TypeKind::String),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a callee name matches any configured terminator.
|
||||
pub(super) fn is_configured_terminator(
|
||||
callee: &str,
|
||||
|
|
@ -407,3 +801,157 @@ pub(super) fn is_configured_terminator(
|
|||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod typed_extractor_tests {
|
||||
use super::{
|
||||
contains_fastapi_marker, java_type_to_kind, python_primitive_to_kind, python_type_to_kind,
|
||||
rust_primitive_to_kind, rust_type_to_kind,
|
||||
};
|
||||
use crate::ssa::type_facts::TypeKind;
|
||||
|
||||
// ── Java (Spring) ────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn java_long_path_variable_maps_to_int() {
|
||||
assert_eq!(java_type_to_kind("Long"), Some(TypeKind::Int));
|
||||
assert_eq!(java_type_to_kind("long"), Some(TypeKind::Int));
|
||||
assert_eq!(java_type_to_kind("Integer"), Some(TypeKind::Int));
|
||||
assert_eq!(java_type_to_kind("int"), Some(TypeKind::Int));
|
||||
assert_eq!(java_type_to_kind("Short"), Some(TypeKind::Int));
|
||||
assert_eq!(java_type_to_kind("BigInteger"), Some(TypeKind::Int));
|
||||
assert_eq!(
|
||||
java_type_to_kind("java.lang.Long"),
|
||||
Some(TypeKind::Int),
|
||||
"fully-qualified Long must still map to Int"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_string_request_param_maps_to_string() {
|
||||
assert_eq!(java_type_to_kind("String"), Some(TypeKind::String));
|
||||
assert_eq!(java_type_to_kind("CharSequence"), Some(TypeKind::String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_boolean_maps_to_bool() {
|
||||
assert_eq!(java_type_to_kind("Boolean"), Some(TypeKind::Bool));
|
||||
assert_eq!(java_type_to_kind("boolean"), Some(TypeKind::Bool));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_request_body_dto_returns_none_until_phase_six() {
|
||||
// @RequestBody CreateUserDto dto — no kind today; Phase 6 will
|
||||
// return DtoObject(name) once cross-file class resolution lands.
|
||||
assert_eq!(java_type_to_kind("CreateUserDto"), None);
|
||||
assert_eq!(java_type_to_kind("List<String>"), None);
|
||||
}
|
||||
|
||||
// ── Rust (Axum / Rocket / Actix) ─────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn rust_path_int_extractor_maps_to_int() {
|
||||
assert_eq!(rust_type_to_kind("Path<i64>"), Some(TypeKind::Int));
|
||||
assert_eq!(rust_type_to_kind("Path<u32>"), Some(TypeKind::Int));
|
||||
assert_eq!(rust_type_to_kind("Path<usize>"), Some(TypeKind::Int));
|
||||
assert_eq!(rust_type_to_kind("Path<i32>"), Some(TypeKind::Int));
|
||||
assert_eq!(rust_type_to_kind("web::Path<i64>"), Some(TypeKind::Int));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_path_tuple_first_element_wins() {
|
||||
// Path<(i64, String)> — first slot is the int extractor that
|
||||
// matters for sink suppression.
|
||||
assert_eq!(
|
||||
rust_type_to_kind("Path<(i64, String)>"),
|
||||
Some(TypeKind::Int)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_path_string_maps_to_string() {
|
||||
assert_eq!(rust_type_to_kind("Path<String>"), Some(TypeKind::String));
|
||||
assert_eq!(rust_type_to_kind("Path<&str>"), Some(TypeKind::String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_json_dto_returns_none_until_phase_six() {
|
||||
// Json<T> / Form<T> / Query<T> with a custom struct type — no
|
||||
// primitive resolution available; Phase 6 lifts to DTO.
|
||||
assert_eq!(rust_type_to_kind("Json<CreateUserDto>"), None);
|
||||
assert_eq!(rust_type_to_kind("Form<CreateUserDto>"), None);
|
||||
assert_eq!(rust_type_to_kind("Query<Filters>"), None);
|
||||
}
|
||||
|
||||
/// Per Hard Rule 3, bare primitives (`fn h(id: i64)`) are NOT
|
||||
/// framework extractors — only wrapper types (`Path<i64>` etc.)
|
||||
/// imply a framework runtime gate. Bare i64 must return None.
|
||||
#[test]
|
||||
fn rust_bare_primitives_are_not_framework_extractors() {
|
||||
assert_eq!(rust_type_to_kind("i64"), None);
|
||||
assert_eq!(rust_type_to_kind("u32"), None);
|
||||
assert_eq!(rust_type_to_kind("bool"), None);
|
||||
assert_eq!(rust_type_to_kind("String"), None);
|
||||
// `rust_primitive_to_kind` (used for tuple inner / wrapper inner)
|
||||
// remains a separate primitive-only mapping.
|
||||
assert_eq!(rust_primitive_to_kind("i64"), Some(TypeKind::Int));
|
||||
assert_eq!(rust_primitive_to_kind("bool"), Some(TypeKind::Bool));
|
||||
}
|
||||
|
||||
// ── Python (FastAPI) ─────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn python_bare_primitives_are_not_framework_extractors() {
|
||||
// Per Hard Rule 3: bare `def h(id: int)` is NOT a typed
|
||||
// extractor — without an `Annotated[..., Path()/Query()/Body()]`
|
||||
// wrapper, no FastAPI gate is implied.
|
||||
assert_eq!(python_type_to_kind("int"), None);
|
||||
assert_eq!(python_type_to_kind("float"), None);
|
||||
assert_eq!(python_type_to_kind("bool"), None);
|
||||
assert_eq!(python_type_to_kind("str"), None);
|
||||
// The inner primitive resolver is unchanged.
|
||||
assert_eq!(python_primitive_to_kind("int"), Some(TypeKind::Int));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_annotated_with_fastapi_marker_qualifies() {
|
||||
assert_eq!(
|
||||
python_type_to_kind("Annotated[int, Path()]"),
|
||||
Some(TypeKind::Int)
|
||||
);
|
||||
assert_eq!(
|
||||
python_type_to_kind("typing.Annotated[int, Path()]"),
|
||||
Some(TypeKind::Int)
|
||||
);
|
||||
assert_eq!(
|
||||
python_type_to_kind("Annotated[str, Query(max_length=50)]"),
|
||||
Some(TypeKind::String)
|
||||
);
|
||||
assert_eq!(
|
||||
python_type_to_kind("Annotated[bool, Body()]"),
|
||||
Some(TypeKind::Bool)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_annotated_without_marker_returns_none() {
|
||||
// Annotated without a FastAPI binding marker is a generic
|
||||
// type-system tag — not a framework extractor.
|
||||
assert_eq!(python_type_to_kind("Annotated[int, str]"), None);
|
||||
assert_eq!(python_type_to_kind("Annotated[int, MyMeta]"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_pydantic_model_returns_none_until_phase_six() {
|
||||
assert_eq!(python_type_to_kind("CreateUser"), None);
|
||||
assert_eq!(python_type_to_kind("BaseModel"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fastapi_marker_detection() {
|
||||
assert!(contains_fastapi_marker("int, Path()"));
|
||||
assert!(contains_fastapi_marker("str, Query(max_length=5)"));
|
||||
assert!(contains_fastapi_marker("bytes, File()"));
|
||||
assert!(!contains_fastapi_marker("int, str"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue