Skip to main content

aft_parse/imports/
ruby.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 RUBY_REQUIRE_KIND: &str = "require";
9}
10test_support_visibility! {
11const RUBY_REQUIRE_RELATIVE_KIND: &str = "require_relative";
12}
13/// Ruby's `load` re-runs the target every call, unlike the idempotent
14/// `require` family — organize must never drop a repeat as a duplicate.
15/// Exported so the organizer names this form rather than matching a literal.
16pub const RUBY_LOAD_KIND: &str = "load";
17test_support_visibility! {
18const RUBY_QUOTE_SINGLE: &str = "quote:single";
19}
20test_support_visibility! {
21const RUBY_QUOTE_DOUBLE: &str = "quote:double";
22}
23
24pub fn classify_group_ruby(_module_path: &str) -> ImportGroup {
25    // Ruby has no conventional stdlib/external/internal declaration grouping for
26    // require-like calls, so keep grouping neutral and stable.
27    ImportGroup::External
28}
29
30pub fn parse_ruby_imports(source: &str, tree: &Tree) -> ImportBlock {
31    let root = tree.root_node();
32    let mut imports = Vec::new();
33
34    let mut cursor = root.walk();
35    if cursor.goto_first_child() {
36        loop {
37            let node = cursor.node();
38            if node.kind() == "call" {
39                if let Some(imp) = parse_ruby_require_call(source, &node) {
40                    imports.push(imp);
41                }
42            }
43            if !cursor.goto_next_sibling() {
44                break;
45            }
46        }
47    }
48
49    let byte_range = import_byte_range(&imports);
50    ImportBlock {
51        imports,
52        byte_range,
53    }
54}
55
56fn parse_ruby_require_call(source: &str, node: &Node) -> Option<ImportStatement> {
57    let import_kind = ruby_top_level_require_method(source, node)?;
58    let arg_list = find_direct_child(node, "argument_list")?;
59    let string = find_direct_child(&arg_list, "string")?;
60    let (module_path, quote) = ruby_string_literal_content(source, &string)?;
61    if module_path.is_empty() {
62        return None;
63    }
64
65    let raw_text = source[node.byte_range()].to_string();
66    let byte_range = node.byte_range();
67    let group = classify_group_ruby(&module_path);
68    let quote_modifier = ruby_quote_modifier(quote).to_string();
69    let flat_marker = ruby_flat_marker(&import_kind, quote);
70
71    Some(ImportStatement {
72        module_path,
73        names: Vec::new(),
74        // The flat marker preserves Ruby's require form and quote style through
75        // legacy organize code paths until all readers consume `form` directly.
76        default_import: Some(flat_marker),
77        namespace_import: None,
78        kind: ImportKind::SideEffect,
79        group,
80        byte_range,
81        raw_text,
82        form: ImportForm::Structured {
83            named: Vec::new(),
84            namespace: None,
85            alias: None,
86            modifiers: vec![quote_modifier],
87            import_kind: Some(import_kind),
88        },
89    })
90}
91
92fn ruby_top_level_require_method(source: &str, node: &Node) -> Option<String> {
93    let mut method_name = None;
94    let mut saw_receiver_separator = false;
95
96    let mut cursor = node.walk();
97    if cursor.goto_first_child() {
98        loop {
99            let child = cursor.node();
100            match child.kind() {
101                "." | "::" => saw_receiver_separator = true,
102                "identifier" if method_name.is_none() => {
103                    method_name = Some(source[child.byte_range()].trim().to_string());
104                }
105                _ => {}
106            }
107            if !cursor.goto_next_sibling() {
108                break;
109            }
110        }
111    }
112
113    if saw_receiver_separator {
114        return None;
115    }
116
117    let method_name = method_name?;
118    if is_ruby_require_kind(&method_name) {
119        Some(method_name)
120    } else {
121        None
122    }
123}
124
125fn is_ruby_require_kind(kind: &str) -> bool {
126    matches!(
127        kind,
128        RUBY_REQUIRE_KIND | RUBY_REQUIRE_RELATIVE_KIND | RUBY_LOAD_KIND
129    )
130}
131
132fn ruby_string_literal_content(source: &str, node: &Node) -> Option<(String, char)> {
133    let raw = source[node.byte_range()].trim();
134    let quote = raw.chars().next()?;
135    if quote != '\'' && quote != '"' {
136        return None;
137    }
138    if raw.chars().last()? != quote {
139        return None;
140    }
141
142    // Interpolated requires are dynamic runtime expressions, not static import
143    // declarations that AFT can safely sort/remove/regenerate.
144    if raw.contains("#{") {
145        return None;
146    }
147
148    let content = &raw[quote.len_utf8()..raw.len() - quote.len_utf8()];
149    Some((content.to_string(), quote))
150}
151
152fn ruby_quote_modifier(quote: char) -> &'static str {
153    if quote == '"' {
154        RUBY_QUOTE_DOUBLE
155    } else {
156        RUBY_QUOTE_SINGLE
157    }
158}
159
160fn ruby_flat_marker(import_kind: &str, quote: char) -> String {
161    let quote_suffix = ruby_quote_suffix(quote);
162    if quote_suffix.is_empty() {
163        import_kind.to_string()
164    } else {
165        format!("{import_kind}|{quote_suffix}")
166    }
167}
168
169fn ruby_quote_suffix(quote: char) -> &'static str {
170    if quote == '"' {
171        "double"
172    } else {
173        ""
174    }
175}
176
177fn ruby_marker_parts(marker: &str) -> (Option<&str>, Option<char>) {
178    let (kind, quote) = marker.split_once('|').unwrap_or((marker, ""));
179    let kind = is_ruby_require_kind(kind).then_some(kind);
180    let quote = match quote {
181        "double" | RUBY_QUOTE_DOUBLE => Some('"'),
182        "single" | RUBY_QUOTE_SINGLE => Some('\''),
183        _ => None,
184    };
185    (kind, quote)
186}
187
188fn ruby_quote_from_modifiers(modifiers: &[String]) -> Option<char> {
189    if modifiers
190        .iter()
191        .any(|modifier| modifier == RUBY_QUOTE_DOUBLE)
192    {
193        Some('"')
194    } else if modifiers
195        .iter()
196        .any(|modifier| modifier == RUBY_QUOTE_SINGLE)
197    {
198        Some('\'')
199    } else {
200        None
201    }
202}
203
204fn find_direct_child<'tree>(node: &Node<'tree>, kind: &str) -> Option<Node<'tree>> {
205    let mut cursor = node.walk();
206    if cursor.goto_first_child() {
207        loop {
208            let child = cursor.node();
209            if child.kind() == kind {
210                return Some(child);
211            }
212            if !cursor.goto_next_sibling() {
213                break;
214            }
215        }
216    }
217    None
218}
219
220pub fn generate_ruby_import_line(req: &ImportRequest) -> String {
221    let (marker_kind, marker_quote) = req
222        .default_import
223        .map(ruby_marker_parts)
224        .unwrap_or((None, None));
225    let import_kind = req
226        .import_kind
227        .filter(|kind| is_ruby_require_kind(kind))
228        .or(marker_kind)
229        .unwrap_or(RUBY_REQUIRE_KIND);
230    let quote = ruby_quote_from_modifiers(req.modifiers)
231        .or(marker_quote)
232        .unwrap_or('\'');
233
234    format!("{import_kind} {quote}{}{quote}", req.module_path)
235}
236
237pub struct RubySyntax;
238
239impl ImportSyntax for RubySyntax {
240    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
241        parse_ruby_imports(source, tree)
242    }
243
244    fn generate_line(&self, req: &ImportRequest) -> String {
245        generate_ruby_import_line(req)
246    }
247
248    fn classify_group(&self, module_path: &str) -> ImportGroup {
249        classify_group_ruby(module_path)
250    }
251}
252
253pub static RUBY_SYNTAX: RubySyntax = RubySyntax;