Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ resolver = "2"

[workspace.package]
edition = "2021"
rust-version = "1.83"
rust-version = "1.84"
homepage = "https://docs.astral.sh/ruff"
documentation = "https://docs.astral.sh/ruff"
repository = "https://github.com/astral-sh/ruff"
Expand Down Expand Up @@ -209,6 +209,7 @@ must_use_candidate = "allow"
similar_names = "allow"
single_match_else = "allow"
too_many_lines = "allow"
needless_continue = "allow" # An explicit continue can be more readable, especially if the alternative is an empty block.
# Without the hashes we run into a `rustfmt` bug in some snapshot tests, see #13250
needless_raw_string_hashes = "allow"
# Disallowed restriction lints
Expand All @@ -227,6 +228,10 @@ redundant_clone = "warn"
debug_assert_with_mut_call = "warn"
unused_peekable = "warn"

# Has false positives
# https://github.com/rust-lang/rust-clippy/issues/14275
doc_overindented_list_items = "allow"

# Diagnostics are not actionable: Enable once https://github.com/rust-lang/rust-clippy/issues/13774 is resolved.
large_stack_arrays = "allow"

Expand Down
2 changes: 1 addition & 1 deletion crates/red_knot_project/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ impl salsa::Database for ProjectDatabase {
}

let event = event();
if matches!(event.kind, salsa::EventKind::WillCheckCancellation { .. }) {
if matches!(event.kind, salsa::EventKind::WillCheckCancellation) {
return;
}

Expand Down
2 changes: 1 addition & 1 deletion crates/red_knot_project/src/db/changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ impl ProjectDatabase {
let program = Program::get(self);
if let Err(error) = program.update_from_settings(self, program_settings) {
tracing::error!("Failed to update the program settings, keeping the old program settings: {error}");
};
}

if metadata.root() == project.root(self) {
tracing::debug!("Reloading project after structural change");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ fn python_version_from_versions_file_string(

#[cfg(test)]
mod tests {
use std::fmt::Write as _;
use std::num::{IntErrorKind, NonZeroU16};
use std::path::Path;

Expand All @@ -333,8 +334,7 @@ mod tests {

const TYPESHED_STDLIB_DIR: &str = "stdlib";

#[allow(unsafe_code)]
const ONE: Option<NonZeroU16> = Some(unsafe { NonZeroU16::new_unchecked(1) });
const ONE: Option<NonZeroU16> = Some(NonZeroU16::new(1).unwrap());

impl TypeshedVersions {
#[must_use]
Expand Down Expand Up @@ -571,7 +571,7 @@ foo: 3.8- # trailing comment

let mut massive_versions_file = String::new();
for i in 0..too_many {
massive_versions_file.push_str(&format!("x{i}: 3.8-\n"));
let _ = writeln!(&mut massive_versions_file, "x{i}: 3.8-");
}

assert_eq!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1448,7 +1448,7 @@ where
self.visit_expr(subject);
if cases.is_empty() {
return;
};
}

let after_subject = self.flow_snapshot();
let mut vis_constraints = vec![];
Expand Down
6 changes: 3 additions & 3 deletions crates/red_knot_python_semantic/src/suppression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ pub(crate) fn check_suppressions(db: &dyn Db, file: File, diagnostics: &mut Type
fn check_unknown_rule(context: &mut CheckSuppressionsContext) {
if context.is_lint_disabled(&UNKNOWN_RULE) {
return;
};
}

for unknown in &context.suppressions.unknown {
match &unknown.reason {
Expand Down Expand Up @@ -174,7 +174,7 @@ fn check_unknown_rule(context: &mut CheckSuppressionsContext) {
format_args!("Unknown rule `{prefixed}`. Did you mean `{suggestion}`?"),
);
}
};
}
}
}

Expand Down Expand Up @@ -267,7 +267,7 @@ fn check_unused_suppressions(context: &mut CheckSuppressionsContext) {
suppression.range,
format_args!("Unused `{kind}` without a code", kind = suppression.kind),
),
};
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions crates/red_knot_python_semantic/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,7 @@ fn symbol_from_bindings_impl<'db>(
binding,
visibility_constraint,
narrowing_constraint: _,
}) if binding.map_or(true, is_non_exported) => {
}) if binding.is_none_or(is_non_exported) => {
visibility_constraints.evaluate(db, predicates, *visibility_constraint)
}
_ => Truthiness::AlwaysFalse,
Expand Down Expand Up @@ -794,7 +794,7 @@ fn symbol_from_declarations_impl<'db>(
Some(DeclarationWithConstraint {
declaration,
visibility_constraint,
}) if declaration.map_or(true, is_non_exported) => {
}) if declaration.is_none_or(is_non_exported) => {
visibility_constraints.evaluate(db, predicates, *visibility_constraint)
}
_ => Truthiness::AlwaysFalse,
Expand Down
4 changes: 2 additions & 2 deletions crates/red_knot_python_semantic/src/types/call/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,13 +502,13 @@ impl<'db> Bindings<'db> {
if let Some(len_ty) = first_arg.len(db) {
overload.set_return_type(len_ty);
}
};
}
}

Some(KnownFunction::Repr) => {
if let [Some(first_arg)] = overload.parameter_types() {
overload.set_return_type(first_arg.repr(db));
};
}
}

Some(KnownFunction::Cast) => {
Expand Down
14 changes: 7 additions & 7 deletions crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -985,7 +985,7 @@ impl<'db> TypeInferenceBuilder<'db> {
Some(KnownClass::Float | KnownClass::Int | KnownClass::Bool)
) => {}
_ => return false,
};
}

let (op, by_zero) = match op {
ast::Operator::Div => ("divide", "by zero"),
Expand Down Expand Up @@ -1036,7 +1036,7 @@ impl<'db> TypeInferenceBuilder<'db> {
report_invalid_assignment(&self.context, node, declared_ty, bound_ty);
// allow declarations to override inference in case of invalid assignment
bound_ty = declared_ty;
};
}

self.types.bindings.insert(binding, bound_ty);
}
Expand Down Expand Up @@ -2216,7 +2216,7 @@ impl<'db> TypeInferenceBuilder<'db> {
}
}
ast::Pattern::MatchStar(_) | ast::Pattern::MatchSingleton(_) => {}
};
}
}

fn infer_assignment_statement(&mut self, assignment: &ast::StmtAssign) {
Expand Down Expand Up @@ -3242,7 +3242,7 @@ impl<'db> TypeInferenceBuilder<'db> {
&DeclaredAndInferredType::AreTheSame(ty),
);
return;
};
}

// If the module doesn't bind the symbol, check if it's a submodule. This won't get
// handled by the `Type::member` call because it relies on the semantic index's
Expand Down Expand Up @@ -4044,7 +4044,7 @@ impl<'db> TypeInferenceBuilder<'db> {
parameter_ty=parameter_ty.display(self.db())
),
);
};
}
}
}
}
Expand Down Expand Up @@ -4895,7 +4895,7 @@ impl<'db> TypeInferenceBuilder<'db> {

if done {
return Type::Never;
};
}

match (truthiness, op) {
(Truthiness::AlwaysTrue, ast::BoolOp::And) => Type::Never,
Expand Down Expand Up @@ -5815,7 +5815,7 @@ impl<'db> TypeInferenceBuilder<'db> {
Err(CallDunderError::MethodNotAvailable) => {
// try `__class_getitem__`
}
};
}

// Otherwise, if the value is itself a class and defines `__class_getitem__`,
// return its return type.
Expand Down
4 changes: 2 additions & 2 deletions crates/red_knot_python_semantic/src/types/slots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl SlotsKind {

if matches!(bound, Boundness::PossiblyUnbound) {
return Self::Dynamic;
};
}

match slots_ty {
// __slots__ = ("a", "b")
Expand Down Expand Up @@ -98,6 +98,6 @@ pub(super) fn check_class_slots(context: &InferContext, class: Class, node: &ast
if let Some(index) = first_with_solid_base {
let base_node = &node.bases()[index];
report_base_with_incompatible_slots(context, base_node);
};
}
}
}
6 changes: 4 additions & 2 deletions crates/red_knot_python_semantic/src/types/unpacker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,10 @@ impl<'db> Unpacker<'db> {
// it's worth it.
TupleType::from_elements(
self.db(),
std::iter::repeat(Type::LiteralString)
.take(string_literal_ty.python_len(self.db())),
std::iter::repeat_n(
Type::LiteralString,
string_literal_ty.python_len(self.db()),
),
)
}
_ => ty,
Expand Down
2 changes: 1 addition & 1 deletion crates/red_knot_test/src/assertion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl<'a> Iterator for AssertionWithRangeIterator<'a> {
let comment = &self.file_assertions.source[inner_next];
if let Some(assertion) = UnparsedAssertion::from_comment(comment) {
return Some(AssertionWithRange(assertion, inner_next));
};
}
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/red_knot_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,13 +265,13 @@ fn run_test(
match info.location {
Some(location) => messages.push(format!("panicked at {location}")),
None => messages.push("panicked at unknown location".to_string()),
};
}
match info.payload {
Some(payload) => messages.push(payload),
// Mimic the default panic hook's rendering of the panic payload if it's
// not a string.
None => messages.push("Box<dyn Any>".to_string()),
};
}
if let Some(backtrace) = info.backtrace {
if std::env::var("RUST_BACKTRACE").is_ok() {
messages.extend(backtrace.to_string().split('\n').map(String::from));
Expand Down
2 changes: 1 addition & 1 deletion crates/red_knot_test/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -673,7 +673,7 @@ impl<'s> Parser<'s> {
"Test `{test_name}` has duplicate files named `{}`.",
path.as_str(),
);
};
}

if has_explicit_file_paths {
bail!("Merged snippets in test `{test_name}` are not allowed in the presence of other files.");
Expand Down
17 changes: 10 additions & 7 deletions crates/ruff/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::cmp::Ordering;
use std::fmt::Formatter;
use std::fmt::{Formatter, Write as _};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
Expand Down Expand Up @@ -974,12 +974,13 @@ A `--config` flag must either be a path to a `.toml` configuration file
.is_some_and(|ext| ext.eq_ignore_ascii_case("toml"))
{
if !value.contains('=') {
tip.push_str(&format!(
let _ = write!(
&mut tip,
"

It looks like you were trying to pass a path to a configuration file.
The path `{value}` does not point to a configuration file"
));
);
}
} else if let Some((key, value)) = value.split_once('=') {
let key = key.trim_ascii();
Expand All @@ -993,7 +994,8 @@ The path `{value}` does not point to a configuration file"
.map(|(name, _)| format!("- `{key}.{name}`"))
.join("\n");

tip.push_str(&format!(
let _ = write!(
&mut tip,
"

`{key}` is a table of configuration options.
Expand All @@ -1002,13 +1004,14 @@ Did you want to override one of the table's subkeys?
Possible choices:

{prefixed_subfields}"
));
);
}
_ => {
tip.push_str(&format!(
let _ = write!(
&mut tip,
"\n\n{}:\n\n{underlying_error}",
config_parse_error.description()
));
);
}
}
}
Expand Down
13 changes: 9 additions & 4 deletions crates/ruff/src/commands/rule.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::fmt::Write as _;
use std::io::{self, BufWriter, Write};

use anyhow::Result;
Expand Down Expand Up @@ -43,12 +44,16 @@ impl<'a> Explanation<'a> {

fn format_rule_text(rule: Rule) -> String {
let mut output = String::new();
output.push_str(&format!("# {} ({})", rule.as_ref(), rule.noqa_code()));
let _ = write!(&mut output, "# {} ({})", rule.as_ref(), rule.noqa_code());
output.push('\n');
output.push('\n');

let (linter, _) = Linter::parse_code(&rule.noqa_code().to_string()).unwrap();
output.push_str(&format!("Derived from the **{}** linter.", linter.name()));
let _ = write!(
&mut output,
"Derived from the **{}** linter.",
linter.name()
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kinda wonder if we should propose add something to std to make this nicer. I like the way the x.push_str(&format!("...")) construction reads much nicer, but I guess this approach avoids an intermediate allocation. But this approach has the very ugly let _ = ...; construction.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be great. I definitely don't love it and it has the downside that later refactoring the code to eg use a Write instead of a string now incorrectly suppresses errors (instead of Rust telling you that this might now fail)

output.push('\n');
output.push('\n');

Expand Down Expand Up @@ -76,7 +81,7 @@ fn format_rule_text(rule: Rule) -> String {
output.push_str("Message formats:");
for format in rule.message_formats() {
output.push('\n');
output.push_str(&format!("* {format}"));
let _ = write!(&mut output, "* {format}");
}
}
output
Expand All @@ -92,7 +97,7 @@ pub(crate) fn rule(rule: Rule, format: HelpFormat) -> Result<()> {
HelpFormat::Json => {
serde_json::to_writer_pretty(stdout, &Explanation::from_rule(&rule))?;
}
};
}
Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/ruff/src/commands/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ pub(crate) fn version(output_format: HelpFormat) -> Result<()> {
HelpFormat::Json => {
serde_json::to_writer_pretty(stdout, &version_info)?;
}
};
}
Ok(())
}
2 changes: 1 addition & 1 deletion crates/ruff/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub fn main() -> ExitCode {

// support FORCE_COLOR env var
if let Some(force_color) = std::env::var_os("FORCE_COLOR") {
if force_color.len() > 0 {
if !force_color.is_empty() {
colored::control::set_override(true);
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ruff_annotate_snippets/src/renderer/display_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ impl DisplaySet<'_> {
None => {
buffer.putc(line_offset, lineno_width + 1, '|', *lineno_color);
}
};
}
}
if let DisplaySourceLine::Content { text, .. } = line {
// The width of the line number, a space, pipe, and a space
Expand Down Expand Up @@ -1753,7 +1753,7 @@ fn format_inline_marks(
DisplayMarkType::AnnotationThrough(depth) => {
buf.putc(line, 3 + lineno_width + depth, '|', *annotation_style);
}
};
}
}
Ok(())
}
Loading
Loading