gather_all_code_from_crates/
extract_items_from_ast.rs

1crate::ix!();
2
3/// Extracts items from the AST node, returning a list of `ItemInfo`.
4pub fn extract_items_from_ast(syntax: &SyntaxNode, remove_doc_comments: bool) -> Vec<ItemInfo> {
5    let mut results = Vec::new();
6
7    for node in syntax.descendants() {
8        if let Some(fn_def) = ast::Fn::cast(node.clone()) {
9            results.push(parse_function_item(fn_def, remove_doc_comments));
10        } else if let Some(strct) = ast::Struct::cast(node.clone()) {
11            results.push(parse_struct_item(strct, remove_doc_comments));
12        } else if let Some(en) = ast::Enum::cast(node.clone()) {
13            results.push(parse_enum_item(en, remove_doc_comments));
14        } else if let Some(ta) = ast::TypeAlias::cast(node.clone()) {
15            results.push(parse_type_alias_item(ta, remove_doc_comments));
16        } else if let Some(imp) = ast::Impl::cast(node.clone()) {
17            results.push(parse_impl_block_item(imp, remove_doc_comments));
18        }
19    }
20
21    deduplicate_items(results)
22}
23
24#[cfg(test)]
25mod extract_items_from_ast_tests {
26    use super::*;
27
28
29    #[test]
30    fn test_extract_items_from_ast() {
31        let code = r#"
32#[derive(Debug)]
33struct S {
34    field: i32,
35}
36
37#[test]
38fn f() {}
39
40impl S {
41    fn method() {}
42}
43
44enum E { A, B }
45"#;
46        let syntax = parse_source(code);
47        let items = super::extract_items_from_ast(&syntax, false);
48
49        // We expect a struct S, a function f, an impl block with a method, and an enum E.
50        assert!(items.iter().any(|i| matches!(i, ItemInfo::Struct { name, .. } if name == "S")));
51        assert!(items.iter().any(|i| matches!(i, ItemInfo::Function(f) if f.name() == "f")));
52        assert!(items.iter().any(|i| matches!(i, ItemInfo::ImplBlock{ name, ..} if name.as_ref().unwrap() == "S")));
53        assert!(items.iter().any(|i| matches!(i, ItemInfo::Enum{name, ..} if name == "E")));
54    }
55}
56
57