use tree_sitter::Node;
use sephera_core::types::ImportStatement;
use sephera_core::plugins::{line_of, node_text};
pub fn extract_from_node(
source: &[u8],
node: &Node<'_>,
) -> Option<Vec<ImportStatement>> {
if node.kind() != "preproc_include" {
return None;
}
let line = line_of(node)?;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
let raw = node_text(source, &child);
match child.kind() {
"string_literal" => {
let path = raw.trim_matches('"');
if !path.is_empty() {
return Some(vec![ImportStatement::new(path, line)]);
}
}
"system_lib_string" => {
let path = raw.trim_start_matches('<').trim_end_matches('>');
if !path.is_empty() {
return Some(vec![ImportStatement::new(
format!("<{path}>"),
line,
)]);
}
}
_ => {}
}
}
None
}
#[cfg(test)]
mod tests {
use sephera_compression::{SupportedLanguage, with_parser};
use sephera_core::plugins::imports_found_by;
fn paths(source: &[u8], language: SupportedLanguage) -> Vec<String> {
with_parser(language, source.len(), |parser| {
Ok(imports_found_by(
source,
parser,
&crate::CCppPlugin { language },
))
})
.expect("a parser exists")
.into_iter()
.map(|s| s.raw_path)
.collect()
}
#[test]
fn a_quoted_include_names_its_path_without_quotes() {
let found = paths(b"#include \"myheader.h\"\n", SupportedLanguage::C);
assert_eq!(found, vec!["myheader.h".to_owned()]);
}
#[test]
fn an_angle_include_keeps_its_brackets() {
let found = paths(b"#include <stdio.h>\n", SupportedLanguage::C);
assert_eq!(found, vec!["<stdio.h>".to_owned()]);
}
#[test]
fn both_forms_are_read_from_one_file() {
let found = paths(
b"#include <iostream>\n#include \"utils.h\"\n",
SupportedLanguage::Cpp,
);
assert_eq!(found, vec!["<iostream>".to_owned(), "utils.h".to_owned()]);
}
#[test]
fn a_macro_include_names_nothing() {
let found = paths(b"#include MISSING_MACRO\n", SupportedLanguage::C);
assert!(found.is_empty(), "got {found:?}");
}
#[test]
fn a_file_with_no_includes_reports_none() {
assert_eq!(
paths(b"int main(void) { return 0; }\n", SupportedLanguage::C),
Vec::<String>::new()
);
}
}