pub mod quotes;
use std::ops::Range;
use tree_sitter::{Node, Tree};
use crate::parser::LangId;
test_support_visibility! {
mod c;
}
pub use c::{c_insertion_block, classify_group_c_import_kind, normalize_include_module};
test_support_visibility! {
mod csharp;
}
test_support_visibility! {
mod java;
}
test_support_visibility! {
mod kotlin;
}
test_support_visibility! {
mod lua;
}
pub mod perl;
test_support_visibility! {
mod php;
}
pub use php::{
php_grouped_use_matches_module, php_grouped_use_shares_prefix, php_import_matches_module,
rewrite_php_import_without_module,
};
pub mod ruby;
test_support_visibility! {
mod scala;
}
pub use scala::scala_block_uses_scala2_dialect;
test_support_visibility! {
mod swift;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportKind {
Value,
Type,
SideEffect,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ImportGroup {
Stdlib,
External,
Internal,
}
impl ImportGroup {
pub fn label(&self) -> &'static str {
match self {
ImportGroup::Stdlib => "stdlib",
ImportGroup::External => "external",
ImportGroup::Internal => "internal",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhpImportClause {
pub module_path: String,
pub alias: Option<String>,
pub import_kind: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportForm {
Es {
default_import: Option<String>,
namespace_import: Option<String>,
named: Vec<String>,
type_only: bool,
side_effect: bool,
attribute_clause: Option<String>,
attribute_type: Option<String>,
},
Python {
from_import: bool,
named: Vec<String>,
},
RustUse {
visibility: Option<String>,
named: Vec<String>,
},
Go { alias: Option<String> },
Solidity {
named: Vec<String>,
namespace: Option<String>,
alias: Option<String>,
},
Php { clauses: Vec<PhpImportClause> },
Structured {
named: Vec<String>,
namespace: Option<String>,
alias: Option<String>,
modifiers: Vec<String>,
import_kind: Option<String>,
},
}
#[derive(Debug, Clone)]
pub struct ImportRequest<'a> {
pub module_path: &'a str,
pub names: &'a [String],
pub default_import: Option<&'a str>,
pub namespace: Option<&'a str>,
pub alias: Option<&'a str>,
pub type_only: bool,
pub modifiers: &'a [String],
pub import_kind: Option<&'a str>,
}
const NO_MODIFIERS: &[String] = &[];
impl<'a> ImportRequest<'a> {
pub fn legacy(
module_path: &'a str,
names: &'a [String],
default_import: Option<&'a str>,
namespace: Option<&'a str>,
type_only: bool,
) -> Self {
ImportRequest {
module_path,
names,
default_import,
namespace,
alias: None,
type_only,
modifiers: NO_MODIFIERS,
import_kind: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportStatement {
pub module_path: String,
pub names: Vec<String>,
pub default_import: Option<String>,
pub namespace_import: Option<String>,
pub kind: ImportKind,
pub group: ImportGroup,
pub byte_range: Range<usize>,
pub raw_text: String,
pub form: ImportForm,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportBlock {
pub imports: Vec<ImportStatement>,
pub byte_range: Option<Range<usize>>,
}
impl ImportBlock {
pub fn empty() -> Self {
ImportBlock {
imports: Vec::new(),
byte_range: None,
}
}
}
pub fn import_byte_range(imports: &[ImportStatement]) -> Option<Range<usize>> {
imports.first().zip(imports.last()).map(|(first, last)| {
let start = first.byte_range.start;
let end = last.byte_range.end;
start..end
})
}
pub fn for_each_preorder_until<'tree>(
root: Node<'tree>,
kind: &str,
mut found: impl FnMut(Node<'tree>),
) {
let mut cursor = root.walk();
loop {
let node = cursor.node();
if node.kind() == kind {
found(node);
} else if cursor.goto_first_child() {
continue;
}
while !cursor.goto_next_sibling() {
if !cursor.goto_parent() {
return;
}
}
}
}
pub fn specifier_local_name(spec: &str) -> &str {
let trimmed = spec.trim();
let after_type = trimmed
.strip_prefix("type ")
.unwrap_or(trimmed)
.trim_start();
if let Some(idx) = after_type.find(" as ") {
after_type[idx + 4..].trim()
} else {
after_type
}
}
pub fn specifier_imported_name(spec: &str) -> &str {
let trimmed = spec.trim();
let after_type = trimmed
.strip_prefix("type ")
.unwrap_or(trimmed)
.trim_start();
after_type
.find(" as ")
.map(|idx| after_type[..idx].trim())
.unwrap_or(after_type)
}
pub fn specifier_matches(spec: &str, target: &str) -> bool {
specifier_imported_name(spec) == target || specifier_local_name(spec) == target
}
pub trait ImportSyntax: Sync {
fn parse(&self, source: &str, tree: &Tree) -> ImportBlock;
fn generate_line(&self, req: &ImportRequest) -> String;
fn classify_group(&self, module_path: &str) -> ImportGroup;
}
struct EsSyntax;
impl ImportSyntax for EsSyntax {
fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
parse_ts_imports(source, tree)
}
fn generate_line(&self, req: &ImportRequest) -> String {
generate_ts_import_line(
req.module_path,
req.names,
req.default_import,
req.namespace,
req.type_only,
)
}
fn classify_group(&self, module_path: &str) -> ImportGroup {
classify_group_ts(module_path)
}
}
struct PythonSyntax;
impl ImportSyntax for PythonSyntax {
fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
parse_py_imports(source, tree)
}
fn generate_line(&self, req: &ImportRequest) -> String {
generate_py_import_line(req.module_path, req.names, req.default_import)
}
fn classify_group(&self, module_path: &str) -> ImportGroup {
classify_group_py(module_path)
}
}
struct RustSyntax;
impl ImportSyntax for RustSyntax {
fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
parse_rs_imports(source, tree)
}
fn generate_line(&self, req: &ImportRequest) -> String {
let line = generate_rs_import_line(req.module_path, req.names, req.type_only);
match req.default_import {
Some(visibility) if !visibility.is_empty() => format!("{visibility} {line}"),
_ => line,
}
}
fn classify_group(&self, module_path: &str) -> ImportGroup {
classify_group_rs(module_path)
}
}
struct GoSyntax;
impl ImportSyntax for GoSyntax {
fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
parse_go_imports(source, tree)
}
fn generate_line(&self, req: &ImportRequest) -> String {
generate_go_import_line(req.module_path, req.default_import, false)
}
fn classify_group(&self, module_path: &str) -> ImportGroup {
classify_group_go(module_path)
}
}
struct SoliditySyntax;
impl ImportSyntax for SoliditySyntax {
fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
parse_solidity_imports(source, tree)
}
fn generate_line(&self, req: &ImportRequest) -> String {
generate_solidity_import_line(req)
}
fn classify_group(&self, module_path: &str) -> ImportGroup {
classify_group_solidity(module_path)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VueScriptRangeError {
MissingScript,
MultipleScripts,
}
impl VueScriptRangeError {
pub fn code(self) -> &'static str {
match self {
VueScriptRangeError::MissingScript => "missing_vue_script",
VueScriptRangeError::MultipleScripts => "ambiguous_vue_script",
}
}
pub fn message(self, command: &str) -> String {
match self {
VueScriptRangeError::MissingScript => format!(
"{command}: Vue import management requires exactly one <script> block; found none"
),
VueScriptRangeError::MultipleScripts => format!(
"{command}: Vue import management requires exactly one <script> block; found multiple"
),
}
}
}
pub fn vue_single_script_content_range(tree: &Tree) -> Result<(usize, usize), VueScriptRangeError> {
let root = tree.root_node();
let mut ranges = Vec::new();
let mut cursor = root.walk();
for child in root.named_children(&mut cursor) {
if child.kind() == "script_element" {
ranges.push(vue_script_element_content_range(&child));
}
}
match ranges.len() {
0 => Err(VueScriptRangeError::MissingScript),
1 => Ok(ranges[0]),
_ => Err(VueScriptRangeError::MultipleScripts),
}
}
pub fn vue_script_content_range(tree: &Tree) -> Option<(usize, usize)> {
vue_single_script_content_range(tree).ok()
}
fn vue_script_element_content_range(child: &Node) -> (usize, usize) {
let mut inner = child.walk();
for sub in child.named_children(&mut inner) {
if sub.kind() == "raw_text" {
return (sub.start_byte(), sub.end_byte());
}
}
let mut inner2 = child.walk();
for sub in child.named_children(&mut inner2) {
if sub.kind() == "start_tag" {
return (sub.end_byte(), sub.end_byte());
}
}
(child.end_byte(), child.end_byte())
}
fn parse_vue_imports(source: &str, tree: &Tree) -> ImportBlock {
let Ok((start, end)) = vue_single_script_content_range(tree) else {
return ImportBlock {
imports: Vec::new(),
byte_range: None,
};
};
let inner = &source[start..end];
let Ok(inner_tree) = crate::parser::parse_source_with_cached_parser(
std::path::Path::new("<vue script>"),
inner,
LangId::TypeScript,
) else {
return ImportBlock {
imports: Vec::new(),
byte_range: None,
};
};
let mut block = parse_ts_imports(inner, &inner_tree);
for imp in &mut block.imports {
imp.byte_range = (imp.byte_range.start + start)..(imp.byte_range.end + start);
}
block.byte_range = block.byte_range.map(|r| (r.start + start)..(r.end + start));
block
}
struct VueSyntax;
impl ImportSyntax for VueSyntax {
fn parse(&self, source: &str, tree: &Tree) -> ImportBlock {
parse_vue_imports(source, tree)
}
fn generate_line(&self, req: &ImportRequest) -> String {
generate_ts_import_line(
req.module_path,
req.names,
req.default_import,
req.namespace,
req.type_only,
)
}
fn classify_group(&self, module_path: &str) -> ImportGroup {
classify_group_ts(module_path)
}
}
static ES_SYNTAX: EsSyntax = EsSyntax;
static PYTHON_SYNTAX: PythonSyntax = PythonSyntax;
static RUST_SYNTAX: RustSyntax = RustSyntax;
static GO_SYNTAX: GoSyntax = GoSyntax;
static SOLIDITY_SYNTAX: SoliditySyntax = SoliditySyntax;
static VUE_SYNTAX: VueSyntax = VueSyntax;
pub fn syntax_for(lang: LangId) -> Option<&'static dyn ImportSyntax> {
match lang {
LangId::TypeScript | LangId::Tsx | LangId::JavaScript => Some(&ES_SYNTAX),
LangId::Python => Some(&PYTHON_SYNTAX),
LangId::Rust => Some(&RUST_SYNTAX),
LangId::Go => Some(&GO_SYNTAX),
LangId::Solidity => Some(&SOLIDITY_SYNTAX),
LangId::Vue => Some(&VUE_SYNTAX),
LangId::C => Some(&c::C_SYNTAX),
LangId::Cpp | LangId::Cuda | LangId::Metal => Some(&c::C_SYNTAX),
LangId::Java => Some(&java::JAVA_SYNTAX),
LangId::Kotlin => Some(&kotlin::KOTLIN_SYNTAX),
LangId::Lua => Some(&lua::LUA_SYNTAX),
LangId::CSharp => Some(&csharp::CSHARP_SYNTAX),
LangId::Php => Some(&php::PHP_SYNTAX),
LangId::Perl => Some(&perl::PERL_SYNTAX),
LangId::Ruby => Some(&ruby::RUBY_SYNTAX),
LangId::Scala => Some(&scala::SCALA_SYNTAX),
LangId::Swift => Some(&swift::SWIFT_SYNTAX),
LangId::Zig
| LangId::Bash
| LangId::Scss
| LangId::Json
| LangId::Html
| LangId::Markdown
| LangId::Yaml
| LangId::Pascal
| LangId::R
| LangId::Groovy
| LangId::ObjC
| LangId::Toml
| LangId::Luau => None,
}
}
pub fn parse_imports(source: &str, tree: &Tree, lang: LangId) -> ImportBlock {
if lang == LangId::Luau {
return crate::luau::imports(source, tree.root_node());
}
match syntax_for(lang) {
Some(engine) => engine.parse(source, tree),
None => ImportBlock::empty(),
}
}
pub fn is_duplicate(
block: &ImportBlock,
module_path: &str,
names: &[String],
default_import: Option<&str>,
type_only: bool,
) -> bool {
is_duplicate_with_namespace(block, module_path, names, default_import, None, type_only)
}
pub fn is_duplicate_with_namespace(
block: &ImportBlock,
module_path: &str,
names: &[String],
default_import: Option<&str>,
namespace_import: Option<&str>,
type_only: bool,
) -> bool {
let target_kind = if type_only {
ImportKind::Type
} else {
ImportKind::Value
};
for imp in &block.imports {
if imp.module_path != module_path {
continue;
}
if names.is_empty()
&& default_import.is_none()
&& namespace_import.is_none()
&& imp.names.is_empty()
&& imp.default_import.is_none()
&& imp.namespace_import.is_none()
{
return true;
}
if names.is_empty()
&& default_import.is_none()
&& namespace_import.is_none()
&& imp.kind == ImportKind::SideEffect
{
return true;
}
if imp.kind != target_kind && imp.kind != ImportKind::SideEffect {
continue;
}
if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
if imp.default_import.as_deref() == Some(def)
&& imp.namespace_import.as_deref() == Some(namespace)
&& names
.iter()
.all(|n| imp.names.iter().any(|stored| specifier_matches(stored, n)))
{
return true;
}
continue;
}
if names.is_empty()
&& default_import.is_none()
&& namespace_import.is_some()
&& imp.namespace_import.as_deref() == namespace_import
{
return true;
}
if let Some(def) = default_import {
if namespace_import.is_none() && imp.default_import.as_deref() == Some(def) {
return true;
}
}
if !names.is_empty()
&& names
.iter()
.all(|n| imp.names.iter().any(|stored| specifier_matches(stored, n)))
{
return true;
}
}
false
}
pub fn is_duplicate_import_request(
lang: LangId,
block: &ImportBlock,
req: &ImportRequest<'_>,
) -> bool {
if lang == LangId::Php
&& block
.imports
.iter()
.any(|imp| php::php_import_satisfies_request(imp, req))
{
return true;
}
if lang == LangId::Python && req.names.is_empty() && req.default_import.is_none() {
return block.imports.iter().any(|imp| {
matches!(
&imp.form,
ImportForm::Python {
from_import: false,
named,
} if named.iter().any(|specifier| {
specifier_imported_name(specifier) == req.module_path
})
)
});
}
if !uses_form_aware_dedup(lang) {
return is_duplicate_with_namespace(
block,
req.module_path,
req.names,
req.default_import,
req.namespace,
req.type_only,
);
}
let target = request_dedup_key(lang, req);
block
.imports
.iter()
.map(|imp| statement_dedup_key(lang, imp))
.any(|key| key == target)
}
fn uses_form_aware_dedup(lang: LangId) -> bool {
matches!(
lang,
LangId::Solidity
| LangId::C
| LangId::Cpp
| LangId::Java
| LangId::CSharp
| LangId::Php
| LangId::Kotlin
| LangId::Scala
| LangId::Swift
| LangId::Ruby
| LangId::Lua
| LangId::Perl
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ImportDedupKey {
module_path: String,
kind: ImportKind,
form: ImportForm,
}
fn statement_dedup_key(lang: LangId, imp: &ImportStatement) -> ImportDedupKey {
canonical_dedup_key(
lang,
ImportDedupKey {
module_path: imp.module_path.clone(),
kind: imp.kind,
form: imp.form.clone(),
},
)
}
fn request_dedup_key(lang: LangId, req: &ImportRequest<'_>) -> ImportDedupKey {
let key = match lang {
LangId::Solidity => {
let kind = if req.names.is_empty() && req.namespace.is_none() && req.alias.is_none() {
ImportKind::SideEffect
} else {
ImportKind::Value
};
ImportDedupKey {
module_path: req.module_path.to_string(),
kind,
form: ImportForm::Solidity {
named: req.names.to_vec(),
namespace: req.namespace.map(str::to_string),
alias: req.alias.map(str::to_string),
},
}
}
LangId::C | LangId::Cpp => structured_dedup_key(
req.module_path,
ImportKind::SideEffect,
&[],
None,
None,
&[],
Some(req.import_kind.or(req.default_import).unwrap_or("system")),
),
LangId::Java => {
let (mut module_path, modifiers) = wildcard_suffix_request(
req.module_path,
req.modifiers,
req.default_import == Some("*"),
);
let mut names = req.names.to_vec();
normalize_java_static_member_key(&mut module_path, &modifiers, &mut names);
structured_dedup_key(
&module_path,
ImportKind::Value,
&names,
None,
None,
&modifiers,
None,
)
}
LangId::CSharp => structured_dedup_key(
req.module_path,
ImportKind::Value,
&[],
None,
req.alias,
req.modifiers,
None,
),
LangId::Php => structured_dedup_key(
req.module_path,
ImportKind::Value,
&[],
None,
req.alias,
req.modifiers,
req.import_kind,
),
LangId::Kotlin => {
let wildcard = req.default_import == Some("*") || req.module_path.ends_with(".*");
let (module_path, modifiers) =
wildcard_suffix_request(req.module_path, req.modifiers, wildcard);
let alias = req
.alias
.or(req.default_import.filter(|value| *value != "*"));
structured_dedup_key(
&module_path,
ImportKind::Value,
&[],
None,
alias,
&modifiers,
None,
)
}
LangId::Scala => scala_request_dedup_key(req),
LangId::Swift => structured_dedup_key(
req.module_path,
ImportKind::Value,
&[],
None,
None,
req.modifiers,
req.import_kind,
),
LangId::Ruby => {
let mut modifiers = req.modifiers.to_vec();
if !modifiers
.iter()
.any(|modifier| modifier == "quote:single" || modifier == "quote:double")
{
modifiers.push("quote:single".to_string());
}
structured_dedup_key(
req.module_path,
ImportKind::SideEffect,
&[],
None,
None,
&modifiers,
Some(req.import_kind.unwrap_or("require")),
)
}
LangId::Lua => {
let alias = req.default_import.or(req.alias);
let kind = if alias.is_some() {
ImportKind::Value
} else {
ImportKind::SideEffect
};
structured_dedup_key(req.module_path, kind, &[], None, alias, req.modifiers, None)
}
LangId::Perl => structured_dedup_key(
req.module_path,
ImportKind::SideEffect,
&[],
None,
None,
req.modifiers,
Some(req.import_kind.unwrap_or("use")),
),
_ => structured_dedup_key(
req.module_path,
if req.type_only {
ImportKind::Type
} else {
ImportKind::Value
},
req.names,
req.namespace,
req.alias,
req.modifiers,
req.import_kind,
),
};
canonical_dedup_key(lang, key)
}
fn structured_dedup_key(
module_path: &str,
kind: ImportKind,
named: &[String],
namespace: Option<&str>,
alias: Option<&str>,
modifiers: &[String],
import_kind: Option<&str>,
) -> ImportDedupKey {
ImportDedupKey {
module_path: module_path.to_string(),
kind,
form: ImportForm::Structured {
named: named.to_vec(),
namespace: namespace.map(str::to_string),
alias: alias.map(str::to_string),
modifiers: modifiers.to_vec(),
import_kind: import_kind.map(str::to_string),
},
}
}
fn wildcard_suffix_request(
module_path: &str,
modifiers: &[String],
wildcard: bool,
) -> (String, Vec<String>) {
let stripped = module_path.strip_suffix(".*").unwrap_or(module_path);
let mut modifiers = modifiers.to_vec();
if (wildcard || stripped.len() != module_path.len())
&& !modifiers.iter().any(|modifier| modifier == "wildcard")
{
modifiers.push("wildcard".to_string());
}
(stripped.to_string(), modifiers)
}
fn normalize_java_static_member_key(
module_path: &mut String,
modifiers: &[String],
names: &mut Vec<String>,
) {
let is_static = modifiers.iter().any(|modifier| modifier == "static");
let is_wildcard = modifiers.iter().any(|modifier| modifier == "wildcard");
if !is_static || is_wildcard || !names.is_empty() {
return;
}
if let Some((prefix, member)) = module_path.rsplit_once('.') {
if !prefix.is_empty() && !member.is_empty() {
names.push(member.to_string());
*module_path = prefix.to_string();
}
}
}
fn scala_request_dedup_key(req: &ImportRequest<'_>) -> ImportDedupKey {
let mut module_path = req.module_path.to_string();
let mut names: Vec<String> = req
.names
.iter()
.map(|name| normalize_scala_selector_for_dedup(name))
.collect();
let mut identity_modifiers: Vec<String> = req
.modifiers
.iter()
.filter(|modifier| modifier.as_str() != "scala2")
.cloned()
.collect();
let mut import_kind = req.import_kind.map(str::to_string);
if req.default_import == Some("given") || module_path.ends_with(".given") {
import_kind.get_or_insert_with(|| "given".to_string());
if let Some(stripped) = module_path.strip_suffix(".given") {
module_path = stripped.to_string();
}
}
if matches!(req.default_import, Some("*") | Some("_"))
|| matches!(req.namespace, Some("*") | Some("_"))
|| module_path.ends_with(".*")
|| module_path.ends_with("._")
{
if !identity_modifiers
.iter()
.any(|modifier| modifier == "wildcard")
{
identity_modifiers.push("wildcard".to_string());
}
module_path = module_path
.strip_suffix(".*")
.or_else(|| module_path.strip_suffix("._"))
.unwrap_or(&module_path)
.to_string();
}
if names.is_empty() {
if let Some(alias) = req.alias.filter(|alias| !alias.is_empty()) {
if let Some((prefix, leaf)) = module_path.rsplit_once('.') {
names.push(format!("{leaf} as {alias}"));
module_path = prefix.to_string();
}
}
}
structured_dedup_key(
&module_path,
ImportKind::Value,
&names,
None,
None,
&identity_modifiers,
import_kind.as_deref(),
)
}
fn normalize_scala_selector_for_dedup(name: &str) -> String {
let trimmed = name.trim();
if let Some((from, to)) = trimmed.split_once("=>") {
format!("{} as {}", from.trim(), to.trim())
} else {
trimmed.to_string()
}
}
fn canonical_dedup_key(lang: LangId, mut key: ImportDedupKey) -> ImportDedupKey {
match &mut key.form {
ImportForm::Structured { named, .. } | ImportForm::Solidity { named, .. } => {
sort_named_specifiers(named);
}
ImportForm::Es { named, .. } | ImportForm::Python { named, .. } => {
sort_named_specifiers(named);
}
ImportForm::RustUse { named, .. } => {
sort_named_specifiers(named);
}
ImportForm::Go { .. } | ImportForm::Php { .. } => {}
}
if matches!(lang, LangId::Java | LangId::Kotlin) {
if let Some(stripped) = key.module_path.strip_suffix(".*") {
key.module_path = stripped.to_string();
}
if matches!(lang, LangId::Java) {
if let ImportForm::Structured {
named, modifiers, ..
} = &mut key.form
{
normalize_java_static_member_key(&mut key.module_path, modifiers, named);
}
}
} else if matches!(lang, LangId::Scala) {
key.module_path = key
.module_path
.strip_suffix(".given")
.or_else(|| key.module_path.strip_suffix(".*"))
.or_else(|| key.module_path.strip_suffix("._"))
.unwrap_or(&key.module_path)
.to_string();
}
key
}
test_support_visibility! {
fn sort_named_specifiers(names: &mut [String]) {
names.sort_by(|a, b| {
specifier_imported_name(a)
.cmp(specifier_imported_name(b))
.then_with(|| a.cmp(b))
});
}
}
pub fn find_insertion_point(
source: &str,
block: &ImportBlock,
group: ImportGroup,
module_path: &str,
type_only: bool,
) -> (usize, bool, bool) {
if block.imports.is_empty() {
return (0, false, source.is_empty().then_some(false).unwrap_or(true));
}
let target_kind = if type_only {
ImportKind::Type
} else {
ImportKind::Value
};
let group_imports: Vec<&ImportStatement> =
block.imports.iter().filter(|i| i.group == group).collect();
if group_imports.is_empty() {
let preceding_last = block.imports.iter().filter(|i| i.group < group).last();
if let Some(last) = preceding_last {
let end = last.byte_range.end;
let insert_at = skip_newline(source, end);
return (insert_at, true, true);
}
let following_first = block.imports.iter().find(|i| i.group > group);
if let Some(first) = following_first {
return (first.byte_range.start, false, true);
}
let first_byte = import_byte_range(&block.imports)
.map(|range| range.start)
.unwrap_or(0);
return (first_byte, false, true);
}
for imp in &group_imports {
let cmp = module_path.cmp(&imp.module_path);
match cmp {
std::cmp::Ordering::Less => {
return (imp.byte_range.start, false, false);
}
std::cmp::Ordering::Equal => {
if target_kind == ImportKind::Type && imp.kind == ImportKind::Value {
let end = imp.byte_range.end;
let insert_at = skip_newline(source, end);
return (insert_at, false, false);
}
return (imp.byte_range.start, false, false);
}
std::cmp::Ordering::Greater => continue,
}
}
let Some(last) = group_imports.last() else {
return (
import_byte_range(&block.imports)
.map(|range| range.end)
.unwrap_or(0),
false,
false,
);
};
let end = last.byte_range.end;
let insert_at = skip_newline(source, end);
(insert_at, false, false)
}
pub fn find_insertion_point_with_prologue(
source: &str,
tree: &Tree,
lang: LangId,
block: &ImportBlock,
group: ImportGroup,
module_path: &str,
type_only: bool,
) -> (usize, bool, bool) {
let c_block;
let block = if matches!(lang, LangId::C | LangId::Cpp) {
c_block = c::c_insertion_block(source, tree, block);
&c_block
} else {
block
};
if !block.imports.is_empty() {
let mut insertion = find_insertion_point(source, block, group, module_path, type_only);
if lang == LangId::Python {
if module_path == "__future__" {
insertion = (
block.imports.first().unwrap().byte_range.start,
false,
false,
);
} else if let Some(last) = block
.imports
.iter()
.filter(|import| import.module_path == "__future__")
.last()
{
insertion.0 = insertion.0.max(skip_newline(source, last.byte_range.end));
}
}
if matches!(lang, LangId::C | LangId::Cpp) {
insertion.1 = false;
insertion.2 = false;
}
return insertion;
}
if lang == LangId::Vue {
if let Some((start, _)) = vue_script_content_range(tree) {
return (skip_newline(source, start), false, false);
}
}
if matches!(lang, LangId::C | LangId::Cpp) {
if let (_, Some(anchor)) = c::default_include_context(source, tree) {
return (skip_newline(source, anchor), false, false);
}
}
let (anchor, blank_before) = import_prologue_anchor(source, tree, lang);
let at = skip_newline(source, anchor);
let next_is_newline = source
.as_bytes()
.get(at)
.is_some_and(|byte| matches!(byte, b'\r' | b'\n'));
(at, blank_before, !next_is_newline && at < source.len())
}
fn import_prologue_anchor(source: &str, tree: &Tree, lang: LangId) -> (usize, bool) {
let bom = if source.starts_with('\u{feff}') {
'\u{feff}'.len_utf8()
} else {
0
};
let root = tree.root_node();
let (strong, skippable): (&[&str], &[&str]) = match lang {
LangId::Go => (&["package_clause"], &["comment"]),
LangId::Java => (&["package_declaration"], &["comment"]),
LangId::Kotlin => (&["package_header"], &["comment"]),
LangId::Scala => (&["package_clause"], &["comment"]),
LangId::Solidity => (&["pragma_directive"], &["comment"]),
LangId::Php => (&["php_tag", "namespace_definition"], &["comment"]),
LangId::Perl => (&["package_statement"], &["comment"]),
_ => (&[], &[]),
};
let mut cursor = root.walk();
let mut header = None;
for child in root.named_children(&mut cursor) {
if strong.contains(&child.kind()) {
header = Some(
if lang == LangId::Php && child.kind() == "namespace_definition" {
let mut cursor = child.walk();
let brace = child
.children(&mut cursor)
.find(|node| node.kind() == "{")
.map(|node| node.end_byte())
.or_else(|| {
crate::parser::node_text(source, &child)
.find('{')
.map(|offset| child.start_byte() + offset + 1)
});
brace.unwrap_or(child.end_byte())
} else {
child.end_byte()
},
);
} else if !skippable.contains(&child.kind()) {
break;
}
}
if let Some(header) = header {
return (header, true);
}
let mut anchor = bom;
if matches!(
lang,
LangId::TypeScript
| LangId::Tsx
| LangId::JavaScript
| LangId::Python
| LangId::Ruby
| LangId::Perl
| LangId::Lua
) && source[bom..].starts_with("#!")
{
anchor = source.find('\n').unwrap_or(source.len());
}
if matches!(
lang,
LangId::TypeScript | LangId::Tsx | LangId::JavaScript | LangId::Python
) {
let mut cursor = root.walk();
let mut docstring_seen = false;
let mut run_end: Option<usize> = None;
for child in root.named_children(&mut cursor) {
if let Some(end) = run_end {
if has_blank_line_between(source, end, child.start_byte()) {
anchor = anchor.max(end);
run_end = None;
}
}
if matches!(child.kind(), "comment" | "hash_bang_line") {
if child.end_byte() <= anchor
|| child.kind() == "hash_bang_line"
|| (lang == LangId::Python && is_python_encoding_cookie(source, &child))
{
anchor = anchor.max(run_end.unwrap_or(0)).max(child.end_byte());
run_end = None;
} else {
run_end = Some(child.end_byte());
}
} else if child.kind() == "expression_statement"
&& child
.named_child(0)
.is_some_and(|expression| expression.kind() == "string")
&& (lang != LangId::Python || !docstring_seen)
{
anchor = child.end_byte();
docstring_seen = true;
run_end = None;
} else {
run_end = None;
break;
}
}
if let Some(end) = run_end {
anchor = anchor.max(end);
}
}
if lang == LangId::Solidity
&& source[bom..]
.trim_start()
.starts_with("// SPDX-License-Identifier:")
{
anchor = source.find('\n').unwrap_or(source.len());
}
(anchor, false)
}
fn has_blank_line_between(source: &str, end: usize, start: usize) -> bool {
source
.get(end..start)
.is_some_and(|gap| gap.matches('\n').count() >= 2)
}
fn is_python_encoding_cookie(source: &str, comment: &Node) -> bool {
if comment.start_position().row > 1 {
return false;
}
let text = crate::parser::node_text(source, comment);
text.match_indices("coding").any(|(at, word)| {
let rest = &text[at + word.len()..];
let Some(rest) = rest.strip_prefix([':', '=']) else {
return false;
};
rest.trim_start_matches([' ', '\t'])
.starts_with(|ch: char| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
})
}
pub fn import_insertion_text(
source: &str,
offset: usize,
line: &str,
before: bool,
after: bool,
) -> String {
let ending = crate::indent::source_line_ending(source);
let mut text = String::new();
let prefix = &source[..offset];
if !prefix.trim_start_matches('\u{feff}').is_empty() && !prefix.ends_with('\n') {
text.push_str(ending);
}
if before {
text.push_str(ending);
}
text.push_str(&line.replace("\r\n", "\n").replace('\n', ending));
text.push_str(ending);
if after {
text.push_str(ending);
}
text
}
pub fn generate_import(lang: LangId, req: &ImportRequest) -> String {
match syntax_for(lang) {
Some(engine) => engine.generate_line(req),
None => String::new(),
}
}
pub fn generate_import_line(
lang: LangId,
module_path: &str,
names: &[String],
default_import: Option<&str>,
type_only: bool,
) -> String {
generate_import(
lang,
&ImportRequest::legacy(module_path, names, default_import, None, type_only),
)
}
pub fn generate_import_line_with_namespace(
lang: LangId,
module_path: &str,
names: &[String],
default_import: Option<&str>,
namespace_import: Option<&str>,
type_only: bool,
) -> String {
generate_import_line_with_namespace_and_attribute_clause(
lang,
module_path,
names,
default_import,
namespace_import,
type_only,
None,
)
}
pub fn generate_import_line_with_namespace_and_attribute_clause(
lang: LangId,
module_path: &str,
names: &[String],
default_import: Option<&str>,
namespace_import: Option<&str>,
type_only: bool,
attribute_clause: Option<&str>,
) -> String {
generate_import_line_with_namespace_and_attribute_clause_and_style(
lang,
module_path,
names,
default_import,
namespace_import,
type_only,
attribute_clause,
None,
)
}
pub fn generate_import_line_with_namespace_and_attribute_clause_and_style(
lang: LangId,
module_path: &str,
names: &[String],
default_import: Option<&str>,
namespace_import: Option<&str>,
type_only: bool,
attribute_clause: Option<&str>,
style: Option<quotes::EsImportStyle>,
) -> String {
if matches!(
lang,
LangId::TypeScript | LangId::Tsx | LangId::JavaScript | LangId::Vue
) {
return generate_ts_import_line_with_attribute_clause(
module_path,
names,
default_import,
namespace_import,
type_only,
attribute_clause,
style.unwrap_or_default(),
);
}
generate_import(
lang,
&ImportRequest::legacy(
module_path,
names,
default_import,
namespace_import,
type_only,
),
)
}
pub fn is_supported(lang: LangId) -> bool {
syntax_for(lang).is_some()
}
pub fn classify_group_ts(module_path: &str) -> ImportGroup {
if module_path.starts_with('.') {
ImportGroup::Internal
} else {
ImportGroup::External
}
}
pub fn classify_group(lang: LangId, module_path: &str) -> ImportGroup {
match syntax_for(lang) {
Some(engine) => engine.classify_group(module_path),
None => ImportGroup::External,
}
}
pub fn parse_file_imports(
path: &std::path::Path,
lang: LangId,
) -> Result<(String, Tree, ImportBlock), crate::error::AftError> {
let source =
std::fs::read_to_string(path).map_err(|e| crate::error::AftError::FileNotFound {
path: format!("{}: {}", path.display(), e),
})?;
let tree = crate::parser::parse_source_with_cached_parser(path, &source, lang)?;
let block = parse_imports(&source, &tree, lang);
Ok((source, tree, block))
}
fn parse_ts_imports(source: &str, tree: &Tree) -> ImportBlock {
let root = tree.root_node();
let mut imports = Vec::new();
let mut cursor = root.walk();
if !cursor.goto_first_child() {
return ImportBlock::empty();
}
loop {
let node = cursor.node();
if node.kind() == "import_statement" {
if let Some(imp) = parse_single_ts_import(source, &node) {
imports.push(imp);
}
}
if !cursor.goto_next_sibling() {
break;
}
}
let byte_range = import_byte_range(&imports);
ImportBlock {
imports,
byte_range,
}
}
fn parse_single_ts_import(source: &str, node: &Node) -> Option<ImportStatement> {
let raw_text = source[node.byte_range()].to_string();
let byte_range = node.byte_range();
let module_path = node
.child_by_field_name("source")
.and_then(|module| decode_js_attribute_atom(&source[module.byte_range()]))
.or_else(|| extract_module_path(source, node))?;
let is_type_only = has_type_keyword(node);
let mut names = Vec::new();
let mut default_import = None;
let mut namespace_import = None;
let mut child_cursor = node.walk();
if child_cursor.goto_first_child() {
loop {
let child = child_cursor.node();
match child.kind() {
"import_clause" => {
extract_import_clause(
source,
&child,
&mut names,
&mut default_import,
&mut namespace_import,
);
}
"identifier" => {
let text = &source[child.byte_range()];
if text != "import" && text != "from" && text != "type" {
default_import = Some(text.to_string());
}
}
_ => {}
}
if !child_cursor.goto_next_sibling() {
break;
}
}
}
let kind = if names.is_empty() && default_import.is_none() && namespace_import.is_none() {
ImportKind::SideEffect
} else if is_type_only {
ImportKind::Type
} else {
ImportKind::Value
};
let group = classify_group_ts(&module_path);
let attribute_clause = extract_es_import_attribute_clause(source, node);
let attribute_type = attribute_clause
.as_deref()
.and_then(parse_es_import_attribute_type);
let form = ImportForm::Es {
default_import: default_import.clone(),
namespace_import: namespace_import.clone(),
named: names.clone(),
type_only: is_type_only,
side_effect: matches!(kind, ImportKind::SideEffect),
attribute_clause,
attribute_type,
};
Some(ImportStatement {
module_path,
names,
default_import,
namespace_import,
kind,
group,
byte_range,
raw_text,
form,
})
}
fn extract_es_import_attribute_clause(source: &str, node: &Node) -> Option<String> {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return None;
}
let module_end = loop {
let child = cursor.node();
if child.kind() == "string" {
break child.end_byte();
}
if !cursor.goto_next_sibling() {
return None;
}
};
let tail = source[module_end..node.end_byte()].trim();
let clause = tail.strip_suffix(';').unwrap_or(tail).trim();
(clause.starts_with("with") || clause.starts_with("assert")).then(|| clause.to_string())
}
pub fn es_import_attribute_clause(imp: &ImportStatement) -> Option<&str> {
match &imp.form {
ImportForm::Es {
attribute_clause, ..
} => attribute_clause.as_deref(),
_ => None,
}
}
pub fn es_import_attribute_type(imp: &ImportStatement) -> Option<&str> {
match &imp.form {
ImportForm::Es { attribute_type, .. } => attribute_type.as_deref(),
_ => None,
}
}
fn parse_es_import_attribute_type(clause: &str) -> Option<String> {
let body = ["with", "assert"].into_iter().find_map(|keyword| {
let rest = clause.strip_prefix(keyword)?;
rest.chars()
.next()
.is_some_and(|ch| ch.is_whitespace() || ch == '{' || ch == '/')
.then_some(rest)
})?;
let synthetic = format!("import 'module' with{body};");
let tree = crate::parser::parse_source_with_cached_parser(
std::path::Path::new("<import attributes>"),
&synthetic,
LangId::TypeScript,
)
.ok()?;
(!tree.root_node().has_error())
.then(|| find_type_attribute(&synthetic, tree.root_node()))
.flatten()
}
fn find_type_attribute(source: &str, node: Node<'_>) -> Option<String> {
if node.kind() == "pair" {
let key = node
.child_by_field_name("key")
.or_else(|| node.named_child(0))?;
let value = node
.child_by_field_name("value")
.or_else(|| node.named_child(1))?;
if decode_js_attribute_atom(source.get(key.byte_range())?)?.as_str() == "type" {
return decode_js_attribute_atom(source.get(value.byte_range())?);
}
}
let mut cursor = node.walk();
let found = node
.children(&mut cursor)
.find_map(|child| find_type_attribute(source, child));
found
}
fn decode_js_attribute_atom(text: &str) -> Option<String> {
let text = text.trim();
let quote = text.as_bytes().first().copied();
if !matches!(quote, Some(b'\'') | Some(b'"')) {
return Some(text.to_string());
}
if text.as_bytes().last().copied() != quote || text.len() < 2 {
return None;
}
let mut chars = text[1..text.len() - 1].chars();
let mut decoded = String::new();
while let Some(ch) = chars.next() {
if ch != '\\' {
decoded.push(ch);
continue;
}
match chars.next()? {
'\n' => {}
'\r' => {
if chars.clone().next() == Some('\n') {
chars.next();
}
}
'b' => decoded.push('\u{0008}'),
'f' => decoded.push('\u{000c}'),
'n' => decoded.push('\n'),
'r' => decoded.push('\r'),
't' => decoded.push('\t'),
'v' => decoded.push('\u{000b}'),
'0' => decoded.push('\0'),
'x' => decoded.push(decode_hex_escape(&mut chars, 2)?),
'u' => {
let digits = if chars.clone().next() == Some('{') {
chars.next();
let mut digits = String::new();
loop {
let ch = chars.next()?;
if ch == '}' {
break;
}
digits.push(ch);
}
digits
} else {
chars.by_ref().take(4).collect()
};
decoded.push(char::from_u32(u32::from_str_radix(&digits, 16).ok()?)?);
}
escaped => decoded.push(escaped),
}
}
Some(decoded)
}
fn decode_hex_escape(chars: &mut impl Iterator<Item = char>, count: usize) -> Option<char> {
let digits: String = chars.take(count).collect();
(digits.len() == count)
.then(|| u32::from_str_radix(&digits, 16).ok())
.flatten()
.and_then(char::from_u32)
}
fn extract_module_path(source: &str, node: &Node) -> Option<String> {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return None;
}
loop {
let child = cursor.node();
if child.kind() == "string" {
let text = &source[child.byte_range()];
let stripped = text
.trim_start_matches(|c| c == '\'' || c == '"')
.trim_end_matches(|c| c == '\'' || c == '"');
return Some(stripped.to_string());
}
if !cursor.goto_next_sibling() {
break;
}
}
None
}
fn has_type_keyword(node: &Node) -> bool {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return false;
}
loop {
let child = cursor.node();
if child.kind() == "type" {
return true;
}
if !cursor.goto_next_sibling() {
break;
}
}
false
}
fn extract_import_clause(
source: &str,
node: &Node,
names: &mut Vec<String>,
default_import: &mut Option<String>,
namespace_import: &mut Option<String>,
) {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return;
}
loop {
let child = cursor.node();
match child.kind() {
"identifier" => {
let text = &source[child.byte_range()];
if text != "type" {
*default_import = Some(text.to_string());
}
}
"named_imports" => {
extract_named_imports(source, &child, names);
}
"namespace_import" => {
extract_namespace_import(source, &child, namespace_import);
}
_ => {}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
fn extract_named_imports(source: &str, node: &Node, names: &mut Vec<String>) {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return;
}
loop {
let child = cursor.node();
if child.kind() == "import_specifier" {
let raw = source[child.byte_range()].trim().to_string();
if !raw.is_empty() {
names.push(raw);
} else if let Some(name_node) = child.child_by_field_name("name") {
names.push(source[name_node.byte_range()].to_string());
}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
fn extract_namespace_import(source: &str, node: &Node, namespace_import: &mut Option<String>) {
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return;
}
loop {
let child = cursor.node();
if child.kind() == "identifier" {
*namespace_import = Some(source[child.byte_range()].to_string());
return;
}
if !cursor.goto_next_sibling() {
break;
}
}
}
fn generate_ts_import_line(
module_path: &str,
names: &[String],
default_import: Option<&str>,
namespace_import: Option<&str>,
type_only: bool,
) -> String {
generate_ts_import_line_with_attribute_clause(
module_path,
names,
default_import,
namespace_import,
type_only,
None,
quotes::EsImportStyle::default(),
)
}
fn generate_ts_import_line_with_attribute_clause(
module_path: &str,
names: &[String],
default_import: Option<&str>,
namespace_import: Option<&str>,
type_only: bool,
attribute_clause: Option<&str>,
style: quotes::EsImportStyle,
) -> String {
let mut line = generate_ts_import_line_base(
module_path,
names,
default_import,
namespace_import,
type_only,
style.quote,
);
if let Some(attribute_clause) = attribute_clause {
line.push(' ');
line.push_str(attribute_clause.trim());
}
if style.semicolon {
line.push(';');
}
line
}
fn generate_ts_import_line_base(
module_path: &str,
names: &[String],
default_import: Option<&str>,
namespace_import: Option<&str>,
type_only: bool,
quote: char,
) -> String {
let module_path = quotes::module_literal(module_path, quote);
let type_prefix = if type_only { "type " } else { "" };
if names.is_empty() && default_import.is_none() && namespace_import.is_none() {
return format!("import {module_path}");
}
if names.is_empty() && default_import.is_none() {
if let Some(namespace) = namespace_import {
return format!("import {type_prefix}* as {namespace} from {module_path}");
}
}
if names.is_empty() {
if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
return format!("import {type_prefix}{def}, * as {namespace} from {module_path}");
}
}
if names.is_empty() && namespace_import.is_none() {
if let Some(def) = default_import {
return format!("import {type_prefix}{def} from {module_path}");
}
}
if default_import.is_none() && namespace_import.is_none() {
let mut sorted_names = names.to_vec();
sort_named_specifiers(&mut sorted_names);
let names_str = sorted_names.join(", ");
return format!("import {type_prefix}{{ {names_str} }} from {module_path}");
}
if default_import.is_none() {
if let Some(namespace) = namespace_import {
let mut sorted_names = names.to_vec();
sort_named_specifiers(&mut sorted_names);
let names_str = sorted_names.join(", ");
return format!(
"import {type_prefix}{{ {names_str} }}, * as {namespace} from {module_path}"
);
}
}
if let (Some(def), Some(namespace)) = (default_import, namespace_import) {
let mut sorted_names = names.to_vec();
sort_named_specifiers(&mut sorted_names);
let names_str = sorted_names.join(", ");
return format!(
"import {type_prefix}{def}, {{ {names_str} }}, * as {namespace} from {module_path}"
);
}
if let Some(def) = default_import {
let mut sorted_names = names.to_vec();
sort_named_specifiers(&mut sorted_names);
let names_str = sorted_names.join(", ");
return format!("import {type_prefix}{def}, {{ {names_str} }} from {module_path}");
}
format!("import {module_path}")
}
test_support_visibility! {
const PYTHON_STDLIB: &[&str] = &[
"__future__",
"_thread",
"abc",
"aifc",
"argparse",
"array",
"ast",
"asynchat",
"asyncio",
"asyncore",
"atexit",
"audioop",
"base64",
"bdb",
"binascii",
"bisect",
"builtins",
"bz2",
"cProfile",
"calendar",
"cgi",
"cgitb",
"chunk",
"cmath",
"cmd",
"code",
"codecs",
"codeop",
"collections",
"colorsys",
"compileall",
"concurrent",
"configparser",
"contextlib",
"contextvars",
"copy",
"copyreg",
"crypt",
"csv",
"ctypes",
"curses",
"dataclasses",
"datetime",
"dbm",
"decimal",
"difflib",
"dis",
"distutils",
"doctest",
"email",
"encodings",
"enum",
"errno",
"faulthandler",
"fcntl",
"filecmp",
"fileinput",
"fnmatch",
"fractions",
"ftplib",
"functools",
"gc",
"getopt",
"getpass",
"gettext",
"glob",
"graphlib",
"grp",
"gzip",
"hashlib",
"heapq",
"hmac",
"html",
"http",
"idlelib",
"imaplib",
"imghdr",
"importlib",
"inspect",
"io",
"ipaddress",
"itertools",
"json",
"keyword",
"lib2to3",
"linecache",
"locale",
"logging",
"lzma",
"mailbox",
"mailcap",
"marshal",
"math",
"mimetypes",
"mmap",
"modulefinder",
"msvcrt",
"multiprocessing",
"netrc",
"ntpath",
"numbers",
"operator",
"optparse",
"os",
"pathlib",
"pdb",
"pickle",
"pickletools",
"pipes",
"pkgutil",
"platform",
"plistlib",
"poplib",
"posix",
"posixpath",
"pprint",
"profile",
"pstats",
"pty",
"pwd",
"py_compile",
"pyclbr",
"pydoc",
"queue",
"quopri",
"random",
"re",
"readline",
"reprlib",
"resource",
"rlcompleter",
"runpy",
"sched",
"secrets",
"select",
"selectors",
"shelve",
"shlex",
"shutil",
"signal",
"site",
"smtplib",
"sndhdr",
"socket",
"socketserver",
"sqlite3",
"ssl",
"stat",
"statistics",
"string",
"stringprep",
"struct",
"subprocess",
"symtable",
"sys",
"sysconfig",
"syslog",
"tabnanny",
"tarfile",
"tempfile",
"termios",
"textwrap",
"threading",
"time",
"timeit",
"tkinter",
"token",
"tokenize",
"tomllib",
"trace",
"traceback",
"tracemalloc",
"tty",
"turtle",
"types",
"typing",
"unicodedata",
"unittest",
"urllib",
"uuid",
"venv",
"warnings",
"wave",
"weakref",
"webbrowser",
"winreg",
"winsound",
"wsgiref",
"xml",
"xmlrpc",
"zipapp",
"zipfile",
"zipimport",
"zlib",
"zoneinfo",
];
}
pub fn classify_group_py(module_path: &str) -> ImportGroup {
if module_path.starts_with('.') {
return ImportGroup::Internal;
}
let top_module = module_path.split('.').next().unwrap_or(module_path);
if PYTHON_STDLIB
.binary_search_by(|module| {
#[cfg(any(test, feature = "test-support"))]
PYTHON_STDLIB_COMPARISONS.with(|count| count.set(count.get() + 1));
module.cmp(&top_module)
})
.is_ok()
{
ImportGroup::Stdlib
} else {
ImportGroup::External
}
}
fn parse_py_imports(source: &str, tree: &Tree) -> ImportBlock {
let root = tree.root_node();
let mut imports = Vec::new();
let mut cursor = root.walk();
if !cursor.goto_first_child() {
return ImportBlock::empty();
}
loop {
let node = cursor.node();
match node.kind() {
"import_statement" => {
if let Some(imp) = parse_py_import_statement(source, &node) {
imports.push(imp);
}
}
"import_from_statement" | "future_import_statement" => {
if let Some(imp) = parse_py_import_from_statement(source, &node) {
imports.push(imp);
}
}
_ => {}
}
if !cursor.goto_next_sibling() {
break;
}
}
let byte_range = import_byte_range(&imports);
ImportBlock {
imports,
byte_range,
}
}
pub fn parse_py_import_node(source: &str, node: &Node) -> Option<ImportStatement> {
match node.kind() {
"import_statement" => parse_py_import_statement(source, node),
"import_from_statement" | "future_import_statement" => {
parse_py_import_from_statement(source, node)
}
_ => None,
}
}
fn parse_py_import_statement(source: &str, node: &Node) -> Option<ImportStatement> {
let raw_text = source[node.byte_range()].to_string();
let byte_range = node.byte_range();
let mut specifiers = Vec::new();
let mut c = node.walk();
if c.goto_first_child() {
loop {
let child = c.node();
if matches!(child.kind(), "dotted_name" | "aliased_import") {
specifiers.push(source[child.byte_range()].trim().to_string());
}
if !c.goto_next_sibling() {
break;
}
}
}
let module_path = specifiers
.first()
.map(|specifier| specifier_imported_name(specifier).to_string())?;
let group = classify_group_py(&module_path);
Some(ImportStatement {
module_path,
names: Vec::new(),
default_import: None,
namespace_import: None,
kind: ImportKind::Value,
group,
byte_range,
raw_text,
form: ImportForm::Python {
from_import: false,
named: specifiers,
},
})
}
fn parse_py_import_from_statement(source: &str, node: &Node) -> Option<ImportStatement> {
let raw_text = source[node.byte_range()].to_string();
let byte_range = node.byte_range();
let mut module_path = if node.kind() == "future_import_statement" {
"__future__".to_string()
} else {
String::new()
};
let mut names = Vec::new();
let mut c = node.walk();
if c.goto_first_child() {
loop {
let child = c.node();
match child.kind() {
"dotted_name" => {
if module_path.is_empty()
&& !has_seen_import_keyword(source, node, child.start_byte())
{
module_path = source[child.byte_range()].to_string();
} else {
names.push(source[child.byte_range()].to_string());
}
}
"relative_import" => {
module_path = source[child.byte_range()].to_string();
}
"aliased_import" => {
names.push(source[child.byte_range()].trim().to_string());
}
_ => {}
}
if !c.goto_next_sibling() {
break;
}
}
}
if module_path.is_empty() {
return None;
}
let group = classify_group_py(&module_path);
Some(ImportStatement {
module_path,
names: names.clone(),
default_import: None,
namespace_import: None,
kind: ImportKind::Value,
group,
byte_range,
raw_text,
form: ImportForm::Python {
from_import: true,
named: names,
},
})
}
fn has_seen_import_keyword(_source: &str, parent: &Node, before_byte: usize) -> bool {
let mut c = parent.walk();
if c.goto_first_child() {
loop {
let child = c.node();
if child.kind() == "import" && child.start_byte() < before_byte {
return true;
}
if child.start_byte() >= before_byte {
return false;
}
if !c.goto_next_sibling() {
break;
}
}
}
false
}
fn generate_py_import_line(
module_path: &str,
names: &[String],
_default_import: Option<&str>,
) -> String {
if names.is_empty() {
format!("import {module_path}")
} else {
let mut sorted = names.to_vec();
sorted.sort();
let names_str = sorted.join(", ");
format!("from {module_path} import {names_str}")
}
}
pub fn classify_group_rs(module_path: &str) -> ImportGroup {
let first_seg = module_path.split("::").next().unwrap_or(module_path);
match first_seg {
"std" | "core" | "alloc" => ImportGroup::Stdlib,
"crate" | "self" | "super" => ImportGroup::Internal,
_ => ImportGroup::External,
}
}
fn parse_rs_imports(source: &str, tree: &Tree) -> ImportBlock {
let root = tree.root_node();
let mut imports = Vec::new();
let mut cursor = root.walk();
if !cursor.goto_first_child() {
return ImportBlock::empty();
}
loop {
let node = cursor.node();
if node.kind() == "use_declaration" {
if let Some(imp) = parse_rs_use_declaration(source, &node) {
imports.push(imp);
}
}
if !cursor.goto_next_sibling() {
break;
}
}
let byte_range = import_byte_range(&imports);
ImportBlock {
imports,
byte_range,
}
}
fn parse_rs_use_declaration(source: &str, node: &Node) -> Option<ImportStatement> {
let raw_text = source[node.byte_range()].to_string();
let byte_range = node.byte_range();
let mut visibility: Option<String> = None;
let mut use_path = String::new();
let mut names = Vec::new();
let mut c = node.walk();
if c.goto_first_child() {
loop {
let child = c.node();
match child.kind() {
"visibility_modifier" => {
visibility = Some(source[child.byte_range()].to_string());
}
"scoped_identifier" | "identifier" | "use_as_clause" => {
use_path = source[child.byte_range()].to_string();
}
"scoped_use_list" => {
use_path = child
.child_by_field_name("path")
.map(|path| source[path.byte_range()].to_string())
.unwrap_or_default();
extract_rs_use_list_names(source, &child, &mut names);
}
"use_list" => extract_rs_use_list_names(source, &child, &mut names),
_ => {}
}
if !c.goto_next_sibling() {
break;
}
}
}
if use_path.is_empty() && names.is_empty() {
return None;
}
let group = classify_group_rs(&use_path);
Some(ImportStatement {
module_path: use_path,
names: names.clone(),
default_import: visibility.clone(),
namespace_import: None,
kind: ImportKind::Value,
group,
byte_range,
raw_text,
form: ImportForm::RustUse {
visibility,
named: names,
},
})
}
fn extract_rs_use_list_names(source: &str, node: &Node, names: &mut Vec<String>) {
let list = if node.kind() == "use_list" {
*node
} else {
let mut cursor = node.walk();
let Some(list) = node
.named_children(&mut cursor)
.find(|child| child.kind() == "use_list")
else {
return;
};
list
};
let mut cursor = list.walk();
for child in list.named_children(&mut cursor) {
if !matches!(child.kind(), "line_comment" | "block_comment") {
names.push(source[child.byte_range()].to_string());
}
}
}
pub fn rust_use_tree(import: &ImportStatement) -> String {
if import.names.is_empty() {
import.module_path.clone()
} else if import.module_path.is_empty() {
format!("{{{}}}", import.names.join(", "))
} else {
format!("{}::{{{}}}", import.module_path, import.names.join(", "))
}
}
fn generate_rs_import_line(module_path: &str, names: &[String], _type_only: bool) -> String {
if names.is_empty() {
format!("use {module_path};")
} else {
let mut sorted_names = names.to_vec();
sort_named_specifiers(&mut sorted_names);
let separator = if module_path.is_empty() { "" } else { "::" };
format!(
"use {module_path}{separator}{{{}}};",
sorted_names.join(", ")
)
}
}
pub fn classify_group_go(module_path: &str) -> ImportGroup {
if module_path.contains('.') {
ImportGroup::External
} else {
ImportGroup::Stdlib
}
}
fn parse_go_imports(source: &str, tree: &Tree) -> ImportBlock {
let root = tree.root_node();
let mut imports = Vec::new();
let mut cursor = root.walk();
if !cursor.goto_first_child() {
return ImportBlock::empty();
}
loop {
let node = cursor.node();
if node.kind() == "import_declaration" {
parse_go_import_declaration(source, &node, &mut imports);
}
if !cursor.goto_next_sibling() {
break;
}
}
let byte_range = import_byte_range(&imports);
ImportBlock {
imports,
byte_range,
}
}
fn parse_go_import_declaration(source: &str, node: &Node, imports: &mut Vec<ImportStatement>) {
let mut c = node.walk();
if c.goto_first_child() {
loop {
let child = c.node();
match child.kind() {
"import_spec" => {
if let Some(imp) = parse_go_import_spec(source, &child) {
imports.push(imp);
}
}
"import_spec_list" => {
let mut lc = child.walk();
if lc.goto_first_child() {
loop {
if lc.node().kind() == "import_spec" {
if let Some(imp) = parse_go_import_spec(source, &lc.node()) {
imports.push(imp);
}
}
if !lc.goto_next_sibling() {
break;
}
}
}
}
_ => {}
}
if !c.goto_next_sibling() {
break;
}
}
}
}
fn parse_go_import_spec(source: &str, node: &Node) -> Option<ImportStatement> {
let raw_text = source[node.byte_range()].to_string();
let byte_range = node.byte_range();
let mut import_path = String::new();
let mut alias = None;
let mut c = node.walk();
if c.goto_first_child() {
loop {
let child = c.node();
match child.kind() {
"interpreted_string_literal" => {
let text = source[child.byte_range()].to_string();
import_path = text.trim_matches('"').to_string();
}
"identifier" | "blank_identifier" | "dot" => {
alias = Some(source[child.byte_range()].to_string());
}
_ => {}
}
if !c.goto_next_sibling() {
break;
}
}
}
if import_path.is_empty() {
return None;
}
let group = classify_group_go(&import_path);
Some(ImportStatement {
module_path: import_path,
names: Vec::new(),
default_import: alias.clone(),
namespace_import: None,
kind: ImportKind::Value,
group,
byte_range,
raw_text,
form: ImportForm::Go { alias },
})
}
pub fn generate_go_import_line_pub(
module_path: &str,
alias: Option<&str>,
in_group: bool,
) -> String {
generate_go_import_line(module_path, alias, in_group)
}
test_support_visibility! {
fn generate_go_import_line(module_path: &str, alias: Option<&str>, in_group: bool) -> String {
if in_group {
match alias {
Some(a) => format!("\t{a} \"{module_path}\""),
None => format!("\t\"{module_path}\""),
}
} else {
match alias {
Some(a) => format!("import {a} \"{module_path}\""),
None => format!("import \"{module_path}\""),
}
}
}
}
pub fn go_has_grouped_import(_source: &str, tree: &Tree) -> Option<Range<usize>> {
let root = tree.root_node();
let mut cursor = root.walk();
if !cursor.goto_first_child() {
return None;
}
loop {
let node = cursor.node();
if node.kind() == "import_declaration" && go_import_declaration_is_grouped(&node) {
return Some(node.byte_range());
}
if !cursor.goto_next_sibling() {
break;
}
}
None
}
pub fn go_import_declarations_range(_source: &str, tree: &Tree) -> Option<Range<usize>> {
let root = tree.root_node();
let mut cursor = root.walk();
let mut range: Option<Range<usize>> = None;
if !cursor.goto_first_child() {
return None;
}
loop {
let node = cursor.node();
if node.kind() == "import_declaration" {
let node_range = node.byte_range();
range = Some(match range {
Some(existing) => {
existing.start.min(node_range.start)..existing.end.max(node_range.end)
}
None => node_range,
});
}
if !cursor.goto_next_sibling() {
break;
}
}
range
}
pub fn go_offset_is_in_grouped_import(_source: &str, tree: &Tree, offset: usize) -> bool {
let root = tree.root_node();
let mut cursor = root.walk();
if !cursor.goto_first_child() {
return false;
}
loop {
let node = cursor.node();
if node.kind() == "import_declaration"
&& node.start_byte() < offset
&& offset < node.end_byte()
&& go_import_declaration_is_grouped(&node)
{
return true;
}
if !cursor.goto_next_sibling() {
break;
}
}
false
}
fn go_import_declaration_is_grouped(node: &Node) -> bool {
let mut c = node.walk();
if c.goto_first_child() {
loop {
if c.node().kind() == "import_spec_list" {
return true;
}
if !c.goto_next_sibling() {
break;
}
}
}
false
}
pub fn classify_group_solidity(module_path: &str) -> ImportGroup {
if module_path.starts_with('.') {
ImportGroup::Internal
} else {
ImportGroup::External
}
}
fn parse_solidity_imports(source: &str, tree: &Tree) -> ImportBlock {
let root = tree.root_node();
let mut imports = Vec::new();
let mut cursor = root.walk();
if cursor.goto_first_child() {
loop {
let node = cursor.node();
if node.kind() == "import_directive" {
if let Some(imp) = parse_solidity_import_directive(source, &node) {
imports.push(imp);
}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
let byte_range = import_byte_range(&imports);
ImportBlock {
imports,
byte_range,
}
}
test_support_visibility! {
fn strip_one_matching_solidity_quote_pair(value: &str) -> &str {
if value.len() < 2 {
return value;
}
let bytes = value.as_bytes();
let quote = bytes[0];
if matches!(quote, b'\'' | b'"') && bytes.last() == Some("e) {
&value[1..value.len() - 1]
} else {
value
}
}
}
fn parse_solidity_import_directive(source: &str, node: &Node) -> Option<ImportStatement> {
let raw_text = source[node.byte_range()].to_string();
let byte_range = node.byte_range();
let mut children: Vec<(String, String)> = Vec::new();
let mut c = node.walk();
if c.goto_first_child() {
loop {
let ch = c.node();
children.push((ch.kind().to_string(), source[ch.byte_range()].to_string()));
if !c.goto_next_sibling() {
break;
}
}
}
let module_path = children
.iter()
.find(|(k, _)| k == "string")
.map(|(_, text)| strip_one_matching_solidity_quote_pair(text).to_string())?;
if module_path.is_empty() {
return None;
}
let has_brace = children.iter().any(|(k, _)| k == "{");
let has_star = children.iter().any(|(k, _)| k == "*");
let mut named: Vec<String> = Vec::new();
let mut namespace: Option<String> = None;
let mut alias: Option<String> = None;
if has_brace {
named = parse_solidity_named_specifiers(&children);
} else if has_star {
namespace = solidity_identifier_after_as(&children);
} else {
alias = solidity_identifier_after_as(&children);
}
let kind = if named.is_empty() && namespace.is_none() && alias.is_none() {
ImportKind::SideEffect
} else {
ImportKind::Value
};
let group = classify_group_solidity(&module_path);
Some(ImportStatement {
module_path,
names: named.clone(),
default_import: None,
namespace_import: namespace.clone(),
kind,
group,
byte_range,
raw_text,
form: ImportForm::Solidity {
named,
namespace,
alias,
},
})
}
fn solidity_identifier_after_as(children: &[(String, String)]) -> Option<String> {
let as_pos = children.iter().position(|(k, _)| k == "as")?;
children[as_pos + 1..]
.iter()
.find(|(k, _)| k == "identifier")
.map(|(_, t)| t.clone())
}
fn parse_solidity_named_specifiers(children: &[(String, String)]) -> Vec<String> {
let mut names = Vec::new();
let mut in_braces = false;
let mut current: Option<String> = None;
let mut expect_alias = false;
for (k, t) in children {
match k.as_str() {
"{" => in_braces = true,
"}" => {
if let Some(n) = current.take() {
names.push(n);
}
in_braces = false;
}
_ if !in_braces => {}
"identifier" => {
if expect_alias {
if let Some(n) = current.take() {
names.push(format!("{n} as {t}"));
}
expect_alias = false;
} else {
if let Some(n) = current.take() {
names.push(n);
}
current = Some(t.clone());
}
}
"as" => expect_alias = true,
"," => {
if let Some(n) = current.take() {
names.push(n);
}
expect_alias = false;
}
_ => {}
}
}
names
}
fn generate_solidity_import_line(req: &ImportRequest) -> String {
if !req.names.is_empty() {
format!(
"import {{ {} }} from \"{}\";",
req.names.join(", "),
req.module_path
)
} else if let Some(ns) = req.namespace {
format!("import * as {} from \"{}\";", ns, req.module_path)
} else if let Some(al) = req.alias {
format!("import \"{}\" as {};", req.module_path, al)
} else {
format!("import \"{}\";", req.module_path)
}
}
fn skip_newline(source: &str, pos: usize) -> usize {
if pos < source.len() {
let bytes = source.as_bytes();
if bytes[pos] == b'\n' {
return pos + 1;
}
if bytes[pos] == b'\r' {
if pos + 1 < source.len() && bytes[pos + 1] == b'\n' {
return pos + 2;
}
return pos + 1;
}
}
pos
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
pub static PYTHON_STDLIB_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}