Update Rust to v1.77 (#10510)

This commit is contained in:
Charlie Marsh 2024-03-21 12:10:33 -04:00 committed by GitHub
parent ac150b9314
commit 60fd98eb2f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 35 additions and 84 deletions

View file

@ -252,6 +252,7 @@ mod test {
for file in [&pyproject_toml, &python_file, &notebook] { for file in [&pyproject_toml, &python_file, &notebook] {
fs::OpenOptions::new() fs::OpenOptions::new()
.create(true) .create(true)
.truncate(true)
.write(true) .write(true)
.mode(0o000) .mode(0o000)
.open(file)?; .open(file)?;

View file

@ -16,7 +16,7 @@ impl std::fmt::Display for PanicError {
} }
thread_local! { thread_local! {
static LAST_PANIC: std::cell::Cell<Option<PanicError>> = std::cell::Cell::new(None); static LAST_PANIC: std::cell::Cell<Option<PanicError>> = const { std::cell::Cell::new(None) };
} }
/// [`catch_unwind`](std::panic::catch_unwind) wrapper that sets a custom [`set_hook`](std::panic::set_hook) /// [`catch_unwind`](std::panic::catch_unwind) wrapper that sets a custom [`set_hook`](std::panic::set_hook)

View file

@ -1353,6 +1353,7 @@ fn unreadable_pyproject_toml() -> Result<()> {
// Create an empty file with 000 permissions // Create an empty file with 000 permissions
fs::OpenOptions::new() fs::OpenOptions::new()
.create(true) .create(true)
.truncate(true)
.write(true) .write(true)
.mode(0o000) .mode(0o000)
.open(pyproject_toml)?; .open(pyproject_toml)?;

View file

@ -20,12 +20,7 @@ use crate::rules::isort::block::{Block, BlockBuilder};
use crate::settings::LinterSettings; use crate::settings::LinterSettings;
fn extract_import_map(path: &Path, package: Option<&Path>, blocks: &[&Block]) -> Option<ImportMap> { fn extract_import_map(path: &Path, package: Option<&Path>, blocks: &[&Block]) -> Option<ImportMap> {
let Some(package) = package else { let module_path = to_module_path(package?, path)?;
return None;
};
let Some(module_path) = to_module_path(package, path) else {
return None;
};
let num_imports = blocks.iter().map(|block| block.imports.len()).sum(); let num_imports = blocks.iter().map(|block| block.imports.len()).sum();
let mut module_imports = Vec::with_capacity(num_imports); let mut module_imports = Vec::with_capacity(num_imports);

View file

@ -40,10 +40,7 @@ pub(crate) fn delete_stmt(
locator: &Locator, locator: &Locator,
indexer: &Indexer, indexer: &Indexer,
) -> Edit { ) -> Edit {
if parent if parent.is_some_and(|parent| is_lone_child(stmt, parent)) {
.map(|parent| is_lone_child(stmt, parent))
.unwrap_or_default()
{
// If removing this node would lead to an invalid syntax tree, replace // If removing this node would lead to an invalid syntax tree, replace
// it with a `pass`. // it with a `pass`.
Edit::range_replacement("pass".to_string(), stmt.range()) Edit::range_replacement("pass".to_string(), stmt.range())

View file

@ -278,9 +278,7 @@ impl<'a> Insertion<'a> {
/// Find the end of the last docstring. /// Find the end of the last docstring.
fn match_docstring_end(body: &[Stmt]) -> Option<TextSize> { fn match_docstring_end(body: &[Stmt]) -> Option<TextSize> {
let mut iter = body.iter(); let mut iter = body.iter();
let Some(mut stmt) = iter.next() else { let mut stmt = iter.next()?;
return None;
};
if !is_docstring_stmt(stmt) { if !is_docstring_stmt(stmt) {
return None; return None;
} }

View file

@ -80,9 +80,7 @@ pub(crate) fn compare_to_hardcoded_password_string(
.diagnostics .diagnostics
.extend(comparators.iter().filter_map(|comp| { .extend(comparators.iter().filter_map(|comp| {
string_literal(comp).filter(|string| !string.is_empty())?; string_literal(comp).filter(|string| !string.is_empty())?;
let Some(name) = password_target(left) else { let name = password_target(left)?;
return None;
};
Some(Diagnostic::new( Some(Diagnostic::new(
HardcodedPasswordString { HardcodedPasswordString {
name: name.to_string(), name: name.to_string(),

View file

@ -159,9 +159,7 @@ fn get_element_type(element: &Stmt, semantic: &SemanticModel) -> Option<ContentT
return Some(ContentType::FieldDeclaration); return Some(ContentType::FieldDeclaration);
} }
} }
let Some(expr) = targets.first() else { let expr = targets.first()?;
return None;
};
let Expr::Name(ast::ExprName { id, .. }) = expr else { let Expr::Name(ast::ExprName { id, .. }) = expr else {
return None; return None;
}; };

View file

@ -61,15 +61,9 @@ pub(crate) fn unconventional_import_alias(
binding: &Binding, binding: &Binding,
conventions: &FxHashMap<String, String>, conventions: &FxHashMap<String, String>,
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
let Some(import) = binding.as_any_import() else { let import = binding.as_any_import()?;
return None;
};
let qualified_name = import.qualified_name().to_string(); let qualified_name = import.qualified_name().to_string();
let expected_alias = conventions.get(qualified_name.as_str())?;
let Some(expected_alias) = conventions.get(qualified_name.as_str()) else {
return None;
};
let name = binding.name(checker.locator()); let name = binding.name(checker.locator());
if binding.is_alias() && name == expected_alias { if binding.is_alias() && name == expected_alias {

View file

@ -148,10 +148,7 @@ fn match_builtin_type(expr: &Expr, semantic: &SemanticModel) -> Option<ExprType>
/// Return the [`ExprType`] of an [`Expr`] if it is a literal (e.g., an `int`, like `1`, or a /// Return the [`ExprType`] of an [`Expr`] if it is a literal (e.g., an `int`, like `1`, or a
/// `bool`, like `True`). /// `bool`, like `True`).
fn match_literal_type(expr: &Expr) -> Option<ExprType> { fn match_literal_type(expr: &Expr) -> Option<ExprType> {
let Some(literal_expr) = expr.as_literal_expr() else { Some(match expr.as_literal_expr()? {
return None;
};
let result = match literal_expr {
LiteralExpressionRef::BooleanLiteral(_) => ExprType::Bool, LiteralExpressionRef::BooleanLiteral(_) => ExprType::Bool,
LiteralExpressionRef::StringLiteral(_) => ExprType::Str, LiteralExpressionRef::StringLiteral(_) => ExprType::Str,
LiteralExpressionRef::BytesLiteral(_) => ExprType::Bytes, LiteralExpressionRef::BytesLiteral(_) => ExprType::Bytes,
@ -163,6 +160,5 @@ fn match_literal_type(expr: &Expr) -> Option<ExprType> {
LiteralExpressionRef::NoneLiteral(_) | LiteralExpressionRef::EllipsisLiteral(_) => { LiteralExpressionRef::NoneLiteral(_) | LiteralExpressionRef::EllipsisLiteral(_) => {
return None; return None;
} }
}; })
Some(result)
} }

View file

@ -8,9 +8,7 @@ pub(super) fn get_mark_decorators(
decorators: &[Decorator], decorators: &[Decorator],
) -> impl Iterator<Item = (&Decorator, &str)> { ) -> impl Iterator<Item = (&Decorator, &str)> {
decorators.iter().filter_map(|decorator| { decorators.iter().filter_map(|decorator| {
let Some(name) = UnqualifiedName::from_expr(map_callable(&decorator.expression)) else { let name = UnqualifiedName::from_expr(map_callable(&decorator.expression))?;
return None;
};
let ["pytest", "mark", marker] = name.segments() else { let ["pytest", "mark", marker] = name.segments() else {
return None; return None;
}; };

View file

@ -541,7 +541,7 @@ pub(crate) fn compare_with_tuple(checker: &mut Checker, expr: &Expr) {
// Create a `x in (a, b)` expression. // Create a `x in (a, b)` expression.
let node = ast::ExprTuple { let node = ast::ExprTuple {
elts: comparators.into_iter().map(Clone::clone).collect(), elts: comparators.into_iter().cloned().collect(),
ctx: ExprContext::Load, ctx: ExprContext::Load,
range: TextRange::default(), range: TextRange::default(),
parenthesized: true, parenthesized: true,

View file

@ -274,10 +274,11 @@ fn match_loop(stmt: &Stmt) -> Option<Loop> {
if !nested_elif_else_clauses.is_empty() { if !nested_elif_else_clauses.is_empty() {
return None; return None;
} }
let [Stmt::Return(ast::StmtReturn { value, range: _ })] = nested_body.as_slice() else { let [Stmt::Return(ast::StmtReturn {
return None; value: Some(value),
}; range: _,
let Some(value) = value else { })] = nested_body.as_slice()
else {
return None; return None;
}; };
let Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) = value.as_ref() else { let Expr::BooleanLiteral(ast::ExprBooleanLiteral { value, .. }) = value.as_ref() else {

View file

@ -82,9 +82,7 @@ fn fix_banned_relative_import(
generator: Generator, generator: Generator,
) -> Option<Fix> { ) -> Option<Fix> {
// Only fix is the module path is known. // Only fix is the module path is known.
let Some(module_path) = resolve_imported_module_path(level, module, module_path) else { let module_path = resolve_imported_module_path(level, module, module_path)?;
return None;
};
// Require import to be a valid module: // Require import to be a valid module:
// https://python.org/dev/peps/pep-0008/#package-and-module-names // https://python.org/dev/peps/pep-0008/#package-and-module-names

View file

@ -80,10 +80,12 @@ enum Reason<'a> {
Future, Future,
KnownStandardLibrary, KnownStandardLibrary,
SamePackage, SamePackage,
#[allow(dead_code)]
SourceMatch(&'a Path), SourceMatch(&'a Path),
NoMatch, NoMatch,
UserDefinedSection, UserDefinedSection,
NoSections, NoSections,
#[allow(dead_code)]
DisabledSection(&'a ImportSection), DisabledSection(&'a ImportSection),
} }

View file

@ -103,9 +103,7 @@ impl<'a> ModuleKey<'a> {
) -> Self { ) -> Self {
let level = level.unwrap_or_default(); let level = level.unwrap_or_default();
let force_to_top = !name let force_to_top = !name.is_some_and(|name| settings.force_to_top.contains(name)); // `false` < `true` so we get forced to top first
.map(|name| settings.force_to_top.contains(name))
.unwrap_or_default(); // `false` < `true` so we get forced to top first
let maybe_length = (settings.length_sort let maybe_length = (settings.length_sort
|| (settings.length_sort_straight && style == ImportStyle::Straight)) || (settings.length_sort_straight && style == ImportStyle::Straight))

View file

@ -87,10 +87,7 @@ pub(crate) fn doc_line_too_long(
indexer: &Indexer, indexer: &Indexer,
settings: &LinterSettings, settings: &LinterSettings,
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
let Some(limit) = settings.pycodestyle.max_doc_length else { let limit = settings.pycodestyle.max_doc_length?;
return None;
};
Overlong::try_from_line( Overlong::try_from_line(
line, line,
indexer, indexer,

View file

@ -35,9 +35,7 @@ impl Violation for ImportSelf {
/// PLW0406 /// PLW0406
pub(crate) fn import_self(alias: &Alias, module_path: Option<&[String]>) -> Option<Diagnostic> { pub(crate) fn import_self(alias: &Alias, module_path: Option<&[String]>) -> Option<Diagnostic> {
let Some(module_path) = module_path else { let module_path = module_path?;
return None;
};
if alias.name.split('.').eq(module_path) { if alias.name.split('.').eq(module_path) {
return Some(Diagnostic::new( return Some(Diagnostic::new(
@ -58,13 +56,8 @@ pub(crate) fn import_from_self(
names: &[Alias], names: &[Alias],
module_path: Option<&[String]>, module_path: Option<&[String]>,
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
let Some(module_path) = module_path else { let module_path = module_path?;
return None; let imported_module_path = resolve_imported_module_path(level, module, Some(module_path))?;
};
let Some(imported_module_path) = resolve_imported_module_path(level, module, Some(module_path))
else {
return None;
};
if imported_module_path if imported_module_path
.split('.') .split('.')

View file

@ -86,9 +86,7 @@ impl<'a> FormatSummaryValues<'a> {
value, value,
range: _, range: _,
} = keyword; } = keyword;
let Some(key) = arg else { let key = arg.as_ref()?;
return None;
};
if contains_quotes(locator.slice(value)) || locator.contains_line_break(value.range()) { if contains_quotes(locator.slice(value)) || locator.contains_line_break(value.range()) {
return None; return None;
} }

View file

@ -260,9 +260,7 @@ fn clean_params_dictionary(right: &Expr, locator: &Locator, stylist: &Stylist) -
} }
contents.push('('); contents.push('(');
if is_multi_line { if is_multi_line {
let Some(indent) = indent else { let indent = indent?;
return None;
};
for item in &arguments { for item in &arguments {
contents.push_str(stylist.line_ending().as_str()); contents.push_str(stylist.line_ending().as_str());

View file

@ -127,8 +127,7 @@ impl<'src, 'loc> UselessSuppressionComments<'src, 'loc> {
// check if the comment is inside of an expression. // check if the comment is inside of an expression.
if comment if comment
.enclosing .enclosing
.map(|n| !is_valid_enclosing_node(n)) .is_some_and(|n| !is_valid_enclosing_node(n))
.unwrap_or_default()
{ {
return Err(IgnoredReason::InNonStatement); return Err(IgnoredReason::InNonStatement);
} }

View file

@ -83,12 +83,7 @@ fn match_slice_info(expr: &Expr) -> Option<SliceInfo> {
else { else {
return None; return None;
}; };
Some(int.as_i32()?)
let Some(slice_start) = int.as_i32() else {
return None;
};
Some(slice_start)
} else { } else {
None None
}; };

View file

@ -92,7 +92,7 @@ pub fn test_snippet(contents: &str, settings: &LinterSettings) -> Vec<Message> {
} }
thread_local! { thread_local! {
static MAX_ITERATIONS: std::cell::Cell<usize> = std::cell::Cell::new(8); static MAX_ITERATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(8) };
} }
pub fn set_max_iterations(max: usize) { pub fn set_max_iterations(max: usize) {

View file

@ -878,9 +878,7 @@ pub fn resolve_imported_module_path<'a>(
return Some(Cow::Borrowed(module.unwrap_or(""))); return Some(Cow::Borrowed(module.unwrap_or("")));
} }
let Some(module_path) = module_path else { let module_path = module_path?;
return None;
};
if level as usize >= module_path.len() { if level as usize >= module_path.len() {
return None; return None;

View file

@ -175,9 +175,7 @@ fn find_double_star(pattern: &PatternMatchMapping, source: &str) -> Option<(Text
} = pattern; } = pattern;
// If there's no `rest` element, there's no `**`. // If there's no `rest` element, there's no `**`.
let Some(rest) = rest else { let rest = rest.as_ref()?;
return None;
};
let mut tokenizer = let mut tokenizer =
SimpleTokenizer::starts_at(patterns.last().map_or(pattern.start(), Ranged::end), source); SimpleTokenizer::starts_at(patterns.last().map_or(pattern.start(), Ranged::end), source);

View file

@ -1,2 +1,2 @@
[toolchain] [toolchain]
channel = "1.76" channel = "1.77"