use tree_sitter::Node;
use sephera_core::types::{ImportKind, ImportStatement};
use sephera_core::plugins::{line_of, node_text};
pub fn extract_from_node(
source: &[u8],
node: &Node<'_>,
) -> Option<Vec<ImportStatement>> {
match node.kind() {
"mod_item" => extract_mod(source, node),
"use_declaration" => extract_use(source, node),
_ => None,
}
}
fn extract_mod(source: &[u8], node: &Node<'_>) -> Option<Vec<ImportStatement>> {
if node.child_by_field_name("body").is_some() {
return None;
}
if has_path_attribute(source, node) {
return None;
}
let name = node.child_by_field_name("name")?;
let module_name = node_text(source, &name);
if module_name.is_empty() {
return None;
}
Some(vec![
ImportStatement::new(
format!("self::{module_name}"),
line_of(node)?,
)
.with_kind(ImportKind::ModuleDeclaration),
])
}
fn has_path_attribute(source: &[u8], node: &Node<'_>) -> bool {
let mut current = node.prev_sibling();
while let Some(sibling) = current {
match sibling.kind() {
"attribute_item" => {
let text = node_text(source, &sibling);
if text.contains("path") && text.contains('=') {
return true;
}
}
_ => return false,
}
current = sibling.prev_sibling();
}
false
}
fn extract_use(source: &[u8], node: &Node<'_>) -> Option<Vec<ImportStatement>> {
let line = line_of(node)?;
let argument = node.child_by_field_name("argument")?;
let mut paths = Vec::new();
collect_use_paths(source, &argument, None, line, &mut paths);
Some(paths)
}
fn collect_use_paths(
source: &[u8],
node: &Node<'_>,
prefix: Option<&str>,
line: u64,
out: &mut Vec<ImportStatement>,
) {
match node.kind() {
"use_list" => {
for child in node.named_children(&mut node.walk()) {
collect_use_paths(source, &child, prefix, line, out);
}
}
"scoped_use_list" => {
let Some(path) = node.child_by_field_name("path") else {
return;
};
let Some(list) = node.child_by_field_name("list") else {
return;
};
let base = join_use_path(prefix, &node_text(source, &path));
collect_use_paths(source, &list, Some(&base), line, out);
}
"use_as_clause" => {
if let Some(path) = node.child_by_field_name("path") {
push_use_path(
source,
&path,
prefix,
ImportKind::TypeAlias,
line,
out,
);
}
}
"use_wildcard" => {
if let Some(path) = node.named_child(0) {
push_use_path(
source,
&path,
prefix,
ImportKind::Namespace,
line,
out,
);
}
}
"use_declaration" => {
if let Some(argument) = node.child_by_field_name("argument") {
collect_use_paths(source, &argument, prefix, line, out);
}
}
_ => {
push_use_path(
source,
node,
prefix,
ImportKind::Dependency,
line,
out,
);
}
}
}
fn push_use_path(
source: &[u8],
node: &Node<'_>,
prefix: Option<&str>,
kind: ImportKind,
line: u64,
out: &mut Vec<ImportStatement>,
) {
let text = node_text(source, node);
if text.is_empty() {
return;
}
out.push(
ImportStatement::new(join_use_path(prefix, &text), line)
.with_kind(kind),
);
}
fn join_use_path(prefix: Option<&str>, leaf: &str) -> String {
match prefix {
Some(base) if !base.is_empty() => format!("{base}::{leaf}"),
_ => leaf.to_owned(),
}
}
pub fn opens_inline_module(node: &Node<'_>) -> bool {
node.kind() == "mod_item" && node.child_by_field_name("body").is_some()
}
pub fn is_cfg_gated(source: &[u8], node: &Node<'_>) -> bool {
let Some(previous) = node.prev_sibling() else {
return false;
};
if previous.kind() != "attribute_item"
|| previous.end_position().row + 1 != node.start_position().row
{
return false;
}
previous.named_child(0).is_some_and(|attribute| {
node_text(source, &attribute).starts_with("cfg")
})
}
#[cfg(test)]
fn walk(source: &[u8]) -> Vec<ImportStatement> {
use sephera_compression::{SupportedLanguage, with_parser};
use sephera_core::plugins::imports_found_by;
with_parser(SupportedLanguage::Rust, source.len(), |parser| {
Ok(imports_found_by(source, parser, &super::RustPlugin))
})
.expect("a parser exists")
}
#[cfg(test)]
mod tests {
use super::*;
fn paths(source: &[u8]) -> Vec<String> {
walk(source).into_iter().map(|s| s.raw_path).collect()
}
#[test]
fn a_simple_use_names_its_path() {
assert_eq!(paths(b"use std::io;\n"), vec!["std::io".to_owned()]);
}
#[test]
fn a_crate_use_names_its_path() {
assert_eq!(
paths(b"use crate::core::graph;\n"),
vec!["crate::core::graph".to_owned()]
);
}
#[test]
fn a_super_use_names_its_path() {
assert_eq!(
paths(b"use super::types::Token;\n"),
vec!["super::types::Token".to_owned()]
);
}
#[test]
fn several_uses_are_all_reported() {
assert_eq!(
paths(b"use std::io;\nuse std::fs;\n\nfn main() {}\n"),
vec!["std::io".to_owned(), "std::fs".to_owned()]
);
}
#[test]
fn a_grouped_use_yields_one_path_per_name() {
assert_eq!(
paths(b"use std::collections::{HashMap, BTreeMap};\n"),
vec![
"std::collections::HashMap".to_owned(),
"std::collections::BTreeMap".to_owned(),
]
);
}
#[test]
fn a_nested_group_yields_full_paths_not_bare_identifiers() {
let found = paths(
b"use self::{\n datasets::{AVAILABLE, resolve_specs},\n writer::generate,\n};\n",
);
assert_eq!(
found,
vec![
"self::datasets::AVAILABLE",
"self::datasets::resolve_specs",
"self::writer::generate",
]
);
assert!(
!found
.iter()
.any(|path| path.contains('{') || path.contains('}')),
"no brace may survive into a path: {found:?}"
);
}
#[test]
fn a_use_alias_drops_the_alias_from_the_path() {
let found = walk(b"use crate::alias::Thing as Other;\n");
assert_eq!(found[0].raw_path, "crate::alias::Thing");
assert_eq!(found[0].kind, ImportKind::TypeAlias);
}
#[test]
fn a_namespace_use_is_recorded() {
let found = walk(b"use crate::foo::*;\n");
assert_eq!(found[0].raw_path, "crate::foo");
assert_eq!(found[0].kind, ImportKind::Namespace);
}
#[test]
fn an_ordinary_use_is_a_plain_dependency() {
let found = walk(b"use crate::core::graph;\n");
assert_eq!(found[0].kind, ImportKind::Dependency);
assert!(found[0].kind.is_dependency());
}
#[test]
fn a_mod_declaration_is_marked_as_structural() {
let found = walk(b"mod types;\n");
assert_eq!(found[0].raw_path, "self::types");
assert_eq!(found[0].kind, ImportKind::ModuleDeclaration);
assert!(
!found[0].kind.is_dependency(),
"a declaration is structural, not a dependency"
);
}
#[test]
fn a_path_attribute_module_is_skipped_because_the_name_no_longer_holds() {
let found = walk(
b"#[path = \"generated_language_data.rs\"]\nmod generated_language_data;\n",
);
assert!(
found.is_empty(),
"`#[path]` renames the file, so the declared name is not a path"
);
}
#[test]
fn a_cfg_attribute_does_not_hide_a_module_declaration() {
let found = walk(b"#[cfg(test)]\nmod gated;\n");
assert_eq!(found.len(), 1);
assert_eq!(found[0].kind, ImportKind::ModuleDeclaration);
}
#[test]
fn an_inline_module_itself_produces_no_declaration() {
let found = walk(b"mod tests {\n use super::Cli;\n}\n");
assert!(
found.iter().all(
|statement| statement.kind != ImportKind::ModuleDeclaration
),
"an inline module must not emit a declaration: {found:?}"
);
}
#[test]
fn a_declaration_outside_an_inline_module_has_no_depth() {
assert_eq!(walk(b"mod types;\n")[0].module_depth, 0);
}
#[test]
fn super_inside_an_inline_module_lands_back_on_the_file() {
let found =
walk(b"pub struct Cli;\n\nmod tests {\n use super::Cli;\n}\n");
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].module_depth, 1, "one inline module deep");
}
#[test]
fn module_depth_accumulates_through_nested_inline_modules() {
let found = walk(
b"pub struct Cli;\n\nmod tests {\n mod nested {\n use super::Cli;\n }\n}\n",
);
assert_eq!(found[0].module_depth, 2);
}
#[test]
fn a_cfg_attribute_marks_the_reference_it_gates() {
let gated = walk(b"#[cfg(feature = \"form\")]\npub use crate::Form;\n");
assert!(gated[0].cfg_gated, "the feature gate must be recorded");
let plain = walk(b"pub use crate::Form;\n");
assert!(!plain[0].cfg_gated, "an ungated use must not be marked");
}
#[test]
fn a_cfg_attribute_on_a_different_line_does_not_gate() {
let found = walk(b"#[cfg(test)]\n\npub use crate::Form;\n");
assert!(!found[0].cfg_gated);
}
}