Skip to main content

aft_parse/imports/
perl.rs

1use super::{
2    import_byte_range, ImportBlock, ImportForm, ImportGroup, ImportKind, ImportRequest,
3    ImportStatement, ImportSyntax,
4};
5use tree_sitter::{Node, Tree};
6
7pub const PERL_USE_KIND: &str = "use";
8test_support_visibility! {
9const PERL_REQUIRE_KIND: &str = "require";
10}
11pub const PERL_NO_KIND: &str = "no";
12const PERL_FLAT_MARKER_PREFIX: &str = "perl:";
13
14pub fn classify_group_perl(_module_path: &str) -> ImportGroup {
15    // Perl pragmas/modules do not have a source-level stdlib/external/internal
16    // grouping convention, so keep grouping neutral and stable.
17    ImportGroup::External
18}
19
20pub fn parse_perl_imports(source: &str, tree: &Tree) -> ImportBlock {
21    let root = tree.root_node();
22    let mut imports = Vec::new();
23
24    let mut cursor = root.walk();
25    if cursor.goto_first_child() {
26        loop {
27            let node = cursor.node();
28            if let Some(imp) = parse_perl_import_statement(source, &node) {
29                imports.push(imp);
30            }
31            if !cursor.goto_next_sibling() {
32                break;
33            }
34        }
35    }
36
37    let byte_range = import_byte_range(&imports);
38    ImportBlock {
39        imports,
40        byte_range,
41    }
42}
43
44fn parse_perl_import_statement(source: &str, node: &Node) -> Option<ImportStatement> {
45    match node.kind() {
46        // `use`/`no` pragmas — including `use parent ...` and `use constant ...`
47        // — all parse as a single `use_statement`. The leading `use`/`no`
48        // keyword carries the kind and the `module` field carries the pragma
49        // name ("parent", "constant", or an ordinary module), so no per-pragma
50        // special-casing is needed.
51        "use_statement" => parse_perl_use_statement(source, node),
52        // `require Foo;` parses as an expression statement wrapping a
53        // `require_expression`.
54        "expression_statement" => {
55            let require = find_direct_child(node, "require_expression")?;
56            let module_node = first_named_child(&require)?;
57            build_perl_import(source, node, &module_node, PERL_REQUIRE_KIND)
58        }
59        _ => None,
60    }
61}
62
63fn parse_perl_use_statement(source: &str, node: &Node) -> Option<ImportStatement> {
64    let import_kind = if find_direct_child(node, PERL_USE_KIND).is_some() {
65        PERL_USE_KIND
66    } else if find_direct_child(node, PERL_NO_KIND).is_some() {
67        PERL_NO_KIND
68    } else {
69        return None;
70    };
71    let module_node = node.child_by_field_name("module")?;
72    build_perl_import(source, node, &module_node, import_kind)
73}
74
75fn build_perl_import(
76    source: &str,
77    statement: &Node,
78    module_node: &Node,
79    import_kind: &str,
80) -> Option<ImportStatement> {
81    let module_path = source[module_node.byte_range()].trim().to_string();
82    if module_path.is_empty() {
83        return None;
84    }
85
86    let raw_args = raw_args_after_module(source, statement, module_node)?;
87    let modifiers = perl_arg_modifiers(&raw_args);
88    // `use_statement` spans its own terminating `;`, but an `expression_statement`
89    // (e.g. `require Foo;`) does not — the `;` is a following sibling. Extend the
90    // range through it so organize/remove replaces the whole statement and leaves
91    // no stray semicolon behind.
92    let end_byte = match statement.next_sibling() {
93        Some(next) if next.kind() == ";" => next.end_byte(),
94        _ => statement.end_byte(),
95    };
96    let raw_text = source[statement.start_byte()..end_byte].to_string();
97    let byte_range = statement.start_byte()..end_byte;
98    let group = classify_group_perl(&module_path);
99
100    Some(ImportStatement {
101        module_path,
102        names: Vec::new(),
103        // Generic organize only carries flat fields into the generator. Preserve
104        // Perl's statement kind and raw argument tail here until it consumes
105        // `ImportForm::Structured` directly.
106        default_import: Some(perl_flat_marker(import_kind, &raw_args)),
107        namespace_import: None,
108        kind: ImportKind::SideEffect,
109        group,
110        byte_range,
111        raw_text,
112        form: ImportForm::Structured {
113            named: Vec::new(),
114            namespace: None,
115            alias: None,
116            modifiers,
117            import_kind: Some(import_kind.to_string()),
118        },
119    })
120}
121
122fn raw_args_after_module(source: &str, statement: &Node, module_node: &Node) -> Option<String> {
123    let statement_end = find_direct_child(statement, ";")
124        .map(|semicolon| semicolon.start_byte())
125        .unwrap_or_else(|| statement.end_byte());
126    if module_node.end_byte() > statement_end {
127        return None;
128    }
129
130    Some(
131        source[module_node.end_byte()..statement_end]
132            .trim()
133            .to_string(),
134    )
135}
136
137fn perl_arg_modifiers(raw_args: &str) -> Vec<String> {
138    if raw_args.is_empty() {
139        Vec::new()
140    } else {
141        vec![raw_args.to_string()]
142    }
143}
144
145fn find_direct_child<'tree>(node: &Node<'tree>, kind: &str) -> Option<Node<'tree>> {
146    let mut cursor = node.walk();
147    if cursor.goto_first_child() {
148        loop {
149            let child = cursor.node();
150            if child.kind() == kind {
151                return Some(child);
152            }
153            if !cursor.goto_next_sibling() {
154                break;
155            }
156        }
157    }
158    None
159}
160
161fn first_named_child<'tree>(node: &Node<'tree>) -> Option<Node<'tree>> {
162    let mut cursor = node.walk();
163    if cursor.goto_first_child() {
164        loop {
165            let child = cursor.node();
166            if child.is_named() {
167                return Some(child);
168            }
169            if !cursor.goto_next_sibling() {
170                break;
171            }
172        }
173    }
174    None
175}
176
177fn is_perl_import_kind(kind: &str) -> bool {
178    matches!(kind, PERL_USE_KIND | PERL_REQUIRE_KIND | PERL_NO_KIND)
179}
180
181test_support_visibility! {
182fn perl_flat_marker(import_kind: &str, raw_args: &str) -> String {
183    format!(
184        "{PERL_FLAT_MARKER_PREFIX}{}:{import_kind}{raw_args}",
185        import_kind.len()
186    )
187}
188}
189
190test_support_visibility! {
191fn perl_marker_parts(marker: &str) -> Option<(&str, &str)> {
192    let payload = marker.strip_prefix(PERL_FLAT_MARKER_PREFIX)?;
193    let (kind_len, rest) = payload.split_once(':')?;
194    let kind_len = kind_len.parse::<usize>().ok()?;
195    if rest.len() < kind_len || !rest.is_char_boundary(kind_len) {
196        return None;
197    }
198
199    let (kind, raw_args) = rest.split_at(kind_len);
200    is_perl_import_kind(kind).then_some((kind, raw_args))
201}
202}
203
204fn perl_args_from_modifiers(modifiers: &[String]) -> Option<String> {
205    let raw_args = modifiers
206        .iter()
207        .map(|modifier| modifier.trim())
208        .filter(|modifier| !modifier.is_empty())
209        .collect::<Vec<_>>()
210        .join(" ");
211    (!raw_args.is_empty()).then_some(raw_args)
212}
213
214pub fn generate_perl_import_line(req: &ImportRequest) -> String {
215    let (marker_kind, marker_args) = req
216        .default_import
217        .and_then(perl_marker_parts)
218        .map(|(kind, raw_args)| (Some(kind), Some(raw_args)))
219        .unwrap_or((None, None));
220    let import_kind = req
221        .import_kind
222        .filter(|kind| is_perl_import_kind(kind))
223        .or(marker_kind)
224        .unwrap_or(PERL_USE_KIND);
225    let raw_args = perl_args_from_modifiers(req.modifiers)
226        .or_else(|| marker_args.map(str::to_string))
227        .unwrap_or_default();
228
229    let mut line = String::new();
230    line.push_str(import_kind);
231    line.push(' ');
232    line.push_str(req.module_path);
233    if !raw_args.is_empty() {
234        line.push(' ');
235        line.push_str(&raw_args);
236    }
237    line.push(';');
238    line
239}
240
241pub struct PerlSyntax;
242
243impl ImportSyntax for PerlSyntax {
244    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
245        parse_perl_imports(source, tree)
246    }
247
248    fn generate_line(&self, req: &ImportRequest) -> String {
249        generate_perl_import_line(req)
250    }
251
252    fn classify_group(&self, module_path: &str) -> ImportGroup {
253        classify_group_perl(module_path)
254    }
255}
256
257pub static PERL_SYNTAX: PerlSyntax = PerlSyntax;