Switch to Rust 2024 edition (#18129)

This commit is contained in:
Micha Reiser 2025-05-16 13:25:28 +02:00 committed by GitHub
parent e67b35743a
commit 9ae698fe30
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
1082 changed files with 4211 additions and 3300 deletions

View file

@ -17,7 +17,7 @@ impl<'fmt, Context> Argument<'fmt, Context> {
/// Called by the [ruff_formatter::format_args] macro.
#[doc(hidden)]
#[inline]
pub fn new<F: Format<Context>>(value: &'fmt F) -> Self {
pub const fn new<F: Format<Context>>(value: &'fmt F) -> Self {
Self { value }
}
@ -55,7 +55,7 @@ pub struct Arguments<'fmt, Context>(pub &'fmt [Argument<'fmt, Context>]);
impl<'fmt, Context> Arguments<'fmt, Context> {
#[doc(hidden)]
#[inline]
pub fn new(arguments: &'fmt [Argument<'fmt, Context>]) -> Self {
pub const fn new(arguments: &'fmt [Argument<'fmt, Context>]) -> Self {
Self(arguments)
}
@ -98,7 +98,7 @@ impl<'fmt, Context> From<&'fmt Argument<'fmt, Context>> for Arguments<'fmt, Cont
mod tests {
use crate::format_element::tag::Tag;
use crate::prelude::*;
use crate::{format_args, write, FormatState, VecBuffer};
use crate::{FormatState, VecBuffer, format_args, write};
#[test]
fn test_nesting() {

View file

@ -1,4 +1,4 @@
use super::{write, Arguments, FormatElement};
use super::{Arguments, FormatElement, write};
use crate::format_element::Interned;
use crate::prelude::{LineMode, Tag};
use crate::{FormatResult, FormatState};

View file

@ -2,14 +2,14 @@ use std::cell::Cell;
use std::marker::PhantomData;
use std::num::NonZeroU8;
use ruff_text_size::TextRange;
#[allow(clippy::enum_glob_use)]
use Tag::*;
use ruff_text_size::TextRange;
use crate::format_element::tag::{Condition, Tag};
use crate::prelude::tag::{DedentMode, GroupMode, LabelId};
use crate::prelude::*;
use crate::{write, Argument, Arguments, FormatContext, FormatOptions, GroupId, TextSize};
use crate::{Argument, Arguments, FormatContext, FormatOptions, GroupId, TextSize, write};
use crate::{Buffer, VecBuffer};
/// A line break that only gets printed if the enclosing `Group` doesn't fit on a single line.
@ -402,7 +402,10 @@ where
}
fn debug_assert_no_newlines(text: &str) {
debug_assert!(!text.contains('\r'), "The content '{text}' contains an unsupported '\\r' line terminator character but text must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings.");
debug_assert!(
!text.contains('\r'),
"The content '{text}' contains an unsupported '\\r' line terminator character but text must only use line feeds '\\n' as line separator. Use '\\n' instead of '\\r' and '\\r\\n' to insert a line break in strings."
);
}
/// Pushes some content to the end of the current line.
@ -2564,7 +2567,7 @@ impl<'a, Context> BestFitting<'a, Context> {
/// # Panics
///
/// When the slice contains less than two variants.
pub fn from_arguments_unchecked(variants: Arguments<'a, Context>) -> Self {
pub const fn from_arguments_unchecked(variants: Arguments<'a, Context>) -> Self {
assert!(
variants.0.len() >= 2,
"Requires at least the least expanded and most expanded variants"
@ -2572,7 +2575,7 @@ impl<'a, Context> BestFitting<'a, Context> {
Self {
variants,
mode: BestFittingMode::default(),
mode: BestFittingMode::FirstLine,
}
}

View file

@ -1,5 +1,5 @@
use crate::prelude::TagKind;
use crate::GroupId;
use crate::prelude::TagKind;
use ruff_text_size::TextRange;
use std::error::Error;
@ -29,16 +29,22 @@ pub enum FormatError {
impl std::fmt::Display for FormatError {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FormatError::SyntaxError {message} => {
FormatError::SyntaxError { message } => {
std::write!(fmt, "syntax error: {message}")
},
}
FormatError::RangeError { input, tree } => std::write!(
fmt,
"formatting range {input:?} is larger than syntax tree {tree:?}"
),
FormatError::InvalidDocument(error) => std::write!(fmt, "Invalid document: {error}\n\n This is an internal Rome error. Please report if necessary."),
FormatError::InvalidDocument(error) => std::write!(
fmt,
"Invalid document: {error}\n\n This is an internal Rome error. Please report if necessary."
),
FormatError::PoorLayout => {
std::write!(fmt, "Poor layout: The formatter wasn't able to pick a good layout for your document. This is an internal Rome error. Please report if necessary.")
std::write!(
fmt,
"Poor layout: The formatter wasn't able to pick a good layout for your document. This is an internal Rome error. Please report if necessary."
)
}
}
}
@ -139,24 +145,37 @@ impl std::fmt::Display for InvalidDocumentError {
InvalidDocumentError::ExpectedStart {
expected_start,
actual,
} => {
match actual {
ActualStart::EndOfDocument => {
std::write!(f, "Expected start tag of kind {expected_start:?} but at the end of document.")
}
ActualStart::Start(start) => {
std::write!(f, "Expected start tag of kind {expected_start:?} but found start tag of kind {start:?}.")
}
ActualStart::End(end) => {
std::write!(f, "Expected start tag of kind {expected_start:?} but found end tag of kind {end:?}.")
}
ActualStart::Content => {
std::write!(f, "Expected start tag of kind {expected_start:?} but found non-tag element.")
}
} => match actual {
ActualStart::EndOfDocument => {
std::write!(
f,
"Expected start tag of kind {expected_start:?} but at the end of document."
)
}
}
ActualStart::Start(start) => {
std::write!(
f,
"Expected start tag of kind {expected_start:?} but found start tag of kind {start:?}."
)
}
ActualStart::End(end) => {
std::write!(
f,
"Expected start tag of kind {expected_start:?} but found end tag of kind {end:?}."
)
}
ActualStart::Content => {
std::write!(
f,
"Expected start tag of kind {expected_start:?} but found non-tag element."
)
}
},
InvalidDocumentError::UnknownGroupId { group_id } => {
std::write!(f, "Encountered unknown group id {group_id:?}. Ensure that the group with the id {group_id:?} exists and that the group is a parent of or comes before the element referring to it.")
std::write!(
f,
"Encountered unknown group id {group_id:?}. Ensure that the group with the id {group_id:?} exists and that the group is a parent of or comes before the element referring to it."
)
}
}
}

View file

@ -543,7 +543,7 @@ impl TextWidth {
#[cfg(test)]
mod tests {
use crate::format_element::{normalize_newlines, LINE_TERMINATORS};
use crate::format_element::{LINE_TERMINATORS, normalize_newlines};
#[test]
fn test_normalize_newlines() {

View file

@ -8,8 +8,8 @@ use crate::prelude::tag::GroupMode;
use crate::prelude::*;
use crate::source_code::SourceCode;
use crate::{
format, write, BufferExtensions, Format, FormatContext, FormatElement, FormatOptions,
FormatResult, Formatter, IndentStyle, IndentWidth, LineWidth, PrinterOptions,
BufferExtensions, Format, FormatContext, FormatElement, FormatOptions, FormatResult, Formatter,
IndentStyle, IndentWidth, LineWidth, PrinterOptions, format, write,
};
use super::tag::Tag;
@ -811,8 +811,8 @@ mod tests {
use ruff_text_size::{TextRange, TextSize};
use crate::prelude::*;
use crate::{format, format_args, write};
use crate::{SimpleFormatContext, SourceCode};
use crate::{format, format_args, write};
#[test]
fn display_elements() {

View file

@ -370,7 +370,10 @@ impl PartialEq for LabelId {
#[cfg(debug_assertions)]
{
if is_equal {
assert_eq!(self.name, other.name, "Two `LabelId`s with different names have the same `value`. Are you mixing labels of two different `LabelDefinition` or are the values returned by the `LabelDefinition` not unique?");
assert_eq!(
self.name, other.name,
"Two `LabelId`s with different names have the same `value`. Are you mixing labels of two different `LabelDefinition` or are the values returned by the `LabelDefinition` not unique?"
);
}
}

View file

@ -38,7 +38,7 @@ use crate::prelude::TagKind;
use std::fmt;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::num::{NonZeroU16, NonZeroU8, TryFromIntError};
use std::num::{NonZeroU8, NonZeroU16, TryFromIntError};
use crate::format_element::document::Document;
use crate::printer::{Printer, PrinterOptions};
@ -50,7 +50,7 @@ pub use builders::BestFitting;
pub use source_code::{SourceCode, SourceCodeSlice};
pub use crate::diagnostics::{ActualStart, FormatError, InvalidDocumentError, PrintError};
pub use format_element::{normalize_newlines, FormatElement, LINE_TERMINATORS};
pub use format_element::{FormatElement, LINE_TERMINATORS, normalize_newlines};
pub use group_id::GroupId;
use ruff_macros::CacheKey;
use ruff_text_size::{TextLen, TextRange, TextSize};

View file

@ -328,16 +328,16 @@ macro_rules! format {
/// [`MostExpanded`]: crate::format_element::BestFittingVariants::most_expanded
#[macro_export]
macro_rules! best_fitting {
($least_expanded:expr, $($tail:expr),+ $(,)?) => {{
($least_expanded:expr, $($tail:expr),+ $(,)?) => {
// OK because the macro syntax requires at least two variants.
$crate::BestFitting::from_arguments_unchecked($crate::format_args!($least_expanded, $($tail),+))
}}
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
use crate::{write, FormatState, SimpleFormatOptions, VecBuffer};
use crate::{FormatState, SimpleFormatOptions, VecBuffer, write};
struct TestFormat;
@ -386,7 +386,7 @@ mod tests {
#[test]
fn best_fitting_variants_print_as_lists() {
use crate::prelude::*;
use crate::{format, format_args, Formatted};
use crate::{Formatted, format, format_args};
// The second variant below should be selected when printing at a width of 30
let formatted_best_fitting = format!(
@ -398,34 +398,36 @@ mod tests {
format_args![token(
"Something that will not fit on a line with 30 character print width."
)],
format_args![group(&format_args![
token("Start"),
soft_line_break(),
group(&soft_block_indent(&format_args![
token("1,"),
soft_line_break_or_space(),
token("2,"),
soft_line_break_or_space(),
token("3"),
])),
soft_line_break_or_space(),
soft_block_indent(&format_args![
token("1,"),
soft_line_break_or_space(),
token("2,"),
soft_line_break_or_space(),
group(&format_args!(
token("A,"),
format_args![
group(&format_args![
token("Start"),
soft_line_break(),
group(&soft_block_indent(&format_args![
token("1,"),
soft_line_break_or_space(),
token("B")
)),
token("2,"),
soft_line_break_or_space(),
token("3"),
])),
soft_line_break_or_space(),
token("3")
]),
soft_line_break_or_space(),
token("End")
])
.should_expand(true)],
soft_block_indent(&format_args![
token("1,"),
soft_line_break_or_space(),
token("2,"),
soft_line_break_or_space(),
group(&format_args!(
token("A,"),
soft_line_break_or_space(),
token("B")
)),
soft_line_break_or_space(),
token("3")
]),
soft_line_break_or_space(),
token("End")
])
.should_expand(true)
],
format_args!(token("Most"), hard_line_break(), token("Expanded"))
]
]

View file

@ -7,6 +7,6 @@ pub use crate::formatter::Formatter;
pub use crate::printer::PrinterOptions;
pub use crate::{
best_fitting, dbg_write, format, format_args, write, Buffer as _, BufferExtensions, Format,
Format as _, FormatResult, FormatRule, FormatWithRule as _, SimpleFormatContext,
Buffer as _, BufferExtensions, Format, Format as _, FormatResult, FormatRule,
FormatWithRule as _, SimpleFormatContext, best_fitting, dbg_write, format, format_args, write,
};

View file

@ -1,5 +1,5 @@
use crate::format_element::tag::TagKind;
use crate::format_element::PrintMode;
use crate::format_element::tag::TagKind;
use crate::printer::stack::{Stack, StackedStack};
use crate::printer::{Indentation, MeasureMode};
use crate::{IndentStyle, InvalidDocumentError, PrintError, PrintResult};

View file

@ -1,5 +1,5 @@
use crate::printer::call_stack::PrintElementArgs;
use crate::FormatElement;
use crate::printer::call_stack::PrintElementArgs;
/// Stores the queued line suffixes.
#[derive(Debug, Default)]

View file

@ -10,7 +10,7 @@ use crate::format_element::document::Document;
use crate::format_element::tag::{Condition, GroupMode};
use crate::format_element::{BestFittingMode, BestFittingVariants, LineMode, PrintMode};
use crate::prelude::tag::{DedentMode, Tag, TagKind, VerbatimKind};
use crate::prelude::{tag, TextWidth};
use crate::prelude::{TextWidth, tag};
use crate::printer::call_stack::{
CallStack, FitsCallStack, PrintCallStack, PrintElementArgs, StackFrame,
};
@ -1199,7 +1199,7 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
text_width: *text_width,
},
args,
))
));
}
FormatElement::SourceCodeSlice { slice, text_width } => {
let text = slice.text(self.printer.source_code);
@ -1597,11 +1597,7 @@ enum Fits {
impl From<bool> for Fits {
fn from(value: bool) -> Self {
if value {
Fits::Yes
} else {
Fits::No
}
if value { Fits::Yes } else { Fits::No }
}
}
@ -1662,8 +1658,8 @@ mod tests {
use crate::printer::{LineEnding, Printer, PrinterOptions};
use crate::source_code::SourceCode;
use crate::{
format_args, write, Document, FormatState, IndentStyle, IndentWidth, LineWidth, Printed,
VecBuffer,
Document, FormatState, IndentStyle, IndentWidth, LineWidth, Printed, VecBuffer,
format_args, write,
};
fn format(root: &dyn Format<SimpleFormatContext>) -> Printed {
@ -1985,10 +1981,21 @@ two lines`,
token("]")
]),
token(";"),
line_suffix(&format_args![space(), token("// Using reserved width causes this content to not fit even though it's a line suffix element")], 93)
line_suffix(
&format_args![
space(),
token(
"// Using reserved width causes this content to not fit even though it's a line suffix element"
)
],
93
)
]);
assert_eq!(printed.as_code(), "[\n 1, 2, 3\n]; // Using reserved width causes this content to not fit even though it's a line suffix element");
assert_eq!(
printed.as_code(),
"[\n 1, 2, 3\n]; // Using reserved width causes this content to not fit even though it's a line suffix element"
);
}
#[test]
@ -2015,7 +2022,10 @@ two lines`,
let printed = format(&content);
assert_eq!(printed.as_code(), "The referenced group breaks.\nThis group breaks because:\nIt measures with the 'if_group_breaks' variant because the referenced group breaks and that's just way too much text.");
assert_eq!(
printed.as_code(),
"The referenced group breaks.\nThis group breaks because:\nIt measures with the 'if_group_breaks' variant because the referenced group breaks and that's just way too much text."
);
}
#[test]

View file

@ -325,10 +325,10 @@ impl FitsEndPredicate for SingleEntryPredicate {
#[cfg(test)]
mod tests {
use crate::FormatElement;
use crate::format_element::LineMode;
use crate::prelude::Tag;
use crate::printer::queue::{PrintQueue, Queue};
use crate::FormatElement;
#[test]
fn extend_back_pop_last() {

View file

@ -65,7 +65,10 @@ pub struct SourceCodeSlice {
impl SourceCodeSlice {
/// Returns the slice's text.
pub fn text<'a>(&self, code: SourceCode<'a>) -> &'a str {
assert!(usize::from(self.range.end()) <= code.text.len(), "The range of this slice is out of bounds. Did you provide the correct source code for this slice?");
assert!(
usize::from(self.range.end()) <= code.text.len(),
"The range of this slice is out of bounds. Did you provide the correct source code for this slice?"
);
&code.text[self.range]
}
}