1pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum ImportKind {
58 Value,
60 Type,
62 SideEffect,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub enum ImportGroup {
78 Stdlib,
81 External,
83 Internal,
85}
86
87impl ImportGroup {
88 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#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct PhpImportClause {
101 pub module_path: String,
103 pub alias: Option<String>,
105 pub import_kind: Option<String>,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum ImportForm {
122 Es {
126 default_import: Option<String>,
127 namespace_import: Option<String>,
128 named: Vec<String>,
129 type_only: bool,
131 side_effect: bool,
133 attribute_clause: Option<String>,
137 attribute_type: Option<String>,
139 },
140 Python {
143 from_import: bool,
144 named: Vec<String>,
145 },
146 RustUse {
151 visibility: Option<String>,
152 named: Vec<String>,
153 },
154 Go { alias: Option<String> },
157 Solidity {
166 named: Vec<String>,
167 namespace: Option<String>,
168 alias: Option<String>,
169 },
170 Php { clauses: Vec<PhpImportClause> },
173 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#[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 pub namespace: Option<&'a str>,
198 pub alias: Option<&'a str>,
200 pub type_only: bool,
201 pub modifiers: &'a [String],
204 pub import_kind: Option<&'a str>,
207}
208
209const NO_MODIFIERS: &[String] = &[];
211
212impl<'a> ImportRequest<'a> {
213 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#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct ImportStatement {
239 pub module_path: String,
241 pub names: Vec<String>,
243 pub default_import: Option<String>,
245 pub namespace_import: Option<String>,
247 pub kind: ImportKind,
249 pub group: ImportGroup,
251 pub byte_range: Range<usize>,
253 pub raw_text: String,
255 pub form: ImportForm,
259}
260
261#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct ImportBlock {
264 pub imports: Vec<ImportStatement>,
266 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
288pub 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 while !cursor.goto_next_sibling() {
309 if !cursor.goto_parent() {
310 return;
311 }
312 }
313 }
314}
315
316pub 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
344pub 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
364pub fn specifier_matches(spec: &str, target: &str) -> bool {
369 specifier_imported_name(spec) == target || specifier_local_name(spec) == target
370}
371
372pub trait ImportSyntax: Sync {
385 fn parse(&self, source: &str, tree: &Tree) -> ImportBlock;
387
388 fn generate_line(&self, req: &ImportRequest) -> String;
391
392 fn classify_group(&self, module_path: &str) -> ImportGroup;
394}
395
396struct 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
459struct 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
500pub 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
524pub 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 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
549fn 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 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
581struct 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
612pub 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
648pub 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
663pub 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
678pub 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 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 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 if imp.kind != target_kind && imp.kind != ImportKind::SideEffect {
724 continue;
725 }
726
727 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 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 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 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
778pub 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
1189pub 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 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 let group_imports: Vec<&ImportStatement> =
1219 block.imports.iter().filter(|i| i.group == group).collect();
1220
1221 if group_imports.is_empty() {
1222 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 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 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 for imp in &group_imports {
1248 let cmp = module_path.cmp(&imp.module_path);
1249 match cmp {
1250 std::cmp::Ordering::Less => {
1251 return (imp.byte_range.start, false, false);
1253 }
1254 std::cmp::Ordering::Equal => {
1255 if target_kind == ImportKind::Type && imp.kind == ImportKind::Value {
1257 let end = imp.byte_range.end;
1259 let insert_at = skip_newline(source, end);
1260 return (insert_at, false, false);
1261 }
1262 return (imp.byte_range.start, false, false);
1264 }
1265 std::cmp::Ordering::Greater => continue,
1266 }
1267 }
1268
1269 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
1284pub 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
1344fn 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 let mut cursor = root.walk();
1414 let mut docstring_seen = false;
1415 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 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 run_end = None;
1448 break;
1449 }
1450 }
1451 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
1466fn 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
1473fn 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
1514pub 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
1524pub 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
1539pub 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
1560pub 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
1583pub 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
1623pub fn is_supported(lang: LangId) -> bool {
1625 syntax_for(lang).is_some()
1626}
1627
1628pub 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
1637pub fn classify_group(lang: LangId, module_path: &str) -> ImportGroup {
1639 match syntax_for(lang) {
1640 Some(engine) => engine.classify_group(module_path),
1641 None => ImportGroup::External,
1644 }
1645}
1646
1647pub 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 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
1666fn 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
1702fn 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 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 let is_type_only = has_type_keyword(node);
1715
1716 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 "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 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
1788fn 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
1811pub 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
1821pub 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
1829fn 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
1936fn 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 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
1962fn 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
1985fn 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 let text = &source[child.byte_range()];
2004 if text != "type" {
2005 *default_import = Some(text.to_string());
2006 }
2007 }
2008 "named_imports" => {
2009 extract_named_imports(source, &child, names);
2011 }
2012 "namespace_import" => {
2013 extract_namespace_import(source, &child, namespace_import);
2015 }
2016 _ => {}
2017 }
2018 if !cursor.goto_next_sibling() {
2019 break;
2020 }
2021 }
2022}
2023
2024fn 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 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
2068fn 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
2087fn 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
2133fn 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 if names.is_empty() && default_import.is_none() && namespace_import.is_none() {
2147 return format!("import {module_path}");
2148 }
2149
2150 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 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 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 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 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 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 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 format!("import {module_path}")
2211}
2212
2213test_support_visibility! {
2214const 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
2421pub fn classify_group_py(module_path: &str) -> ImportGroup {
2423 if module_path.starts_with('.') {
2425 return ImportGroup::Internal;
2426 }
2427 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
2443fn 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
2481pub 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
2492fn 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 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
2535fn 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 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 names.push(source[child.byte_range()].to_string());
2564 }
2565 }
2566 "relative_import" => {
2567 module_path = source[child.byte_range()].to_string();
2569 }
2570 "aliased_import" => {
2571 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 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
2606fn 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
2626fn generate_py_import_line(
2628 module_path: &str,
2629 names: &[String],
2630 _default_import: Option<&str>,
2631) -> String {
2632 if names.is_empty() {
2633 format!("import {module_path}")
2635 } else {
2636 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
2644pub fn classify_group_rs(module_path: &str) -> ImportGroup {
2650 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
2659fn 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
2689fn 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 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 use_path = source[child.byte_range()].to_string();
2712 }
2713 "scoped_use_list" => {
2714 use_path = child
2716 .child_by_field_name("path")
2717 .map(|path| source[path.byte_range()].to_string())
2718 .unwrap_or_default();
2719 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: 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
2755fn 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
2777pub 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
2788fn 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
2803pub fn classify_group_go(module_path: &str) -> ImportGroup {
2809 if module_path.contains('.') {
2812 ImportGroup::External
2813 } else {
2814 ImportGroup::Stdlib
2815 }
2816}
2817
2818fn 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
2846fn 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 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
2883fn 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 let text = source[child.byte_range()].to_string();
2899 import_path = text.trim_matches('"').to_string();
2900 }
2901 "identifier" | "blank_identifier" | "dot" => {
2902 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
2932pub 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! {
2942fn generate_go_import_line(module_path: &str, alias: Option<&str>, in_group: bool) -> String {
2947 if in_group {
2948 match alias {
2950 Some(a) => format!("\t{a} \"{module_path}\""),
2951 None => format!("\t\"{module_path}\""),
2952 }
2953 } else {
2954 match alias {
2956 Some(a) => format!("import {a} \"{module_path}\""),
2957 None => format!("import \"{module_path}\""),
2958 }
2959 }
2960}
2961}
2962
2963pub 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
3050pub 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("e) {
3097 &value[1..value.len() - 1]
3098 } else {
3099 value
3100 }
3101}
3102}
3103
3104fn 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 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 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_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
3176fn 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
3185fn 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
3228fn 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
3245fn 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#[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}