Skip to content

Commit

Permalink
bug: Fix formatting for ItemTraitItem and Annotated<T> (#5182)
Browse files Browse the repository at this point in the history
Closes #5179 

- Centralizes the use case of `ItemTraitItem`'s format method
- Fixes indentation problems around `Annotated<T>`
- Adds a `write_ident_into_buffer` method which checks if the buffer is
already indented
- Adds documentation for methods the interact with the indentation of
the formatter to avoid confusion on what they actually do
  • Loading branch information
eureka-cpu authored Oct 11, 2023
1 parent f12d5d4 commit 5406057
Show file tree
Hide file tree
Showing 21 changed files with 72 additions and 90 deletions.
2 changes: 1 addition & 1 deletion swayfmt/src/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ pub fn write_comments(
write!(
formatted_code,
"{}{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
comment.span().as_str(),
newlines
)?;
Expand Down
17 changes: 16 additions & 1 deletion swayfmt/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,33 @@ impl Formatter {
})
}

/// Adds a block to the indentation level of the current [`Shape`].
pub fn indent(&mut self) {
self.shape.block_indent(&self.config);
}

/// Removes a block from the indentation level of the current [`Shape`].
pub fn unindent(&mut self) {
self.shape.block_unindent(&self.config);
}

pub fn indent_str(&self) -> Result<Cow<'static, str>, FormatterError> {
/// Returns the [`Shape`]'s indentation blocks as a `Cow<'static, str>`.
pub fn indent_to_str(&self) -> Result<Cow<'static, str>, FormatterError> {
self.shape.indent.to_string(&self.config)
}

/// Checks the current level of indentation before writing the indent str into the buffer.
pub fn write_indent_into_buffer(
&self,
formatted_code: &mut FormattedCode,
) -> Result<(), FormatterError> {
let indent_str = self.indent_to_str()?;
if !formatted_code.ends_with(indent_str.as_ref()) {
write!(formatted_code, "{indent_str}")?
}
Ok(())
}

/// Collect a mapping of Span -> Comment from unformatted input.
pub fn with_comments_context(&mut self, src: &str) -> Result<&mut Self, FormatterError> {
let comments_context =
Expand Down
11 changes: 3 additions & 8 deletions swayfmt/src/items/item_abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,8 @@ impl Format for ItemAbi {
let abi_items = self.abi_items.get();

// abi_items
for annotated in abi_items.iter() {
// add indent + format item
write!(formatted_code, "{}", formatter.indent_str()?)?;
annotated.format(formatted_code, formatter)?;
for trait_item in abi_items.iter() {
trait_item.format(formatted_code, formatter)?;
}

if abi_items.is_empty() {
Expand All @@ -56,12 +54,9 @@ impl Format for ItemAbi {
if let Some(abi_defs) = self.abi_defs_opt.clone() {
Self::open_curly_brace(formatted_code, formatter)?;
for item in abi_defs.get().iter() {
// add indent + format item
write!(formatted_code, "{}", formatter.indent_str()?,)?;
item.format(formatted_code, formatter)?;
}
writeln!(formatted_code)?;

Self::close_curly_brace(formatted_code, formatter)?;
}

Expand Down Expand Up @@ -107,7 +102,7 @@ impl CurlyBrace for ItemAbi {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;

Expand Down
4 changes: 2 additions & 2 deletions swayfmt/src/items/item_configurable/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl Format for ItemConfigurable {
for (field_index, (configurable_field, comma_token)) in
value_pairs_iter.clone()
{
write!(formatted_code, "{}", &formatter.indent_str()?)?;
write!(formatted_code, "{}", &formatter.indent_to_str()?)?;

// Add name
configurable_field.name.format(formatted_code, formatter)?;
Expand Down Expand Up @@ -156,7 +156,7 @@ impl CurlyBrace for ItemConfigurable {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;

Expand Down
4 changes: 2 additions & 2 deletions swayfmt/src/items/item_enum/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl Format for ItemEnum {

let value_pairs_iter = value_pairs.iter().enumerate();
for (var_index, (type_field, comma_token)) in value_pairs_iter.clone() {
write!(formatted_code, "{}", &formatter.indent_str()?)?;
write!(formatted_code, "{}", &formatter.indent_to_str()?)?;

// Add name
type_field.name.format(formatted_code, formatter)?;
Expand Down Expand Up @@ -165,7 +165,7 @@ impl CurlyBrace for ItemEnum {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;

Expand Down
6 changes: 3 additions & 3 deletions swayfmt/src/items/item_fn/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl CurlyBrace for ItemFn {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;

Expand Down Expand Up @@ -208,7 +208,7 @@ fn format_fn_args(
formatter.indent();
args.format(formatted_code, formatter)?;
formatter.unindent();
write!(formatted_code, "{}", formatter.indent_str()?)?;
write!(formatted_code, "{}", formatter.indent_to_str()?)?;
}
}
_ => args.format(formatted_code, formatter)?,
Expand All @@ -222,7 +222,7 @@ fn format_fn_args(
match formatter.shape.code_line.line_style {
LineStyle::Multiline => {
formatter.indent();
write!(formatted_code, "\n{}", formatter.indent_str()?)?;
write!(formatted_code, "\n{}", formatter.indent_to_str()?)?;
format_self(self_token, ref_self, mutable_self, formatted_code)?;
// `args_opt`
if let Some((comma, args)) = args_opt {
Expand Down
4 changes: 2 additions & 2 deletions swayfmt/src/items/item_impl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl Format for ItemImpl {
Self::open_curly_brace(formatted_code, formatter)?;
let contents = self.contents.get();
for item in contents.iter() {
write!(formatted_code, "{}", formatter.indent_str()?,)?;
write!(formatted_code, "{}", formatter.indent_to_str()?,)?;
item.format(formatted_code, formatter)?;
writeln!(formatted_code)?;
}
Expand Down Expand Up @@ -111,7 +111,7 @@ impl CurlyBrace for ItemImpl {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;

Expand Down
5 changes: 2 additions & 3 deletions swayfmt/src/items/item_storage/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ impl Format for ItemStorage {
let value_pairs_iter = value_pairs.iter().enumerate();
for (field_index, (storage_field, comma_token)) in value_pairs_iter.clone()
{
write!(formatted_code, "{}", &formatter.indent_str()?)?;

write!(formatted_code, "{}", formatter.indent_to_str()?)?;
// Add name
storage_field.name.format(formatted_code, formatter)?;

Expand Down Expand Up @@ -161,7 +160,7 @@ impl CurlyBrace for ItemStorage {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;

Expand Down
5 changes: 2 additions & 3 deletions swayfmt/src/items/item_struct/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ impl Format for ItemStruct {

let value_pairs_iter = value_pairs.iter().enumerate();
for (var_index, (type_field, comma_token)) in value_pairs_iter.clone() {
write!(formatted_code, "{}", &formatter.indent_str()?)?;

write!(formatted_code, "{}", formatter.indent_to_str()?)?;
// Add name
type_field.name.format(formatted_code, formatter)?;
let current_variant_length = variant_length[var_index];
Expand Down Expand Up @@ -162,7 +161,7 @@ impl CurlyBrace for ItemStruct {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;

Expand Down
38 changes: 6 additions & 32 deletions swayfmt/src/items/item_trait/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ use crate::{
};
use std::fmt::Write;
use sway_ast::{keywords::Token, ItemTrait, ItemTraitItem, Traits};
use sway_types::{
ast::{Delimiter, PunctKind},
Spanned,
};
use sway_types::{ast::Delimiter, Spanned};

#[cfg(test)]
mod tests;
Expand Down Expand Up @@ -59,29 +56,7 @@ impl Format for ItemTrait {
write_comments(formatted_code, self.trait_items.span().into(), formatter)?;
} else {
for item in trait_items {
for attr in &item.attribute_list {
write!(formatted_code, "{}", &formatter.indent_str()?)?;
attr.format(formatted_code, formatter)?;
}
match &item.value {
sway_ast::ItemTraitItem::Fn(fn_signature, _) => {
write!(formatted_code, "{}", formatter.indent_str()?)?;
fn_signature.format(formatted_code, formatter)?;
write!(formatted_code, "{}", PunctKind::Semicolon.as_char())?;
}
sway_ast::ItemTraitItem::Const(const_decl, _) => {
write!(formatted_code, "{}", formatter.indent_str()?)?;
const_decl.format(formatted_code, formatter)?;
}
sway_ast::ItemTraitItem::Type(type_decl, _) => {
write!(formatted_code, "{}", formatter.indent_str()?)?;
type_decl.format(formatted_code, formatter)?;
}
ItemTraitItem::Error(_, _) => {
return Err(FormatterError::SyntaxError);
}
}
writeln!(formatted_code)?;
item.format(formatted_code, formatter)?;
}
}

Expand All @@ -90,7 +65,6 @@ impl Format for ItemTrait {
write!(formatted_code, " ")?;
Self::open_curly_brace(formatted_code, formatter)?;
for trait_items in trait_defs.get() {
write!(formatted_code, "{}", formatter.indent_str()?)?;
// format `Annotated<ItemFn>`
trait_items.format(formatted_code, formatter)?;
}
Expand Down Expand Up @@ -120,20 +94,20 @@ impl Format for ItemTraitItem {
ItemTraitItem::Fn(fn_decl, _) => {
fn_decl.format(formatted_code, formatter)?;
writeln!(formatted_code, ";")?;
Ok(())
}
ItemTraitItem::Const(const_decl, _) => {
const_decl.format(formatted_code, formatter)?;
writeln!(formatted_code)?;
Ok(())
}
ItemTraitItem::Type(type_decl, _) => {
type_decl.format(formatted_code, formatter)?;
writeln!(formatted_code)?;
Ok(())
}
ItemTraitItem::Error(_, _) => Err(FormatterError::SyntaxError),
ItemTraitItem::Error(_, _) => {
return Err(FormatterError::SyntaxError);
}
}
Ok(())
}
}

Expand Down
6 changes: 3 additions & 3 deletions swayfmt/src/items/item_use/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ impl Format for UseTree {
writeln!(
formatted_code,
"{}{}",
formatter.indent_str()?,
ord_vec.join(&format!("\n{}", formatter.indent_str()?)),
formatter.indent_to_str()?,
ord_vec.join(&format!("\n{}", formatter.indent_to_str()?)),
)?;
}
_ => {
Expand Down Expand Up @@ -182,7 +182,7 @@ impl CurlyBrace for UseTree {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;
}
Expand Down
4 changes: 2 additions & 2 deletions swayfmt/src/utils/language/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ impl<T: Format + Spanned> Format for Annotated<T> {
) -> Result<(), FormatterError> {
// format each `Attribute`
for attr in &self.attribute_list {
formatter.write_indent_into_buffer(formatted_code)?;
attr.format(formatted_code, formatter)?;

write!(formatted_code, "{}", &formatter.indent_str()?,)?;
}
// format `ItemKind`
formatter.write_indent_into_buffer(formatted_code)?;
self.value.format(formatted_code, formatter)?;

Ok(())
Expand Down
6 changes: 3 additions & 3 deletions swayfmt/src/utils/language/expr/asm_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl CurlyBrace for AsmBlock {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;
}
Expand Down Expand Up @@ -174,13 +174,13 @@ impl Format for AsmBlockContents {
formatter: &mut Formatter,
) -> Result<(), FormatterError> {
for (instruction, semicolon_token) in self.instructions.iter() {
write!(formatted_code, "{}", formatter.indent_str()?)?;
write!(formatted_code, "{}", formatter.indent_to_str()?)?;
instruction.format(formatted_code, formatter)?;
writeln!(formatted_code, "{}", semicolon_token.span().as_str())?
}
if let Some(final_expr) = &self.final_expr_opt {
if formatter.shape.code_line.line_style == LineStyle::Multiline {
write!(formatted_code, "{}", formatter.indent_str()?)?;
write!(formatted_code, "{}", formatter.indent_to_str()?)?;
final_expr.format(formatted_code, formatter)?;
writeln!(formatted_code)?;
} else {
Expand Down
6 changes: 3 additions & 3 deletions swayfmt/src/utils/language/expr/code_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ impl Format for CodeBlockContents {
_ => {
writeln!(formatted_code)?;
for statement in self.statements.iter() {
write!(formatted_code, "{}", formatter.indent_str()?)?;
write!(formatted_code, "{}", formatter.indent_to_str()?)?;
statement.format(formatted_code, formatter)?;
if !formatted_code.ends_with('\n') {
writeln!(formatted_code)?;
}
}
if let Some(final_expr) = &self.final_expr_opt {
write!(formatted_code, "{}", formatter.indent_str()?)?;
write!(formatted_code, "{}", formatter.indent_to_str()?)?;
final_expr.format(formatted_code, formatter)?;
writeln!(formatted_code)?;
}
Expand Down Expand Up @@ -90,7 +90,7 @@ impl CurlyBrace for CodeBlockContents {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Brace.as_close_char()
)?;
Ok(())
Expand Down
6 changes: 3 additions & 3 deletions swayfmt/src/utils/language/expr/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl Format for ExprTupleDescriptor {
tail,
} => match formatter.shape.code_line.line_style {
LineStyle::Multiline => {
write!(formatted_code, "{}", formatter.indent_str()?)?;
write!(formatted_code, "{}", formatter.indent_to_str()?)?;
head.format(formatted_code, formatter)?;
write!(formatted_code, "{}", comma_token.span().as_str())?;
tail.format(formatted_code, formatter)?;
Expand Down Expand Up @@ -67,7 +67,7 @@ impl Parenthesis for ExprTupleDescriptor {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Parenthesis.as_close_char()
)?;
}
Expand Down Expand Up @@ -130,7 +130,7 @@ impl SquareBracket for ExprArrayDescriptor {
write!(
line,
"{}{}",
formatter.indent_str()?,
formatter.indent_to_str()?,
Delimiter::Bracket.as_close_char()
)?;
}
Expand Down
Loading

0 comments on commit 5406057

Please sign in to comment.