Update Rust toolchain to 1.89 (#19807)

This commit is contained in:
Micha Reiser 2025-08-07 18:21:50 +02:00 committed by GitHub
parent b22586fa0e
commit 7dfde3b929
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
101 changed files with 234 additions and 200 deletions

View file

@ -1,3 +1,5 @@
#![expect(clippy::needless_doctest_main)]
//! A library for formatting of text or programming code snippets. //! A library for formatting of text or programming code snippets.
//! //!
//! It's primary purpose is to build an ASCII-graphical representation of the snippet //! It's primary purpose is to build an ASCII-graphical representation of the snippet

View file

@ -212,7 +212,7 @@ impl Diagnostic {
/// The type returned implements the `std::fmt::Display` trait. In most /// The type returned implements the `std::fmt::Display` trait. In most
/// cases, just converting it to a string (or printing it) will do what /// cases, just converting it to a string (or printing it) will do what
/// you want. /// you want.
pub fn concise_message(&self) -> ConciseMessage { pub fn concise_message(&self) -> ConciseMessage<'_> {
let main = self.inner.message.as_str(); let main = self.inner.message.as_str();
let annotation = self let annotation = self
.primary_annotation() .primary_annotation()
@ -654,7 +654,7 @@ impl SubDiagnostic {
/// The type returned implements the `std::fmt::Display` trait. In most /// The type returned implements the `std::fmt::Display` trait. In most
/// cases, just converting it to a string (or printing it) will do what /// cases, just converting it to a string (or printing it) will do what
/// you want. /// you want.
pub fn concise_message(&self) -> ConciseMessage { pub fn concise_message(&self) -> ConciseMessage<'_> {
let main = self.inner.message.as_str(); let main = self.inner.message.as_str();
let annotation = self let annotation = self
.primary_annotation() .primary_annotation()
@ -1099,7 +1099,7 @@ enum DiagnosticSource {
impl DiagnosticSource { impl DiagnosticSource {
/// Returns this input as a `SourceCode` for convenient querying. /// Returns this input as a `SourceCode` for convenient querying.
fn as_source_code(&self) -> SourceCode { fn as_source_code(&self) -> SourceCode<'_, '_> {
match self { match self {
DiagnosticSource::Ty(input) => SourceCode::new(input.text.as_str(), &input.line_index), DiagnosticSource::Ty(input) => SourceCode::new(input.text.as_str(), &input.line_index),
DiagnosticSource::Ruff(source) => SourceCode::new(source.source_text(), source.index()), DiagnosticSource::Ruff(source) => SourceCode::new(source.source_text(), source.index()),

View file

@ -236,7 +236,7 @@ impl SystemPath {
/// ///
/// [`CurDir`]: camino::Utf8Component::CurDir /// [`CurDir`]: camino::Utf8Component::CurDir
#[inline] #[inline]
pub fn components(&self) -> camino::Utf8Components { pub fn components(&self) -> camino::Utf8Components<'_> {
self.0.components() self.0.components()
} }

View file

@ -195,7 +195,7 @@ impl VendoredFileSystem {
/// ///
/// ## Panics: /// ## Panics:
/// If the current thread already holds the lock. /// If the current thread already holds the lock.
fn lock_archive(&self) -> LockedZipArchive { fn lock_archive(&self) -> LockedZipArchive<'_> {
self.inner.lock().unwrap() self.inner.lock().unwrap()
} }
} }
@ -360,7 +360,7 @@ impl VendoredZipArchive {
Ok(Self(ZipArchive::new(io::Cursor::new(data))?)) Ok(Self(ZipArchive::new(io::Cursor::new(data))?))
} }
fn lookup_path(&mut self, path: &NormalizedVendoredPath) -> Result<ZipFile> { fn lookup_path(&mut self, path: &NormalizedVendoredPath) -> Result<ZipFile<'_>> {
Ok(self.0.by_name(path.as_str())?) Ok(self.0.by_name(path.as_str())?)
} }

View file

@ -37,7 +37,7 @@ impl VendoredPath {
self.0.as_std_path() self.0.as_std_path()
} }
pub fn components(&self) -> Utf8Components { pub fn components(&self) -> Utf8Components<'_> {
self.0.components() self.0.components()
} }

View file

@ -348,7 +348,7 @@ fn format_dev_multi_project(
debug!(parent: None, "Starting {}", project_path.display()); debug!(parent: None, "Starting {}", project_path.display());
match format_dev_project( match format_dev_project(
&[project_path.clone()], std::slice::from_ref(&project_path),
args.stability_check, args.stability_check,
args.write, args.write,
args.preview, args.preview,
@ -628,7 +628,7 @@ struct CheckRepoResult {
} }
impl CheckRepoResult { impl CheckRepoResult {
fn display(&self, format: Format) -> DisplayCheckRepoResult { fn display(&self, format: Format) -> DisplayCheckRepoResult<'_> {
DisplayCheckRepoResult { DisplayCheckRepoResult {
result: self, result: self,
format, format,
@ -665,7 +665,7 @@ struct Diagnostic {
} }
impl Diagnostic { impl Diagnostic {
fn display(&self, format: Format) -> DisplayDiagnostic { fn display(&self, format: Format) -> DisplayDiagnostic<'_> {
DisplayDiagnostic { DisplayDiagnostic {
diagnostic: self, diagnostic: self,
format, format,

View file

@ -562,7 +562,7 @@ struct RemoveSoftLinebreaksSnapshot {
pub trait BufferExtensions: Buffer + Sized { pub trait BufferExtensions: Buffer + Sized {
/// Returns a new buffer that calls the passed inspector for every element that gets written to the output /// Returns a new buffer that calls the passed inspector for every element that gets written to the output
#[must_use] #[must_use]
fn inspect<F>(&mut self, inspector: F) -> Inspect<Self::Context, F> fn inspect<F>(&mut self, inspector: F) -> Inspect<'_, Self::Context, F>
where where
F: FnMut(&FormatElement), F: FnMut(&FormatElement),
{ {
@ -607,7 +607,7 @@ pub trait BufferExtensions: Buffer + Sized {
/// # } /// # }
/// ``` /// ```
#[must_use] #[must_use]
fn start_recording(&mut self) -> Recording<Self> { fn start_recording(&mut self) -> Recording<'_, Self> {
Recording::new(self) Recording::new(self)
} }

View file

@ -340,7 +340,7 @@ impl<Context> Format<Context> for SourcePosition {
/// Creates a text from a dynamic string. /// Creates a text from a dynamic string.
/// ///
/// This is done by allocating a new string internally. /// This is done by allocating a new string internally.
pub fn text(text: &str) -> Text { pub fn text(text: &str) -> Text<'_> {
debug_assert_no_newlines(text); debug_assert_no_newlines(text);
Text { text } Text { text }
@ -459,7 +459,10 @@ fn debug_assert_no_newlines(text: &str) {
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn line_suffix<Content, Context>(inner: &Content, reserved_width: u32) -> LineSuffix<Context> pub fn line_suffix<Content, Context>(
inner: &Content,
reserved_width: u32,
) -> LineSuffix<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -597,7 +600,10 @@ impl<Context> Format<Context> for LineSuffixBoundary {
/// Use `Memoized.inspect(f)?.has_label(LabelId::of::<SomeLabelId>()` if you need to know if some content breaks that should /// Use `Memoized.inspect(f)?.has_label(LabelId::of::<SomeLabelId>()` if you need to know if some content breaks that should
/// only be written later. /// only be written later.
#[inline] #[inline]
pub fn labelled<Content, Context>(label_id: LabelId, content: &Content) -> FormatLabelled<Context> pub fn labelled<Content, Context>(
label_id: LabelId,
content: &Content,
) -> FormatLabelled<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -700,7 +706,7 @@ impl<Context> Format<Context> for Space {
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn indent<Content, Context>(content: &Content) -> Indent<Context> pub fn indent<Content, Context>(content: &Content) -> Indent<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -771,7 +777,7 @@ impl<Context> std::fmt::Debug for Indent<'_, Context> {
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn dedent<Content, Context>(content: &Content) -> Dedent<Context> pub fn dedent<Content, Context>(content: &Content) -> Dedent<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -846,7 +852,7 @@ impl<Context> std::fmt::Debug for Dedent<'_, Context> {
/// ///
/// This resembles the behaviour of Prettier's `align(Number.NEGATIVE_INFINITY, content)` IR element. /// This resembles the behaviour of Prettier's `align(Number.NEGATIVE_INFINITY, content)` IR element.
#[inline] #[inline]
pub fn dedent_to_root<Content, Context>(content: &Content) -> Dedent<Context> pub fn dedent_to_root<Content, Context>(content: &Content) -> Dedent<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -960,7 +966,7 @@ where
/// ///
/// - tab indentation: Printer indents the expression with two tabs because the `align` increases the indentation level. /// - tab indentation: Printer indents the expression with two tabs because the `align` increases the indentation level.
/// - space indentation: Printer indents the expression by 4 spaces (one indentation level) **and** 2 spaces for the align. /// - space indentation: Printer indents the expression by 4 spaces (one indentation level) **and** 2 spaces for the align.
pub fn align<Content, Context>(count: u8, content: &Content) -> Align<Context> pub fn align<Content, Context>(count: u8, content: &Content) -> Align<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -1030,7 +1036,7 @@ impl<Context> std::fmt::Debug for Align<'_, Context> {
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<Context> { pub fn block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<'_, Context> {
BlockIndent { BlockIndent {
content: Argument::new(content), content: Argument::new(content),
mode: IndentMode::Block, mode: IndentMode::Block,
@ -1101,7 +1107,7 @@ pub fn block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<Cont
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn soft_block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<Context> { pub fn soft_block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<'_, Context> {
BlockIndent { BlockIndent {
content: Argument::new(content), content: Argument::new(content),
mode: IndentMode::Soft, mode: IndentMode::Soft,
@ -1175,7 +1181,9 @@ pub fn soft_block_indent<Context>(content: &impl Format<Context>) -> BlockIndent
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn soft_line_indent_or_space<Context>(content: &impl Format<Context>) -> BlockIndent<Context> { pub fn soft_line_indent_or_space<Context>(
content: &impl Format<Context>,
) -> BlockIndent<'_, Context> {
BlockIndent { BlockIndent {
content: Argument::new(content), content: Argument::new(content),
mode: IndentMode::SoftLineOrSpace, mode: IndentMode::SoftLineOrSpace,
@ -1308,7 +1316,9 @@ impl<Context> std::fmt::Debug for BlockIndent<'_, Context> {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn soft_space_or_block_indent<Context>(content: &impl Format<Context>) -> BlockIndent<Context> { pub fn soft_space_or_block_indent<Context>(
content: &impl Format<Context>,
) -> BlockIndent<'_, Context> {
BlockIndent { BlockIndent {
content: Argument::new(content), content: Argument::new(content),
mode: IndentMode::SoftSpace, mode: IndentMode::SoftSpace,
@ -1388,7 +1398,7 @@ pub fn soft_space_or_block_indent<Context>(content: &impl Format<Context>) -> Bl
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn group<Context>(content: &impl Format<Context>) -> Group<Context> { pub fn group<Context>(content: &impl Format<Context>) -> Group<'_, Context> {
Group { Group {
content: Argument::new(content), content: Argument::new(content),
id: None, id: None,
@ -1551,7 +1561,7 @@ impl<Context> std::fmt::Debug for Group<'_, Context> {
#[inline] #[inline]
pub fn best_fit_parenthesize<Context>( pub fn best_fit_parenthesize<Context>(
content: &impl Format<Context>, content: &impl Format<Context>,
) -> BestFitParenthesize<Context> { ) -> BestFitParenthesize<'_, Context> {
BestFitParenthesize { BestFitParenthesize {
content: Argument::new(content), content: Argument::new(content),
group_id: None, group_id: None,
@ -1691,7 +1701,7 @@ impl<Context> std::fmt::Debug for BestFitParenthesize<'_, Context> {
pub fn conditional_group<Content, Context>( pub fn conditional_group<Content, Context>(
content: &Content, content: &Content,
condition: Condition, condition: Condition,
) -> ConditionalGroup<Context> ) -> ConditionalGroup<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -1852,7 +1862,7 @@ impl<Context> Format<Context> for ExpandParent {
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn if_group_breaks<Content, Context>(content: &Content) -> IfGroupBreaks<Context> pub fn if_group_breaks<Content, Context>(content: &Content) -> IfGroupBreaks<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -1933,7 +1943,7 @@ where
/// # } /// # }
/// ``` /// ```
#[inline] #[inline]
pub fn if_group_fits_on_line<Content, Context>(flat_content: &Content) -> IfGroupBreaks<Context> pub fn if_group_fits_on_line<Content, Context>(flat_content: &Content) -> IfGroupBreaks<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -2122,7 +2132,7 @@ impl<Context> std::fmt::Debug for IfGroupBreaks<'_, Context> {
pub fn indent_if_group_breaks<Content, Context>( pub fn indent_if_group_breaks<Content, Context>(
content: &Content, content: &Content,
group_id: GroupId, group_id: GroupId,
) -> IndentIfGroupBreaks<Context> ) -> IndentIfGroupBreaks<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {
@ -2205,7 +2215,7 @@ impl<Context> std::fmt::Debug for IndentIfGroupBreaks<'_, Context> {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub fn fits_expanded<Content, Context>(content: &Content) -> FitsExpanded<Context> pub fn fits_expanded<Content, Context>(content: &Content) -> FitsExpanded<'_, Context>
where where
Content: Format<Context>, Content: Format<Context>,
{ {

View file

@ -197,7 +197,7 @@ pub const LINE_TERMINATORS: [char; 3] = ['\r', LINE_SEPARATOR, PARAGRAPH_SEPARAT
/// Replace the line terminators matching the provided list with "\n" /// Replace the line terminators matching the provided list with "\n"
/// since its the only line break type supported by the printer /// since its the only line break type supported by the printer
pub fn normalize_newlines<const N: usize>(text: &str, terminators: [char; N]) -> Cow<str> { pub fn normalize_newlines<const N: usize>(text: &str, terminators: [char; N]) -> Cow<'_, str> {
let mut result = String::new(); let mut result = String::new();
let mut last_end = 0; let mut last_end = 0;

View file

@ -222,7 +222,7 @@ impl FormatContext for IrFormatContext<'_> {
&IrFormatOptions &IrFormatOptions
} }
fn source_code(&self) -> SourceCode { fn source_code(&self) -> SourceCode<'_> {
self.source_code self.source_code
} }
} }

View file

@ -193,7 +193,7 @@ pub trait FormatContext {
fn options(&self) -> &Self::Options; fn options(&self) -> &Self::Options;
/// Returns the source code from the document that gets formatted. /// Returns the source code from the document that gets formatted.
fn source_code(&self) -> SourceCode; fn source_code(&self) -> SourceCode<'_>;
} }
/// Options customizing how the source code should be formatted. /// Options customizing how the source code should be formatted.
@ -239,7 +239,7 @@ impl FormatContext for SimpleFormatContext {
&self.options &self.options
} }
fn source_code(&self) -> SourceCode { fn source_code(&self) -> SourceCode<'_> {
SourceCode::new(&self.source_code) SourceCode::new(&self.source_code)
} }
} }
@ -326,7 +326,7 @@ where
printer.print_with_indent(&self.document, indent) printer.print_with_indent(&self.document, indent)
} }
fn create_printer(&self) -> Printer { fn create_printer(&self) -> Printer<'_> {
let source_code = self.context.source_code(); let source_code = self.context.source_code();
let print_options = self.context.options().as_print_options(); let print_options = self.context.options().as_print_options();

View file

@ -315,7 +315,7 @@ impl<'a> Checker<'a> {
} }
/// Create a [`Generator`] to generate source code based on the current AST state. /// Create a [`Generator`] to generate source code based on the current AST state.
pub(crate) fn generator(&self) -> Generator { pub(crate) fn generator(&self) -> Generator<'_> {
Generator::new(self.stylist.indentation(), self.stylist.line_ending()) Generator::new(self.stylist.indentation(), self.stylist.line_ending())
} }

View file

@ -8,14 +8,14 @@ use libcst_native::{
}; };
use ruff_python_codegen::Stylist; use ruff_python_codegen::Stylist;
pub(crate) fn match_module(module_text: &str) -> Result<Module> { pub(crate) fn match_module(module_text: &str) -> Result<Module<'_>> {
match libcst_native::parse_module(module_text, None) { match libcst_native::parse_module(module_text, None) {
Ok(module) => Ok(module), Ok(module) => Ok(module),
Err(_) => bail!("Failed to extract CST from source"), Err(_) => bail!("Failed to extract CST from source"),
} }
} }
pub(crate) fn match_statement(statement_text: &str) -> Result<Statement> { pub(crate) fn match_statement(statement_text: &str) -> Result<Statement<'_>> {
match libcst_native::parse_statement(statement_text) { match libcst_native::parse_statement(statement_text) {
Ok(statement) => Ok(statement), Ok(statement) => Ok(statement),
Err(_) => bail!("Failed to extract statement from source"), Err(_) => bail!("Failed to extract statement from source"),
@ -220,7 +220,7 @@ pub(crate) fn match_if<'a, 'b>(statement: &'a mut Statement<'b>) -> Result<&'a m
/// ///
/// If the expression is not guaranteed to be valid as a standalone expression (e.g., if it may /// If the expression is not guaranteed to be valid as a standalone expression (e.g., if it may
/// span multiple lines and/or require parentheses), use [`transform_expression`] instead. /// span multiple lines and/or require parentheses), use [`transform_expression`] instead.
pub(crate) fn match_expression(expression_text: &str) -> Result<Expression> { pub(crate) fn match_expression(expression_text: &str) -> Result<Expression<'_>> {
match libcst_native::parse_expression(expression_text) { match libcst_native::parse_expression(expression_text) {
Ok(expression) => Ok(expression), Ok(expression) => Ok(expression),
Err(_) => bail!("Failed to extract expression from source"), Err(_) => bail!("Failed to extract expression from source"),

View file

@ -13,7 +13,7 @@ use ruff_text_size::{Ranged, TextSize};
use crate::Locator; use crate::Locator;
/// Extract doc lines (standalone comments) from a token sequence. /// Extract doc lines (standalone comments) from a token sequence.
pub(crate) fn doc_lines_from_tokens(tokens: &Tokens) -> DocLines { pub(crate) fn doc_lines_from_tokens(tokens: &Tokens) -> DocLines<'_> {
DocLines::new(tokens) DocLines::new(tokens)
} }

View file

@ -32,7 +32,7 @@ impl<'a> Docstring<'a> {
} }
/// The contents of the docstring, excluding the opening and closing quotes. /// The contents of the docstring, excluding the opening and closing quotes.
pub(crate) fn body(&self) -> DocstringBody { pub(crate) fn body(&self) -> DocstringBody<'_> {
DocstringBody { docstring: self } DocstringBody { docstring: self }
} }

View file

@ -208,7 +208,7 @@ impl<'a> SectionContexts<'a> {
self.contexts.len() self.contexts.len()
} }
pub(crate) fn iter(&self) -> SectionContextsIter { pub(crate) fn iter(&self) -> SectionContextsIter<'_> {
SectionContextsIter { SectionContextsIter {
docstring_body: self.docstring.body(), docstring_body: self.docstring.body(),
inner: self.contexts.iter(), inner: self.contexts.iter(),

View file

@ -329,7 +329,7 @@ mod tests {
#[test] #[test]
fn start_of_file() -> Result<()> { fn start_of_file() -> Result<()> {
fn insert(contents: &str) -> Result<Insertion> { fn insert(contents: &str) -> Result<Insertion<'_>> {
let parsed = parse_module(contents)?; let parsed = parse_module(contents)?;
let locator = Locator::new(contents); let locator = Locator::new(contents);
let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents());
@ -450,7 +450,7 @@ x = 1
#[test] #[test]
fn start_of_block() { fn start_of_block() {
fn insert(contents: &str, offset: TextSize) -> Insertion { fn insert(contents: &str, offset: TextSize) -> Insertion<'_> {
let parsed = parse_module(contents).unwrap(); let parsed = parse_module(contents).unwrap();
let locator = Locator::new(contents); let locator = Locator::new(contents);
let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents()); let stylist = Stylist::from_tokens(parsed.tokens(), locator.contents());

View file

@ -49,7 +49,7 @@ impl<'a> Locator<'a> {
self.index.get() self.index.get()
} }
pub fn to_source_code(&self) -> SourceCode { pub fn to_source_code(&self) -> SourceCode<'_, '_> {
SourceCode::new(self.contents, self.to_index()) SourceCode::new(self.contents, self.to_index())
} }

View file

@ -149,7 +149,7 @@ impl Deref for MessageWithLocation<'_> {
fn group_diagnostics_by_filename( fn group_diagnostics_by_filename(
diagnostics: &[Diagnostic], diagnostics: &[Diagnostic],
) -> BTreeMap<String, Vec<MessageWithLocation>> { ) -> BTreeMap<String, Vec<MessageWithLocation<'_>>> {
let mut grouped_messages = BTreeMap::default(); let mut grouped_messages = BTreeMap::default();
for diagnostic in diagnostics { for diagnostic in diagnostics {
grouped_messages grouped_messages

View file

@ -286,7 +286,7 @@ impl Display for MessageCodeFrame<'_> {
/// modify the annotation ranges by inserting 3-byte Unicode replacements /// modify the annotation ranges by inserting 3-byte Unicode replacements
/// because `annotate-snippets` will account for their actual width when /// because `annotate-snippets` will account for their actual width when
/// rendering and displaying the column to the user. /// rendering and displaying the column to the user.
fn replace_unprintable(source: &str, annotation_range: TextRange) -> SourceCode { fn replace_unprintable(source: &str, annotation_range: TextRange) -> SourceCode<'_> {
let mut result = String::new(); let mut result = String::new();
let mut last_end = 0; let mut last_end = 0;
let mut range = annotation_range; let mut range = annotation_range;

View file

@ -99,7 +99,7 @@ pub(crate) struct Codes<'a> {
impl Codes<'_> { impl Codes<'_> {
/// Returns an iterator over the [`Code`]s in the `noqa` directive. /// Returns an iterator over the [`Code`]s in the `noqa` directive.
pub(crate) fn iter(&self) -> std::slice::Iter<Code> { pub(crate) fn iter(&self) -> std::slice::Iter<'_, Code<'_>> {
self.codes.iter() self.codes.iter()
} }
@ -306,7 +306,7 @@ impl<'a> FileNoqaDirectives<'a> {
Self(lines) Self(lines)
} }
pub(crate) fn lines(&self) -> &[FileNoqaDirectiveLine] { pub(crate) fn lines(&self) -> &[FileNoqaDirectiveLine<'_>] {
&self.0 &self.0
} }
@ -1106,7 +1106,10 @@ impl<'a> NoqaDirectives<'a> {
Self { inner: directives } Self { inner: directives }
} }
pub(crate) fn find_line_with_directive(&self, offset: TextSize) -> Option<&NoqaDirectiveLine> { pub(crate) fn find_line_with_directive(
&self,
offset: TextSize,
) -> Option<&NoqaDirectiveLine<'_>> {
self.find_line_index(offset).map(|index| &self.inner[index]) self.find_line_index(offset).map(|index| &self.inner[index])
} }
@ -1139,7 +1142,7 @@ impl<'a> NoqaDirectives<'a> {
.ok() .ok()
} }
pub(crate) fn lines(&self) -> &[NoqaDirectiveLine] { pub(crate) fn lines(&self) -> &[NoqaDirectiveLine<'_>] {
&self.inner &self.inner
} }

View file

@ -178,7 +178,7 @@ impl<'a> From<&NestedIf<'a>> for AnyNodeRef<'a> {
} }
/// Returns the body, the range of the `if` or `elif` and whether the range is for an `if` or `elif` /// Returns the body, the range of the `if` or `elif` and whether the range is for an `if` or `elif`
fn nested_if_body(stmt_if: &ast::StmtIf) -> Option<NestedIf> { fn nested_if_body(stmt_if: &ast::StmtIf) -> Option<NestedIf<'_>> {
let ast::StmtIf { let ast::StmtIf {
test, test,
body, body,

View file

@ -267,7 +267,7 @@ struct Terminal<'a> {
stmt: &'a Stmt, stmt: &'a Stmt,
} }
fn match_loop(stmt: &Stmt) -> Option<Loop> { fn match_loop(stmt: &Stmt) -> Option<Loop<'_>> {
let Stmt::For(ast::StmtFor { let Stmt::For(ast::StmtFor {
body, target, iter, .. body, target, iter, ..
}) = stmt }) = stmt
@ -324,7 +324,7 @@ fn match_loop(stmt: &Stmt) -> Option<Loop> {
/// return True /// return True
/// return False /// return False
/// ``` /// ```
fn match_else_return(stmt: &Stmt) -> Option<Terminal> { fn match_else_return(stmt: &Stmt) -> Option<Terminal<'_>> {
let Stmt::For(ast::StmtFor { orelse, .. }) = stmt else { let Stmt::For(ast::StmtFor { orelse, .. }) = stmt else {
return None; return None;
}; };

View file

@ -388,7 +388,7 @@ impl KnownModules {
/// Return the [`ImportSection`] for a given module, if it's been categorized as a known module /// Return the [`ImportSection`] for a given module, if it's been categorized as a known module
/// by the user. /// by the user.
fn categorize(&self, module_name: &str) -> Option<(&ImportSection, Reason)> { fn categorize(&self, module_name: &str) -> Option<(&ImportSection, Reason<'_>)> {
if self.has_submodules { if self.has_submodules {
// Check all module prefixes from the longest to the shortest (e.g., given // Check all module prefixes from the longest to the shortest (e.g., given
// `foo.bar.baz`, check `foo.bar.baz`, then `foo.bar`, then `foo`, taking the first, // `foo.bar.baz`, check `foo.bar.baz`, then `foo.bar`, then `foo`, taking the first,
@ -412,7 +412,7 @@ impl KnownModules {
} }
} }
fn categorize_submodule(&self, submodule: &str) -> Option<(&ImportSection, Reason)> { fn categorize_submodule(&self, submodule: &str) -> Option<(&ImportSection, Reason<'_>)> {
let section = self.known.iter().find_map(|(pattern, section)| { let section = self.known.iter().find_map(|(pattern, section)| {
if pattern.matches(submodule) { if pattern.matches(submodule) {
Some(section) Some(section)

View file

@ -452,7 +452,7 @@ impl<'a> DocstringSections<'a> {
/// ///
/// Attempts to parse using the specified [`SectionStyle`], falling back to the other style if no /// Attempts to parse using the specified [`SectionStyle`], falling back to the other style if no
/// entries are found. /// entries are found.
fn parse_entries(content: &str, style: Option<SectionStyle>) -> Vec<QualifiedName> { fn parse_entries(content: &str, style: Option<SectionStyle>) -> Vec<QualifiedName<'_>> {
match style { match style {
Some(SectionStyle::Google) => parse_entries_google(content), Some(SectionStyle::Google) => parse_entries_google(content),
Some(SectionStyle::Numpy) => parse_entries_numpy(content), Some(SectionStyle::Numpy) => parse_entries_numpy(content),
@ -474,7 +474,7 @@ fn parse_entries(content: &str, style: Option<SectionStyle>) -> Vec<QualifiedNam
/// FasterThanLightError: If speed is greater than the speed of light. /// FasterThanLightError: If speed is greater than the speed of light.
/// DivisionByZero: If attempting to divide by zero. /// DivisionByZero: If attempting to divide by zero.
/// ``` /// ```
fn parse_entries_google(content: &str) -> Vec<QualifiedName> { fn parse_entries_google(content: &str) -> Vec<QualifiedName<'_>> {
let mut entries: Vec<QualifiedName> = Vec::new(); let mut entries: Vec<QualifiedName> = Vec::new();
for potential in content.lines() { for potential in content.lines() {
let Some(colon_idx) = potential.find(':') else { let Some(colon_idx) = potential.find(':') else {
@ -496,7 +496,7 @@ fn parse_entries_google(content: &str) -> Vec<QualifiedName> {
/// DivisionByZero /// DivisionByZero
/// If attempting to divide by zero. /// If attempting to divide by zero.
/// ``` /// ```
fn parse_entries_numpy(content: &str) -> Vec<QualifiedName> { fn parse_entries_numpy(content: &str) -> Vec<QualifiedName<'_>> {
let mut entries: Vec<QualifiedName> = Vec::new(); let mut entries: Vec<QualifiedName> = Vec::new();
let mut lines = content.lines(); let mut lines = content.lines();
let Some(dashes) = lines.next() else { let Some(dashes) = lines.next() else {

View file

@ -177,7 +177,6 @@ pub(crate) fn multi_line_summary_start(checker: &Checker, docstring: &Docstring)
// "\ // "\
// " // "
// ``` // ```
return;
} else { } else {
if checker.is_rule_enabled(Rule::MultiLineSummarySecondLine) { if checker.is_rule_enabled(Rule::MultiLineSummarySecondLine) {
let mut diagnostic = let mut diagnostic =

View file

@ -98,11 +98,11 @@ impl Settings {
self.convention self.convention
} }
pub fn ignore_decorators(&self) -> DecoratorIterator { pub fn ignore_decorators(&self) -> DecoratorIterator<'_> {
DecoratorIterator::new(&self.ignore_decorators) DecoratorIterator::new(&self.ignore_decorators)
} }
pub fn property_decorators(&self) -> DecoratorIterator { pub fn property_decorators(&self) -> DecoratorIterator<'_> {
DecoratorIterator::new(&self.property_decorators) DecoratorIterator::new(&self.property_decorators)
} }

View file

@ -100,7 +100,7 @@ impl Ranged for AttributeAssignment<'_> {
/// Return a list of attributes that are assigned to but not included in `__slots__`. /// Return a list of attributes that are assigned to but not included in `__slots__`.
/// ///
/// If the `__slots__` attribute cannot be statically determined, returns an empty vector. /// If the `__slots__` attribute cannot be statically determined, returns an empty vector.
fn is_attributes_not_in_slots(body: &[Stmt]) -> Vec<AttributeAssignment> { fn is_attributes_not_in_slots(body: &[Stmt]) -> Vec<AttributeAssignment<'_>> {
// First, collect all the attributes that are assigned to `__slots__`. // First, collect all the attributes that are assigned to `__slots__`.
let mut slots = FxHashSet::default(); let mut slots = FxHashSet::default();
for statement in body { for statement in body {

View file

@ -115,7 +115,7 @@ fn check_super_slots(checker: &Checker, class_def: &ast::StmtClassDef, slot: &Sl
} }
} }
fn slots_members(body: &[Stmt]) -> FxHashSet<Slot> { fn slots_members(body: &[Stmt]) -> FxHashSet<Slot<'_>> {
let mut members = FxHashSet::default(); let mut members = FxHashSet::default();
for stmt in body { for stmt in body {
match stmt { match stmt {
@ -161,7 +161,7 @@ fn slots_members(body: &[Stmt]) -> FxHashSet<Slot> {
members members
} }
fn slots_attributes(expr: &Expr) -> impl Iterator<Item = Slot> { fn slots_attributes(expr: &Expr) -> impl Iterator<Item = Slot<'_>> {
// Ex) `__slots__ = ("name",)` // Ex) `__slots__ = ("name",)`
let elts_iter = match expr { let elts_iter = match expr {
Expr::Tuple(ast::ExprTuple { elts, .. }) Expr::Tuple(ast::ExprTuple { elts, .. })

View file

@ -96,7 +96,7 @@ enum EncodingArg<'a> {
/// Return the encoding argument to an `encode` call, if it can be determined to be a /// Return the encoding argument to an `encode` call, if it can be determined to be a
/// UTF-8-equivalent encoding. /// UTF-8-equivalent encoding.
fn match_encoding_arg(arguments: &Arguments) -> Option<EncodingArg> { fn match_encoding_arg(arguments: &Arguments) -> Option<EncodingArg<'_>> {
match (&*arguments.args, &*arguments.keywords) { match (&*arguments.args, &*arguments.keywords) {
// Ex `"".encode()` // Ex `"".encode()`
([], []) => return Some(EncodingArg::Empty), ([], []) => return Some(EncodingArg::Empty),

View file

@ -343,7 +343,9 @@ enum ComprehensionTarget<'a> {
} }
/// Extract the target from the comprehension (e.g., `(x, y, z)` in `(x, y, z, ...) in iter`). /// Extract the target from the comprehension (e.g., `(x, y, z)` in `(x, y, z, ...) in iter`).
fn match_comprehension_target(comprehension: &ast::Comprehension) -> Option<ComprehensionTarget> { fn match_comprehension_target(
comprehension: &ast::Comprehension,
) -> Option<ComprehensionTarget<'_>> {
if comprehension.is_async || !comprehension.ifs.is_empty() { if comprehension.is_async || !comprehension.ifs.is_empty() {
return None; return None;
} }

View file

@ -89,7 +89,7 @@ pub(crate) fn single_item_membership_test(
generate_comparison( generate_comparison(
left, left,
&[membership_test.replacement_op()], &[membership_test.replacement_op()],
&[item.clone()], std::slice::from_ref(item),
expr.into(), expr.into(),
checker.comment_ranges(), checker.comment_ranges(),
checker.source(), checker.source(),

View file

@ -139,7 +139,7 @@ pub(crate) fn slice_to_remove_affix_stmt(checker: &Checker, if_stmt: &ast::StmtI
/// where `func` is either `startswith` or `endswith`, /// where `func` is either `startswith` or `endswith`,
/// this function collects `text`,`func`, `affix`, and the non-null /// this function collects `text`,`func`, `affix`, and the non-null
/// bound of the slice. Otherwise, returns `None`. /// bound of the slice. Otherwise, returns `None`.
fn affix_removal_data_expr(if_expr: &ast::ExprIf) -> Option<RemoveAffixData> { fn affix_removal_data_expr(if_expr: &ast::ExprIf) -> Option<RemoveAffixData<'_>> {
let ast::ExprIf { let ast::ExprIf {
test, test,
body, body,
@ -166,7 +166,7 @@ fn affix_removal_data_expr(if_expr: &ast::ExprIf) -> Option<RemoveAffixData> {
/// where `func` is either `startswith` or `endswith`, /// where `func` is either `startswith` or `endswith`,
/// this function collects `text`,`func`, `affix`, and the non-null /// this function collects `text`,`func`, `affix`, and the non-null
/// bound of the slice. Otherwise, returns `None`. /// bound of the slice. Otherwise, returns `None`.
fn affix_removal_data_stmt(if_stmt: &ast::StmtIf) -> Option<RemoveAffixData> { fn affix_removal_data_stmt(if_stmt: &ast::StmtIf) -> Option<RemoveAffixData<'_>> {
let ast::StmtIf { let ast::StmtIf {
test, test,
body, body,

View file

@ -39,7 +39,7 @@ where
} }
/// Metadata of an option that can either be a [`OptionField`] or [`OptionSet`]. /// Metadata of an option that can either be a [`OptionField`] or [`OptionSet`].
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize), serde(untagged))] #[cfg_attr(feature = "serde", derive(::serde::Serialize), serde(untagged))]
pub enum OptionEntry { pub enum OptionEntry {
/// A single option. /// A single option.
@ -49,6 +49,15 @@ pub enum OptionEntry {
Set(OptionSet), Set(OptionSet),
} }
impl OptionEntry {
pub fn into_field(self) -> Option<OptionField> {
match self {
OptionEntry::Field(field) => Some(field),
OptionEntry::Set(_) => None,
}
}
}
impl Display for OptionEntry { impl Display for OptionEntry {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self { match self {
@ -62,7 +71,7 @@ impl Display for OptionEntry {
/// ///
/// It extracts the options by calling the [`OptionsMetadata::record`] of a type implementing /// It extracts the options by calling the [`OptionsMetadata::record`] of a type implementing
/// [`OptionsMetadata`]. /// [`OptionsMetadata`].
#[derive(Copy, Clone, Eq, PartialEq)] #[derive(Copy, Clone)]
pub struct OptionSet { pub struct OptionSet {
record: fn(&mut dyn Visit), record: fn(&mut dyn Visit),
doc: fn() -> Option<&'static str>, doc: fn() -> Option<&'static str>,
@ -192,8 +201,8 @@ impl OptionSet {
/// } /// }
/// } /// }
/// ///
/// assert_eq!(WithOptions::metadata().find("ignore-git-ignore"), Some(OptionEntry::Field(IGNORE_GIT_IGNORE.clone()))); /// assert_eq!(WithOptions::metadata().find("ignore-git-ignore").and_then(OptionEntry::into_field), Some(IGNORE_GIT_IGNORE.clone()));
/// assert_eq!(WithOptions::metadata().find("does-not-exist"), None); /// assert!(WithOptions::metadata().find("does-not-exist").is_none());
/// ``` /// ```
/// ### Find a nested option /// ### Find a nested option
/// ///
@ -234,10 +243,10 @@ impl OptionSet {
/// } /// }
/// } /// }
/// ///
/// assert_eq!(Root::metadata().find("format.hard-tabs"), Some(OptionEntry::Field(HARD_TABS.clone()))); /// assert_eq!(Root::metadata().find("format.hard-tabs").and_then(OptionEntry::into_field), Some(HARD_TABS.clone()));
/// assert_eq!(Root::metadata().find("format"), Some(OptionEntry::Set(Nested::metadata()))); /// assert!(matches!(Root::metadata().find("format"), Some(OptionEntry::Set(_))));
/// assert_eq!(Root::metadata().find("format.spaces"), None); /// assert!(Root::metadata().find("format.spaces").is_none());
/// assert_eq!(Root::metadata().find("lint.hard-tabs"), None); /// assert!(Root::metadata().find("lint.hard-tabs").is_none());
/// ``` /// ```
pub fn find(&self, name: &str) -> Option<OptionEntry> { pub fn find(&self, name: &str) -> Option<OptionEntry> {
struct FindOptionVisitor<'a> { struct FindOptionVisitor<'a> {

View file

@ -1900,7 +1900,7 @@ impl<'a> From<&'a Expr> for HashableExpr<'a> {
fn from(expr: &'a Expr) -> Self { fn from(expr: &'a Expr) -> Self {
/// Returns a version of the given expression that can be hashed and compared according to /// Returns a version of the given expression that can be hashed and compared according to
/// Python semantics. /// Python semantics.
fn as_hashable(expr: &Expr) -> ComparableExpr { fn as_hashable(expr: &Expr) -> ComparableExpr<'_> {
match expr { match expr {
Expr::Named(named) => ComparableExpr::NamedExpr(ExprNamed { Expr::Named(named) => ComparableExpr::NamedExpr(ExprNamed {
target: Box::new(ComparableExpr::from(&named.target)), target: Box::new(ComparableExpr::from(&named.target)),

View file

@ -789,7 +789,7 @@ where
/// assert_eq!(format_import_from(1, None), ".".to_string()); /// assert_eq!(format_import_from(1, None), ".".to_string());
/// assert_eq!(format_import_from(1, Some("foo")), ".foo".to_string()); /// assert_eq!(format_import_from(1, Some("foo")), ".foo".to_string());
/// ``` /// ```
pub fn format_import_from(level: u32, module: Option<&str>) -> Cow<str> { pub fn format_import_from(level: u32, module: Option<&str>) -> Cow<'_, str> {
match (level, module) { match (level, module) {
(0, Some(module)) => Cow::Borrowed(module), (0, Some(module)) => Cow::Borrowed(module),
(level, module) => { (level, module) => {
@ -1509,7 +1509,7 @@ pub fn pep_604_union(elts: &[Expr]) -> Expr {
[rest @ .., elt] => Expr::BinOp(ast::ExprBinOp { [rest @ .., elt] => Expr::BinOp(ast::ExprBinOp {
left: Box::new(pep_604_union(rest)), left: Box::new(pep_604_union(rest)),
op: Operator::BitOr, op: Operator::BitOr,
right: Box::new(pep_604_union(&[elt.clone()])), right: Box::new(pep_604_union(std::slice::from_ref(elt))),
range: TextRange::default(), range: TextRange::default(),
node_index: AtomicNodeIndex::dummy(), node_index: AtomicNodeIndex::dummy(),
}), }),

View file

@ -162,13 +162,13 @@ impl Ranged for DictItem {
impl ExprDict { impl ExprDict {
/// Returns an `Iterator` over the AST nodes representing the /// Returns an `Iterator` over the AST nodes representing the
/// dictionary's keys. /// dictionary's keys.
pub fn iter_keys(&self) -> DictKeyIterator { pub fn iter_keys(&self) -> DictKeyIterator<'_> {
DictKeyIterator::new(&self.items) DictKeyIterator::new(&self.items)
} }
/// Returns an `Iterator` over the AST nodes representing the /// Returns an `Iterator` over the AST nodes representing the
/// dictionary's values. /// dictionary's values.
pub fn iter_values(&self) -> DictValueIterator { pub fn iter_values(&self) -> DictValueIterator<'_> {
DictValueIterator::new(&self.items) DictValueIterator::new(&self.items)
} }
@ -462,13 +462,13 @@ impl FStringValue {
} }
/// Returns an iterator over all the [`FStringPart`]s contained in this value. /// Returns an iterator over all the [`FStringPart`]s contained in this value.
pub fn iter(&self) -> Iter<FStringPart> { pub fn iter(&self) -> Iter<'_, FStringPart> {
self.as_slice().iter() self.as_slice().iter()
} }
/// Returns an iterator over all the [`FStringPart`]s contained in this value /// Returns an iterator over all the [`FStringPart`]s contained in this value
/// that allows modification. /// that allows modification.
pub fn iter_mut(&mut self) -> IterMut<FStringPart> { pub fn iter_mut(&mut self) -> IterMut<'_, FStringPart> {
self.as_mut_slice().iter_mut() self.as_mut_slice().iter_mut()
} }
@ -657,13 +657,13 @@ impl TStringValue {
} }
/// Returns an iterator over all the [`TString`]s contained in this value. /// Returns an iterator over all the [`TString`]s contained in this value.
pub fn iter(&self) -> Iter<TString> { pub fn iter(&self) -> Iter<'_, TString> {
self.as_slice().iter() self.as_slice().iter()
} }
/// Returns an iterator over all the [`TString`]s contained in this value /// Returns an iterator over all the [`TString`]s contained in this value
/// that allows modification. /// that allows modification.
pub fn iter_mut(&mut self) -> IterMut<TString> { pub fn iter_mut(&mut self) -> IterMut<'_, TString> {
self.as_mut_slice().iter_mut() self.as_mut_slice().iter_mut()
} }
@ -765,7 +765,7 @@ pub trait StringFlags: Copy {
AnyStringFlags::new(self.prefix(), self.quote_style(), self.triple_quotes()) AnyStringFlags::new(self.prefix(), self.quote_style(), self.triple_quotes())
} }
fn display_contents(self, contents: &str) -> DisplayFlags { fn display_contents(self, contents: &str) -> DisplayFlags<'_> {
DisplayFlags { DisplayFlags {
flags: self.as_any_string_flags(), flags: self.as_any_string_flags(),
contents, contents,
@ -1289,13 +1289,13 @@ impl StringLiteralValue {
} }
/// Returns an iterator over all the [`StringLiteral`] parts contained in this value. /// Returns an iterator over all the [`StringLiteral`] parts contained in this value.
pub fn iter(&self) -> Iter<StringLiteral> { pub fn iter(&self) -> Iter<'_, StringLiteral> {
self.as_slice().iter() self.as_slice().iter()
} }
/// Returns an iterator over all the [`StringLiteral`] parts contained in this value /// Returns an iterator over all the [`StringLiteral`] parts contained in this value
/// that allows modification. /// that allows modification.
pub fn iter_mut(&mut self) -> IterMut<StringLiteral> { pub fn iter_mut(&mut self) -> IterMut<'_, StringLiteral> {
self.as_mut_slice().iter_mut() self.as_mut_slice().iter_mut()
} }
@ -1717,13 +1717,13 @@ impl BytesLiteralValue {
} }
/// Returns an iterator over all the [`BytesLiteral`] parts contained in this value. /// Returns an iterator over all the [`BytesLiteral`] parts contained in this value.
pub fn iter(&self) -> Iter<BytesLiteral> { pub fn iter(&self) -> Iter<'_, BytesLiteral> {
self.as_slice().iter() self.as_slice().iter()
} }
/// Returns an iterator over all the [`BytesLiteral`] parts contained in this value /// Returns an iterator over all the [`BytesLiteral`] parts contained in this value
/// that allows modification. /// that allows modification.
pub fn iter_mut(&mut self) -> IterMut<BytesLiteral> { pub fn iter_mut(&mut self) -> IterMut<'_, BytesLiteral> {
self.as_mut_slice().iter_mut() self.as_mut_slice().iter_mut()
} }
@ -3011,7 +3011,7 @@ impl Parameters {
} }
/// Returns an iterator over all parameters included in this [`Parameters`] node. /// Returns an iterator over all parameters included in this [`Parameters`] node.
pub fn iter(&self) -> ParametersIterator { pub fn iter(&self) -> ParametersIterator<'_> {
ParametersIterator::new(self) ParametersIterator::new(self)
} }
@ -3328,7 +3328,7 @@ impl Arguments {
/// Return the argument with the given name or at the given position, or `None` if no such /// Return the argument with the given name or at the given position, or `None` if no such
/// argument exists. Used to retrieve arguments that can be provided _either_ as keyword or /// argument exists. Used to retrieve arguments that can be provided _either_ as keyword or
/// positional arguments. /// positional arguments.
pub fn find_argument(&self, name: &str, position: usize) -> Option<ArgOrKeyword> { pub fn find_argument(&self, name: &str, position: usize) -> Option<ArgOrKeyword<'_>> {
self.find_keyword(name) self.find_keyword(name)
.map(ArgOrKeyword::from) .map(ArgOrKeyword::from)
.or_else(|| self.find_positional(position).map(ArgOrKeyword::from)) .or_else(|| self.find_positional(position).map(ArgOrKeyword::from))

View file

@ -33,7 +33,7 @@ impl Ranged for IfElifBranch<'_> {
} }
} }
pub fn if_elif_branches(stmt_if: &StmtIf) -> impl Iterator<Item = IfElifBranch> { pub fn if_elif_branches(stmt_if: &StmtIf) -> impl Iterator<Item = IfElifBranch<'_>> {
iter::once(IfElifBranch { iter::once(IfElifBranch {
kind: BranchKind::If, kind: BranchKind::If,
test: stmt_if.test.as_ref(), test: stmt_if.test.as_ref(),

View file

@ -1871,10 +1871,10 @@ class Foo:
} }
/// test all of the valid string literal prefix and quote combinations from /// test all of the valid string literal prefix and quote combinations from
/// https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals /// <https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals>
/// ///
/// Note that the numeric ids on the input/output and quote fields prevent name conflicts from /// Note that the numeric ids on the input/output and quote fields prevent name conflicts from
/// the test_matrix but are otherwise unnecessary /// the `test_matrix` but are otherwise unnecessary
#[test_case::test_matrix( #[test_case::test_matrix(
[ [
("r", "r", 0), ("r", "r", 0),

View file

@ -21,7 +21,7 @@ where
} }
/// Formats the passed comments as leading comments /// Formats the passed comments as leading comments
pub(crate) const fn leading_comments(comments: &[SourceComment]) -> FormatLeadingComments { pub(crate) const fn leading_comments(comments: &[SourceComment]) -> FormatLeadingComments<'_> {
FormatLeadingComments::Comments(comments) FormatLeadingComments::Comments(comments)
} }
@ -135,7 +135,7 @@ impl Format<PyFormatContext<'_>> for FormatLeadingAlternateBranchComments<'_> {
} }
/// Formats the passed comments as trailing comments /// Formats the passed comments as trailing comments
pub(crate) fn trailing_comments(comments: &[SourceComment]) -> FormatTrailingComments { pub(crate) fn trailing_comments(comments: &[SourceComment]) -> FormatTrailingComments<'_> {
FormatTrailingComments(comments) FormatTrailingComments(comments)
} }
@ -199,7 +199,7 @@ where
FormatDanglingComments::Node(node.into()) FormatDanglingComments::Node(node.into())
} }
pub(crate) fn dangling_comments(comments: &[SourceComment]) -> FormatDanglingComments { pub(crate) fn dangling_comments(comments: &[SourceComment]) -> FormatDanglingComments<'_> {
FormatDanglingComments::Comments(comments) FormatDanglingComments::Comments(comments)
} }
@ -260,7 +260,7 @@ impl Format<PyFormatContext<'_>> for FormatDanglingComments<'_> {
/// ``` /// ```
pub(crate) fn dangling_open_parenthesis_comments( pub(crate) fn dangling_open_parenthesis_comments(
comments: &[SourceComment], comments: &[SourceComment],
) -> FormatDanglingOpenParenthesisComments { ) -> FormatDanglingOpenParenthesisComments<'_> {
FormatDanglingOpenParenthesisComments { comments } FormatDanglingOpenParenthesisComments { comments }
} }
@ -292,7 +292,7 @@ impl Format<PyFormatContext<'_>> for FormatDanglingOpenParenthesisComments<'_> {
/// ///
/// * Adds a whitespace between `#` and the comment text except if the first character is a `#`, `:`, `'`, or `!` /// * Adds a whitespace between `#` and the comment text except if the first character is a `#`, `:`, `'`, or `!`
/// * Replaces non breaking whitespaces with regular whitespaces except if in front of a `types:` comment /// * Replaces non breaking whitespaces with regular whitespaces except if in front of a `types:` comment
pub(crate) const fn format_comment(comment: &SourceComment) -> FormatComment { pub(crate) const fn format_comment(comment: &SourceComment) -> FormatComment<'_> {
FormatComment { comment } FormatComment { comment }
} }
@ -361,7 +361,7 @@ impl Format<PyFormatContext<'_>> for FormatEmptyLines {
/// * Expands parent node. /// * Expands parent node.
pub(crate) const fn trailing_end_of_line_comment( pub(crate) const fn trailing_end_of_line_comment(
comment: &SourceComment, comment: &SourceComment,
) -> FormatTrailingEndOfLineComment { ) -> FormatTrailingEndOfLineComment<'_> {
FormatTrailingEndOfLineComment { comment } FormatTrailingEndOfLineComment { comment }
} }
@ -537,7 +537,7 @@ fn strip_comment_prefix(comment_text: &str) -> FormatResult<&str> {
pub(crate) fn empty_lines_before_trailing_comments( pub(crate) fn empty_lines_before_trailing_comments(
comments: &[SourceComment], comments: &[SourceComment],
node_kind: NodeKind, node_kind: NodeKind,
) -> FormatEmptyLinesBeforeTrailingComments { ) -> FormatEmptyLinesBeforeTrailingComments<'_> {
FormatEmptyLinesBeforeTrailingComments { FormatEmptyLinesBeforeTrailingComments {
comments, comments,
node_kind, node_kind,
@ -589,7 +589,7 @@ impl Format<PyFormatContext<'_>> for FormatEmptyLinesBeforeTrailingComments<'_>
/// additional empty line before the comment. /// additional empty line before the comment.
pub(crate) fn empty_lines_after_leading_comments( pub(crate) fn empty_lines_after_leading_comments(
comments: &[SourceComment], comments: &[SourceComment],
) -> FormatEmptyLinesAfterLeadingComments { ) -> FormatEmptyLinesAfterLeadingComments<'_> {
FormatEmptyLinesAfterLeadingComments { comments } FormatEmptyLinesAfterLeadingComments { comments }
} }

View file

@ -249,7 +249,7 @@ impl<K: std::hash::Hash + Eq, V> MultiMap<K, V> {
} }
/// Returns the *leading*, *dangling*, and *trailing* parts of `key`. /// Returns the *leading*, *dangling*, and *trailing* parts of `key`.
pub(super) fn leading_dangling_trailing(&self, key: &K) -> LeadingDanglingTrailing<V> { pub(super) fn leading_dangling_trailing(&self, key: &K) -> LeadingDanglingTrailing<'_, V> {
match self.index.get(key) { match self.index.get(key) {
None => LeadingDanglingTrailing { None => LeadingDanglingTrailing {
leading: &[], leading: &[],

View file

@ -358,7 +358,10 @@ impl<'a> Comments<'a> {
} }
/// Returns an iterator over the [leading](self#leading-comments), [dangling](self#dangling-comments), and [trailing](self#trailing) comments of `node`. /// Returns an iterator over the [leading](self#leading-comments), [dangling](self#dangling-comments), and [trailing](self#trailing) comments of `node`.
pub(crate) fn leading_dangling_trailing<T>(&self, node: T) -> LeadingDanglingTrailingComments pub(crate) fn leading_dangling_trailing<T>(
&self,
node: T,
) -> LeadingDanglingTrailingComments<'_>
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
@ -540,7 +543,7 @@ mod tests {
} }
} }
fn to_comments(&self) -> Comments { fn to_comments(&self) -> Comments<'_> {
Comments::from_ast(self.parsed.syntax(), self.source_code, &self.comment_ranges) Comments::from_ast(self.parsed.syntax(), self.source_code, &self.comment_ranges)
} }
} }

View file

@ -18,7 +18,7 @@ impl<'a> NodeRefEqualityKey<'a> {
} }
/// Returns the underlying node. /// Returns the underlying node.
pub(super) fn node(&self) -> AnyNodeRef { pub(super) fn node(&self) -> AnyNodeRef<'_> {
self.node self.node
} }
} }

View file

@ -121,7 +121,7 @@ impl FormatContext for PyFormatContext<'_> {
&self.options &self.options
} }
fn source_code(&self) -> SourceCode { fn source_code(&self) -> SourceCode<'_> {
SourceCode::new(self.contents) SourceCode::new(self.contents)
} }
} }

View file

@ -62,7 +62,7 @@ impl NeedsParentheses for ExprNumberLiteral {
} }
/// Returns the normalized integer string. /// Returns the normalized integer string.
fn normalize_integer(input: &str) -> Cow<str> { fn normalize_integer(input: &str) -> Cow<'_, str> {
// The normalized string if `input` is not yet normalized. // The normalized string if `input` is not yet normalized.
// `output` must remain empty if `input` is already normalized. // `output` must remain empty if `input` is already normalized.
let mut output = String::new(); let mut output = String::new();
@ -107,7 +107,7 @@ fn normalize_integer(input: &str) -> Cow<str> {
} }
/// Returns the normalized floating number string. /// Returns the normalized floating number string.
fn normalize_floating_number(input: &str) -> Cow<str> { fn normalize_floating_number(input: &str) -> Cow<'_, str> {
// The normalized string if `input` is not yet normalized. // The normalized string if `input` is not yet normalized.
// `output` must remain empty if `input` is already normalized. // `output` must remain empty if `input` is already normalized.
let mut output = String::new(); let mut output = String::new();

View file

@ -645,7 +645,7 @@ pub(crate) fn normalize_string(
start_offset: usize, start_offset: usize,
new_flags: AnyStringFlags, new_flags: AnyStringFlags,
escape_braces: bool, escape_braces: bool,
) -> Cow<str> { ) -> Cow<'_, str> {
// The normalized string if `input` is not yet normalized. // The normalized string if `input` is not yet normalized.
// `output` must remain empty if `input` is already normalized. // `output` must remain empty if `input` is already normalized.
let mut output = String::new(); let mut output = String::new();
@ -798,7 +798,7 @@ impl UnicodeEscape {
/// ///
/// * `\u`, `\U'` and `\x`: To use lower case for the characters `a-f`. /// * `\u`, `\U'` and `\x`: To use lower case for the characters `a-f`.
/// * `\N`: To use uppercase letters /// * `\N`: To use uppercase letters
fn normalize(self, input: &str) -> Option<Cow<str>> { fn normalize(self, input: &str) -> Option<Cow<'_, str>> {
let mut normalised = String::new(); let mut normalised = String::new();
let len = match self { let len = match self {

View file

@ -1687,7 +1687,7 @@ impl<'a> LexedText<'a> {
} }
/// Create a new [`Lexer`] for the given source code and [`Mode`]. /// Create a new [`Lexer`] for the given source code and [`Mode`].
pub fn lex(source: &str, mode: Mode) -> Lexer { pub fn lex(source: &str, mode: Mode) -> Lexer<'_> {
Lexer::new(source, mode, TextSize::default()) Lexer::new(source, mode, TextSize::default())
} }

View file

@ -485,7 +485,7 @@ impl Tokens {
} }
/// Returns an iterator over all the tokens that provides context. /// Returns an iterator over all the tokens that provides context.
pub fn iter_with_context(&self) -> TokenIterWithContext { pub fn iter_with_context(&self) -> TokenIterWithContext<'_> {
TokenIterWithContext::new(&self.raw) TokenIterWithContext::new(&self.raw)
} }

View file

@ -21,8 +21,9 @@ pub(super) fn set_expr_ctx(expr: &mut Expr, new_ctx: ExprContext) {
Expr::List(ast::ExprList { elts, ctx, .. }) Expr::List(ast::ExprList { elts, ctx, .. })
| Expr::Tuple(ast::ExprTuple { elts, ctx, .. }) => { | Expr::Tuple(ast::ExprTuple { elts, ctx, .. }) => {
*ctx = new_ctx; *ctx = new_ctx;
elts.iter_mut() for element in elts.iter_mut() {
.for_each(|element| set_expr_ctx(element, new_ctx)); set_expr_ctx(element, new_ctx);
}
} }
_ => {} _ => {}
} }

View file

@ -57,7 +57,7 @@ impl NameImport {
} }
/// Returns the [`QualifiedName`] of the imported name (e.g., given `from foo import bar as baz`, returns `["foo", "bar"]`). /// Returns the [`QualifiedName`] of the imported name (e.g., given `from foo import bar as baz`, returns `["foo", "bar"]`).
pub fn qualified_name(&self) -> QualifiedName { pub fn qualified_name(&self) -> QualifiedName<'_> {
match self { match self {
NameImport::Import(import) => QualifiedName::user_defined(&import.name.name), NameImport::Import(import) => QualifiedName::user_defined(&import.name.name),
NameImport::ImportFrom(import_from) => collect_import_from_member( NameImport::ImportFrom(import_from) => collect_import_from_member(

View file

@ -2100,7 +2100,7 @@ impl<'a> SemanticModel<'a> {
/// This method searches all scopes created by a function definition, comparing the /// This method searches all scopes created by a function definition, comparing the
/// [`TextRange`] of the provided `function_def` with the the range of the function /// [`TextRange`] of the provided `function_def` with the the range of the function
/// associated with the scope. /// associated with the scope.
pub fn function_scope(&self, function_def: &ast::StmtFunctionDef) -> Option<&Scope> { pub fn function_scope(&self, function_def: &ast::StmtFunctionDef) -> Option<&Scope<'_>> {
self.scopes.iter().find(|scope| { self.scopes.iter().find(|scope| {
let Some(function) = scope.kind.as_function() else { let Some(function) = scope.kind.as_function() else {
return false; return false;

View file

@ -33,7 +33,7 @@ use super::{Result, schedule::BackgroundSchedule};
/// that is of type [`lsp_types::Url`]. /// that is of type [`lsp_types::Url`].
macro_rules! define_document_url { macro_rules! define_document_url {
($params:ident: &$p:ty) => { ($params:ident: &$p:ty) => {
fn document_url($params: &$p) -> std::borrow::Cow<lsp_types::Url> { fn document_url($params: &$p) -> std::borrow::Cow<'_, lsp_types::Url> {
std::borrow::Cow::Borrowed(&$params.text_document.uri) std::borrow::Cow::Borrowed(&$params.text_document.uri)
} }
}; };

View file

@ -21,7 +21,7 @@ impl super::RequestHandler for CodeActionResolve {
} }
impl super::BackgroundDocumentRequestHandler for CodeActionResolve { impl super::BackgroundDocumentRequestHandler for CodeActionResolve {
fn document_url(params: &types::CodeAction) -> Cow<types::Url> { fn document_url(params: &types::CodeAction) -> Cow<'_, types::Url> {
let uri: lsp_types::Url = serde_json::from_value(params.data.clone().unwrap_or_default()) let uri: lsp_types::Url = serde_json::from_value(params.data.clone().unwrap_or_default())
.expect("code actions should have a URI in their data fields"); .expect("code actions should have a URI in their data fields");
Cow::Owned(uri) Cow::Owned(uri)

View file

@ -15,7 +15,7 @@ impl super::RequestHandler for Hover {
} }
impl super::BackgroundDocumentRequestHandler for Hover { impl super::BackgroundDocumentRequestHandler for Hover {
fn document_url(params: &types::HoverParams) -> std::borrow::Cow<lsp_types::Url> { fn document_url(params: &types::HoverParams) -> std::borrow::Cow<'_, lsp_types::Url> {
std::borrow::Cow::Borrowed(&params.text_document_position_params.text_document.uri) std::borrow::Cow::Borrowed(&params.text_document_position_params.text_document.uri)
} }
fn run_with_snapshot( fn run_with_snapshot(

View file

@ -62,7 +62,7 @@ pub(super) trait BackgroundDocumentRequestHandler: RequestHandler {
/// [`define_document_url`]: super::define_document_url /// [`define_document_url`]: super::define_document_url
fn document_url( fn document_url(
params: &<<Self as RequestHandler>::RequestType as Request>::Params, params: &<<Self as RequestHandler>::RequestType as Request>::Params,
) -> std::borrow::Cow<lsp_types::Url>; ) -> std::borrow::Cow<'_, lsp_types::Url>;
fn run_with_snapshot( fn run_with_snapshot(
snapshot: DocumentSnapshot, snapshot: DocumentSnapshot,
@ -100,7 +100,7 @@ pub(super) trait BackgroundDocumentNotificationHandler: NotificationHandler {
/// [`define_document_url`]: super::define_document_url /// [`define_document_url`]: super::define_document_url
fn document_url( fn document_url(
params: &<<Self as NotificationHandler>::NotificationType as LSPNotification>::Params, params: &<<Self as NotificationHandler>::NotificationType as LSPNotification>::Params,
) -> std::borrow::Cow<lsp_types::Url>; ) -> std::borrow::Cow<'_, lsp_types::Url>;
fn run_with_snapshot( fn run_with_snapshot(
snapshot: DocumentSnapshot, snapshot: DocumentSnapshot,

View file

@ -619,7 +619,7 @@ impl DocumentQuery {
/// Get the path for the document selected by this query, ignoring whether the file exists on disk. /// Get the path for the document selected by this query, ignoring whether the file exists on disk.
/// ///
/// Returns the URL's path if this is an unsaved (untitled) document. /// Returns the URL's path if this is an unsaved (untitled) document.
pub(crate) fn virtual_file_path(&self) -> Cow<Path> { pub(crate) fn virtual_file_path(&self) -> Cow<'_, Path> {
self.file_path() self.file_path()
.map(Cow::Owned) .map(Cow::Owned)
.unwrap_or_else(|| Cow::Borrowed(Path::new(self.file_url().path()))) .unwrap_or_else(|| Cow::Borrowed(Path::new(self.file_url().path())))

View file

@ -190,7 +190,7 @@ impl SourceFile {
&self.source_text()[range] &self.source_text()[range]
} }
pub fn to_source_code(&self) -> SourceCode { pub fn to_source_code(&self) -> SourceCode<'_, '_> {
SourceCode { SourceCode {
text: self.source_text(), text: self.source_text(),
index: self.index(), index: self.index(),

View file

@ -308,7 +308,7 @@ impl<'a> ParsedModule<'a> {
}) })
} }
fn format(&self, settings: &Settings) -> FormatResult<Formatted<PyFormatContext>> { fn format(&self, settings: &Settings) -> FormatResult<Formatted<PyFormatContext<'_>>> {
// TODO(konstin): Add an options for py/pyi to the UI (2/2) // TODO(konstin): Add an options for py/pyi to the UI (2/2)
let options = settings let options = settings
.formatter .formatter

View file

@ -611,7 +611,7 @@ Checks for exception handlers that catch non-exception classes.
**Why is this bad?** **Why is this bad?**
Catching classes that do not inherit from `BaseException` will raise a TypeError at runtime. Catching classes that do not inherit from `BaseException` will raise a `TypeError` at runtime.
**Example** **Example**

View file

@ -331,7 +331,7 @@ impl GotoTarget<'_> {
/// Returns `None` if no meaningful string representation can be provided. /// Returns `None` if no meaningful string representation can be provided.
/// This is used by the "references" feature, which looks for references /// This is used by the "references" feature, which looks for references
/// to this goto target. /// to this goto target.
pub(crate) fn to_string(&self) -> Option<Cow<str>> { pub(crate) fn to_string(&self) -> Option<Cow<'_, str>> {
match self { match self {
GotoTarget::Expression(expression) => match expression { GotoTarget::Expression(expression) => match expression {
ast::ExprRef::Name(name) => Some(Cow::Borrowed(name.id.as_str())), ast::ExprRef::Name(name) => Some(Cow::Borrowed(name.id.as_str())),

View file

@ -8,7 +8,11 @@ pub enum MarkupKind {
} }
impl MarkupKind { impl MarkupKind {
pub(crate) const fn fenced_code_block<T>(self, code: T, language: &str) -> FencedCodeBlock<T> pub(crate) const fn fenced_code_block<T>(
self,
code: T,
language: &str,
) -> FencedCodeBlock<'_, T>
where where
T: fmt::Display, T: fmt::Display,
{ {

View file

@ -38,7 +38,7 @@ impl IndexedFiles {
} }
} }
pub(super) fn get(&self) -> Index { pub(super) fn get(&self) -> Index<'_> {
let state = self.state.lock().unwrap(); let state = self.state.lock().unwrap();
match &*state { match &*state {
@ -57,7 +57,7 @@ impl IndexedFiles {
/// Returns a mutable view on the index that allows cheap in-place mutations. /// Returns a mutable view on the index that allows cheap in-place mutations.
/// ///
/// The changes are automatically written back to the database once the view is dropped. /// The changes are automatically written back to the database once the view is dropped.
pub(super) fn indexed_mut(db: &mut dyn Db, project: Project) -> Option<IndexedMut> { pub(super) fn indexed_mut(db: &mut dyn Db, project: Project) -> Option<IndexedMut<'_>> {
// Calling `trigger_cancellation` cancels all pending salsa queries. This ensures that there are no pending // Calling `trigger_cancellation` cancels all pending salsa queries. This ensures that there are no pending
// reads to the file set (this `db` is the only alive db). // reads to the file set (this `db` is the only alive db).
db.trigger_cancellation(); db.trigger_cancellation();

View file

@ -196,7 +196,7 @@ impl<K, V> ListBuilder<K, V> {
/// entries to duplicate for each insertion. If you construct the list in reverse order, we /// entries to duplicate for each insertion. If you construct the list in reverse order, we
/// will have to duplicate O(n) entries for each insertion, making it _quadratic_ to construct /// will have to duplicate O(n) entries for each insertion, making it _quadratic_ to construct
/// the entire list. /// the entire list.
pub(crate) fn entry(&mut self, list: List<K, V>, key: K) -> ListEntry<K, V> pub(crate) fn entry(&mut self, list: List<K, V>, key: K) -> ListEntry<'_, K, V>
where where
K: Clone + Ord, K: Clone + Ord,
V: Clone, V: Clone,
@ -373,7 +373,7 @@ impl<K, V> ListBuilder<K, V> {
impl<K> ListStorage<K, ()> { impl<K> ListStorage<K, ()> {
/// Iterates through the elements in a set _in reverse order_. /// Iterates through the elements in a set _in reverse order_.
#[expect(clippy::needless_pass_by_value)] #[expect(clippy::needless_pass_by_value)]
pub(crate) fn iter_set_reverse(&self, set: List<K, ()>) -> ListSetReverseIterator<K> { pub(crate) fn iter_set_reverse(&self, set: List<K, ()>) -> ListSetReverseIterator<'_, K> {
ListSetReverseIterator { ListSetReverseIterator {
storage: self, storage: self,
curr: set.last, curr: set.last,

View file

@ -21,7 +21,7 @@ mod typeshed;
mod testing; mod testing;
/// Returns an iterator over all search paths pointing to a system path /// Returns an iterator over all search paths pointing to a system path
pub fn system_module_search_paths(db: &dyn Db) -> SystemModuleSearchPathsIter { pub fn system_module_search_paths(db: &dyn Db) -> SystemModuleSearchPathsIter<'_> {
SystemModuleSearchPathsIter { SystemModuleSearchPathsIter {
inner: search_paths(db), inner: search_paths(db),
} }

View file

@ -153,7 +153,7 @@ pub(crate) fn file_to_module(db: &dyn Db, file: File) -> Option<Module<'_>> {
} }
} }
pub(crate) fn search_paths(db: &dyn Db) -> SearchPathIterator { pub(crate) fn search_paths(db: &dyn Db) -> SearchPathIterator<'_> {
Program::get(db).search_paths(db).iter(db) Program::get(db).search_paths(db).iter(db)
} }

View file

@ -301,7 +301,7 @@ impl<'db> SemanticIndex<'db> {
&self.scopes[id] &self.scopes[id]
} }
pub(crate) fn scope_ids(&self) -> impl Iterator<Item = ScopeId> { pub(crate) fn scope_ids(&self) -> impl Iterator<Item = ScopeId<'db>> + '_ {
self.scope_ids_by_scope.iter().copied() self.scope_ids_by_scope.iter().copied()
} }
@ -371,18 +371,18 @@ impl<'db> SemanticIndex<'db> {
/// Returns an iterator over the descendent scopes of `scope`. /// Returns an iterator over the descendent scopes of `scope`.
#[allow(unused)] #[allow(unused)]
pub(crate) fn descendent_scopes(&self, scope: FileScopeId) -> DescendantsIter { pub(crate) fn descendent_scopes(&self, scope: FileScopeId) -> DescendantsIter<'_> {
DescendantsIter::new(self, scope) DescendantsIter::new(self, scope)
} }
/// Returns an iterator over the direct child scopes of `scope`. /// Returns an iterator over the direct child scopes of `scope`.
#[allow(unused)] #[allow(unused)]
pub(crate) fn child_scopes(&self, scope: FileScopeId) -> ChildrenIter { pub(crate) fn child_scopes(&self, scope: FileScopeId) -> ChildrenIter<'_> {
ChildrenIter::new(self, scope) ChildrenIter::new(self, scope)
} }
/// Returns an iterator over all ancestors of `scope`, starting with `scope` itself. /// Returns an iterator over all ancestors of `scope`, starting with `scope` itself.
pub(crate) fn ancestor_scopes(&self, scope: FileScopeId) -> AncestorsIter { pub(crate) fn ancestor_scopes(&self, scope: FileScopeId) -> AncestorsIter<'_> {
AncestorsIter::new(self, scope) AncestorsIter::new(self, scope)
} }
@ -400,7 +400,7 @@ impl<'db> SemanticIndex<'db> {
/// print(x) # Refers to global x=1, not class x=2 /// print(x) # Refers to global x=1, not class x=2
/// ``` /// ```
/// The `method` function can see the global scope but not the class scope. /// The `method` function can see the global scope but not the class scope.
pub(crate) fn visible_ancestor_scopes(&self, scope: FileScopeId) -> VisibleAncestorsIter { pub(crate) fn visible_ancestor_scopes(&self, scope: FileScopeId) -> VisibleAncestorsIter<'_> {
VisibleAncestorsIter::new(self, scope) VisibleAncestorsIter::new(self, scope)
} }

View file

@ -243,7 +243,7 @@ impl MemberExpr {
self.segments.len() self.segments.len()
} }
pub(crate) fn as_ref(&self) -> MemberExprRef { pub(crate) fn as_ref(&self) -> MemberExprRef<'_> {
MemberExprRef { MemberExprRef {
path: self.path.as_str(), path: self.path.as_str(),
segments: SegmentsRef::from(&self.segments), segments: SegmentsRef::from(&self.segments),
@ -381,7 +381,7 @@ impl MemberTable {
} }
/// Returns an iterator over all members in the table. /// Returns an iterator over all members in the table.
pub(crate) fn iter(&self) -> std::slice::Iter<Member> { pub(crate) fn iter(&self) -> std::slice::Iter<'_, Member> {
self.members.iter() self.members.iter()
} }

View file

@ -162,12 +162,12 @@ impl PlaceTable {
} }
/// Iterator over all symbols in this scope. /// Iterator over all symbols in this scope.
pub(crate) fn symbols(&self) -> std::slice::Iter<Symbol> { pub(crate) fn symbols(&self) -> std::slice::Iter<'_, Symbol> {
self.symbols.iter() self.symbols.iter()
} }
/// Iterator over all members in this scope. /// Iterator over all members in this scope.
pub(crate) fn members(&self) -> std::slice::Iter<Member> { pub(crate) fn members(&self) -> std::slice::Iter<'_, Member> {
self.members.iter() self.members.iter()
} }
@ -220,7 +220,7 @@ impl PlaceTable {
/// ## Panics /// ## Panics
/// If the place ID is not found in the table. /// If the place ID is not found in the table.
#[track_caller] #[track_caller]
pub(crate) fn place(&self, place_id: impl Into<ScopedPlaceId>) -> PlaceExprRef { pub(crate) fn place(&self, place_id: impl Into<ScopedPlaceId>) -> PlaceExprRef<'_> {
match place_id.into() { match place_id.into() {
ScopedPlaceId::Symbol(symbol) => self.symbol(symbol).into(), ScopedPlaceId::Symbol(symbol) => self.symbol(symbol).into(),
ScopedPlaceId::Member(member) => self.member(member).into(), ScopedPlaceId::Member(member) => self.member(member).into(),
@ -275,7 +275,7 @@ impl PlaceTableBuilder {
} }
#[track_caller] #[track_caller]
pub(crate) fn place(&self, place_id: impl Into<ScopedPlaceId>) -> PlaceExprRef { pub(crate) fn place(&self, place_id: impl Into<ScopedPlaceId>) -> PlaceExprRef<'_> {
match place_id.into() { match place_id.into() {
ScopedPlaceId::Symbol(id) => PlaceExprRef::Symbol(self.symbols.symbol(id)), ScopedPlaceId::Symbol(id) => PlaceExprRef::Symbol(self.symbols.symbol(id)),
ScopedPlaceId::Member(id) => PlaceExprRef::Member(self.member.member(id)), ScopedPlaceId::Member(id) => PlaceExprRef::Member(self.member.member(id)),
@ -289,7 +289,7 @@ impl PlaceTableBuilder {
} }
} }
pub(crate) fn iter(&self) -> impl Iterator<Item = PlaceExprRef> { pub(crate) fn iter(&self) -> impl Iterator<Item = PlaceExprRef<'_>> {
self.symbols self.symbols
.iter() .iter()
.map(Into::into) .map(Into::into)

View file

@ -153,7 +153,7 @@ impl SymbolTable {
} }
/// Iterate over the symbols in this symbol table. /// Iterate over the symbols in this symbol table.
pub(crate) fn iter(&self) -> std::slice::Iter<Symbol> { pub(crate) fn iter(&self) -> std::slice::Iter<'_, Symbol> {
self.symbols.iter() self.symbols.iter()
} }

View file

@ -36,7 +36,7 @@ impl<'db> SemanticModel<'db> {
line_index(self.db, self.file) line_index(self.db, self.file)
} }
pub fn resolve_module(&self, module_name: &ModuleName) -> Option<Module> { pub fn resolve_module(&self, module_name: &ModuleName) -> Option<Module<'_>> {
resolve_module(self.db, module_name) resolve_module(self.db, module_name)
} }

View file

@ -402,7 +402,7 @@ impl Suppressions {
}) })
} }
fn iter(&self) -> SuppressionsIter { fn iter(&self) -> SuppressionsIter<'_> {
self.file.iter().chain(&self.line) self.file.iter().chain(&self.line)
} }
} }

View file

@ -2507,7 +2507,7 @@ impl<'db> Type<'db> {
/// This function is roughly equivalent to `find_name_in_mro` as defined in the [descriptor guide] or /// This function is roughly equivalent to `find_name_in_mro` as defined in the [descriptor guide] or
/// [`_PyType_Lookup`] in CPython's `Objects/typeobject.c`. It should typically be called through /// [`_PyType_Lookup`] in CPython's `Objects/typeobject.c`. It should typically be called through
/// [Type::class_member], unless it is known that `self` is a class-like type. This function returns /// [`Type::class_member`], unless it is known that `self` is a class-like type. This function returns
/// `None` if called on an instance-like type. /// `None` if called on an instance-like type.
/// ///
/// [descriptor guide]: https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance /// [descriptor guide]: https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
@ -5009,7 +5009,7 @@ impl<'db> Type<'db> {
} }
} }
/// Given a class literal or non-dynamic SubclassOf type, try calling it (creating an instance) /// Given a class literal or non-dynamic `SubclassOf` type, try calling it (creating an instance)
/// and return the resulting instance type. /// and return the resulting instance type.
/// ///
/// Models `type.__call__` behavior. /// Models `type.__call__` behavior.
@ -6328,7 +6328,7 @@ impl<'db> KnownInstanceType<'db> {
/// For example, an alias created using the `type` statement is an instance of /// For example, an alias created using the `type` statement is an instance of
/// `typing.TypeAliasType`, so `KnownInstanceType::TypeAliasType(_).instance_fallback(db)` /// `typing.TypeAliasType`, so `KnownInstanceType::TypeAliasType(_).instance_fallback(db)`
/// returns `Type::NominalInstance(NominalInstanceType { class: <typing.TypeAliasType> })`. /// returns `Type::NominalInstance(NominalInstanceType { class: <typing.TypeAliasType> })`.
fn instance_fallback(self, db: &dyn Db) -> Type { fn instance_fallback(self, db: &dyn Db) -> Type<'_> {
self.class().to_instance(db) self.class().to_instance(db)
} }
@ -7908,7 +7908,7 @@ impl Truthiness {
} }
} }
fn into_type(self, db: &dyn Db) -> Type { fn into_type(self, db: &dyn Db) -> Type<'_> {
match self { match self {
Self::AlwaysTrue => Type::BooleanLiteral(true), Self::AlwaysTrue => Type::BooleanLiteral(true),
Self::AlwaysFalse => Type::BooleanLiteral(false), Self::AlwaysFalse => Type::BooleanLiteral(false),
@ -8606,7 +8606,7 @@ impl<'db> UnionType<'db> {
Self::from_elements(db, self.elements(db).iter().filter(filter_fn)) Self::from_elements(db, self.elements(db).iter().filter(filter_fn))
} }
pub fn iter(&self, db: &'db dyn Db) -> Iter<Type<'db>> { pub fn iter(&self, db: &'db dyn Db) -> Iter<'_, Type<'db>> {
self.elements(db).iter() self.elements(db).iter()
} }

View file

@ -97,7 +97,7 @@ impl<'a, 'db> CallArguments<'a, 'db> {
/// Prepend an optional extra synthetic argument (for a `self` or `cls` parameter) to the front /// Prepend an optional extra synthetic argument (for a `self` or `cls` parameter) to the front
/// of this argument list. (If `bound_self` is none, we return the argument list /// of this argument list. (If `bound_self` is none, we return the argument list
/// unmodified.) /// unmodified.)
pub(crate) fn with_self(&self, bound_self: Option<Type<'db>>) -> Cow<Self> { pub(crate) fn with_self(&self, bound_self: Option<Type<'db>>) -> Cow<'_, Self> {
if bound_self.is_some() { if bound_self.is_some() {
let arguments = std::iter::once(Argument::Synthetic) let arguments = std::iter::once(Argument::Synthetic)
.chain(self.arguments.iter().copied()) .chain(self.arguments.iter().copied())

View file

@ -591,7 +591,7 @@ impl<'db> ClassType<'db> {
} }
/// Returns the inferred type of the class member named `name`. Only bound members /// Returns the inferred type of the class member named `name`. Only bound members
/// or those marked as ClassVars are considered. /// or those marked as `ClassVars` are considered.
/// ///
/// You must provide the `inherited_generic_context` that we should use for the `__new__` or /// You must provide the `inherited_generic_context` that we should use for the `__new__` or
/// `__init__` member. This is inherited from the containing class -­but importantly, from the /// `__init__` member. This is inherited from the containing class -­but importantly, from the
@ -1146,7 +1146,8 @@ pub struct ClassLiteral<'db> {
// The Salsa heap is tracked separately. // The Salsa heap is tracked separately.
impl get_size2::GetSize for ClassLiteral<'_> {} impl get_size2::GetSize for ClassLiteral<'_> {}
#[expect(clippy::trivially_copy_pass_by_ref, clippy::ref_option)] #[expect(clippy::ref_option)]
#[allow(clippy::trivially_copy_pass_by_ref)]
fn pep695_generic_context_cycle_recover<'db>( fn pep695_generic_context_cycle_recover<'db>(
_db: &'db dyn Db, _db: &'db dyn Db,
_value: &Option<GenericContext<'db>>, _value: &Option<GenericContext<'db>>,
@ -1778,7 +1779,7 @@ impl<'db> ClassLiteral<'db> {
} }
/// Returns the inferred type of the class member named `name`. Only bound members /// Returns the inferred type of the class member named `name`. Only bound members
/// or those marked as ClassVars are considered. /// or those marked as `ClassVars` are considered.
/// ///
/// Returns [`Place::Unbound`] if `name` cannot be found in this class's scope /// Returns [`Place::Unbound`] if `name` cannot be found in this class's scope
/// directly. Use [`ClassLiteral::class_member`] if you require a method that will /// directly. Use [`ClassLiteral::class_member`] if you require a method that will
@ -3614,7 +3615,7 @@ impl KnownClass {
/// representing all possible instances of the class. /// representing all possible instances of the class.
/// ///
/// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this. /// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this.
pub(crate) fn to_instance(self, db: &dyn Db) -> Type { pub(crate) fn to_instance(self, db: &dyn Db) -> Type<'_> {
self.to_class_literal(db) self.to_class_literal(db)
.to_class_type(db) .to_class_type(db)
.map(|class| Type::instance(db, class)) .map(|class| Type::instance(db, class))
@ -3676,7 +3677,7 @@ impl KnownClass {
fn try_to_class_literal_without_logging( fn try_to_class_literal_without_logging(
self, self,
db: &dyn Db, db: &dyn Db,
) -> Result<ClassLiteral, KnownClassLookupError> { ) -> Result<ClassLiteral<'_>, KnownClassLookupError<'_>> {
let symbol = known_module_symbol(db, self.canonical_module(db), self.name(db)).place; let symbol = known_module_symbol(db, self.canonical_module(db), self.name(db)).place;
match symbol { match symbol {
Place::Type(Type::ClassLiteral(class_literal), Boundness::Bound) => Ok(class_literal), Place::Type(Type::ClassLiteral(class_literal), Boundness::Bound) => Ok(class_literal),
@ -3693,7 +3694,7 @@ impl KnownClass {
/// Lookup a [`KnownClass`] in typeshed and return a [`Type`] representing that class-literal. /// Lookup a [`KnownClass`] in typeshed and return a [`Type`] representing that class-literal.
/// ///
/// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this. /// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this.
pub(crate) fn try_to_class_literal(self, db: &dyn Db) -> Option<ClassLiteral> { pub(crate) fn try_to_class_literal(self, db: &dyn Db) -> Option<ClassLiteral<'_>> {
// a cache of the `KnownClass`es that we have already failed to lookup in typeshed // a cache of the `KnownClass`es that we have already failed to lookup in typeshed
// (and therefore that we've already logged a warning for) // (and therefore that we've already logged a warning for)
static MESSAGES: LazyLock<Mutex<FxHashSet<KnownClass>>> = LazyLock::new(Mutex::default); static MESSAGES: LazyLock<Mutex<FxHashSet<KnownClass>>> = LazyLock::new(Mutex::default);
@ -3728,7 +3729,7 @@ impl KnownClass {
/// Lookup a [`KnownClass`] in typeshed and return a [`Type`] representing that class-literal. /// Lookup a [`KnownClass`] in typeshed and return a [`Type`] representing that class-literal.
/// ///
/// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this. /// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this.
pub(crate) fn to_class_literal(self, db: &dyn Db) -> Type { pub(crate) fn to_class_literal(self, db: &dyn Db) -> Type<'_> {
self.try_to_class_literal(db) self.try_to_class_literal(db)
.map(Type::ClassLiteral) .map(Type::ClassLiteral)
.unwrap_or_else(Type::unknown) .unwrap_or_else(Type::unknown)
@ -3738,7 +3739,7 @@ impl KnownClass {
/// representing that class and all possible subclasses of the class. /// representing that class and all possible subclasses of the class.
/// ///
/// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this. /// If the class cannot be found in typeshed, a debug-level log message will be emitted stating this.
pub(crate) fn to_subclass_of(self, db: &dyn Db) -> Type { pub(crate) fn to_subclass_of(self, db: &dyn Db) -> Type<'_> {
self.to_class_literal(db) self.to_class_literal(db)
.to_class_type(db) .to_class_type(db)
.map(|class| SubclassOfType::from(db, class)) .map(|class| SubclassOfType::from(db, class))

View file

@ -678,7 +678,7 @@ declare_lint! {
/// Checks for exception handlers that catch non-exception classes. /// Checks for exception handlers that catch non-exception classes.
/// ///
/// ## Why is this bad? /// ## Why is this bad?
/// Catching classes that do not inherit from `BaseException` will raise a TypeError at runtime. /// Catching classes that do not inherit from `BaseException` will raise a `TypeError` at runtime.
/// ///
/// ## Example /// ## Example
/// ```python /// ```python

View file

@ -20,7 +20,7 @@ use crate::types::{
use crate::{Db, FxOrderSet}; use crate::{Db, FxOrderSet};
impl<'db> Type<'db> { impl<'db> Type<'db> {
pub fn display(&self, db: &'db dyn Db) -> DisplayType { pub fn display(&self, db: &'db dyn Db) -> DisplayType<'_> {
DisplayType { ty: self, db } DisplayType { ty: self, db }
} }
fn representation(self, db: &'db dyn Db) -> DisplayRepresentation<'db> { fn representation(self, db: &'db dyn Db) -> DisplayRepresentation<'db> {
@ -980,23 +980,23 @@ impl Display for DisplayMaybeParenthesizedType<'_> {
} }
pub(crate) trait TypeArrayDisplay<'db> { pub(crate) trait TypeArrayDisplay<'db> {
fn display(&self, db: &'db dyn Db) -> DisplayTypeArray; fn display(&self, db: &'db dyn Db) -> DisplayTypeArray<'_, 'db>;
} }
impl<'db> TypeArrayDisplay<'db> for Box<[Type<'db>]> { impl<'db> TypeArrayDisplay<'db> for Box<[Type<'db>]> {
fn display(&self, db: &'db dyn Db) -> DisplayTypeArray { fn display(&self, db: &'db dyn Db) -> DisplayTypeArray<'_, 'db> {
DisplayTypeArray { types: self, db } DisplayTypeArray { types: self, db }
} }
} }
impl<'db> TypeArrayDisplay<'db> for Vec<Type<'db>> { impl<'db> TypeArrayDisplay<'db> for Vec<Type<'db>> {
fn display(&self, db: &'db dyn Db) -> DisplayTypeArray { fn display(&self, db: &'db dyn Db) -> DisplayTypeArray<'_, 'db> {
DisplayTypeArray { types: self, db } DisplayTypeArray { types: self, db }
} }
} }
impl<'db> TypeArrayDisplay<'db> for [Type<'db>] { impl<'db> TypeArrayDisplay<'db> for [Type<'db>] {
fn display(&self, db: &'db dyn Db) -> DisplayTypeArray { fn display(&self, db: &'db dyn Db) -> DisplayTypeArray<'_, 'db> {
DisplayTypeArray { types: self, db } DisplayTypeArray { types: self, db }
} }
} }

View file

@ -9631,7 +9631,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
&self, &self,
expression: &ast::Expr, expression: &ast::Expr,
message: std::fmt::Arguments, message: std::fmt::Arguments,
) -> Option<LintDiagnosticGuard> { ) -> Option<LintDiagnosticGuard<'_, '_>> {
self.context self.context
.report_lint(&INVALID_TYPE_FORM, expression) .report_lint(&INVALID_TYPE_FORM, expression)
.map(|builder| { .map(|builder| {
@ -11231,7 +11231,7 @@ impl StringPartsCollector {
self.expression = true; self.expression = true;
} }
fn string_type(self, db: &dyn Db) -> Type { fn string_type(self, db: &dyn Db) -> Type<'_> {
if self.expression { if self.expression {
KnownClass::Str.to_instance(db) KnownClass::Str.to_instance(db)
} else if let Some(concatenated) = self.concatenated { } else if let Some(concatenated) = self.concatenated {

View file

@ -1183,7 +1183,7 @@ impl<'db> Parameters<'db> {
self.value.len() self.value.len()
} }
pub(crate) fn iter(&self) -> std::slice::Iter<Parameter<'db>> { pub(crate) fn iter(&self) -> std::slice::Iter<'_, Parameter<'db>> {
self.value.iter() self.value.iter()
} }

View file

@ -171,7 +171,7 @@ impl SpecialFormType {
/// For example, the symbol `typing.Literal` is an instance of `typing._SpecialForm`, /// For example, the symbol `typing.Literal` is an instance of `typing._SpecialForm`,
/// so `SpecialFormType::Literal.instance_fallback(db)` /// so `SpecialFormType::Literal.instance_fallback(db)`
/// returns `Type::NominalInstance(NominalInstanceType { class: <typing._SpecialForm> })`. /// returns `Type::NominalInstance(NominalInstanceType { class: <typing._SpecialForm> })`.
pub(super) fn instance_fallback(self, db: &dyn Db) -> Type { pub(super) fn instance_fallback(self, db: &dyn Db) -> Type<'_> {
self.class().to_instance(db) self.class().to_instance(db)
} }
@ -244,7 +244,7 @@ impl SpecialFormType {
} }
} }
pub(super) fn to_meta_type(self, db: &dyn Db) -> Type { pub(super) fn to_meta_type(self, db: &dyn Db) -> Type<'_> {
self.class().to_class_literal(db) self.class().to_class_literal(db)
} }

View file

@ -22,7 +22,7 @@ impl RequestHandler for CompletionRequestHandler {
} }
impl BackgroundDocumentRequestHandler for CompletionRequestHandler { impl BackgroundDocumentRequestHandler for CompletionRequestHandler {
fn document_url(params: &CompletionParams) -> Cow<Url> { fn document_url(params: &CompletionParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position.text_document.uri) Cow::Borrowed(&params.text_document_position.text_document.uri)
} }

View file

@ -23,7 +23,7 @@ impl RequestHandler for DocumentDiagnosticRequestHandler {
} }
impl BackgroundDocumentRequestHandler for DocumentDiagnosticRequestHandler { impl BackgroundDocumentRequestHandler for DocumentDiagnosticRequestHandler {
fn document_url(params: &DocumentDiagnosticParams) -> Cow<Url> { fn document_url(params: &DocumentDiagnosticParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document.uri) Cow::Borrowed(&params.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for DocumentHighlightRequestHandler {
} }
impl BackgroundDocumentRequestHandler for DocumentHighlightRequestHandler { impl BackgroundDocumentRequestHandler for DocumentHighlightRequestHandler {
fn document_url(params: &DocumentHighlightParams) -> Cow<Url> { fn document_url(params: &DocumentHighlightParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position_params.text_document.uri) Cow::Borrowed(&params.text_document_position_params.text_document.uri)
} }

View file

@ -22,7 +22,7 @@ impl RequestHandler for DocumentSymbolRequestHandler {
} }
impl BackgroundDocumentRequestHandler for DocumentSymbolRequestHandler { impl BackgroundDocumentRequestHandler for DocumentSymbolRequestHandler {
fn document_url(params: &DocumentSymbolParams) -> Cow<Url> { fn document_url(params: &DocumentSymbolParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document.uri) Cow::Borrowed(&params.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for GotoDeclarationRequestHandler {
} }
impl BackgroundDocumentRequestHandler for GotoDeclarationRequestHandler { impl BackgroundDocumentRequestHandler for GotoDeclarationRequestHandler {
fn document_url(params: &GotoDeclarationParams) -> Cow<Url> { fn document_url(params: &GotoDeclarationParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position_params.text_document.uri) Cow::Borrowed(&params.text_document_position_params.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for GotoDefinitionRequestHandler {
} }
impl BackgroundDocumentRequestHandler for GotoDefinitionRequestHandler { impl BackgroundDocumentRequestHandler for GotoDefinitionRequestHandler {
fn document_url(params: &GotoDefinitionParams) -> Cow<Url> { fn document_url(params: &GotoDefinitionParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position_params.text_document.uri) Cow::Borrowed(&params.text_document_position_params.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for ReferencesRequestHandler {
} }
impl BackgroundDocumentRequestHandler for ReferencesRequestHandler { impl BackgroundDocumentRequestHandler for ReferencesRequestHandler {
fn document_url(params: &ReferenceParams) -> Cow<Url> { fn document_url(params: &ReferenceParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position.text_document.uri) Cow::Borrowed(&params.text_document_position.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for GotoTypeDefinitionRequestHandler {
} }
impl BackgroundDocumentRequestHandler for GotoTypeDefinitionRequestHandler { impl BackgroundDocumentRequestHandler for GotoTypeDefinitionRequestHandler {
fn document_url(params: &GotoTypeDefinitionParams) -> Cow<Url> { fn document_url(params: &GotoTypeDefinitionParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position_params.text_document.uri) Cow::Borrowed(&params.text_document_position_params.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for HoverRequestHandler {
} }
impl BackgroundDocumentRequestHandler for HoverRequestHandler { impl BackgroundDocumentRequestHandler for HoverRequestHandler {
fn document_url(params: &HoverParams) -> Cow<Url> { fn document_url(params: &HoverParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position_params.text_document.uri) Cow::Borrowed(&params.text_document_position_params.text_document.uri)
} }

View file

@ -19,7 +19,7 @@ impl RequestHandler for InlayHintRequestHandler {
} }
impl BackgroundDocumentRequestHandler for InlayHintRequestHandler { impl BackgroundDocumentRequestHandler for InlayHintRequestHandler {
fn document_url(params: &InlayHintParams) -> Cow<Url> { fn document_url(params: &InlayHintParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document.uri) Cow::Borrowed(&params.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for PrepareRenameRequestHandler {
} }
impl BackgroundDocumentRequestHandler for PrepareRenameRequestHandler { impl BackgroundDocumentRequestHandler for PrepareRenameRequestHandler {
fn document_url(params: &TextDocumentPositionParams) -> Cow<Url> { fn document_url(params: &TextDocumentPositionParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document.uri) Cow::Borrowed(&params.text_document.uri)
} }

View file

@ -21,7 +21,7 @@ impl RequestHandler for RenameRequestHandler {
} }
impl BackgroundDocumentRequestHandler for RenameRequestHandler { impl BackgroundDocumentRequestHandler for RenameRequestHandler {
fn document_url(params: &RenameParams) -> Cow<Url> { fn document_url(params: &RenameParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position.text_document.uri) Cow::Borrowed(&params.text_document_position.text_document.uri)
} }

View file

@ -20,7 +20,7 @@ impl RequestHandler for SelectionRangeRequestHandler {
} }
impl BackgroundDocumentRequestHandler for SelectionRangeRequestHandler { impl BackgroundDocumentRequestHandler for SelectionRangeRequestHandler {
fn document_url(params: &SelectionRangeParams) -> Cow<Url> { fn document_url(params: &SelectionRangeParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document.uri) Cow::Borrowed(&params.text_document.uri)
} }

View file

@ -16,7 +16,7 @@ impl RequestHandler for SemanticTokensRequestHandler {
} }
impl BackgroundDocumentRequestHandler for SemanticTokensRequestHandler { impl BackgroundDocumentRequestHandler for SemanticTokensRequestHandler {
fn document_url(params: &SemanticTokensParams) -> Cow<Url> { fn document_url(params: &SemanticTokensParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document.uri) Cow::Borrowed(&params.text_document.uri)
} }

View file

@ -18,7 +18,7 @@ impl RequestHandler for SemanticTokensRangeRequestHandler {
} }
impl BackgroundDocumentRequestHandler for SemanticTokensRangeRequestHandler { impl BackgroundDocumentRequestHandler for SemanticTokensRangeRequestHandler {
fn document_url(params: &SemanticTokensRangeParams) -> Cow<Url> { fn document_url(params: &SemanticTokensRangeParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document.uri) Cow::Borrowed(&params.text_document.uri)
} }

View file

@ -22,7 +22,7 @@ impl RequestHandler for SignatureHelpRequestHandler {
} }
impl BackgroundDocumentRequestHandler for SignatureHelpRequestHandler { impl BackgroundDocumentRequestHandler for SignatureHelpRequestHandler {
fn document_url(params: &SignatureHelpParams) -> Cow<Url> { fn document_url(params: &SignatureHelpParams) -> Cow<'_, Url> {
Cow::Borrowed(&params.text_document_position_params.text_document.uri) Cow::Borrowed(&params.text_document_position_params.text_document.uri)
} }

View file

@ -89,7 +89,7 @@ pub(super) trait BackgroundDocumentRequestHandler: RetriableRequestHandler {
/// Returns the URL of the document that this request handler operates on. /// Returns the URL of the document that this request handler operates on.
fn document_url( fn document_url(
params: &<<Self as RequestHandler>::RequestType as Request>::Params, params: &<<Self as RequestHandler>::RequestType as Request>::Params,
) -> Cow<Url>; ) -> Cow<'_, Url>;
/// Processes the request parameters and returns the LSP request result. /// Processes the request parameters and returns the LSP request result.
/// ///
@ -184,7 +184,7 @@ pub(super) trait BackgroundDocumentNotificationHandler: NotificationHandler {
/// Returns the URL of the document that this notification handler operates on. /// Returns the URL of the document that this notification handler operates on.
fn document_url( fn document_url(
params: &<<Self as NotificationHandler>::NotificationType as Notification>::Params, params: &<<Self as NotificationHandler>::NotificationType as Notification>::Params,
) -> Cow<Url>; ) -> Cow<'_, Url>;
fn run_with_snapshot( fn run_with_snapshot(
snapshot: DocumentSnapshot, snapshot: DocumentSnapshot,

View file

@ -821,7 +821,7 @@ impl Session {
/// This method drops all references to the index and returns a guard that will restore the /// This method drops all references to the index and returns a guard that will restore the
/// references when dropped. This guard holds the only reference to the index and allows /// references when dropped. This guard holds the only reference to the index and allows
/// modifying it. /// modifying it.
fn index_mut(&mut self) -> MutIndexGuard { fn index_mut(&mut self) -> MutIndexGuard<'_> {
let index = self.index.take().unwrap(); let index = self.index.take().unwrap();
for db in self.projects_mut() { for db in self.projects_mut() {

View file

@ -27,7 +27,7 @@ impl EnvVars {
/// Accepted values: /// Accepted values:
/// ///
/// * `short` - Display short memory report /// * `short` - Display short memory report
/// * `mypy_primer` - Display mypy_primer format and suppress workspace diagnostics /// * `mypy_primer` - Display `mypy_primer` format and suppress workspace diagnostics
/// * `full` - Display full memory report /// * `full` - Display full memory report
#[attr_hidden] #[attr_hidden]
pub const TY_MEMORY_REPORT: &'static str = "TY_MEMORY_REPORT"; pub const TY_MEMORY_REPORT: &'static str = "TY_MEMORY_REPORT";

View file

@ -514,7 +514,7 @@ mod tests {
InlineFileAssertions::from_file(&db, file) InlineFileAssertions::from_file(&db, file)
} }
fn as_vec(assertions: &InlineFileAssertions) -> Vec<LineAssertions> { fn as_vec(assertions: &InlineFileAssertions) -> Vec<LineAssertions<'_>> {
assertions.into_iter().collect() assertions.into_iter().collect()
} }

View file

@ -1,2 +1,2 @@
[toolchain] [toolchain]
channel = "1.88" channel = "1.89"

Some files were not shown because too many files have changed in this diff Show more