Skip to main content

aft_parse/imports/
mod.rs

1//! Import analysis engine: parsing, grouping, deduplication, and insertion.
2//!
3//! Per-language behavior is provided by [`ImportSyntax`] implementations,
4//! resolved through the [`syntax_for`] registry. Each engine extracts imports
5//! from tree-sitter ASTs, classifies them into groups, and generates import
6//! text. A single import's structured shape is carried by [`ImportForm`].
7//!
8//! Currently supports: TypeScript, TSX, JavaScript, Python, Rust, Go.
9
10pub mod quotes;
11
12use std::ops::Range;
13
14use tree_sitter::{Node, Tree};
15
16use crate::parser::LangId;
17
18test_support_visibility! {
19    mod c;
20}
21pub use c::{c_insertion_block, classify_group_c_import_kind, normalize_include_module};
22test_support_visibility! {
23    mod csharp;
24}
25test_support_visibility! {
26    mod java;
27}
28test_support_visibility! {
29    mod kotlin;
30}
31test_support_visibility! {
32    mod lua;
33}
34pub mod perl;
35test_support_visibility! {
36    mod php;
37}
38pub use php::{
39    php_grouped_use_matches_module, php_grouped_use_shares_prefix, php_import_matches_module,
40    rewrite_php_import_without_module,
41};
42pub mod ruby;
43test_support_visibility! {
44    mod scala;
45}
46pub use scala::scala_block_uses_scala2_dialect;
47test_support_visibility! {
48    mod swift;
49}
50
51// ---------------------------------------------------------------------------
52// Shared types
53// ---------------------------------------------------------------------------
54
55/// What kind of import this is.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum ImportKind {
58    /// `import { X } from 'y'` or `import X from 'y'`
59    Value,
60    /// `import type { X } from 'y'`
61    Type,
62    /// `import './side-effect'`
63    SideEffect,
64}
65
66/// Which logical group an import belongs to (language-specific).
67///
68/// Ordering matches conventional import group sorting:
69///   Stdlib (first) < External < Internal (last)
70///
71/// Language mapping:
72///   - TS/JS/TSX: External (no `.` prefix), Internal (`.`/`..` prefix)
73///   - Python:    Stdlib, External (third-party), Internal (relative `.`/`..`)
74///   - Rust:      Stdlib (std/core/alloc), External (crates), Internal (crate/self/super)
75///   - Go:        Stdlib (no dots in path), External (dots in path)
76#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub enum ImportGroup {
78    /// Standard library (Python stdlib, Rust std/core/alloc, Go stdlib).
79    /// TS/JS don't use this group.
80    Stdlib,
81    /// External/third-party packages.
82    External,
83    /// Internal/relative imports (TS relative, Python local, Rust crate/self/super).
84    Internal,
85}
86
87impl ImportGroup {
88    /// Human-readable label for the group.
89    pub fn label(&self) -> &'static str {
90        match self {
91            ImportGroup::Stdlib => "stdlib",
92            ImportGroup::External => "external",
93            ImportGroup::Internal => "internal",
94        }
95    }
96}
97
98/// One clause in a PHP `use` declaration.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct PhpImportClause {
101    /// Fully qualified imported symbol for this clause.
102    pub module_path: String,
103    /// Local alias introduced by `as`, when present.
104    pub alias: Option<String>,
105    /// PHP import namespace (`function` or `const`), when present.
106    pub import_kind: Option<String>,
107}
108
109/// Structured, language-honest representation of a single import's shape.
110///
111/// This is the migration target that replaces the TS-shaped flat fields
112/// (`names`/`default_import`/`namespace_import`) and their per-language
113/// overloads (Rust packs `"pub"` into `default_import`; Go packs the alias
114/// there). It is introduced additively alongside the flat fields (Stream M of
115/// the imports-refactor plan): parsers populate BOTH, readers migrate onto
116/// `form` one at a time behind the golden-parity gate, and the flat fields are
117/// removed once no reader depends on them. New-language variants (Static,
118/// Include, RuntimeRequire, …) are added when their engines land — only the
119/// variants the existing engines produce exist today.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum ImportForm {
122    /// ES modules: TypeScript, TSX, JavaScript.
123    /// `named` holds verbatim specifiers (`"useState"`, `"stdin as input"`,
124    /// `"type Foo"`, `"type Foo as Bar"`) — see [`specifier_imported_name`].
125    Es {
126        default_import: Option<String>,
127        namespace_import: Option<String>,
128        named: Vec<String>,
129        /// Statement-level `import type { ... }`.
130        type_only: bool,
131        /// Side-effect-only `import "mod"` (no bindings).
132        side_effect: bool,
133        /// Verbatim `with { ... }` or legacy `assert { ... }` clause.
134        /// Import attributes select the module type, so dropping this clause can
135        /// change a valid import into one the runtime refuses to load.
136        attribute_clause: Option<String>,
137        /// Decoded value of the clause's `type` attribute, when parsed.
138        attribute_type: Option<String>,
139    },
140    /// Python `import module` (`from_import = false`) or
141    /// `from module import a, b` (`from_import = true`).
142    Python {
143        from_import: bool,
144        named: Vec<String>,
145    },
146    /// Rust `use path;` / `pub use path;`. `visibility` replaces the
147    /// `default_import == "pub"` overload (`Some("pub")`, `Some("pub(crate)")`,
148    /// …). For use lists, `module_path` is the prefix (empty for a root list)
149    /// and `named` contains complete top-level entries, including nested trees.
150    RustUse {
151        visibility: Option<String>,
152        named: Vec<String>,
153    },
154    /// Go import. `alias` replaces the `default_import` overload, including the
155    /// blank (`_`) and dot (`.`) import bindings.
156    Go { alias: Option<String> },
157    /// Solidity import, in one of four forms:
158    /// - side-effect: `import "x";` (all empty)
159    /// - named: `import { A, B as C } from "x";` (`named`)
160    /// - namespace: `import * as A from "x";` (`namespace`)
161    /// - whole-file alias: `import "x" as A;` (`alias`)
162    ///
163    /// `named` holds verbatim specifiers (`"A"`, `"B as C"`) like the ES form,
164    /// so [`specifier_imported_name`] / [`specifier_local_name`] apply.
165    Solidity {
166        named: Vec<String>,
167        namespace: Option<String>,
168        alias: Option<String>,
169    },
170    /// One physical PHP `use` declaration. A declaration may contain multiple
171    /// comma-separated clauses, each with its own path, alias, and import kind.
172    Php { clauses: Vec<PhpImportClause> },
173    /// Generic structured form shared by Java, C#, grouped PHP uses, Kotlin,
174    /// Scala, Swift, and other engines that use this common schema. Includes all
175    /// schema fields so a new engine does not need its own enum variant;
176    /// `module_path` on the parent `ImportStatement` stores the full path or
177    /// fully qualified name, while `named` stores each specifier exactly as parsed.
178    Structured {
179        named: Vec<String>,
180        namespace: Option<String>,
181        alias: Option<String>,
182        modifiers: Vec<String>,
183        import_kind: Option<String>,
184    },
185}
186
187/// Structured request to generate a single import line. Superset of the fields
188/// the public `aft_import` schema exposes; each engine reads only the subset it
189/// supports. New languages add fields here rather than growing positional
190/// parameters on every generator signature.
191#[derive(Debug, Clone)]
192pub struct ImportRequest<'a> {
193    pub module_path: &'a str,
194    pub names: &'a [String],
195    pub default_import: Option<&'a str>,
196    /// ES `* as ns` / Solidity `* as A`.
197    pub namespace: Option<&'a str>,
198    /// Whole-module local alias (Solidity `import "x" as A`).
199    pub alias: Option<&'a str>,
200    pub type_only: bool,
201    /// Statement-level modifier tokens (Java/C# `static`, C# `global`/`unsafe`,
202    /// `wildcard`, Swift `@testable`, …). Empty for the legacy engines.
203    pub modifiers: &'a [String],
204    /// Symbol-kind-specific import (PHP `function`/`const`, Swift `struct`/…,
205    /// Scala `given`). Absent for the legacy engines.
206    pub import_kind: Option<&'a str>,
207}
208
209/// Empty default for the `modifiers` slice so legacy callers need not allocate.
210const NO_MODIFIERS: &[String] = &[];
211
212impl<'a> ImportRequest<'a> {
213    /// Construct a request carrying only the legacy positional fields; the
214    /// structured fields (alias/modifiers/import_kind) default to absent. Used
215    /// by the back-compat free-function wrappers.
216    pub fn legacy(
217        module_path: &'a str,
218        names: &'a [String],
219        default_import: Option<&'a str>,
220        namespace: Option<&'a str>,
221        type_only: bool,
222    ) -> Self {
223        ImportRequest {
224            module_path,
225            names,
226            default_import,
227            namespace,
228            alias: None,
229            type_only,
230            modifiers: NO_MODIFIERS,
231            import_kind: None,
232        }
233    }
234}
235
236/// A single parsed import statement.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct ImportStatement {
239    /// The module path (e.g., `react`, `./utils`, `../config`).
240    pub module_path: String,
241    /// Named imports (e.g., `["useState", "useEffect"]`).
242    pub names: Vec<String>,
243    /// Default import name (e.g., `React` from `import React from 'react'`).
244    pub default_import: Option<String>,
245    /// Namespace import name (e.g., `path` from `import * as path from 'path'`).
246    pub namespace_import: Option<String>,
247    /// What kind: value, type, or side-effect.
248    pub kind: ImportKind,
249    /// Which group this import belongs to.
250    pub group: ImportGroup,
251    /// Byte range in the original source.
252    pub byte_range: Range<usize>,
253    /// Raw text of the import statement.
254    pub raw_text: String,
255    /// Structured, de-overloaded representation (Stream M migration target).
256    /// Populated by every parser alongside the flat fields above; readers
257    /// migrate onto this incrementally behind the golden-parity gate.
258    pub form: ImportForm,
259}
260
261/// A block of parsed imports from a file.
262#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct ImportBlock {
264    /// All parsed import statements, in source order.
265    pub imports: Vec<ImportStatement>,
266    /// Overall byte range covering all import statements (start of first to end of last).
267    /// `None` if no imports found.
268    pub byte_range: Option<Range<usize>>,
269}
270
271impl ImportBlock {
272    pub fn empty() -> Self {
273        ImportBlock {
274            imports: Vec::new(),
275            byte_range: None,
276        }
277    }
278}
279
280pub fn import_byte_range(imports: &[ImportStatement]) -> Option<Range<usize>> {
281    imports.first().zip(imports.last()).map(|(first, last)| {
282        let start = first.byte_range.start;
283        let end = last.byte_range.end;
284        start..end
285    })
286}
287
288/// Calls `found` on each node of kind `kind` in the tree under `root`
289/// (`root` included), in source order, without descending into a node it
290/// found. The walk keeps its place in a tree cursor instead of recursing, so
291/// its stack use does not grow with the tree's depth: a file can nest tens
292/// of thousands of levels deep, and a stack overflow aborts the process.
293pub fn for_each_preorder_until<'tree>(
294    root: Node<'tree>,
295    kind: &str,
296    mut found: impl FnMut(Node<'tree>),
297) {
298    let mut cursor = root.walk();
299    loop {
300        let node = cursor.node();
301        if node.kind() == kind {
302            found(node);
303        } else if cursor.goto_first_child() {
304            continue;
305        }
306        // Move past this subtree: to the next sibling, or up until an
307        // ancestor has one. The cursor cannot climb above `root`.
308        while !cursor.goto_next_sibling() {
309            if !cursor.goto_parent() {
310                return;
311            }
312        }
313    }
314}
315
316// ---------------------------------------------------------------------------
317// Specifier helpers (TS/JS verbatim-string format)
318// ---------------------------------------------------------------------------
319
320/// Return the local binding name for a TS/JS named-import specifier stored in
321/// `ImportStatement::names`. Specifiers are stored verbatim — e.g.
322/// `"stdin as input"`, `"type Foo"`, `"type Foo as Bar"`, `"useState"` — so
323/// callers that want the name actually introduced into scope must strip the
324/// optional `type ` prefix and prefer the post-`as` identifier when present.
325///
326/// Examples:
327///   `"useState"`            → `"useState"`
328///   `"stdin as input"`      → `"input"`
329///   `"type Foo"`            → `"Foo"`
330///   `"type Foo as Bar"`     → `"Bar"`
331pub fn specifier_local_name(spec: &str) -> &str {
332    let trimmed = spec.trim();
333    let after_type = trimmed
334        .strip_prefix("type ")
335        .unwrap_or(trimmed)
336        .trim_start();
337    if let Some(idx) = after_type.find(" as ") {
338        after_type[idx + 4..].trim()
339    } else {
340        after_type
341    }
342}
343
344/// Return the imported (pre-`as`) name for a TS/JS named-import specifier.
345/// Used by dedup, remove, and any caller that needs the source-side name.
346///
347/// Examples:
348///   `"useState"`            → `"useState"`
349///   `"stdin as input"`      → `"stdin"`
350///   `"type Foo"`            → `"Foo"`
351///   `"type Foo as Bar"`     → `"Foo"`
352pub fn specifier_imported_name(spec: &str) -> &str {
353    let trimmed = spec.trim();
354    let after_type = trimmed
355        .strip_prefix("type ")
356        .unwrap_or(trimmed)
357        .trim_start();
358    after_type
359        .find(" as ")
360        .map(|idx| after_type[..idx].trim())
361        .unwrap_or(after_type)
362}
363
364/// Whether a stored specifier matches a target name. Matches against either
365/// the imported name or the local binding so callers can pass whichever name
366/// they observed in source. Useful for `remove_import` where the agent may
367/// reference an aliased import by either name.
368pub fn specifier_matches(spec: &str, target: &str) -> bool {
369    specifier_imported_name(spec) == target || specifier_local_name(spec) == target
370}
371
372// ---------------------------------------------------------------------------
373// Per-language engine: the ImportSyntax trait + registry
374// ---------------------------------------------------------------------------
375
376/// Per-language import engine. One impl per supported language; [`syntax_for`]
377/// maps a [`LangId`] to its `&'static dyn ImportSyntax`. This is the single
378/// plug-in point that replaces the scattered `match lang` dispatch in
379/// `parse_imports` / `generate_import_line_with_namespace` / `classify_group` /
380/// `is_supported`. Adding a language is a new impl + one registry arm.
381///
382/// The existing engines are thin wrappers over the free functions they already
383/// used, so routing through the trait is behavior-preserving (golden-gated).
384pub trait ImportSyntax: Sync {
385    /// Parse all imports from a file's already-parsed tree.
386    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock;
387
388    /// Generate a single import line from a structured [`ImportRequest`].
389    /// Engines read only the fields they support and ignore the rest.
390    fn generate_line(&self, req: &ImportRequest) -> String;
391
392    /// Classify a module path into stdlib / external / internal.
393    fn classify_group(&self, module_path: &str) -> ImportGroup;
394}
395
396/// ES modules engine: TypeScript, TSX, JavaScript.
397struct EsSyntax;
398impl ImportSyntax for EsSyntax {
399    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
400        parse_ts_imports(source, tree)
401    }
402    fn generate_line(&self, req: &ImportRequest) -> String {
403        generate_ts_import_line(
404            req.module_path,
405            req.names,
406            req.default_import,
407            req.namespace,
408            req.type_only,
409        )
410    }
411    fn classify_group(&self, module_path: &str) -> ImportGroup {
412        classify_group_ts(module_path)
413    }
414}
415
416struct PythonSyntax;
417impl ImportSyntax for PythonSyntax {
418    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
419        parse_py_imports(source, tree)
420    }
421    fn generate_line(&self, req: &ImportRequest) -> String {
422        generate_py_import_line(req.module_path, req.names, req.default_import)
423    }
424    fn classify_group(&self, module_path: &str) -> ImportGroup {
425        classify_group_py(module_path)
426    }
427}
428
429struct RustSyntax;
430impl ImportSyntax for RustSyntax {
431    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
432        parse_rs_imports(source, tree)
433    }
434    fn generate_line(&self, req: &ImportRequest) -> String {
435        let line = generate_rs_import_line(req.module_path, req.names, req.type_only);
436        match req.default_import {
437            Some(visibility) if !visibility.is_empty() => format!("{visibility} {line}"),
438            _ => line,
439        }
440    }
441    fn classify_group(&self, module_path: &str) -> ImportGroup {
442        classify_group_rs(module_path)
443    }
444}
445
446struct GoSyntax;
447impl ImportSyntax for GoSyntax {
448    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
449        parse_go_imports(source, tree)
450    }
451    fn generate_line(&self, req: &ImportRequest) -> String {
452        generate_go_import_line(req.module_path, req.default_import, false)
453    }
454    fn classify_group(&self, module_path: &str) -> ImportGroup {
455        classify_group_go(module_path)
456    }
457}
458
459/// Solidity import engine. Supports named / namespace / whole-file-alias /
460/// side-effect forms.
461struct SoliditySyntax;
462impl ImportSyntax for SoliditySyntax {
463    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
464        parse_solidity_imports(source, tree)
465    }
466    fn generate_line(&self, req: &ImportRequest) -> String {
467        generate_solidity_import_line(req)
468    }
469    fn classify_group(&self, module_path: &str) -> ImportGroup {
470        classify_group_solidity(module_path)
471    }
472}
473
474#[derive(Debug, Clone, Copy, PartialEq, Eq)]
475pub enum VueScriptRangeError {
476    MissingScript,
477    MultipleScripts,
478}
479
480impl VueScriptRangeError {
481    pub fn code(self) -> &'static str {
482        match self {
483            VueScriptRangeError::MissingScript => "missing_vue_script",
484            VueScriptRangeError::MultipleScripts => "ambiguous_vue_script",
485        }
486    }
487
488    pub fn message(self, command: &str) -> String {
489        match self {
490            VueScriptRangeError::MissingScript => format!(
491                "{command}: Vue import management requires exactly one <script> block; found none"
492            ),
493            VueScriptRangeError::MultipleScripts => format!(
494                "{command}: Vue import management requires exactly one <script> block; found multiple"
495            ),
496        }
497    }
498}
499
500/// Locate the byte range of the single `<script>` block's inner content in a
501/// Vue Single-File Component. tree-sitter-vue exposes the script body as a
502/// single `raw_text` node; this returns `(start, end)` of that node, or — for an
503/// empty `<script></script>` with no `raw_text` child — a zero-width range right
504/// after the start tag. Multiple scripts are ambiguous for byte-level edits and
505/// no-script SFCs have no safe insertion region, so callers should surface the
506/// returned error instead of silently editing byte 0 or the first script.
507pub fn vue_single_script_content_range(tree: &Tree) -> Result<(usize, usize), VueScriptRangeError> {
508    let root = tree.root_node();
509    let mut ranges = Vec::new();
510    let mut cursor = root.walk();
511    for child in root.named_children(&mut cursor) {
512        if child.kind() == "script_element" {
513            ranges.push(vue_script_element_content_range(&child));
514        }
515    }
516
517    match ranges.len() {
518        0 => Err(VueScriptRangeError::MissingScript),
519        1 => Ok(ranges[0]),
520        _ => Err(VueScriptRangeError::MultipleScripts),
521    }
522}
523
524/// Back-compat convenience wrapper for callers that only need the safe single
525/// script range and intentionally treat missing/ambiguous scripts as absent.
526pub fn vue_script_content_range(tree: &Tree) -> Option<(usize, usize)> {
527    vue_single_script_content_range(tree).ok()
528}
529
530fn vue_script_element_content_range(child: &Node) -> (usize, usize) {
531    let mut inner = child.walk();
532    for sub in child.named_children(&mut inner) {
533        if sub.kind() == "raw_text" {
534            return (sub.start_byte(), sub.end_byte());
535        }
536    }
537
538    // Empty `<script></script>`: insert right after the start tag.
539    let mut inner2 = child.walk();
540    for sub in child.named_children(&mut inner2) {
541        if sub.kind() == "start_tag" {
542            return (sub.end_byte(), sub.end_byte());
543        }
544    }
545
546    (child.end_byte(), child.end_byte())
547}
548
549/// Parse imports from a Vue SFC `<script>` block. The script body is re-parsed
550/// with the TypeScript grammar (which covers both `lang="ts"` and plain JS
551/// import syntax), then every byte offset is remapped from script-relative to
552/// whole-file positions so insertion, removal, and organize operate correctly.
553fn parse_vue_imports(source: &str, tree: &Tree) -> ImportBlock {
554    let Ok((start, end)) = vue_single_script_content_range(tree) else {
555        return ImportBlock {
556            imports: Vec::new(),
557            byte_range: None,
558        };
559    };
560    let inner = &source[start..end];
561    // This thread's retained parser: building a parser and loading the grammar
562    // per call was a fixed cost on every file an imports scan visits.
563    let Ok(inner_tree) = crate::parser::parse_source_with_cached_parser(
564        std::path::Path::new("<vue script>"),
565        inner,
566        LangId::TypeScript,
567    ) else {
568        return ImportBlock {
569            imports: Vec::new(),
570            byte_range: None,
571        };
572    };
573    let mut block = parse_ts_imports(inner, &inner_tree);
574    for imp in &mut block.imports {
575        imp.byte_range = (imp.byte_range.start + start)..(imp.byte_range.end + start);
576    }
577    block.byte_range = block.byte_range.map(|r| (r.start + start)..(r.end + start));
578    block
579}
580
581/// Vue Single-File Component import engine. The `<script>` body is exposed by
582/// tree-sitter-vue as a single `raw_text` node, so we re-parse it with the
583/// TypeScript grammar and remap the resulting byte offsets back to whole-file
584/// positions. Generation and grouping reuse the ES (TS/JS) engine, since Vue
585/// script imports are TypeScript/JavaScript.
586struct VueSyntax;
587impl ImportSyntax for VueSyntax {
588    fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
589        parse_vue_imports(source, tree)
590    }
591    fn generate_line(&self, req: &ImportRequest) -> String {
592        generate_ts_import_line(
593            req.module_path,
594            req.names,
595            req.default_import,
596            req.namespace,
597            req.type_only,
598        )
599    }
600    fn classify_group(&self, module_path: &str) -> ImportGroup {
601        classify_group_ts(module_path)
602    }
603}
604
605static ES_SYNTAX: EsSyntax = EsSyntax;
606static PYTHON_SYNTAX: PythonSyntax = PythonSyntax;
607static RUST_SYNTAX: RustSyntax = RustSyntax;
608static GO_SYNTAX: GoSyntax = GoSyntax;
609static SOLIDITY_SYNTAX: SoliditySyntax = SoliditySyntax;
610static VUE_SYNTAX: VueSyntax = VueSyntax;
611
612/// Map a language to its import engine, or `None` when imports are unsupported.
613pub fn syntax_for(lang: LangId) -> Option<&'static dyn ImportSyntax> {
614    match lang {
615        LangId::TypeScript | LangId::Tsx | LangId::JavaScript => Some(&ES_SYNTAX),
616        LangId::Python => Some(&PYTHON_SYNTAX),
617        LangId::Rust => Some(&RUST_SYNTAX),
618        LangId::Go => Some(&GO_SYNTAX),
619        LangId::Solidity => Some(&SOLIDITY_SYNTAX),
620        LangId::Vue => Some(&VUE_SYNTAX),
621        LangId::C => Some(&c::C_SYNTAX),
622        LangId::Cpp | LangId::Cuda | LangId::Metal => Some(&c::C_SYNTAX),
623        LangId::Java => Some(&java::JAVA_SYNTAX),
624        LangId::Kotlin => Some(&kotlin::KOTLIN_SYNTAX),
625        LangId::Lua => Some(&lua::LUA_SYNTAX),
626        LangId::CSharp => Some(&csharp::CSHARP_SYNTAX),
627        LangId::Php => Some(&php::PHP_SYNTAX),
628        LangId::Perl => Some(&perl::PERL_SYNTAX),
629        LangId::Ruby => Some(&ruby::RUBY_SYNTAX),
630        LangId::Scala => Some(&scala::SCALA_SYNTAX),
631        LangId::Swift => Some(&swift::SWIFT_SYNTAX),
632        LangId::Zig
633        | LangId::Bash
634        | LangId::Scss
635        | LangId::Json
636        | LangId::Html
637        | LangId::Markdown
638        | LangId::Yaml
639        | LangId::Pascal
640        | LangId::R
641        | LangId::Groovy
642        | LangId::ObjC
643        | LangId::Toml
644        | LangId::Luau => None,
645    }
646}
647
648// ---------------------------------------------------------------------------
649// Core API
650// ---------------------------------------------------------------------------
651
652/// Parse imports from source using the provided tree-sitter tree.
653pub fn parse_imports(source: &str, tree: &Tree, lang: LangId) -> ImportBlock {
654    if lang == LangId::Luau {
655        return crate::luau::imports(source, tree.root_node());
656    }
657    match syntax_for(lang) {
658        Some(engine) => engine.parse(source, tree),
659        None => ImportBlock::empty(),
660    }
661}
662
663/// Check if an import with the given module + name combination already exists.
664///
665/// For dedup: same module path and matching binding shape. Side-effect imports
666/// are only duplicates of side-effect imports; namespace imports are distinct
667/// from side-effect imports and from other namespace aliases.
668pub fn is_duplicate(
669    block: &ImportBlock,
670    module_path: &str,
671    names: &[String],
672    default_import: Option<&str>,
673    type_only: bool,
674) -> bool {
675    is_duplicate_with_namespace(block, module_path, names, default_import, None, type_only)
676}
677
678/// Check if an import with the given module + complete binding shape already exists.
679pub fn is_duplicate_with_namespace(
680    block: &ImportBlock,
681    module_path: &str,
682    names: &[String],
683    default_import: Option<&str>,
684    namespace_import: Option<&str>,
685    type_only: bool,
686) -> bool {
687    let target_kind = if type_only {
688        ImportKind::Type
689    } else {
690        ImportKind::Value
691    };
692
693    for imp in &block.imports {
694        if imp.module_path != module_path {
695            continue;
696        }
697
698        // For side-effect imports (no names/default/namespace): module path
699        // match is sufficient only when the existing import is also a
700        // side-effect import. Namespace imports like `import * as fs from 'fs'`
701        // are distinct local bindings and must not be conflated with
702        // `import 'fs'`.
703        if names.is_empty()
704            && default_import.is_none()
705            && namespace_import.is_none()
706            && imp.names.is_empty()
707            && imp.default_import.is_none()
708            && imp.namespace_import.is_none()
709        {
710            return true;
711        }
712
713        // For side-effect imports specifically (TS/JS): module match is enough
714        if names.is_empty()
715            && default_import.is_none()
716            && namespace_import.is_none()
717            && imp.kind == ImportKind::SideEffect
718        {
719            return true;
720        }
721
722        // Kind must match for dedup (value imports don't dedup against type imports)
723        if imp.kind != target_kind && imp.kind != ImportKind::SideEffect {
724            continue;
725        }
726
727        // Default+namespace imports are one ES binding shape. A plain default
728        // import must not satisfy a request for `default, * as ns`, and a
729        // different namespace alias must not either.
730        if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
731            if imp.default_import.as_deref() == Some(def)
732                && imp.namespace_import.as_deref() == Some(namespace)
733                && names
734                    .iter()
735                    .all(|n| imp.names.iter().any(|stored| specifier_matches(stored, n)))
736            {
737                return true;
738            }
739            continue;
740        }
741
742        // Namespace-only requests are satisfied by any existing same-module
743        // import that already binds that namespace alias, even if it also has a
744        // default binding.
745        if names.is_empty()
746            && default_import.is_none()
747            && namespace_import.is_some()
748            && imp.namespace_import.as_deref() == namespace_import
749        {
750            return true;
751        }
752
753        // Check default import match. This branch only handles requests that do
754        // not also ask for a namespace; that combined shape is checked above.
755        if let Some(def) = default_import {
756            if namespace_import.is_none() && imp.default_import.as_deref() == Some(def) {
757                return true;
758            }
759        }
760
761        // Check named imports — if ALL requested names already exist.
762        // Compare on the imported (pre-`as`) name so adding `Foo` is a
763        // no-op when `Foo as Bar` is already imported, but adding
764        // `Foo as Bar` is NOT a duplicate of bare `Foo` (different
765        // local bindings).
766        if !names.is_empty()
767            && names
768                .iter()
769                .all(|n| imp.names.iter().any(|stored| specifier_matches(stored, n)))
770        {
771            return true;
772        }
773    }
774
775    false
776}
777
778/// Check whether a fully structured add-import request is already present.
779///
780/// Legacy ES/Python/Rust/Go callers intentionally keep the historical
781/// subset/dominance semantics (`import { a, b }` satisfies adding `{ a }`). The
782/// newer engines carry language-specific shape in `ImportForm::Structured` (or
783/// Solidity's dedicated form), where module path alone is not enough: include
784/// delimiters, statement kinds, modifiers, aliases, and runtime import flavors
785/// all affect the generated source. Those languages deduplicate on a canonical
786/// full-form key so `#include <x>` does not block `#include "x"`, `load` does
787/// not block `require`, and side-effect Solidity imports do not block aliases.
788pub fn is_duplicate_import_request(
789    lang: LangId,
790    block: &ImportBlock,
791    req: &ImportRequest<'_>,
792) -> bool {
793    if lang == LangId::Php
794        && block
795            .imports
796            .iter()
797            .any(|imp| php::php_import_satisfies_request(imp, req))
798    {
799        return true;
800    }
801
802    if lang == LangId::Python && req.names.is_empty() && req.default_import.is_none() {
803        return block.imports.iter().any(|imp| {
804            matches!(
805                &imp.form,
806                ImportForm::Python {
807                    from_import: false,
808                    named,
809                } if named.iter().any(|specifier| {
810                    specifier_imported_name(specifier) == req.module_path
811                })
812            )
813        });
814    }
815
816    if !uses_form_aware_dedup(lang) {
817        return is_duplicate_with_namespace(
818            block,
819            req.module_path,
820            req.names,
821            req.default_import,
822            req.namespace,
823            req.type_only,
824        );
825    }
826
827    let target = request_dedup_key(lang, req);
828    block
829        .imports
830        .iter()
831        .map(|imp| statement_dedup_key(lang, imp))
832        .any(|key| key == target)
833}
834
835fn uses_form_aware_dedup(lang: LangId) -> bool {
836    matches!(
837        lang,
838        LangId::Solidity
839            | LangId::C
840            | LangId::Cpp
841            | LangId::Java
842            | LangId::CSharp
843            | LangId::Php
844            | LangId::Kotlin
845            | LangId::Scala
846            | LangId::Swift
847            | LangId::Ruby
848            | LangId::Lua
849            | LangId::Perl
850    )
851}
852
853#[derive(Debug, Clone, PartialEq, Eq)]
854struct ImportDedupKey {
855    module_path: String,
856    kind: ImportKind,
857    form: ImportForm,
858}
859
860fn statement_dedup_key(lang: LangId, imp: &ImportStatement) -> ImportDedupKey {
861    canonical_dedup_key(
862        lang,
863        ImportDedupKey {
864            module_path: imp.module_path.clone(),
865            kind: imp.kind,
866            form: imp.form.clone(),
867        },
868    )
869}
870
871fn request_dedup_key(lang: LangId, req: &ImportRequest<'_>) -> ImportDedupKey {
872    let key = match lang {
873        LangId::Solidity => {
874            let kind = if req.names.is_empty() && req.namespace.is_none() && req.alias.is_none() {
875                ImportKind::SideEffect
876            } else {
877                ImportKind::Value
878            };
879            ImportDedupKey {
880                module_path: req.module_path.to_string(),
881                kind,
882                form: ImportForm::Solidity {
883                    named: req.names.to_vec(),
884                    namespace: req.namespace.map(str::to_string),
885                    alias: req.alias.map(str::to_string),
886                },
887            }
888        }
889        LangId::C | LangId::Cpp => structured_dedup_key(
890            req.module_path,
891            ImportKind::SideEffect,
892            &[],
893            None,
894            None,
895            &[],
896            Some(req.import_kind.or(req.default_import).unwrap_or("system")),
897        ),
898        LangId::Java => {
899            let (mut module_path, modifiers) = wildcard_suffix_request(
900                req.module_path,
901                req.modifiers,
902                req.default_import == Some("*"),
903            );
904            let mut names = req.names.to_vec();
905            normalize_java_static_member_key(&mut module_path, &modifiers, &mut names);
906            structured_dedup_key(
907                &module_path,
908                ImportKind::Value,
909                &names,
910                None,
911                None,
912                &modifiers,
913                None,
914            )
915        }
916        LangId::CSharp => structured_dedup_key(
917            req.module_path,
918            ImportKind::Value,
919            &[],
920            None,
921            req.alias,
922            req.modifiers,
923            None,
924        ),
925        LangId::Php => structured_dedup_key(
926            req.module_path,
927            ImportKind::Value,
928            &[],
929            None,
930            req.alias,
931            req.modifiers,
932            req.import_kind,
933        ),
934        LangId::Kotlin => {
935            let wildcard = req.default_import == Some("*") || req.module_path.ends_with(".*");
936            let (module_path, modifiers) =
937                wildcard_suffix_request(req.module_path, req.modifiers, wildcard);
938            let alias = req
939                .alias
940                .or(req.default_import.filter(|value| *value != "*"));
941            structured_dedup_key(
942                &module_path,
943                ImportKind::Value,
944                &[],
945                None,
946                alias,
947                &modifiers,
948                None,
949            )
950        }
951        LangId::Scala => scala_request_dedup_key(req),
952        LangId::Swift => structured_dedup_key(
953            req.module_path,
954            ImportKind::Value,
955            &[],
956            None,
957            None,
958            req.modifiers,
959            req.import_kind,
960        ),
961        LangId::Ruby => {
962            let mut modifiers = req.modifiers.to_vec();
963            if !modifiers
964                .iter()
965                .any(|modifier| modifier == "quote:single" || modifier == "quote:double")
966            {
967                modifiers.push("quote:single".to_string());
968            }
969            structured_dedup_key(
970                req.module_path,
971                ImportKind::SideEffect,
972                &[],
973                None,
974                None,
975                &modifiers,
976                Some(req.import_kind.unwrap_or("require")),
977            )
978        }
979        LangId::Lua => {
980            let alias = req.default_import.or(req.alias);
981            let kind = if alias.is_some() {
982                ImportKind::Value
983            } else {
984                ImportKind::SideEffect
985            };
986            structured_dedup_key(req.module_path, kind, &[], None, alias, req.modifiers, None)
987        }
988        LangId::Perl => structured_dedup_key(
989            req.module_path,
990            ImportKind::SideEffect,
991            &[],
992            None,
993            None,
994            req.modifiers,
995            Some(req.import_kind.unwrap_or("use")),
996        ),
997        _ => structured_dedup_key(
998            req.module_path,
999            if req.type_only {
1000                ImportKind::Type
1001            } else {
1002                ImportKind::Value
1003            },
1004            req.names,
1005            req.namespace,
1006            req.alias,
1007            req.modifiers,
1008            req.import_kind,
1009        ),
1010    };
1011
1012    canonical_dedup_key(lang, key)
1013}
1014
1015fn structured_dedup_key(
1016    module_path: &str,
1017    kind: ImportKind,
1018    named: &[String],
1019    namespace: Option<&str>,
1020    alias: Option<&str>,
1021    modifiers: &[String],
1022    import_kind: Option<&str>,
1023) -> ImportDedupKey {
1024    ImportDedupKey {
1025        module_path: module_path.to_string(),
1026        kind,
1027        form: ImportForm::Structured {
1028            named: named.to_vec(),
1029            namespace: namespace.map(str::to_string),
1030            alias: alias.map(str::to_string),
1031            modifiers: modifiers.to_vec(),
1032            import_kind: import_kind.map(str::to_string),
1033        },
1034    }
1035}
1036
1037fn wildcard_suffix_request(
1038    module_path: &str,
1039    modifiers: &[String],
1040    wildcard: bool,
1041) -> (String, Vec<String>) {
1042    let stripped = module_path.strip_suffix(".*").unwrap_or(module_path);
1043    let mut modifiers = modifiers.to_vec();
1044    if (wildcard || stripped.len() != module_path.len())
1045        && !modifiers.iter().any(|modifier| modifier == "wildcard")
1046    {
1047        modifiers.push("wildcard".to_string());
1048    }
1049    (stripped.to_string(), modifiers)
1050}
1051
1052fn normalize_java_static_member_key(
1053    module_path: &mut String,
1054    modifiers: &[String],
1055    names: &mut Vec<String>,
1056) {
1057    let is_static = modifiers.iter().any(|modifier| modifier == "static");
1058    let is_wildcard = modifiers.iter().any(|modifier| modifier == "wildcard");
1059    if !is_static || is_wildcard || !names.is_empty() {
1060        return;
1061    }
1062
1063    if let Some((prefix, member)) = module_path.rsplit_once('.') {
1064        if !prefix.is_empty() && !member.is_empty() {
1065            names.push(member.to_string());
1066            *module_path = prefix.to_string();
1067        }
1068    }
1069}
1070
1071fn scala_request_dedup_key(req: &ImportRequest<'_>) -> ImportDedupKey {
1072    let mut module_path = req.module_path.to_string();
1073    let mut names: Vec<String> = req
1074        .names
1075        .iter()
1076        .map(|name| normalize_scala_selector_for_dedup(name))
1077        .collect();
1078    let mut identity_modifiers: Vec<String> = req
1079        .modifiers
1080        .iter()
1081        .filter(|modifier| modifier.as_str() != "scala2")
1082        .cloned()
1083        .collect();
1084    let mut import_kind = req.import_kind.map(str::to_string);
1085
1086    if req.default_import == Some("given") || module_path.ends_with(".given") {
1087        import_kind.get_or_insert_with(|| "given".to_string());
1088        if let Some(stripped) = module_path.strip_suffix(".given") {
1089            module_path = stripped.to_string();
1090        }
1091    }
1092
1093    if matches!(req.default_import, Some("*") | Some("_"))
1094        || matches!(req.namespace, Some("*") | Some("_"))
1095        || module_path.ends_with(".*")
1096        || module_path.ends_with("._")
1097    {
1098        if !identity_modifiers
1099            .iter()
1100            .any(|modifier| modifier == "wildcard")
1101        {
1102            identity_modifiers.push("wildcard".to_string());
1103        }
1104        module_path = module_path
1105            .strip_suffix(".*")
1106            .or_else(|| module_path.strip_suffix("._"))
1107            .unwrap_or(&module_path)
1108            .to_string();
1109    }
1110
1111    if names.is_empty() {
1112        if let Some(alias) = req.alias.filter(|alias| !alias.is_empty()) {
1113            if let Some((prefix, leaf)) = module_path.rsplit_once('.') {
1114                names.push(format!("{leaf} as {alias}"));
1115                module_path = prefix.to_string();
1116            }
1117        }
1118    }
1119
1120    structured_dedup_key(
1121        &module_path,
1122        ImportKind::Value,
1123        &names,
1124        None,
1125        None,
1126        &identity_modifiers,
1127        import_kind.as_deref(),
1128    )
1129}
1130
1131fn normalize_scala_selector_for_dedup(name: &str) -> String {
1132    let trimmed = name.trim();
1133    if let Some((from, to)) = trimmed.split_once("=>") {
1134        format!("{} as {}", from.trim(), to.trim())
1135    } else {
1136        trimmed.to_string()
1137    }
1138}
1139
1140fn canonical_dedup_key(lang: LangId, mut key: ImportDedupKey) -> ImportDedupKey {
1141    match &mut key.form {
1142        ImportForm::Structured { named, .. } | ImportForm::Solidity { named, .. } => {
1143            sort_named_specifiers(named);
1144        }
1145        ImportForm::Es { named, .. } | ImportForm::Python { named, .. } => {
1146            sort_named_specifiers(named);
1147        }
1148        ImportForm::RustUse { named, .. } => {
1149            sort_named_specifiers(named);
1150        }
1151        ImportForm::Go { .. } | ImportForm::Php { .. } => {}
1152    }
1153
1154    if matches!(lang, LangId::Java | LangId::Kotlin) {
1155        if let Some(stripped) = key.module_path.strip_suffix(".*") {
1156            key.module_path = stripped.to_string();
1157        }
1158        if matches!(lang, LangId::Java) {
1159            if let ImportForm::Structured {
1160                named, modifiers, ..
1161            } = &mut key.form
1162            {
1163                normalize_java_static_member_key(&mut key.module_path, modifiers, named);
1164            }
1165        }
1166    } else if matches!(lang, LangId::Scala) {
1167        key.module_path = key
1168            .module_path
1169            .strip_suffix(".given")
1170            .or_else(|| key.module_path.strip_suffix(".*"))
1171            .or_else(|| key.module_path.strip_suffix("._"))
1172            .unwrap_or(&key.module_path)
1173            .to_string();
1174    }
1175
1176    key
1177}
1178
1179test_support_visibility! {
1180fn sort_named_specifiers(names: &mut [String]) {
1181    names.sort_by(|a, b| {
1182        specifier_imported_name(a)
1183            .cmp(specifier_imported_name(b))
1184            .then_with(|| a.cmp(b))
1185    });
1186}
1187}
1188
1189/// Find the byte offset where a new import should be inserted.
1190///
1191/// Strategy:
1192/// - Find all existing imports in the same group.
1193/// - Within that group, find the alphabetical position by module path.
1194/// - Type imports sort after value imports within the same group and module-sort position.
1195/// - If no imports exist in the target group, insert after the last import of the
1196///   nearest preceding group (or before the first import of the nearest following
1197///   group, or at file start if no groups exist).
1198/// - Returns (byte_offset, needs_newline_before, needs_newline_after)
1199pub fn find_insertion_point(
1200    source: &str,
1201    block: &ImportBlock,
1202    group: ImportGroup,
1203    module_path: &str,
1204    type_only: bool,
1205) -> (usize, bool, bool) {
1206    if block.imports.is_empty() {
1207        // No imports at all — insert at start of file
1208        return (0, false, source.is_empty().then_some(false).unwrap_or(true));
1209    }
1210
1211    let target_kind = if type_only {
1212        ImportKind::Type
1213    } else {
1214        ImportKind::Value
1215    };
1216
1217    // Collect imports in the target group
1218    let group_imports: Vec<&ImportStatement> =
1219        block.imports.iter().filter(|i| i.group == group).collect();
1220
1221    if group_imports.is_empty() {
1222        // No imports in this group yet — find nearest neighbor group
1223        // Try preceding groups (lower ordinal) first
1224        let preceding_last = block.imports.iter().filter(|i| i.group < group).last();
1225
1226        if let Some(last) = preceding_last {
1227            let end = last.byte_range.end;
1228            let insert_at = skip_newline(source, end);
1229            return (insert_at, true, true);
1230        }
1231
1232        // No preceding group — try following groups (higher ordinal)
1233        let following_first = block.imports.iter().find(|i| i.group > group);
1234
1235        if let Some(first) = following_first {
1236            return (first.byte_range.start, false, true);
1237        }
1238
1239        // Shouldn't reach here if block is non-empty, but handle gracefully
1240        let first_byte = import_byte_range(&block.imports)
1241            .map(|range| range.start)
1242            .unwrap_or(0);
1243        return (first_byte, false, true);
1244    }
1245
1246    // Find position within the group (alphabetical by module path, type after value)
1247    for imp in &group_imports {
1248        let cmp = module_path.cmp(&imp.module_path);
1249        match cmp {
1250            std::cmp::Ordering::Less => {
1251                // Insert before this import
1252                return (imp.byte_range.start, false, false);
1253            }
1254            std::cmp::Ordering::Equal => {
1255                // Same module — type imports go after value imports
1256                if target_kind == ImportKind::Type && imp.kind == ImportKind::Value {
1257                    // Insert after this value import
1258                    let end = imp.byte_range.end;
1259                    let insert_at = skip_newline(source, end);
1260                    return (insert_at, false, false);
1261                }
1262                // Insert before (or it's a duplicate, caller should have checked)
1263                return (imp.byte_range.start, false, false);
1264            }
1265            std::cmp::Ordering::Greater => continue,
1266        }
1267    }
1268
1269    // Module path sorts after all existing imports in this group — insert at end
1270    let Some(last) = group_imports.last() else {
1271        return (
1272            import_byte_range(&block.imports)
1273                .map(|range| range.end)
1274                .unwrap_or(0),
1275            false,
1276            false,
1277        );
1278    };
1279    let end = last.byte_range.end;
1280    let insert_at = skip_newline(source, end);
1281    (insert_at, false, false)
1282}
1283
1284/// Internal language-aware insertion used by mutations with a parsed source.
1285pub fn find_insertion_point_with_prologue(
1286    source: &str,
1287    tree: &Tree,
1288    lang: LangId,
1289    block: &ImportBlock,
1290    group: ImportGroup,
1291    module_path: &str,
1292    type_only: bool,
1293) -> (usize, bool, bool) {
1294    let c_block;
1295    let block = if matches!(lang, LangId::C | LangId::Cpp) {
1296        c_block = c::c_insertion_block(source, tree, block);
1297        &c_block
1298    } else {
1299        block
1300    };
1301    if !block.imports.is_empty() {
1302        let mut insertion = find_insertion_point(source, block, group, module_path, type_only);
1303        if lang == LangId::Python {
1304            if module_path == "__future__" {
1305                insertion = (
1306                    block.imports.first().unwrap().byte_range.start,
1307                    false,
1308                    false,
1309                );
1310            } else if let Some(last) = block
1311                .imports
1312                .iter()
1313                .filter(|import| import.module_path == "__future__")
1314                .last()
1315            {
1316                insertion.0 = insertion.0.max(skip_newline(source, last.byte_range.end));
1317            }
1318        }
1319        if matches!(lang, LangId::C | LangId::Cpp) {
1320            insertion.1 = false;
1321            insertion.2 = false;
1322        }
1323        return insertion;
1324    }
1325    if lang == LangId::Vue {
1326        if let Some((start, _)) = vue_script_content_range(tree) {
1327            return (skip_newline(source, start), false, false);
1328        }
1329    }
1330    if matches!(lang, LangId::C | LangId::Cpp) {
1331        if let (_, Some(anchor)) = c::default_include_context(source, tree) {
1332            return (skip_newline(source, anchor), false, false);
1333        }
1334    }
1335    let (anchor, blank_before) = import_prologue_anchor(source, tree, lang);
1336    let at = skip_newline(source, anchor);
1337    let next_is_newline = source
1338        .as_bytes()
1339        .get(at)
1340        .is_some_and(|byte| matches!(byte, b'\r' | b'\n'));
1341    (at, blank_before, !next_is_newline && at < source.len())
1342}
1343
1344/// Preserve the language's file-leading declarations and executable string
1345/// directives before placing a new import into an otherwise empty block.
1346fn import_prologue_anchor(source: &str, tree: &Tree, lang: LangId) -> (usize, bool) {
1347    let bom = if source.starts_with('\u{feff}') {
1348        '\u{feff}'.len_utf8()
1349    } else {
1350        0
1351    };
1352    let root = tree.root_node();
1353    let (strong, skippable): (&[&str], &[&str]) = match lang {
1354        LangId::Go => (&["package_clause"], &["comment"]),
1355        LangId::Java => (&["package_declaration"], &["comment"]),
1356        LangId::Kotlin => (&["package_header"], &["comment"]),
1357        LangId::Scala => (&["package_clause"], &["comment"]),
1358        LangId::Solidity => (&["pragma_directive"], &["comment"]),
1359        LangId::Php => (&["php_tag", "namespace_definition"], &["comment"]),
1360        LangId::Perl => (&["package_statement"], &["comment"]),
1361        _ => (&[], &[]),
1362    };
1363    let mut cursor = root.walk();
1364    let mut header = None;
1365    for child in root.named_children(&mut cursor) {
1366        if strong.contains(&child.kind()) {
1367            header = Some(
1368                if lang == LangId::Php && child.kind() == "namespace_definition" {
1369                    let mut cursor = child.walk();
1370                    let brace = child
1371                        .children(&mut cursor)
1372                        .find(|node| node.kind() == "{")
1373                        .map(|node| node.end_byte())
1374                        .or_else(|| {
1375                            crate::parser::node_text(source, &child)
1376                                .find('{')
1377                                .map(|offset| child.start_byte() + offset + 1)
1378                        });
1379                    brace.unwrap_or(child.end_byte())
1380                } else {
1381                    child.end_byte()
1382                },
1383            );
1384        } else if !skippable.contains(&child.kind()) {
1385            break;
1386        }
1387    }
1388    if let Some(header) = header {
1389        return (header, true);
1390    }
1391    let mut anchor = bom;
1392    if matches!(
1393        lang,
1394        LangId::TypeScript
1395            | LangId::Tsx
1396            | LangId::JavaScript
1397            | LangId::Python
1398            | LangId::Ruby
1399            | LangId::Perl
1400            | LangId::Lua
1401    ) && source[bom..].starts_with("#!")
1402    {
1403        anchor = source.find('\n').unwrap_or(source.len());
1404    }
1405    if matches!(
1406        lang,
1407        LangId::TypeScript | LangId::Tsx | LangId::JavaScript | LangId::Python
1408    ) {
1409        // A run of leading comments is skipped only when a blank line or a
1410        // skipped directive/docstring separates it from the code below. A run
1411        // directly above the first ordinary statement documents that statement,
1412        // so the import goes above the run instead of splitting them.
1413        let mut cursor = root.walk();
1414        let mut docstring_seen = false;
1415        // End byte of the pending, still-undecided comment run.
1416        let mut run_end: Option<usize> = None;
1417        for child in root.named_children(&mut cursor) {
1418            if let Some(end) = run_end {
1419                if has_blank_line_between(source, end, child.start_byte()) {
1420                    anchor = anchor.max(end);
1421                    run_end = None;
1422                }
1423            }
1424            if matches!(child.kind(), "comment" | "hash_bang_line") {
1425                if child.end_byte() <= anchor
1426                    || child.kind() == "hash_bang_line"
1427                    || (lang == LangId::Python && is_python_encoding_cookie(source, &child))
1428                {
1429                    // Shebangs and encoding cookies must stay on the file's
1430                    // first lines, so they are always kept above the import.
1431                    anchor = anchor.max(run_end.unwrap_or(0)).max(child.end_byte());
1432                    run_end = None;
1433                } else {
1434                    run_end = Some(child.end_byte());
1435                }
1436            } else if child.kind() == "expression_statement"
1437                && child
1438                    .named_child(0)
1439                    .is_some_and(|expression| expression.kind() == "string")
1440                && (lang != LangId::Python || !docstring_seen)
1441            {
1442                anchor = child.end_byte();
1443                docstring_seen = true;
1444                run_end = None;
1445            } else {
1446                // Any comment run still pending is attached to this statement.
1447                run_end = None;
1448                break;
1449            }
1450        }
1451        // Comments with no code after them document nothing; keep them above.
1452        if let Some(end) = run_end {
1453            anchor = anchor.max(end);
1454        }
1455    }
1456    if lang == LangId::Solidity
1457        && source[bom..]
1458            .trim_start()
1459            .starts_with("// SPDX-License-Identifier:")
1460    {
1461        anchor = source.find('\n').unwrap_or(source.len());
1462    }
1463    (anchor, false)
1464}
1465
1466/// True when the whitespace between two sibling nodes contains an empty line.
1467fn has_blank_line_between(source: &str, end: usize, start: usize) -> bool {
1468    source
1469        .get(end..start)
1470        .is_some_and(|gap| gap.matches('\n').count() >= 2)
1471}
1472
1473/// A PEP 263 source-encoding declaration (`# -*- coding: utf-8 -*-`). Python
1474/// only honours it on the first or second line of the file.
1475fn is_python_encoding_cookie(source: &str, comment: &Node) -> bool {
1476    if comment.start_position().row > 1 {
1477        return false;
1478    }
1479    let text = crate::parser::node_text(source, comment);
1480    text.match_indices("coding").any(|(at, word)| {
1481        let rest = &text[at + word.len()..];
1482        let Some(rest) = rest.strip_prefix([':', '=']) else {
1483            return false;
1484        };
1485        rest.trim_start_matches([' ', '\t'])
1486            .starts_with(|ch: char| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
1487    })
1488}
1489
1490pub fn import_insertion_text(
1491    source: &str,
1492    offset: usize,
1493    line: &str,
1494    before: bool,
1495    after: bool,
1496) -> String {
1497    let ending = crate::indent::source_line_ending(source);
1498    let mut text = String::new();
1499    let prefix = &source[..offset];
1500    if !prefix.trim_start_matches('\u{feff}').is_empty() && !prefix.ends_with('\n') {
1501        text.push_str(ending);
1502    }
1503    if before {
1504        text.push_str(ending);
1505    }
1506    text.push_str(&line.replace("\r\n", "\n").replace('\n', ending));
1507    text.push_str(ending);
1508    if after {
1509        text.push_str(ending);
1510    }
1511    text
1512}
1513
1514/// Generate a single import line from a structured [`ImportRequest`]. The full
1515/// entry point — engines read the fields they support; unsupported languages
1516/// yield an empty string.
1517pub fn generate_import(lang: LangId, req: &ImportRequest) -> String {
1518    match syntax_for(lang) {
1519        Some(engine) => engine.generate_line(req),
1520        None => String::new(),
1521    }
1522}
1523
1524/// Generate an import line for the given language. Back-compat wrapper over
1525/// [`generate_import`] for callers that pass only the legacy positional fields.
1526pub fn generate_import_line(
1527    lang: LangId,
1528    module_path: &str,
1529    names: &[String],
1530    default_import: Option<&str>,
1531    type_only: bool,
1532) -> String {
1533    generate_import(
1534        lang,
1535        &ImportRequest::legacy(module_path, names, default_import, None, type_only),
1536    )
1537}
1538
1539/// Generate an import line including namespace imports
1540/// (`import * as ns from 'mod'`). Back-compat wrapper over [`generate_import`].
1541pub fn generate_import_line_with_namespace(
1542    lang: LangId,
1543    module_path: &str,
1544    names: &[String],
1545    default_import: Option<&str>,
1546    namespace_import: Option<&str>,
1547    type_only: bool,
1548) -> String {
1549    generate_import_line_with_namespace_and_attribute_clause(
1550        lang,
1551        module_path,
1552        names,
1553        default_import,
1554        namespace_import,
1555        type_only,
1556        None,
1557    )
1558}
1559
1560/// Generate a line while retaining an existing ES import-attribute clause.
1561/// Other language engines ignore the clause because it has no meaning there.
1562pub fn generate_import_line_with_namespace_and_attribute_clause(
1563    lang: LangId,
1564    module_path: &str,
1565    names: &[String],
1566    default_import: Option<&str>,
1567    namespace_import: Option<&str>,
1568    type_only: bool,
1569    attribute_clause: Option<&str>,
1570) -> String {
1571    generate_import_line_with_namespace_and_attribute_clause_and_style(
1572        lang,
1573        module_path,
1574        names,
1575        default_import,
1576        namespace_import,
1577        type_only,
1578        attribute_clause,
1579        None,
1580    )
1581}
1582
1583/// Generate a line spelled with `style` (quote and terminator) for ES
1584/// languages; `None` uses [`quotes::EsImportStyle::default`]. Other language
1585/// engines ignore the style.
1586pub fn generate_import_line_with_namespace_and_attribute_clause_and_style(
1587    lang: LangId,
1588    module_path: &str,
1589    names: &[String],
1590    default_import: Option<&str>,
1591    namespace_import: Option<&str>,
1592    type_only: bool,
1593    attribute_clause: Option<&str>,
1594    style: Option<quotes::EsImportStyle>,
1595) -> String {
1596    if matches!(
1597        lang,
1598        LangId::TypeScript | LangId::Tsx | LangId::JavaScript | LangId::Vue
1599    ) {
1600        return generate_ts_import_line_with_attribute_clause(
1601            module_path,
1602            names,
1603            default_import,
1604            namespace_import,
1605            type_only,
1606            attribute_clause,
1607            style.unwrap_or_default(),
1608        );
1609    }
1610
1611    generate_import(
1612        lang,
1613        &ImportRequest::legacy(
1614            module_path,
1615            names,
1616            default_import,
1617            namespace_import,
1618            type_only,
1619        ),
1620    )
1621}
1622
1623/// Check if the given language is supported by the import engine.
1624pub fn is_supported(lang: LangId) -> bool {
1625    syntax_for(lang).is_some()
1626}
1627
1628/// Classify a module path into a group for TS/JS/TSX.
1629pub fn classify_group_ts(module_path: &str) -> ImportGroup {
1630    if module_path.starts_with('.') {
1631        ImportGroup::Internal
1632    } else {
1633        ImportGroup::External
1634    }
1635}
1636
1637/// Classify a module path into a group for the given language.
1638pub fn classify_group(lang: LangId, module_path: &str) -> ImportGroup {
1639    match syntax_for(lang) {
1640        Some(engine) => engine.classify_group(module_path),
1641        // Unsupported languages have no grouping policy; External is the
1642        // historical neutral default.
1643        None => ImportGroup::External,
1644    }
1645}
1646
1647/// Parse a file from disk and return its import block.
1648/// Convenience wrapper that handles parsing.
1649pub fn parse_file_imports(
1650    path: &std::path::Path,
1651    lang: LangId,
1652) -> Result<(String, Tree, ImportBlock), crate::error::AftError> {
1653    let source =
1654        std::fs::read_to_string(path).map_err(|e| crate::error::AftError::FileNotFound {
1655            path: format!("{}: {}", path.display(), e),
1656        })?;
1657
1658    // This thread's retained parser: building a parser and loading the grammar
1659    // per call was a fixed cost on every file an imports scan visits.
1660    let tree = crate::parser::parse_source_with_cached_parser(path, &source, lang)?;
1661
1662    let block = parse_imports(&source, &tree, lang);
1663    Ok((source, tree, block))
1664}
1665
1666// ---------------------------------------------------------------------------
1667// TS/JS/TSX implementation
1668// ---------------------------------------------------------------------------
1669
1670/// Parse imports from a TS/JS/TSX file.
1671///
1672/// Walks the AST root's direct children looking for `import_statement` nodes (D041).
1673fn parse_ts_imports(source: &str, tree: &Tree) -> ImportBlock {
1674    let root = tree.root_node();
1675    let mut imports = Vec::new();
1676
1677    let mut cursor = root.walk();
1678    if !cursor.goto_first_child() {
1679        return ImportBlock::empty();
1680    }
1681
1682    loop {
1683        let node = cursor.node();
1684        if node.kind() == "import_statement" {
1685            if let Some(imp) = parse_single_ts_import(source, &node) {
1686                imports.push(imp);
1687            }
1688        }
1689        if !cursor.goto_next_sibling() {
1690            break;
1691        }
1692    }
1693
1694    let byte_range = import_byte_range(&imports);
1695
1696    ImportBlock {
1697        imports,
1698        byte_range,
1699    }
1700}
1701
1702/// Parse a single `import_statement` node into an `ImportStatement`.
1703fn parse_single_ts_import(source: &str, node: &Node) -> Option<ImportStatement> {
1704    let raw_text = source[node.byte_range()].to_string();
1705    let byte_range = node.byte_range();
1706
1707    // Find the source module (string/string_fragment child of the import)
1708    let module_path = node
1709        .child_by_field_name("source")
1710        .and_then(|module| decode_js_attribute_atom(&source[module.byte_range()]))
1711        .or_else(|| extract_module_path(source, node))?;
1712
1713    // Determine if this is a type-only import: `import type ...`
1714    let is_type_only = has_type_keyword(node);
1715
1716    // Extract import clause details
1717    let mut names = Vec::new();
1718    let mut default_import = None;
1719    let mut namespace_import = None;
1720
1721    let mut child_cursor = node.walk();
1722    if child_cursor.goto_first_child() {
1723        loop {
1724            let child = child_cursor.node();
1725            match child.kind() {
1726                "import_clause" => {
1727                    extract_import_clause(
1728                        source,
1729                        &child,
1730                        &mut names,
1731                        &mut default_import,
1732                        &mut namespace_import,
1733                    );
1734                }
1735                // In some grammars, the default import is a direct identifier child
1736                "identifier" => {
1737                    let text = &source[child.byte_range()];
1738                    if text != "import" && text != "from" && text != "type" {
1739                        default_import = Some(text.to_string());
1740                    }
1741                }
1742                _ => {}
1743            }
1744            if !child_cursor.goto_next_sibling() {
1745                break;
1746            }
1747        }
1748    }
1749
1750    // Classify kind
1751    let kind = if names.is_empty() && default_import.is_none() && namespace_import.is_none() {
1752        ImportKind::SideEffect
1753    } else if is_type_only {
1754        ImportKind::Type
1755    } else {
1756        ImportKind::Value
1757    };
1758
1759    let group = classify_group_ts(&module_path);
1760
1761    let attribute_clause = extract_es_import_attribute_clause(source, node);
1762    let attribute_type = attribute_clause
1763        .as_deref()
1764        .and_then(parse_es_import_attribute_type);
1765    let form = ImportForm::Es {
1766        default_import: default_import.clone(),
1767        namespace_import: namespace_import.clone(),
1768        named: names.clone(),
1769        type_only: is_type_only,
1770        side_effect: matches!(kind, ImportKind::SideEffect),
1771        attribute_clause,
1772        attribute_type,
1773    };
1774
1775    Some(ImportStatement {
1776        module_path,
1777        names,
1778        default_import,
1779        namespace_import,
1780        kind,
1781        group,
1782        byte_range,
1783        raw_text,
1784        form,
1785    })
1786}
1787
1788/// Capture the exact source spelling because `with` and legacy `assert`
1789/// clauses have the same semantics but must not be normalized during a rewrite.
1790fn extract_es_import_attribute_clause(source: &str, node: &Node) -> Option<String> {
1791    let mut cursor = node.walk();
1792    if !cursor.goto_first_child() {
1793        return None;
1794    }
1795
1796    let module_end = loop {
1797        let child = cursor.node();
1798        if child.kind() == "string" {
1799            break child.end_byte();
1800        }
1801        if !cursor.goto_next_sibling() {
1802            return None;
1803        }
1804    };
1805
1806    let tail = source[module_end..node.end_byte()].trim();
1807    let clause = tail.strip_suffix(';').unwrap_or(tail).trim();
1808    (clause.starts_with("with") || clause.starts_with("assert")).then(|| clause.to_string())
1809}
1810
1811/// Return the semantic import-attribute clause attached to an ES import.
1812pub fn es_import_attribute_clause(imp: &ImportStatement) -> Option<&str> {
1813    match &imp.form {
1814        ImportForm::Es {
1815            attribute_clause, ..
1816        } => attribute_clause.as_deref(),
1817        _ => None,
1818    }
1819}
1820
1821/// Return the semantic value of an ES import's `type` attribute.
1822pub fn es_import_attribute_type(imp: &ImportStatement) -> Option<&str> {
1823    match &imp.form {
1824        ImportForm::Es { attribute_type, .. } => attribute_type.as_deref(),
1825        _ => None,
1826    }
1827}
1828
1829/// Decode the module type through one canonical parse. Legacy `assert` and current
1830/// `with` clauses carry the same attribute semantics even though their spelling
1831/// must remain unchanged when the original import is rewritten.
1832fn parse_es_import_attribute_type(clause: &str) -> Option<String> {
1833    let body = ["with", "assert"].into_iter().find_map(|keyword| {
1834        let rest = clause.strip_prefix(keyword)?;
1835        rest.chars()
1836            .next()
1837            .is_some_and(|ch| ch.is_whitespace() || ch == '{' || ch == '/')
1838            .then_some(rest)
1839    })?;
1840    let synthetic = format!("import 'module' with{body};");
1841    let tree = crate::parser::parse_source_with_cached_parser(
1842        std::path::Path::new("<import attributes>"),
1843        &synthetic,
1844        LangId::TypeScript,
1845    )
1846    .ok()?;
1847    (!tree.root_node().has_error())
1848        .then(|| find_type_attribute(&synthetic, tree.root_node()))
1849        .flatten()
1850}
1851
1852fn find_type_attribute(source: &str, node: Node<'_>) -> Option<String> {
1853    if node.kind() == "pair" {
1854        let key = node
1855            .child_by_field_name("key")
1856            .or_else(|| node.named_child(0))?;
1857        let value = node
1858            .child_by_field_name("value")
1859            .or_else(|| node.named_child(1))?;
1860        if decode_js_attribute_atom(source.get(key.byte_range())?)?.as_str() == "type" {
1861            return decode_js_attribute_atom(source.get(value.byte_range())?);
1862        }
1863    }
1864
1865    let mut cursor = node.walk();
1866    let found = node
1867        .children(&mut cursor)
1868        .find_map(|child| find_type_attribute(source, child));
1869    found
1870}
1871
1872fn decode_js_attribute_atom(text: &str) -> Option<String> {
1873    let text = text.trim();
1874    let quote = text.as_bytes().first().copied();
1875    if !matches!(quote, Some(b'\'') | Some(b'"')) {
1876        return Some(text.to_string());
1877    }
1878    if text.as_bytes().last().copied() != quote || text.len() < 2 {
1879        return None;
1880    }
1881
1882    let mut chars = text[1..text.len() - 1].chars();
1883    let mut decoded = String::new();
1884    while let Some(ch) = chars.next() {
1885        if ch != '\\' {
1886            decoded.push(ch);
1887            continue;
1888        }
1889
1890        match chars.next()? {
1891            '\n' => {}
1892            '\r' => {
1893                if chars.clone().next() == Some('\n') {
1894                    chars.next();
1895                }
1896            }
1897            'b' => decoded.push('\u{0008}'),
1898            'f' => decoded.push('\u{000c}'),
1899            'n' => decoded.push('\n'),
1900            'r' => decoded.push('\r'),
1901            't' => decoded.push('\t'),
1902            'v' => decoded.push('\u{000b}'),
1903            '0' => decoded.push('\0'),
1904            'x' => decoded.push(decode_hex_escape(&mut chars, 2)?),
1905            'u' => {
1906                let digits = if chars.clone().next() == Some('{') {
1907                    chars.next();
1908                    let mut digits = String::new();
1909                    loop {
1910                        let ch = chars.next()?;
1911                        if ch == '}' {
1912                            break;
1913                        }
1914                        digits.push(ch);
1915                    }
1916                    digits
1917                } else {
1918                    chars.by_ref().take(4).collect()
1919                };
1920                decoded.push(char::from_u32(u32::from_str_radix(&digits, 16).ok()?)?);
1921            }
1922            escaped => decoded.push(escaped),
1923        }
1924    }
1925    Some(decoded)
1926}
1927
1928fn decode_hex_escape(chars: &mut impl Iterator<Item = char>, count: usize) -> Option<char> {
1929    let digits: String = chars.take(count).collect();
1930    (digits.len() == count)
1931        .then(|| u32::from_str_radix(&digits, 16).ok())
1932        .flatten()
1933        .and_then(char::from_u32)
1934}
1935
1936/// Extract the module path string from an import_statement node.
1937///
1938/// Looks for a `string` child node and extracts the content without quotes.
1939fn extract_module_path(source: &str, node: &Node) -> Option<String> {
1940    let mut cursor = node.walk();
1941    if !cursor.goto_first_child() {
1942        return None;
1943    }
1944
1945    loop {
1946        let child = cursor.node();
1947        if child.kind() == "string" {
1948            // Get the text and strip quotes
1949            let text = &source[child.byte_range()];
1950            let stripped = text
1951                .trim_start_matches(|c| c == '\'' || c == '"')
1952                .trim_end_matches(|c| c == '\'' || c == '"');
1953            return Some(stripped.to_string());
1954        }
1955        if !cursor.goto_next_sibling() {
1956            break;
1957        }
1958    }
1959    None
1960}
1961
1962/// Check if the import_statement has a `type` keyword (import type ...).
1963///
1964/// In tree-sitter-typescript, `import type { X } from 'y'` produces a `type`
1965/// node as a direct child of `import_statement`, between `import` and `import_clause`.
1966fn has_type_keyword(node: &Node) -> bool {
1967    let mut cursor = node.walk();
1968    if !cursor.goto_first_child() {
1969        return false;
1970    }
1971
1972    loop {
1973        let child = cursor.node();
1974        if child.kind() == "type" {
1975            return true;
1976        }
1977        if !cursor.goto_next_sibling() {
1978            break;
1979        }
1980    }
1981
1982    false
1983}
1984
1985/// Extract named imports, default import, and namespace import from an import_clause.
1986fn extract_import_clause(
1987    source: &str,
1988    node: &Node,
1989    names: &mut Vec<String>,
1990    default_import: &mut Option<String>,
1991    namespace_import: &mut Option<String>,
1992) {
1993    let mut cursor = node.walk();
1994    if !cursor.goto_first_child() {
1995        return;
1996    }
1997
1998    loop {
1999        let child = cursor.node();
2000        match child.kind() {
2001            "identifier" => {
2002                // This is a default import: `import Foo from 'bar'`
2003                let text = &source[child.byte_range()];
2004                if text != "type" {
2005                    *default_import = Some(text.to_string());
2006                }
2007            }
2008            "named_imports" => {
2009                // `{ name1, name2 }`
2010                extract_named_imports(source, &child, names);
2011            }
2012            "namespace_import" => {
2013                // `* as name`
2014                extract_namespace_import(source, &child, namespace_import);
2015            }
2016            _ => {}
2017        }
2018        if !cursor.goto_next_sibling() {
2019            break;
2020        }
2021    }
2022}
2023
2024/// Extract individual names from a named_imports node (`{ a, b, c }`).
2025///
2026/// Each name is stored verbatim including any alias and per-name `type`
2027/// modifier so the regenerator can round-trip them losslessly. Examples of
2028/// captured forms:
2029///
2030/// - `useState`               (plain)
2031/// - `stdin as input`         (renamed)
2032/// - `type Foo`               (per-specifier type-only)
2033/// - `type Foo as Bar`        (per-specifier type-only with rename)
2034///
2035/// **Why verbatim strings instead of a struct field per attribute:** dedup,
2036/// sort, dropping a single import, and the regenerator are all driven by
2037/// `Vec<String>` today. Encoding the alias inside the string preserves the
2038/// shape so the rest of the pipeline (organize, remove_import, move_symbol)
2039/// keeps working without a workspace-wide refactor. The cost is that callers
2040/// who want the canonical name (e.g. dedup) must compare on the leading
2041/// identifier only — see `extract_canonical_name` if you need that.
2042fn extract_named_imports(source: &str, node: &Node, names: &mut Vec<String>) {
2043    let mut cursor = node.walk();
2044    if !cursor.goto_first_child() {
2045        return;
2046    }
2047
2048    loop {
2049        let child = cursor.node();
2050        if child.kind() == "import_specifier" {
2051            // Capture the full text of the specifier so per-name `type` markers
2052            // and `as alias` clauses are preserved across organize/regenerate
2053            // round-trips. Falls back to the imported name if the specifier
2054            // text is empty for any reason.
2055            let raw = source[child.byte_range()].trim().to_string();
2056            if !raw.is_empty() {
2057                names.push(raw);
2058            } else if let Some(name_node) = child.child_by_field_name("name") {
2059                names.push(source[name_node.byte_range()].to_string());
2060            }
2061        }
2062        if !cursor.goto_next_sibling() {
2063            break;
2064        }
2065    }
2066}
2067
2068/// Extract the alias name from a namespace_import node (`* as name`).
2069fn extract_namespace_import(source: &str, node: &Node, namespace_import: &mut Option<String>) {
2070    let mut cursor = node.walk();
2071    if !cursor.goto_first_child() {
2072        return;
2073    }
2074
2075    loop {
2076        let child = cursor.node();
2077        if child.kind() == "identifier" {
2078            *namespace_import = Some(source[child.byte_range()].to_string());
2079            return;
2080        }
2081        if !cursor.goto_next_sibling() {
2082            break;
2083        }
2084    }
2085}
2086
2087/// Generate an import line for TS/JS/TSX.
2088fn generate_ts_import_line(
2089    module_path: &str,
2090    names: &[String],
2091    default_import: Option<&str>,
2092    namespace_import: Option<&str>,
2093    type_only: bool,
2094) -> String {
2095    generate_ts_import_line_with_attribute_clause(
2096        module_path,
2097        names,
2098        default_import,
2099        namespace_import,
2100        type_only,
2101        None,
2102        quotes::EsImportStyle::default(),
2103    )
2104}
2105
2106fn generate_ts_import_line_with_attribute_clause(
2107    module_path: &str,
2108    names: &[String],
2109    default_import: Option<&str>,
2110    namespace_import: Option<&str>,
2111    type_only: bool,
2112    attribute_clause: Option<&str>,
2113    style: quotes::EsImportStyle,
2114) -> String {
2115    let mut line = generate_ts_import_line_base(
2116        module_path,
2117        names,
2118        default_import,
2119        namespace_import,
2120        type_only,
2121        style.quote,
2122    );
2123    if let Some(attribute_clause) = attribute_clause {
2124        line.push(' ');
2125        line.push_str(attribute_clause.trim());
2126    }
2127    if style.semicolon {
2128        line.push(';');
2129    }
2130    line
2131}
2132
2133/// The statement without its terminator, which the caller adds per style.
2134fn generate_ts_import_line_base(
2135    module_path: &str,
2136    names: &[String],
2137    default_import: Option<&str>,
2138    namespace_import: Option<&str>,
2139    type_only: bool,
2140    quote: char,
2141) -> String {
2142    let module_path = quotes::module_literal(module_path, quote);
2143    let type_prefix = if type_only { "type " } else { "" };
2144
2145    // Side-effect import
2146    if names.is_empty() && default_import.is_none() && namespace_import.is_none() {
2147        return format!("import {module_path}");
2148    }
2149
2150    // Namespace import only
2151    if names.is_empty() && default_import.is_none() {
2152        if let Some(namespace) = namespace_import {
2153            return format!("import {type_prefix}* as {namespace} from {module_path}");
2154        }
2155    }
2156
2157    // Default + namespace import
2158    if names.is_empty() {
2159        if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
2160            return format!("import {type_prefix}{def}, * as {namespace} from {module_path}");
2161        }
2162    }
2163
2164    // Default import only
2165    if names.is_empty() && namespace_import.is_none() {
2166        if let Some(def) = default_import {
2167            return format!("import {type_prefix}{def} from {module_path}");
2168        }
2169    }
2170
2171    // Named imports only
2172    if default_import.is_none() && namespace_import.is_none() {
2173        let mut sorted_names = names.to_vec();
2174        sort_named_specifiers(&mut sorted_names);
2175        let names_str = sorted_names.join(", ");
2176        return format!("import {type_prefix}{{ {names_str} }} from {module_path}");
2177    }
2178
2179    // Namespace + named imports
2180    if default_import.is_none() {
2181        if let Some(namespace) = namespace_import {
2182            let mut sorted_names = names.to_vec();
2183            sort_named_specifiers(&mut sorted_names);
2184            let names_str = sorted_names.join(", ");
2185            return format!(
2186                "import {type_prefix}{{ {names_str} }}, * as {namespace} from {module_path}"
2187            );
2188        }
2189    }
2190
2191    // Default + named + namespace imports
2192    if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
2193        let mut sorted_names = names.to_vec();
2194        sort_named_specifiers(&mut sorted_names);
2195        let names_str = sorted_names.join(", ");
2196        return format!(
2197            "import {type_prefix}{def}, {{ {names_str} }}, * as {namespace} from {module_path}"
2198        );
2199    }
2200
2201    // Both default and named imports
2202    if let Some(def) = default_import {
2203        let mut sorted_names = names.to_vec();
2204        sort_named_specifiers(&mut sorted_names);
2205        let names_str = sorted_names.join(", ");
2206        return format!("import {type_prefix}{def}, {{ {names_str} }} from {module_path}");
2207    }
2208
2209    // Shouldn't reach here, but handle gracefully
2210    format!("import {module_path}")
2211}
2212
2213test_support_visibility! {
2214// ---------------------------------------------------------------------------
2215// Python implementation
2216// ---------------------------------------------------------------------------
2217
2218/// Sorted union of commonly used Python 3.x standard-library modules, including
2219/// platform-specific names from `sys.stdlib_module_names` (Python 3.10+).
2220/// Older entries remain recognized for projects using earlier Python versions.
2221/// Reference: https://docs.python.org/3/library/sys.html#sys.stdlib_module_names
2222const PYTHON_STDLIB: &[&str] = &[
2223    "__future__",
2224    "_thread",
2225    "abc",
2226    "aifc",
2227    "argparse",
2228    "array",
2229    "ast",
2230    "asynchat",
2231    "asyncio",
2232    "asyncore",
2233    "atexit",
2234    "audioop",
2235    "base64",
2236    "bdb",
2237    "binascii",
2238    "bisect",
2239    "builtins",
2240    "bz2",
2241    "cProfile",
2242    "calendar",
2243    "cgi",
2244    "cgitb",
2245    "chunk",
2246    "cmath",
2247    "cmd",
2248    "code",
2249    "codecs",
2250    "codeop",
2251    "collections",
2252    "colorsys",
2253    "compileall",
2254    "concurrent",
2255    "configparser",
2256    "contextlib",
2257    "contextvars",
2258    "copy",
2259    "copyreg",
2260    "crypt",
2261    "csv",
2262    "ctypes",
2263    "curses",
2264    "dataclasses",
2265    "datetime",
2266    "dbm",
2267    "decimal",
2268    "difflib",
2269    "dis",
2270    "distutils",
2271    "doctest",
2272    "email",
2273    "encodings",
2274    "enum",
2275    "errno",
2276    "faulthandler",
2277    "fcntl",
2278    "filecmp",
2279    "fileinput",
2280    "fnmatch",
2281    "fractions",
2282    "ftplib",
2283    "functools",
2284    "gc",
2285    "getopt",
2286    "getpass",
2287    "gettext",
2288    "glob",
2289    "graphlib",
2290    "grp",
2291    "gzip",
2292    "hashlib",
2293    "heapq",
2294    "hmac",
2295    "html",
2296    "http",
2297    "idlelib",
2298    "imaplib",
2299    "imghdr",
2300    "importlib",
2301    "inspect",
2302    "io",
2303    "ipaddress",
2304    "itertools",
2305    "json",
2306    "keyword",
2307    "lib2to3",
2308    "linecache",
2309    "locale",
2310    "logging",
2311    "lzma",
2312    "mailbox",
2313    "mailcap",
2314    "marshal",
2315    "math",
2316    "mimetypes",
2317    "mmap",
2318    "modulefinder",
2319    "msvcrt",
2320    "multiprocessing",
2321    "netrc",
2322    "ntpath",
2323    "numbers",
2324    "operator",
2325    "optparse",
2326    "os",
2327    "pathlib",
2328    "pdb",
2329    "pickle",
2330    "pickletools",
2331    "pipes",
2332    "pkgutil",
2333    "platform",
2334    "plistlib",
2335    "poplib",
2336    "posix",
2337    "posixpath",
2338    "pprint",
2339    "profile",
2340    "pstats",
2341    "pty",
2342    "pwd",
2343    "py_compile",
2344    "pyclbr",
2345    "pydoc",
2346    "queue",
2347    "quopri",
2348    "random",
2349    "re",
2350    "readline",
2351    "reprlib",
2352    "resource",
2353    "rlcompleter",
2354    "runpy",
2355    "sched",
2356    "secrets",
2357    "select",
2358    "selectors",
2359    "shelve",
2360    "shlex",
2361    "shutil",
2362    "signal",
2363    "site",
2364    "smtplib",
2365    "sndhdr",
2366    "socket",
2367    "socketserver",
2368    "sqlite3",
2369    "ssl",
2370    "stat",
2371    "statistics",
2372    "string",
2373    "stringprep",
2374    "struct",
2375    "subprocess",
2376    "symtable",
2377    "sys",
2378    "sysconfig",
2379    "syslog",
2380    "tabnanny",
2381    "tarfile",
2382    "tempfile",
2383    "termios",
2384    "textwrap",
2385    "threading",
2386    "time",
2387    "timeit",
2388    "tkinter",
2389    "token",
2390    "tokenize",
2391    "tomllib",
2392    "trace",
2393    "traceback",
2394    "tracemalloc",
2395    "tty",
2396    "turtle",
2397    "types",
2398    "typing",
2399    "unicodedata",
2400    "unittest",
2401    "urllib",
2402    "uuid",
2403    "venv",
2404    "warnings",
2405    "wave",
2406    "weakref",
2407    "webbrowser",
2408    "winreg",
2409    "winsound",
2410    "wsgiref",
2411    "xml",
2412    "xmlrpc",
2413    "zipapp",
2414    "zipfile",
2415    "zipimport",
2416    "zlib",
2417    "zoneinfo",
2418];
2419}
2420
2421/// Classify a Python import into a group.
2422pub fn classify_group_py(module_path: &str) -> ImportGroup {
2423    // Relative imports start with '.'
2424    if module_path.starts_with('.') {
2425        return ImportGroup::Internal;
2426    }
2427    // Check stdlib: use the top-level module name (before first '.')
2428    let top_module = module_path.split('.').next().unwrap_or(module_path);
2429    if PYTHON_STDLIB
2430        .binary_search_by(|module| {
2431            #[cfg(any(test, feature = "test-support"))]
2432            PYTHON_STDLIB_COMPARISONS.with(|count| count.set(count.get() + 1));
2433            module.cmp(&top_module)
2434        })
2435        .is_ok()
2436    {
2437        ImportGroup::Stdlib
2438    } else {
2439        ImportGroup::External
2440    }
2441}
2442
2443/// Parse imports from a Python file.
2444fn parse_py_imports(source: &str, tree: &Tree) -> ImportBlock {
2445    let root = tree.root_node();
2446    let mut imports = Vec::new();
2447
2448    let mut cursor = root.walk();
2449    if !cursor.goto_first_child() {
2450        return ImportBlock::empty();
2451    }
2452
2453    loop {
2454        let node = cursor.node();
2455        match node.kind() {
2456            "import_statement" => {
2457                if let Some(imp) = parse_py_import_statement(source, &node) {
2458                    imports.push(imp);
2459                }
2460            }
2461            "import_from_statement" | "future_import_statement" => {
2462                if let Some(imp) = parse_py_import_from_statement(source, &node) {
2463                    imports.push(imp);
2464                }
2465            }
2466            _ => {}
2467        }
2468        if !cursor.goto_next_sibling() {
2469            break;
2470        }
2471    }
2472
2473    let byte_range = import_byte_range(&imports);
2474
2475    ImportBlock {
2476        imports,
2477        byte_range,
2478    }
2479}
2480
2481/// Parse one Python import without imposing the import editor's top-level boundary.
2482pub fn parse_py_import_node(source: &str, node: &Node) -> Option<ImportStatement> {
2483    match node.kind() {
2484        "import_statement" => parse_py_import_statement(source, node),
2485        "import_from_statement" | "future_import_statement" => {
2486            parse_py_import_from_statement(source, node)
2487        }
2488        _ => None,
2489    }
2490}
2491
2492/// Parse `import X` or `import X.Y` Python statements.
2493fn parse_py_import_statement(source: &str, node: &Node) -> Option<ImportStatement> {
2494    let raw_text = source[node.byte_range()].to_string();
2495    let byte_range = node.byte_range();
2496
2497    // Keep every module specifier verbatim. A single Python import statement can
2498    // bind several modules, and aliases must remain in the model so removing or
2499    // merging one binding cannot silently delete its siblings.
2500    let mut specifiers = Vec::new();
2501    let mut c = node.walk();
2502    if c.goto_first_child() {
2503        loop {
2504            let child = c.node();
2505            if matches!(child.kind(), "dotted_name" | "aliased_import") {
2506                specifiers.push(source[child.byte_range()].trim().to_string());
2507            }
2508            if !c.goto_next_sibling() {
2509                break;
2510            }
2511        }
2512    }
2513    let module_path = specifiers
2514        .first()
2515        .map(|specifier| specifier_imported_name(specifier).to_string())?;
2516
2517    let group = classify_group_py(&module_path);
2518
2519    Some(ImportStatement {
2520        module_path,
2521        names: Vec::new(),
2522        default_import: None,
2523        namespace_import: None,
2524        kind: ImportKind::Value,
2525        group,
2526        byte_range,
2527        raw_text,
2528        form: ImportForm::Python {
2529            from_import: false,
2530            named: specifiers,
2531        },
2532    })
2533}
2534
2535/// Parse `from X import Y, Z` or `from . import Y` Python statements.
2536fn parse_py_import_from_statement(source: &str, node: &Node) -> Option<ImportStatement> {
2537    let raw_text = source[node.byte_range()].to_string();
2538    let byte_range = node.byte_range();
2539
2540    let mut module_path = if node.kind() == "future_import_statement" {
2541        "__future__".to_string()
2542    } else {
2543        String::new()
2544    };
2545    let mut names = Vec::new();
2546
2547    let mut c = node.walk();
2548    if c.goto_first_child() {
2549        loop {
2550            let child = c.node();
2551            match child.kind() {
2552                "dotted_name" => {
2553                    // Could be the module name or an imported name
2554                    // The module name comes right after `from`, imported names come after `import`
2555                    // Use position: if we haven't set module_path yet and this comes
2556                    // before the `import` keyword, it's the module.
2557                    if module_path.is_empty()
2558                        && !has_seen_import_keyword(source, node, child.start_byte())
2559                    {
2560                        module_path = source[child.byte_range()].to_string();
2561                    } else {
2562                        // It's an imported name
2563                        names.push(source[child.byte_range()].to_string());
2564                    }
2565                }
2566                "relative_import" => {
2567                    // from . import X or from ..module import X
2568                    module_path = source[child.byte_range()].to_string();
2569                }
2570                "aliased_import" => {
2571                    // Store the full `source as local` spelling so later edits
2572                    // can match either name and reproduce the alias unchanged.
2573                    names.push(source[child.byte_range()].trim().to_string());
2574                }
2575                _ => {}
2576            }
2577            if !c.goto_next_sibling() {
2578                break;
2579            }
2580        }
2581    }
2582
2583    // module_path must be non-empty for a valid import
2584    if module_path.is_empty() {
2585        return None;
2586    }
2587
2588    let group = classify_group_py(&module_path);
2589
2590    Some(ImportStatement {
2591        module_path,
2592        names: names.clone(),
2593        default_import: None,
2594        namespace_import: None,
2595        kind: ImportKind::Value,
2596        group,
2597        byte_range,
2598        raw_text,
2599        form: ImportForm::Python {
2600            from_import: true,
2601            named: names,
2602        },
2603    })
2604}
2605
2606/// Check if the `import` keyword appears before the given byte position in a from...import node.
2607fn has_seen_import_keyword(_source: &str, parent: &Node, before_byte: usize) -> bool {
2608    let mut c = parent.walk();
2609    if c.goto_first_child() {
2610        loop {
2611            let child = c.node();
2612            if child.kind() == "import" && child.start_byte() < before_byte {
2613                return true;
2614            }
2615            if child.start_byte() >= before_byte {
2616                return false;
2617            }
2618            if !c.goto_next_sibling() {
2619                break;
2620            }
2621        }
2622    }
2623    false
2624}
2625
2626/// Generate a Python import line.
2627fn generate_py_import_line(
2628    module_path: &str,
2629    names: &[String],
2630    _default_import: Option<&str>,
2631) -> String {
2632    if names.is_empty() {
2633        // `import module`
2634        format!("import {module_path}")
2635    } else {
2636        // `from module import name1, name2`
2637        let mut sorted = names.to_vec();
2638        sorted.sort();
2639        let names_str = sorted.join(", ");
2640        format!("from {module_path} import {names_str}")
2641    }
2642}
2643
2644// ---------------------------------------------------------------------------
2645// Rust implementation
2646// ---------------------------------------------------------------------------
2647
2648/// Classify a Rust use path into a group.
2649pub fn classify_group_rs(module_path: &str) -> ImportGroup {
2650    // Extract the first path segment (before ::)
2651    let first_seg = module_path.split("::").next().unwrap_or(module_path);
2652    match first_seg {
2653        "std" | "core" | "alloc" => ImportGroup::Stdlib,
2654        "crate" | "self" | "super" => ImportGroup::Internal,
2655        _ => ImportGroup::External,
2656    }
2657}
2658
2659/// Parse imports from a Rust file.
2660fn parse_rs_imports(source: &str, tree: &Tree) -> ImportBlock {
2661    let root = tree.root_node();
2662    let mut imports = Vec::new();
2663
2664    let mut cursor = root.walk();
2665    if !cursor.goto_first_child() {
2666        return ImportBlock::empty();
2667    }
2668
2669    loop {
2670        let node = cursor.node();
2671        if node.kind() == "use_declaration" {
2672            if let Some(imp) = parse_rs_use_declaration(source, &node) {
2673                imports.push(imp);
2674            }
2675        }
2676        if !cursor.goto_next_sibling() {
2677            break;
2678        }
2679    }
2680
2681    let byte_range = import_byte_range(&imports);
2682
2683    ImportBlock {
2684        imports,
2685        byte_range,
2686    }
2687}
2688
2689/// Parse a single `use` declaration from Rust.
2690fn parse_rs_use_declaration(source: &str, node: &Node) -> Option<ImportStatement> {
2691    let raw_text = source[node.byte_range()].to_string();
2692    let byte_range = node.byte_range();
2693
2694    // Capture the EXACT visibility modifier text (`pub`, `pub(crate)`,
2695    // `pub(super)`, `pub(in path)`) so organize re-emits it faithfully instead
2696    // of widening every restricted visibility to a bare `pub`.
2697    let mut visibility: Option<String> = None;
2698    let mut use_path = String::new();
2699    let mut names = Vec::new();
2700
2701    let mut c = node.walk();
2702    if c.goto_first_child() {
2703        loop {
2704            let child = c.node();
2705            match child.kind() {
2706                "visibility_modifier" => {
2707                    visibility = Some(source[child.byte_range()].to_string());
2708                }
2709                "scoped_identifier" | "identifier" | "use_as_clause" => {
2710                    // Full path like `std::collections::HashMap` or just `serde`
2711                    use_path = source[child.byte_range()].to_string();
2712                }
2713                "scoped_use_list" => {
2714                    // e.g. `serde::{Deserialize, Serialize}`
2715                    use_path = child
2716                        .child_by_field_name("path")
2717                        .map(|path| source[path.byte_range()].to_string())
2718                        .unwrap_or_default();
2719                    // Keep each top-level subtree intact when merging or removing names.
2720                    extract_rs_use_list_names(source, &child, &mut names);
2721                }
2722                "use_list" => extract_rs_use_list_names(source, &child, &mut names),
2723                _ => {}
2724            }
2725            if !c.goto_next_sibling() {
2726                break;
2727            }
2728        }
2729    }
2730
2731    if use_path.is_empty() && names.is_empty() {
2732        return None;
2733    }
2734
2735    let group = classify_group_rs(&use_path);
2736
2737    Some(ImportStatement {
2738        module_path: use_path,
2739        names: names.clone(),
2740        // `default_import` carries the visibility text for the Rust engine
2741        // (e.g. "pub", "pub(crate)"). organize re-emits it verbatim.
2742        default_import: visibility.clone(),
2743        namespace_import: None,
2744        kind: ImportKind::Value,
2745        group,
2746        byte_range,
2747        raw_text,
2748        form: ImportForm::RustUse {
2749            visibility,
2750            named: names,
2751        },
2752    })
2753}
2754
2755/// Extract top-level Rust use-list entries, preserving aliases and nested trees.
2756fn extract_rs_use_list_names(source: &str, node: &Node, names: &mut Vec<String>) {
2757    let list = if node.kind() == "use_list" {
2758        *node
2759    } else {
2760        let mut cursor = node.walk();
2761        let Some(list) = node
2762            .named_children(&mut cursor)
2763            .find(|child| child.kind() == "use_list")
2764        else {
2765            return;
2766        };
2767        list
2768    };
2769    let mut cursor = list.walk();
2770    for child in list.named_children(&mut cursor) {
2771        if !matches!(child.kind(), "line_comment" | "block_comment") {
2772            names.push(source[child.byte_range()].to_string());
2773        }
2774    }
2775}
2776
2777/// Reassemble a Rust use tree for consumers that interpret the whole path.
2778pub fn rust_use_tree(import: &ImportStatement) -> String {
2779    if import.names.is_empty() {
2780        import.module_path.clone()
2781    } else if import.module_path.is_empty() {
2782        format!("{{{}}}", import.names.join(", "))
2783    } else {
2784        format!("{}::{{{}}}", import.module_path, import.names.join(", "))
2785    }
2786}
2787
2788/// Generate a Rust import line.
2789fn generate_rs_import_line(module_path: &str, names: &[String], _type_only: bool) -> String {
2790    if names.is_empty() {
2791        format!("use {module_path};")
2792    } else {
2793        let mut sorted_names = names.to_vec();
2794        sort_named_specifiers(&mut sorted_names);
2795        let separator = if module_path.is_empty() { "" } else { "::" };
2796        format!(
2797            "use {module_path}{separator}{{{}}};",
2798            sorted_names.join(", ")
2799        )
2800    }
2801}
2802
2803// ---------------------------------------------------------------------------
2804// Go implementation
2805// ---------------------------------------------------------------------------
2806
2807/// Classify a Go import path into a group.
2808pub fn classify_group_go(module_path: &str) -> ImportGroup {
2809    // stdlib paths don't contain dots (e.g., "fmt", "os", "net/http")
2810    // external paths contain dots (e.g., "github.com/pkg/errors")
2811    if module_path.contains('.') {
2812        ImportGroup::External
2813    } else {
2814        ImportGroup::Stdlib
2815    }
2816}
2817
2818/// Parse imports from a Go file.
2819fn parse_go_imports(source: &str, tree: &Tree) -> ImportBlock {
2820    let root = tree.root_node();
2821    let mut imports = Vec::new();
2822
2823    let mut cursor = root.walk();
2824    if !cursor.goto_first_child() {
2825        return ImportBlock::empty();
2826    }
2827
2828    loop {
2829        let node = cursor.node();
2830        if node.kind() == "import_declaration" {
2831            parse_go_import_declaration(source, &node, &mut imports);
2832        }
2833        if !cursor.goto_next_sibling() {
2834            break;
2835        }
2836    }
2837
2838    let byte_range = import_byte_range(&imports);
2839
2840    ImportBlock {
2841        imports,
2842        byte_range,
2843    }
2844}
2845
2846/// Parse a single Go import_declaration (may contain one or multiple specs).
2847fn parse_go_import_declaration(source: &str, node: &Node, imports: &mut Vec<ImportStatement>) {
2848    let mut c = node.walk();
2849    if c.goto_first_child() {
2850        loop {
2851            let child = c.node();
2852            match child.kind() {
2853                "import_spec" => {
2854                    if let Some(imp) = parse_go_import_spec(source, &child) {
2855                        imports.push(imp);
2856                    }
2857                }
2858                "import_spec_list" => {
2859                    // Grouped imports: walk into the list
2860                    let mut lc = child.walk();
2861                    if lc.goto_first_child() {
2862                        loop {
2863                            if lc.node().kind() == "import_spec" {
2864                                if let Some(imp) = parse_go_import_spec(source, &lc.node()) {
2865                                    imports.push(imp);
2866                                }
2867                            }
2868                            if !lc.goto_next_sibling() {
2869                                break;
2870                            }
2871                        }
2872                    }
2873                }
2874                _ => {}
2875            }
2876            if !c.goto_next_sibling() {
2877                break;
2878            }
2879        }
2880    }
2881}
2882
2883/// Parse a single Go import_spec node.
2884fn parse_go_import_spec(source: &str, node: &Node) -> Option<ImportStatement> {
2885    let raw_text = source[node.byte_range()].to_string();
2886    let byte_range = node.byte_range();
2887
2888    let mut import_path = String::new();
2889    let mut alias = None;
2890
2891    let mut c = node.walk();
2892    if c.goto_first_child() {
2893        loop {
2894            let child = c.node();
2895            match child.kind() {
2896                "interpreted_string_literal" => {
2897                    // Extract the path without quotes
2898                    let text = source[child.byte_range()].to_string();
2899                    import_path = text.trim_matches('"').to_string();
2900                }
2901                "identifier" | "blank_identifier" | "dot" => {
2902                    // This is an alias (e.g., `alias "path"` or `. "path"` or `_ "path"`)
2903                    alias = Some(source[child.byte_range()].to_string());
2904                }
2905                _ => {}
2906            }
2907            if !c.goto_next_sibling() {
2908                break;
2909            }
2910        }
2911    }
2912
2913    if import_path.is_empty() {
2914        return None;
2915    }
2916
2917    let group = classify_group_go(&import_path);
2918
2919    Some(ImportStatement {
2920        module_path: import_path,
2921        names: Vec::new(),
2922        default_import: alias.clone(),
2923        namespace_import: None,
2924        kind: ImportKind::Value,
2925        group,
2926        byte_range,
2927        raw_text,
2928        form: ImportForm::Go { alias },
2929    })
2930}
2931
2932/// Public API for Go import line generation (used by add_import handler).
2933pub fn generate_go_import_line_pub(
2934    module_path: &str,
2935    alias: Option<&str>,
2936    in_group: bool,
2937) -> String {
2938    generate_go_import_line(module_path, alias, in_group)
2939}
2940
2941test_support_visibility! {
2942/// Generate a Go import line (public API for command handler).
2943///
2944/// `in_group` controls whether to generate a spec for insertion into an
2945/// existing grouped import (`\t"path"`) or a standalone import (`import "path"`).
2946fn generate_go_import_line(module_path: &str, alias: Option<&str>, in_group: bool) -> String {
2947    if in_group {
2948        // Spec for grouped import block
2949        match alias {
2950            Some(a) => format!("\t{a} \"{module_path}\""),
2951            None => format!("\t\"{module_path}\""),
2952        }
2953    } else {
2954        // Standalone import
2955        match alias {
2956            Some(a) => format!("import {a} \"{module_path}\""),
2957            None => format!("import \"{module_path}\""),
2958        }
2959    }
2960}
2961}
2962
2963/// Check if a Go import block has a grouped import declaration.
2964/// Returns the byte range of the full import_declaration if found.
2965pub fn go_has_grouped_import(_source: &str, tree: &Tree) -> Option<Range<usize>> {
2966    let root = tree.root_node();
2967    let mut cursor = root.walk();
2968    if !cursor.goto_first_child() {
2969        return None;
2970    }
2971
2972    loop {
2973        let node = cursor.node();
2974        if node.kind() == "import_declaration" && go_import_declaration_is_grouped(&node) {
2975            return Some(node.byte_range());
2976        }
2977        if !cursor.goto_next_sibling() {
2978            break;
2979        }
2980    }
2981    None
2982}
2983
2984pub fn go_import_declarations_range(_source: &str, tree: &Tree) -> Option<Range<usize>> {
2985    let root = tree.root_node();
2986    let mut cursor = root.walk();
2987    let mut range: Option<Range<usize>> = None;
2988    if !cursor.goto_first_child() {
2989        return None;
2990    }
2991
2992    loop {
2993        let node = cursor.node();
2994        if node.kind() == "import_declaration" {
2995            let node_range = node.byte_range();
2996            range = Some(match range {
2997                Some(existing) => {
2998                    existing.start.min(node_range.start)..existing.end.max(node_range.end)
2999                }
3000                None => node_range,
3001            });
3002        }
3003        if !cursor.goto_next_sibling() {
3004            break;
3005        }
3006    }
3007
3008    range
3009}
3010
3011pub fn go_offset_is_in_grouped_import(_source: &str, tree: &Tree, offset: usize) -> bool {
3012    let root = tree.root_node();
3013    let mut cursor = root.walk();
3014    if !cursor.goto_first_child() {
3015        return false;
3016    }
3017
3018    loop {
3019        let node = cursor.node();
3020        if node.kind() == "import_declaration"
3021            && node.start_byte() < offset
3022            && offset < node.end_byte()
3023            && go_import_declaration_is_grouped(&node)
3024        {
3025            return true;
3026        }
3027        if !cursor.goto_next_sibling() {
3028            break;
3029        }
3030    }
3031
3032    false
3033}
3034
3035fn go_import_declaration_is_grouped(node: &Node) -> bool {
3036    let mut c = node.walk();
3037    if c.goto_first_child() {
3038        loop {
3039            if c.node().kind() == "import_spec_list" {
3040                return true;
3041            }
3042            if !c.goto_next_sibling() {
3043                break;
3044            }
3045        }
3046    }
3047    false
3048}
3049
3050// ---------------------------------------------------------------------------
3051// Solidity implementation
3052// ---------------------------------------------------------------------------
3053
3054/// Classify a Solidity import path: relative (`./`, `../`) is internal,
3055/// everything else (remappings, `@scope/...`, bare) is external. No stdlib.
3056pub fn classify_group_solidity(module_path: &str) -> ImportGroup {
3057    if module_path.starts_with('.') {
3058        ImportGroup::Internal
3059    } else {
3060        ImportGroup::External
3061    }
3062}
3063
3064fn parse_solidity_imports(source: &str, tree: &Tree) -> ImportBlock {
3065    let root = tree.root_node();
3066    let mut imports = Vec::new();
3067    let mut cursor = root.walk();
3068    if cursor.goto_first_child() {
3069        loop {
3070            let node = cursor.node();
3071            if node.kind() == "import_directive" {
3072                if let Some(imp) = parse_solidity_import_directive(source, &node) {
3073                    imports.push(imp);
3074                }
3075            }
3076            if !cursor.goto_next_sibling() {
3077                break;
3078            }
3079        }
3080    }
3081    let byte_range = import_byte_range(&imports);
3082    ImportBlock {
3083        imports,
3084        byte_range,
3085    }
3086}
3087
3088test_support_visibility! {
3089fn strip_one_matching_solidity_quote_pair(value: &str) -> &str {
3090    if value.len() < 2 {
3091        return value;
3092    }
3093
3094    let bytes = value.as_bytes();
3095    let quote = bytes[0];
3096    if matches!(quote, b'\'' | b'"') && bytes.last() == Some(&quote) {
3097        &value[1..value.len() - 1]
3098    } else {
3099        value
3100    }
3101}
3102}
3103
3104/// Parse one `import_directive`. The Solidity grammar emits a flat token
3105/// sequence (verified by grammar fixture test), so the four forms are
3106/// distinguished by the presence of `{` (named), `*` (namespace), a trailing
3107/// `as` (whole-file alias), or none (side-effect).
3108fn parse_solidity_import_directive(source: &str, node: &Node) -> Option<ImportStatement> {
3109    let raw_text = source[node.byte_range()].to_string();
3110    let byte_range = node.byte_range();
3111
3112    let mut children: Vec<(String, String)> = Vec::new();
3113    let mut c = node.walk();
3114    if c.goto_first_child() {
3115        loop {
3116            let ch = c.node();
3117            children.push((ch.kind().to_string(), source[ch.byte_range()].to_string()));
3118            if !c.goto_next_sibling() {
3119                break;
3120            }
3121        }
3122    }
3123
3124    // Every form carries exactly one string literal: the imported file path.
3125    let module_path = children
3126        .iter()
3127        .find(|(k, _)| k == "string")
3128        .map(|(_, text)| strip_one_matching_solidity_quote_pair(text).to_string())?;
3129    if module_path.is_empty() {
3130        return None;
3131    }
3132
3133    let has_brace = children.iter().any(|(k, _)| k == "{");
3134    let has_star = children.iter().any(|(k, _)| k == "*");
3135
3136    let mut named: Vec<String> = Vec::new();
3137    let mut namespace: Option<String> = None;
3138    let mut alias: Option<String> = None;
3139
3140    if has_brace {
3141        named = parse_solidity_named_specifiers(&children);
3142    } else if has_star {
3143        namespace = solidity_identifier_after_as(&children);
3144    } else {
3145        // No `{`, no `*`: a trailing `as IDENT` is a whole-file alias;
3146        // otherwise a bare side-effect import.
3147        alias = solidity_identifier_after_as(&children);
3148    }
3149
3150    let kind = if named.is_empty() && namespace.is_none() && alias.is_none() {
3151        ImportKind::SideEffect
3152    } else {
3153        ImportKind::Value
3154    };
3155    let group = classify_group_solidity(&module_path);
3156
3157    Some(ImportStatement {
3158        module_path,
3159        names: named.clone(),
3160        default_import: None,
3161        // Namespace maps to the flat slot so existing readers (dedup) see it;
3162        // the whole-file alias has no flat slot and lives only in `form`.
3163        namespace_import: namespace.clone(),
3164        kind,
3165        group,
3166        byte_range,
3167        raw_text,
3168        form: ImportForm::Solidity {
3169            named,
3170            namespace,
3171            alias,
3172        },
3173    })
3174}
3175
3176/// Return the `identifier` token immediately following the first `as`.
3177fn solidity_identifier_after_as(children: &[(String, String)]) -> Option<String> {
3178    let as_pos = children.iter().position(|(k, _)| k == "as")?;
3179    children[as_pos + 1..]
3180        .iter()
3181        .find(|(k, _)| k == "identifier")
3182        .map(|(_, t)| t.clone())
3183}
3184
3185/// Collect named specifiers between `{` and `}` into verbatim strings,
3186/// combining `A as B` into `"A as B"` to match the ES specifier convention.
3187fn parse_solidity_named_specifiers(children: &[(String, String)]) -> Vec<String> {
3188    let mut names = Vec::new();
3189    let mut in_braces = false;
3190    let mut current: Option<String> = None;
3191    let mut expect_alias = false;
3192    for (k, t) in children {
3193        match k.as_str() {
3194            "{" => in_braces = true,
3195            "}" => {
3196                if let Some(n) = current.take() {
3197                    names.push(n);
3198                }
3199                in_braces = false;
3200            }
3201            _ if !in_braces => {}
3202            "identifier" => {
3203                if expect_alias {
3204                    if let Some(n) = current.take() {
3205                        names.push(format!("{n} as {t}"));
3206                    }
3207                    expect_alias = false;
3208                } else {
3209                    if let Some(n) = current.take() {
3210                        names.push(n);
3211                    }
3212                    current = Some(t.clone());
3213                }
3214            }
3215            "as" => expect_alias = true,
3216            "," => {
3217                if let Some(n) = current.take() {
3218                    names.push(n);
3219                }
3220                expect_alias = false;
3221            }
3222            _ => {}
3223        }
3224    }
3225    names
3226}
3227
3228/// Generate a Solidity import line in the appropriate form.
3229fn generate_solidity_import_line(req: &ImportRequest) -> String {
3230    if !req.names.is_empty() {
3231        format!(
3232            "import {{ {} }} from \"{}\";",
3233            req.names.join(", "),
3234            req.module_path
3235        )
3236    } else if let Some(ns) = req.namespace {
3237        format!("import * as {} from \"{}\";", ns, req.module_path)
3238    } else if let Some(al) = req.alias {
3239        format!("import \"{}\" as {};", req.module_path, al)
3240    } else {
3241        format!("import \"{}\";", req.module_path)
3242    }
3243}
3244
3245/// Skip past a newline character at the given position.
3246fn skip_newline(source: &str, pos: usize) -> usize {
3247    if pos < source.len() {
3248        let bytes = source.as_bytes();
3249        if bytes[pos] == b'\n' {
3250            return pos + 1;
3251        }
3252        if bytes[pos] == b'\r' {
3253            if pos + 1 < source.len() && bytes[pos + 1] == b'\n' {
3254                return pos + 2;
3255            }
3256            return pos + 1;
3257        }
3258    }
3259    pos
3260}
3261
3262// ---------------------------------------------------------------------------
3263// Unit tests
3264// ---------------------------------------------------------------------------
3265
3266#[cfg(any(test, feature = "test-support"))]
3267thread_local! {
3268    pub static PYTHON_STDLIB_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3269}