Skip to main content

aft_parse/imports/
c.rs

1use super::{
2    import_byte_range, ImportBlock, ImportForm, ImportGroup, ImportKind, ImportRequest,
3    ImportStatement, ImportSyntax,
4};
5use tree_sitter::{Node, Tree};
6
7test_support_visibility! {
8const C_INCLUDE_SYSTEM_KIND: &str = "system";
9}
10test_support_visibility! {
11const C_INCLUDE_LOCAL_KIND: &str = "local";
12}
13
14/// Normalize an agent-supplied C/C++ include module.
15///
16/// Agents naturally pass the include with its delimiter (`<vector>` or
17/// `"foo.h"`) because that is how includes are written. Strip the delimiter and
18/// infer the include kind so dedup, classification, and generation all see the
19/// bare header path — otherwise generation double-wraps into `#include
20/// <<vector>>`, which fails syntax validation and rolls the edit back.
21///
22/// Returns the bare header path plus the inferred include kind, or the input
23/// unchanged with `None` when no delimiter is present (the caller then honors an
24/// explicit `import_kind`, defaulting to a system include).
25pub fn normalize_include_module(module: &str) -> (String, Option<&'static str>) {
26    let trimmed = module.trim();
27    if let Some(inner) = trimmed.strip_prefix('<').and_then(|s| s.strip_suffix('>')) {
28        (inner.trim().to_string(), Some(C_INCLUDE_SYSTEM_KIND))
29    } else if let Some(inner) = trimmed.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
30        (inner.trim().to_string(), Some(C_INCLUDE_LOCAL_KIND))
31    } else {
32        (module.to_string(), None)
33    }
34}
35
36pub fn parse_c_imports(source: &str, tree: &Tree) -> ImportBlock {
37    let root = tree.root_node();
38    let mut imports = Vec::new();
39
40    // An explicit work stack instead of recursion: conditional blocks can
41    // nest arbitrarily deep, and a stack overflow aborts the process.
42    // Children are pushed in reverse so includes come out in source order.
43    let mut pending = vec![root];
44    while let Some(node) = pending.pop() {
45        if node.kind() == "preproc_include" {
46            if let Some(import) = parse_c_include(source, &node) {
47                imports.push(import);
48            }
49        } else if node.id() == root.id()
50            || matches!(
51                node.kind(),
52                "preproc_if"
53                    | "preproc_ifdef"
54                    | "preproc_elif"
55                    | "preproc_else"
56                    | "preproc_elifdef"
57            )
58        {
59            let mut cursor = node.walk();
60            let start = pending.len();
61            pending.extend(node.named_children(&mut cursor));
62            pending[start..].reverse();
63        }
64    }
65
66    let byte_range = import_byte_range(&imports);
67    ImportBlock {
68        imports,
69        byte_range,
70    }
71}
72
73/// An include guard is the default insertion context, not an arbitrary feature
74/// conditional. Its matching define must precede newly added includes.
75pub fn default_include_context<'a>(source: &str, tree: &'a Tree) -> (Node<'a>, Option<usize>) {
76    let root = tree.root_node();
77    let mut cursor = root.walk();
78    let first = root
79        .named_children(&mut cursor)
80        .find(|child| child.kind() != "comment");
81    if let Some(guard) = first.filter(|node| node.kind() == "preproc_ifdef") {
82        let text = crate::parser::node_text(source, &guard);
83        if let Some(macro_name) = text
84            .lines()
85            .next()
86            .and_then(|line| line.trim().strip_prefix('#'))
87            .and_then(|line| line.trim_start().strip_prefix("ifndef"))
88            .and_then(|line| line.split_whitespace().next())
89        {
90            let mut cursor = guard.walk();
91            for child in guard.named_children(&mut cursor) {
92                if child.kind() == "preproc_def" {
93                    let directive = crate::parser::node_text(source, &child)
94                        .trim_start()
95                        .strip_prefix('#')
96                        .unwrap_or("");
97                    let mut words = directive.split_whitespace();
98                    if words.next() == Some("define") && words.next() == Some(macro_name) {
99                        return (guard, Some(child.end_byte()));
100                    }
101                }
102            }
103        }
104    }
105    (root, None)
106}
107
108/// Keep feature-conditional includes visible to readers, but do not use them
109/// as duplicate or ordering anchors for a default-context addition.
110pub fn c_insertion_block(source: &str, tree: &Tree, block: &ImportBlock) -> ImportBlock {
111    let (context, _) = default_include_context(source, tree);
112    let imports = block
113        .imports
114        .iter()
115        .filter(|import| {
116            context
117                .named_descendant_for_byte_range(import.byte_range.start, import.byte_range.end)
118                .and_then(|mut node| {
119                    while node.kind() != "preproc_include" {
120                        node = node.parent()?;
121                    }
122                    node.parent()
123                })
124                .is_some_and(|parent| parent.id() == context.id())
125        })
126        .cloned()
127        .collect::<Vec<_>>();
128    ImportBlock {
129        byte_range: import_byte_range(&imports),
130        imports,
131    }
132}
133
134fn parse_c_include(source: &str, node: &Node) -> Option<ImportStatement> {
135    let (module_path, import_kind) = c_include_target(source, node)?;
136    if module_path.is_empty() {
137        return None;
138    }
139
140    let byte_range = include_byte_range(source, node);
141    let raw_text = source[byte_range.clone()].to_string();
142    let group = classify_group_c_import_kind(import_kind);
143    let import_kind_string = import_kind.to_string();
144
145    Some(ImportStatement {
146        module_path,
147        names: Vec::new(),
148        // Preserve the include delimiter through legacy organize paths, which
149        // regenerate from flat fields before they reach the structured form.
150        default_import: Some(import_kind_string.clone()),
151        namespace_import: None,
152        kind: ImportKind::SideEffect,
153        group,
154        byte_range,
155        raw_text,
156        form: ImportForm::Structured {
157            named: Vec::new(),
158            namespace: None,
159            alias: None,
160            modifiers: Vec::new(),
161            import_kind: Some(import_kind_string),
162        },
163    })
164}
165
166fn include_byte_range(source: &str, node: &Node) -> std::ops::Range<usize> {
167    let start = node.byte_range().start;
168    let mut end = node.byte_range().end;
169    let bytes = source.as_bytes();
170    while end > start && matches!(bytes[end - 1], b'\n' | b'\r') {
171        end -= 1;
172    }
173    start..end
174}
175
176fn c_include_target(source: &str, node: &Node) -> Option<(String, &'static str)> {
177    let mut cursor = node.walk();
178    if cursor.goto_first_child() {
179        loop {
180            let child = cursor.node();
181            match child.kind() {
182                "system_lib_string" => {
183                    let module_path = delimited_include_path(source, &child, '<', '>')?;
184                    return Some((module_path, C_INCLUDE_SYSTEM_KIND));
185                }
186                "string_literal" => {
187                    let module_path = delimited_include_path(source, &child, '"', '"')?;
188                    return Some((module_path, C_INCLUDE_LOCAL_KIND));
189                }
190                _ => {}
191            }
192            if !cursor.goto_next_sibling() {
193                break;
194            }
195        }
196    }
197    None
198}
199
200fn delimited_include_path(source: &str, node: &Node, open: char, close: char) -> Option<String> {
201    let raw = source[node.byte_range()].trim();
202    if !raw.starts_with(open) || !raw.ends_with(close) {
203        return None;
204    }
205
206    let start = open.len_utf8();
207    let end = raw.len().checked_sub(close.len_utf8())?;
208    let module_path = raw[start..end].trim();
209    if module_path.is_empty() {
210        None
211    } else {
212        Some(module_path.to_string())
213    }
214}
215
216pub fn classify_group_c_import_kind(import_kind: &str) -> ImportGroup {
217    // C/C++ include delimiters carry search-path semantics: angle/system
218    // includes are grouped as stdlib, while quote/local includes are grouped as
219    // external project/third-party headers. They are deliberately distinct.
220    if import_kind == C_INCLUDE_SYSTEM_KIND {
221        ImportGroup::Stdlib
222    } else {
223        ImportGroup::External
224    }
225}
226
227pub fn classify_group_c(_module_path: &str) -> ImportGroup {
228    // The registry-level classifier only receives a header path, not the
229    // delimiter. Default to system because the legacy add path also defaults to
230    // generating an angle include when no `import_kind` is supplied. Parsed
231    // includes use `classify_group_c_import_kind` and preserve the real delimiter.
232    ImportGroup::Stdlib
233}
234
235pub fn generate_c_import_line(req: &ImportRequest) -> String {
236    let import_kind = req
237        .import_kind
238        .or(req.default_import)
239        .unwrap_or(C_INCLUDE_SYSTEM_KIND);
240
241    if import_kind == C_INCLUDE_LOCAL_KIND {
242        format!("#include \"{}\"", req.module_path)
243    } else {
244        format!("#include <{}>", req.module_path)
245    }
246}
247
248pub struct CSyntax;
249
250impl ImportSyntax for CSyntax {
251    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
252        parse_c_imports(source, tree)
253    }
254
255    fn generate_line(&self, req: &ImportRequest) -> String {
256        generate_c_import_line(req)
257    }
258
259    fn classify_group(&self, module_path: &str) -> ImportGroup {
260        classify_group_c(module_path)
261    }
262}
263
264pub static C_SYNTAX: CSyntax = CSyntax;