Make ImportFrom level just a u32 (#11170)

This commit is contained in:
Carl Meyer 2024-04-26 20:38:35 -06:00 committed by GitHub
parent 5994414739
commit 845ba7cf5f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
34 changed files with 100 additions and 182 deletions

View file

@ -464,7 +464,7 @@ impl<'a> Visitor<'a> for Checker<'a> {
let level = *level;
// Mark the top-level module as "seen" by the semantic model.
if level.map_or(true, |level| level == 0) {
if level == 0 {
if let Some(module) = module.and_then(|module| module.split('.').next()) {
self.semantic.add_module(module);
}

View file

@ -39,7 +39,7 @@ fn extract_import_map(path: &Path, package: Option<&Path>, blocks: &[&Block]) ->
level,
range: _,
}) => {
let level = level.unwrap_or_default() as usize;
let level = *level as usize;
let module = if let Some(module) = module {
let module: &String = module.as_ref();
if level == 0 {

View file

@ -405,7 +405,7 @@ impl<'a> Importer<'a> {
range: _,
}) = stmt
{
if level.map_or(true, |level| level == 0)
if *level == 0
&& name.as_ref().is_some_and(|name| name == module)
&& names.iter().all(|alias| alias.name.as_str() != "*")
{

View file

@ -54,13 +54,11 @@ pub(crate) fn import(import_from: &Stmt, name: &str, asname: Option<&str>) -> Op
pub(crate) fn import_from(
import_from: &Stmt,
module: Option<&str>,
level: Option<u32>,
level: u32,
) -> Option<Diagnostic> {
// If level is not zero or module is none, return
if let Some(level) = level {
if level != 0 {
return None;
}
if level != 0 {
return None;
};
if let Some(module) = module {

View file

@ -76,7 +76,7 @@ impl Violation for RelativeImports {
fn fix_banned_relative_import(
stmt: &Stmt,
level: Option<u32>,
level: u32,
module: Option<&str>,
module_path: Option<&[String]>,
generator: Generator,
@ -99,7 +99,7 @@ fn fix_banned_relative_import(
TextRange::default(),
)),
names: names.clone(),
level: Some(0),
level: 0,
range: TextRange::default(),
};
let content = generator.stmt(&node.into());
@ -113,7 +113,7 @@ fn fix_banned_relative_import(
pub(crate) fn banned_relative_import(
checker: &Checker,
stmt: &Stmt,
level: Option<u32>,
level: u32,
module: Option<&str>,
module_path: Option<&[String]>,
strictness: Strictness,
@ -122,7 +122,7 @@ pub(crate) fn banned_relative_import(
Strictness::All => 0,
Strictness::Parents => 1,
};
if level? > strictness_level {
if level > strictness_level {
let mut diagnostic = Diagnostic::new(RelativeImports { strictness }, stmt.range());
if let Some(fix) =
fix_banned_relative_import(stmt, level, module, module_path, checker.generator())

View file

@ -300,7 +300,7 @@ pub(crate) fn typing_only_runtime_import(
// Categorize the import, using coarse-grained categorization.
let import_type = match categorize(
&qualified_name.to_string(),
None,
0,
&checker.settings.src,
checker.package(),
checker.settings.isort.detect_same_package,

View file

@ -92,7 +92,7 @@ enum Reason<'a> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn categorize<'a>(
module_name: &str,
level: Option<u32>,
level: u32,
src: &[PathBuf],
package: Option<&Path>,
detect_same_package: bool,
@ -104,14 +104,14 @@ pub(crate) fn categorize<'a>(
) -> &'a ImportSection {
let module_base = module_name.split('.').next().unwrap();
let (mut import_type, mut reason) = {
if matches!(level, None | Some(0)) && module_base == "__future__" {
if level == 0 && module_base == "__future__" {
(&ImportSection::Known(ImportType::Future), Reason::Future)
} else if no_sections {
(
&ImportSection::Known(ImportType::FirstParty),
Reason::NoSections,
)
} else if level.is_some_and(|level| level > 0) {
} else if level > 0 {
(
&ImportSection::Known(ImportType::LocalFolder),
Reason::NonZeroLevel,
@ -133,7 +133,7 @@ pub(crate) fn categorize<'a>(
&ImportSection::Known(ImportType::FirstParty),
Reason::SourceMatch(src),
)
} else if matches!(level, None | Some(0)) && module_name == "__main__" {
} else if level == 0 && module_name == "__main__" {
(
&ImportSection::Known(ImportType::FirstParty),
Reason::KnownFirstParty,
@ -191,7 +191,7 @@ pub(crate) fn categorize_imports<'a>(
for (alias, comments) in block.import {
let import_type = categorize(
&alias.module_name(),
None,
0,
src,
package,
detect_same_package,

View file

@ -52,7 +52,7 @@ pub(crate) enum AnnotatedImport<'a> {
ImportFrom {
module: Option<&'a str>,
names: Vec<AnnotatedAliasData<'a>>,
level: Option<u32>,
level: u32,
atop: Vec<Comment<'a>>,
inline: Vec<Comment<'a>>,
trailing_comma: TrailingComma,

View file

@ -73,7 +73,7 @@ pub(crate) fn order_imports<'a>(
ModuleKey::from_module(
Some(alias.name),
alias.asname,
None,
0,
None,
ImportStyle::Straight,
settings,
@ -90,7 +90,7 @@ pub(crate) fn order_imports<'a>(
Import((alias, _)) => ModuleKey::from_module(
Some(alias.name),
alias.asname,
None,
0,
None,
ImportStyle::Straight,
settings,
@ -110,7 +110,7 @@ pub(crate) fn order_imports<'a>(
ModuleKey::from_module(
Some(alias.name),
alias.asname,
None,
0,
None,
ImportStyle::Straight,
settings,

View file

@ -97,7 +97,7 @@ impl<'a> ModuleKey<'a> {
pub(crate) fn from_module(
name: Option<&'a str>,
asname: Option<&'a str>,
level: Option<u32>,
level: u32,
first_alias: Option<(&'a str, Option<&'a str>)>,
style: ImportStyle,
settings: &Settings,
@ -106,13 +106,11 @@ impl<'a> ModuleKey<'a> {
let maybe_length = (settings.length_sort
|| (settings.length_sort_straight && style == ImportStyle::Straight))
.then_some(
name.map(str::width).unwrap_or_default() + level.unwrap_or_default() as usize,
);
.then_some(name.map(str::width).unwrap_or_default() + level as usize);
let distance = match level {
None | Some(0) => Distance::None,
Some(level) => match settings.relative_imports_order {
0 => Distance::None,
_ => match settings.relative_imports_order {
RelativeImportsOrder::ClosestToFurthest => Distance::Nearest(level),
RelativeImportsOrder::FurthestToClosest => Distance::Furthest(Reverse(level)),
},

View file

@ -14,7 +14,7 @@ pub(crate) enum TrailingComma {
#[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq, Clone)]
pub(crate) struct ImportFromData<'a> {
pub(crate) module: Option<&'a str>,
pub(crate) level: Option<u32>,
pub(crate) level: u32,
}
#[derive(Debug, Hash, Ord, PartialOrd, Eq, PartialEq)]

View file

@ -51,7 +51,7 @@ pub(crate) fn import_self(alias: &Alias, module_path: Option<&[String]>) -> Opti
/// PLW0406
pub(crate) fn import_from_self(
level: Option<u32>,
level: u32,
module: Option<&str>,
names: &[Alias],
module_path: Option<&[String]>,

View file

@ -78,7 +78,7 @@ pub(crate) fn manual_from_import(
asname: None,
range: TextRange::default(),
}],
level: Some(0),
level: 0,
range: TextRange::default(),
};
diagnostic.set_fix(Fix::safe_edit(Edit::range_replacement(

View file

@ -68,7 +68,7 @@ pub(crate) fn deprecated_c_element_tree(checker: &mut Checker, stmt: &Stmt) {
level,
range: _,
}) => {
if level.is_some_and(|level| level > 0) {
if *level > 0 {
// Ex) `import .xml.etree.cElementTree as ET`
} else if let Some(module) = module {
if module == "xml.etree.cElementTree" {

View file

@ -643,10 +643,10 @@ pub(crate) fn deprecated_import(
stmt: &Stmt,
names: &[Alias],
module: Option<&str>,
level: Option<u32>,
level: u32,
) {
// Avoid relative and star imports.
if level.is_some_and(|level| level > 0) {
if level > 0 {
return;
}
if names.first().is_some_and(|name| &name.name == "*") {

View file

@ -319,7 +319,7 @@ pub(crate) fn deprecated_mock_import(checker: &mut Checker, stmt: &Stmt) {
level,
..
}) => {
if level.is_some_and(|level| level > 0) {
if *level > 0 {
return;
}

View file

@ -1306,7 +1306,7 @@ pub struct StmtImport<'a> {
pub struct StmtImportFrom<'a> {
module: Option<&'a str>,
names: Vec<ComparableAlias<'a>>,
level: Option<u32>,
level: u32,
}
#[derive(Debug, PartialEq, Eq, Hash)]

View file

@ -732,13 +732,13 @@ where
/// ```rust
/// # use ruff_python_ast::helpers::format_import_from;
///
/// assert_eq!(format_import_from(None, None), "".to_string());
/// assert_eq!(format_import_from(Some(1), None), ".".to_string());
/// assert_eq!(format_import_from(Some(1), Some("foo")), ".foo".to_string());
/// assert_eq!(format_import_from(0, None), "".to_string());
/// assert_eq!(format_import_from(1, None), ".".to_string());
/// assert_eq!(format_import_from(1, Some("foo")), ".foo".to_string());
/// ```
pub fn format_import_from(level: Option<u32>, module: Option<&str>) -> String {
pub fn format_import_from(level: u32, module: Option<&str>) -> String {
let mut module_name = String::with_capacity(16);
if let Some(level) = level {
if level > 0 {
for _ in 0..level {
module_name.push('.');
}
@ -756,18 +756,15 @@ pub fn format_import_from(level: Option<u32>, module: Option<&str>) -> String {
/// ```rust
/// # use ruff_python_ast::helpers::format_import_from_member;
///
/// assert_eq!(format_import_from_member(None, None, "bar"), "bar".to_string());
/// assert_eq!(format_import_from_member(Some(1), None, "bar"), ".bar".to_string());
/// assert_eq!(format_import_from_member(Some(1), Some("foo"), "bar"), ".foo.bar".to_string());
/// assert_eq!(format_import_from_member(0, None, "bar"), "bar".to_string());
/// assert_eq!(format_import_from_member(1, None, "bar"), ".bar".to_string());
/// assert_eq!(format_import_from_member(1, Some("foo"), "bar"), ".foo.bar".to_string());
/// ```
pub fn format_import_from_member(level: Option<u32>, module: Option<&str>, member: &str) -> String {
pub fn format_import_from_member(level: u32, module: Option<&str>, member: &str) -> String {
let mut qualified_name = String::with_capacity(
(level.unwrap_or(0) as usize)
+ module.as_ref().map_or(0, |module| module.len())
+ 1
+ member.len(),
(level as usize) + module.as_ref().map_or(0, |module| module.len()) + 1 + member.len(),
);
if let Some(level) = level {
if level > 0 {
for _ in 0..level {
qualified_name.push('.');
}
@ -801,17 +798,17 @@ pub fn to_module_path(package: &Path, path: &Path) -> Option<Vec<String>> {
/// ```rust
/// # use ruff_python_ast::helpers::collect_import_from_member;
///
/// assert_eq!(collect_import_from_member(None, None, "bar").segments(), ["bar"]);
/// assert_eq!(collect_import_from_member(Some(1), None, "bar").segments(), [".", "bar"]);
/// assert_eq!(collect_import_from_member(Some(1), Some("foo"), "bar").segments(), [".", "foo", "bar"]);
/// assert_eq!(collect_import_from_member(0, None, "bar").segments(), ["bar"]);
/// assert_eq!(collect_import_from_member(1, None, "bar").segments(), [".", "bar"]);
/// assert_eq!(collect_import_from_member(1, Some("foo"), "bar").segments(), [".", "foo", "bar"]);
/// ```
pub fn collect_import_from_member<'a>(
level: Option<u32>,
level: u32,
module: Option<&'a str>,
member: &'a str,
) -> QualifiedName<'a> {
let mut qualified_name_builder = QualifiedNameBuilder::with_capacity(
level.unwrap_or_default() as usize
level as usize
+ module
.map(|module| module.split('.').count())
.unwrap_or_default()
@ -819,11 +816,9 @@ pub fn collect_import_from_member<'a>(
);
// Include the dots as standalone segments.
if let Some(level) = level {
if level > 0 {
for _ in 0..level {
qualified_name_builder.push(".");
}
if level > 0 {
for _ in 0..level {
qualified_name_builder.push(".");
}
}
@ -875,14 +870,10 @@ pub fn from_relative_import<'a>(
/// Given an imported module (based on its relative import level and module name), return the
/// fully-qualified module path.
pub fn resolve_imported_module_path<'a>(
level: Option<u32>,
level: u32,
module: Option<&'a str>,
module_path: Option<&[String]>,
) -> Option<Cow<'a, str>> {
let Some(level) = level else {
return Some(Cow::Borrowed(module.unwrap_or("")));
};
if level == 0 {
return Some(Cow::Borrowed(module.unwrap_or("")));
}
@ -1572,14 +1563,14 @@ mod tests {
fn resolve_import() {
// Return the module directly.
assert_eq!(
resolve_imported_module_path(None, Some("foo"), None),
resolve_imported_module_path(0, Some("foo"), None),
Some(Cow::Borrowed("foo"))
);
// Construct the module path from the calling module's path.
assert_eq!(
resolve_imported_module_path(
Some(1),
1,
Some("foo"),
Some(&["bar".to_string(), "baz".to_string()])
),
@ -1588,19 +1579,16 @@ mod tests {
// We can't return the module if it's a relative import, and we don't know the calling
// module's path.
assert_eq!(
resolve_imported_module_path(Some(1), Some("foo"), None),
None
);
assert_eq!(resolve_imported_module_path(1, Some("foo"), None), None);
// We can't return the module if it's a relative import, and the path goes beyond the
// calling module's path.
assert_eq!(
resolve_imported_module_path(Some(1), Some("foo"), Some(&["bar".to_string()])),
resolve_imported_module_path(1, Some("foo"), Some(&["bar".to_string()])),
None,
);
assert_eq!(
resolve_imported_module_path(Some(2), Some("foo"), Some(&["bar".to_string()])),
resolve_imported_module_path(2, Some("foo"), Some(&["bar".to_string()])),
None
);
}

View file

@ -21,7 +21,7 @@ pub struct Import<'a> {
pub struct ImportFrom<'a> {
pub module: Option<&'a str>,
pub name: Alias<'a>,
pub level: Option<u32>,
pub level: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@ -51,7 +51,7 @@ impl<'a> ImportFrom<'a> {
name,
as_name: None,
},
level: None,
level: 0,
}
}
}
@ -78,8 +78,8 @@ impl std::fmt::Display for Import<'_> {
impl std::fmt::Display for ImportFrom<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "from ")?;
if let Some(level) = self.level {
write!(f, "{}", ".".repeat(level as usize))?;
if self.level > 0 {
write!(f, "{}", ".".repeat(self.level as usize))?;
}
if let Some(module) = self.module {
write!(f, "{module}")?;

View file

@ -471,7 +471,7 @@ pub struct StmtImportFrom {
pub range: TextRange,
pub module: Option<Identifier>,
pub names: Vec<Alias>,
pub level: Option<u32>,
pub level: u32,
}
impl From<StmtImportFrom> for Stmt {

View file

@ -571,7 +571,7 @@ impl<'a> Generator<'a> {
}) => {
statement!({
self.p("from ");
if let Some(level) = level {
if *level > 0 {
for _ in 0..*level {
self.p(".");
}

View file

@ -28,7 +28,7 @@ impl FormatNodeRule<StmtImportFrom> for FormatStmtImportFrom {
token("from"),
space(),
format_with(|f| {
for _ in 0..level.unwrap_or(0) {
for _ in 0..*level {
token(".").fmt(f)?;
}
Ok(())

View file

@ -573,7 +573,7 @@ impl<'src> Parser<'src> {
ast::StmtImportFrom {
module,
names,
level: Some(leading_dots),
level: leading_dots,
range: self.node_range(start),
}
}

View file

@ -28,9 +28,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -60,9 +58,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -132,9 +128,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
],

View file

@ -19,9 +19,7 @@ Module(
},
),
names: [],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -34,9 +32,7 @@ Module(
},
),
names: [],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -49,9 +45,7 @@ Module(
},
),
names: [],
level: Some(
0,
),
level: 0,
},
),
],

View file

@ -14,9 +14,7 @@ Module(
range: 0..4,
module: None,
names: [],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -33,9 +31,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
],

View file

@ -36,9 +36,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
Expr(
@ -95,9 +93,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
Expr(

View file

@ -36,9 +36,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -76,9 +74,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -113,9 +109,7 @@ Module(
),
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -153,9 +147,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
],

View file

@ -28,9 +28,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -57,9 +55,7 @@ Module(
),
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -89,9 +85,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
],

View file

@ -23,9 +23,7 @@ Module(
asname: None,
},
],
level: Some(
1,
),
level: 1,
},
),
ImportFrom(
@ -42,9 +40,7 @@ Module(
asname: None,
},
],
level: Some(
3,
),
level: 3,
},
),
],

View file

@ -36,9 +36,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -68,9 +66,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
Expr(
@ -128,9 +124,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
Expr(
@ -188,9 +182,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
Expr(

View file

@ -49,9 +49,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
Expr(

View file

@ -28,9 +28,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -47,9 +45,7 @@ Module(
asname: None,
},
],
level: Some(
1,
),
level: 1,
},
),
ImportFrom(
@ -89,9 +85,7 @@ Module(
),
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -113,9 +107,7 @@ Module(
asname: None,
},
],
level: Some(
1,
),
level: 1,
},
),
ImportFrom(
@ -132,9 +124,7 @@ Module(
asname: None,
},
],
level: Some(
3,
),
level: 3,
},
),
ImportFrom(
@ -151,9 +141,7 @@ Module(
asname: None,
},
],
level: Some(
26,
),
level: 26,
},
),
ImportFrom(
@ -175,9 +163,7 @@ Module(
asname: None,
},
],
level: Some(
26,
),
level: 26,
},
),
ImportFrom(
@ -220,9 +206,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
ImportFrom(
@ -244,9 +228,7 @@ Module(
asname: None,
},
],
level: Some(
0,
),
level: 0,
},
),
],

View file

@ -1,7 +1,7 @@
#[derive(Debug, Clone)]
pub struct StarImport<'a> {
/// The level of the import. `None` or `Some(0)` indicate an absolute import.
pub level: Option<u32>,
/// The level of the import. `0` indicates an absolute import.
pub level: u32,
/// The module being imported. `None` indicates a wildcard import.
pub module: Option<&'a str>,
}