From 5b715efeba10a854f3308caa11c1a893f0780229 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Fri, 24 Jun 2022 19:00:11 -0500 Subject: [PATCH 01/17] Add generics handling --- sway-fmt-v2/src/utils.rs | 1 + sway-fmt-v2/src/utils/bracket.rs | 12 ++++----- sway-fmt-v2/src/utils/generics.rs | 42 +++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) create mode 100644 sway-fmt-v2/src/utils/generics.rs diff --git a/sway-fmt-v2/src/utils.rs b/sway-fmt-v2/src/utils.rs index 47a62fa3b45..80e0750dd35 100644 --- a/sway-fmt-v2/src/utils.rs +++ b/sway-fmt-v2/src/utils.rs @@ -1,5 +1,6 @@ pub mod attribute; pub mod bracket; +pub mod generics; pub mod indent_style; pub mod item; pub mod newline_style; diff --git a/sway-fmt-v2/src/utils/bracket.rs b/sway-fmt-v2/src/utils/bracket.rs index 906d2bcb50f..2aa8c184f00 100644 --- a/sway-fmt-v2/src/utils/bracket.rs +++ b/sway-fmt-v2/src/utils/bracket.rs @@ -3,7 +3,7 @@ //! contained to each item's file. use crate::Formatter; -pub trait CurlyBrace { +pub(crate) trait CurlyBrace { /// Handles brace open scenerio. Checks the config for the placement of the brace. /// Modifies the current shape of the formatter. fn open_curly_brace(line: &mut String, formatter: &mut Formatter); @@ -13,13 +13,13 @@ pub trait CurlyBrace { fn close_curly_brace(line: &mut String, formatter: &mut Formatter); } -pub trait SquareBracket { +pub(crate) trait SquareBracket { fn open_square_bracket(line: &mut String, formatter: &mut Formatter); fn close_square_bracket(line: &mut String, formatter: &mut Formatter); } -pub trait Parenthesis { +pub(crate) trait Parenthesis { /// Handles open parenthesis scenarios, checking the config for placement /// and modifying the shape of the formatter where necessary. fn open_parenthesis(line: &mut String, formatter: &mut Formatter); @@ -28,8 +28,8 @@ pub trait Parenthesis { fn close_parenthesis(line: &mut String, formatter: &mut Formatter); } -pub trait AngleBracket { - fn open_angle_bracket(line: &mut String, formatter: &mut Formatter); +pub(crate) trait AngleBracket { + fn open_angle_bracket(&self, line: &mut String, formatter: &mut Formatter); - fn close_angle_bracket(line: &mut String, formatter: &mut Formatter); + fn close_angle_bracket(&self, line: &mut String, formatter: &mut Formatter); } diff --git a/sway-fmt-v2/src/utils/generics.rs b/sway-fmt-v2/src/utils/generics.rs new file mode 100644 index 00000000000..0efab57367d --- /dev/null +++ b/sway-fmt-v2/src/utils/generics.rs @@ -0,0 +1,42 @@ +use crate::{ + fmt::{Format, FormattedCode, Formatter}, + utils::bracket::AngleBracket, +}; +use sway_parse::GenericParams; +use sway_types::Spanned; + +// In the future we will need to determine whether the generic arguments +// are better suited as a `where` clause. At present they will be +// formatted in line. +// +impl Format for GenericParams { + fn format(&self, formatter: &mut Formatter) -> FormattedCode { + let mut formatted_code = String::new(); + let params = self.parameters.clone().into_inner().value_separator_pairs; + Self::open_angle_bracket(&self, &mut formatted_code, formatter); + let mut buf = params + .iter() + .map(|param| format!("{}{}", param.0.as_str(), param.1.span().as_str())) + .collect::>() + .join(" "); + if params.len() == 1 { + buf.pop(); // pop the ending comma + formatted_code.push_str(&buf); + } else { + buf.pop(); // pop the ending space + buf.pop(); // pop the ending comma + formatted_code.push_str(&buf); + } + Self::close_angle_bracket(&self, &mut formatted_code, formatter); + formatted_code + } +} + +impl AngleBracket for GenericParams { + fn open_angle_bracket(&self, line: &mut String, _formatter: &mut Formatter) { + line.push_str(self.parameters.open_angle_bracket_token.span().as_str()) + } + fn close_angle_bracket(&self, line: &mut String, _formatter: &mut Formatter) { + line.push_str(self.parameters.close_angle_bracket_token.span().as_str()) + } +} From 731321ad0327a32bb9c713342630c8e229903edf Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Fri, 24 Jun 2022 19:08:47 -0500 Subject: [PATCH 02/17] clippy --- sway-fmt-v2/src/utils/bracket.rs | 4 ++-- sway-fmt-v2/src/utils/generics.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/sway-fmt-v2/src/utils/bracket.rs b/sway-fmt-v2/src/utils/bracket.rs index 2aa8c184f00..dff4888d5b6 100644 --- a/sway-fmt-v2/src/utils/bracket.rs +++ b/sway-fmt-v2/src/utils/bracket.rs @@ -29,7 +29,7 @@ pub(crate) trait Parenthesis { } pub(crate) trait AngleBracket { - fn open_angle_bracket(&self, line: &mut String, formatter: &mut Formatter); + fn open_angle_bracket(self, line: &mut String, formatter: &mut Formatter); - fn close_angle_bracket(&self, line: &mut String, formatter: &mut Formatter); + fn close_angle_bracket(self, line: &mut String, formatter: &mut Formatter); } diff --git a/sway-fmt-v2/src/utils/generics.rs b/sway-fmt-v2/src/utils/generics.rs index 0efab57367d..6811e9969f5 100644 --- a/sway-fmt-v2/src/utils/generics.rs +++ b/sway-fmt-v2/src/utils/generics.rs @@ -13,7 +13,7 @@ impl Format for GenericParams { fn format(&self, formatter: &mut Formatter) -> FormattedCode { let mut formatted_code = String::new(); let params = self.parameters.clone().into_inner().value_separator_pairs; - Self::open_angle_bracket(&self, &mut formatted_code, formatter); + Self::open_angle_bracket(self.clone(), &mut formatted_code, formatter); let mut buf = params .iter() .map(|param| format!("{}{}", param.0.as_str(), param.1.span().as_str())) @@ -27,16 +27,16 @@ impl Format for GenericParams { buf.pop(); // pop the ending comma formatted_code.push_str(&buf); } - Self::close_angle_bracket(&self, &mut formatted_code, formatter); + Self::close_angle_bracket(self.clone(), &mut formatted_code, formatter); formatted_code } } impl AngleBracket for GenericParams { - fn open_angle_bracket(&self, line: &mut String, _formatter: &mut Formatter) { + fn open_angle_bracket(self, line: &mut String, _formatter: &mut Formatter) { line.push_str(self.parameters.open_angle_bracket_token.span().as_str()) } - fn close_angle_bracket(&self, line: &mut String, _formatter: &mut Formatter) { + fn close_angle_bracket(self, line: &mut String, _formatter: &mut Formatter) { line.push_str(self.parameters.close_angle_bracket_token.span().as_str()) } } From b5cdf64ec782b380c668ca99df30ce153ca5c326 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Fri, 24 Jun 2022 19:16:53 -0500 Subject: [PATCH 03/17] add comments --- sway-fmt-v2/src/utils/generics.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sway-fmt-v2/src/utils/generics.rs b/sway-fmt-v2/src/utils/generics.rs index 6811e9969f5..684fdb1ff9d 100644 --- a/sway-fmt-v2/src/utils/generics.rs +++ b/sway-fmt-v2/src/utils/generics.rs @@ -13,7 +13,9 @@ impl Format for GenericParams { fn format(&self, formatter: &mut Formatter) -> FormattedCode { let mut formatted_code = String::new(); let params = self.parameters.clone().into_inner().value_separator_pairs; + // `<` Self::open_angle_bracket(self.clone(), &mut formatted_code, formatter); + // parameters let mut buf = params .iter() .map(|param| format!("{}{}", param.0.as_str(), param.1.span().as_str())) @@ -27,7 +29,9 @@ impl Format for GenericParams { buf.pop(); // pop the ending comma formatted_code.push_str(&buf); } + // `>` Self::close_angle_bracket(self.clone(), &mut formatted_code, formatter); + formatted_code } } From c4e4c9fbfc611a640de95ae7b877f8dd0fc35948 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Fri, 24 Jun 2022 21:23:45 -0500 Subject: [PATCH 04/17] update item_struct --- sway-fmt-v2/src/items/item_struct.rs | 30 +++------------------------- 1 file changed, 3 insertions(+), 27 deletions(-) diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index a0e5ecae448..5542fbdb18c 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -1,10 +1,7 @@ use crate::{ config::items::ItemBraceStyle, fmt::{Format, FormattedCode, Formatter}, - utils::{ - bracket::{AngleBracket, CurlyBrace}, - item_len::ItemLen, - }, + utils::{bracket::CurlyBrace, item_len::ItemLen}, }; use sway_parse::ItemStruct; use sway_types::Spanned; @@ -74,20 +71,9 @@ fn format_struct( // Add struct name formatted_code.push_str(item_struct.name.as_str()); - // Check if there is generic provided + // Format `GenericParams`, if any if let Some(generics) = &item_struct.generics { - // Push angle brace - ItemStruct::open_angle_bracket(formatted_code, formatter); - // Get generics fields - let generics = generics.parameters.inner.value_separator_pairs.clone(); - for (index, generic) in generics.iter().enumerate() { - // Push ident - formatted_code.push_str(generic.0.as_str()); - if index != generics.len() - 1 { - // Push `, ` if this is not the last generic - formatted_code.push_str(", "); - } - } + formatted_code.push_str(&generics.format(formatter)) } // Handle openning brace @@ -198,13 +184,3 @@ impl CurlyBrace for ItemStruct { .unwrap_or_default(); } } - -impl AngleBracket for ItemStruct { - fn open_angle_bracket(line: &mut String, _formatter: &mut Formatter) { - line.push('<'); - } - - fn close_angle_bracket(line: &mut String, _formatter: &mut Formatter) { - line.push('>'); - } -} From 58425daa69ef10d6e0f8bade43fa1235bb7d7bfb Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Fri, 24 Jun 2022 23:19:58 -0500 Subject: [PATCH 05/17] add formatting to Punctuated --- sway-fmt-v2/src/utils.rs | 17 ++++++------- sway-fmt-v2/src/utils/generics.rs | 19 ++++----------- sway-fmt-v2/src/utils/punctuated.rs | 37 +++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 23 deletions(-) create mode 100644 sway-fmt-v2/src/utils/punctuated.rs diff --git a/sway-fmt-v2/src/utils.rs b/sway-fmt-v2/src/utils.rs index e02ba7c40aa..8d97a0a8c28 100644 --- a/sway-fmt-v2/src/utils.rs +++ b/sway-fmt-v2/src/utils.rs @@ -1,8 +1,9 @@ -pub mod attribute; -pub mod bracket; -pub mod generics; -pub mod indent_style; -pub mod item; -pub mod item_len; -pub mod newline_style; -pub mod program_type; +pub(crate) mod attribute; +pub(crate) mod bracket; +pub(crate) mod generics; +pub(crate) mod indent_style; +pub(crate) mod item; +pub(crate) mod item_len; +pub(crate) mod newline_style; +pub(crate) mod program_type; +pub(crate) mod punctuated; diff --git a/sway-fmt-v2/src/utils/generics.rs b/sway-fmt-v2/src/utils/generics.rs index 684fdb1ff9d..ccf98930b9f 100644 --- a/sway-fmt-v2/src/utils/generics.rs +++ b/sway-fmt-v2/src/utils/generics.rs @@ -12,23 +12,12 @@ use sway_types::Spanned; impl Format for GenericParams { fn format(&self, formatter: &mut Formatter) -> FormattedCode { let mut formatted_code = String::new(); - let params = self.parameters.clone().into_inner().value_separator_pairs; + let params = self.parameters.clone().into_inner(); + // `<` Self::open_angle_bracket(self.clone(), &mut formatted_code, formatter); - // parameters - let mut buf = params - .iter() - .map(|param| format!("{}{}", param.0.as_str(), param.1.span().as_str())) - .collect::>() - .join(" "); - if params.len() == 1 { - buf.pop(); // pop the ending comma - formatted_code.push_str(&buf); - } else { - buf.pop(); // pop the ending space - buf.pop(); // pop the ending comma - formatted_code.push_str(&buf); - } + // format and add parameters + params.format(formatter); // `>` Self::close_angle_bracket(self.clone(), &mut formatted_code, formatter); diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs new file mode 100644 index 00000000000..994d50192cf --- /dev/null +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -0,0 +1,37 @@ +use crate::fmt::{Format, FormattedCode, Formatter}; +use sway_parse::punctuated::Punctuated; +use sway_types::Spanned; + +impl Format for Punctuated +where + T: Spanned, + P: Spanned, +{ + fn format(&self, _formatter: &mut Formatter) -> FormattedCode { + let mut formatted_code = FormattedCode::new(); + let sep_pairs = &self.value_separator_pairs; + let value_opt = &self.final_value_opt; + + // format and add Type & Punct + let mut buf = sep_pairs + .iter() + .map(|pair| format!("{}{}", pair.0.span().as_str(), pair.1.span().as_str())) + .collect::>() + .join(" "); + if sep_pairs.len() == 1 { + buf.pop(); // pop the ending comma + formatted_code.push_str(&buf); + } else { + buf.pop(); // pop the ending space + buf.pop(); // pop the ending comma + formatted_code.push_str(&buf); + } + + // add boxed type + if let Some(final_value) = value_opt { + formatted_code.push_str(final_value.span().as_str()); + } + + formatted_code + } +} From 8f67ff86764da0d54878b941c03f872504e49911 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Fri, 24 Jun 2022 23:46:50 -0500 Subject: [PATCH 06/17] fix test for punctuated --- sway-fmt-v2/src/fmt.rs | 4 ++-- sway-fmt-v2/src/utils/attribute.rs | 16 ++-------------- sway-fmt-v2/src/utils/punctuated.rs | 10 ++-------- 3 files changed, 6 insertions(+), 24 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 9891089d66f..6f220807073 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -231,14 +231,14 @@ enum Color { let sway_code_to_format = r#"contract; abi StorageMapExample { - #[storage(write,)]fn insert_into_map1(key: u64, value: u64); + #[storage(write, read,)]fn insert_into_map1(key: u64, value: u64); fn hello(key: u64, value: u64); }"#; let correct_sway_code = r#"contract; abi StorageMapExample { - #[storage(write)] + #[storage(write, read)] fn insert_into_map1(key: u64, value: u64); fn hello(key: u64, value: u64); diff --git a/sway-fmt-v2/src/utils/attribute.rs b/sway-fmt-v2/src/utils/attribute.rs index 085402dafed..675a4b57ed4 100644 --- a/sway-fmt-v2/src/utils/attribute.rs +++ b/sway-fmt-v2/src/utils/attribute.rs @@ -42,20 +42,8 @@ impl FormatDecl for AttributeDecl { Self::open_parenthesis(line, formatter); // format and add args `read, write` if let Some(args) = attr.args { - let args = args.into_inner().value_separator_pairs; - let mut buf = args - .iter() - .map(|arg| format!("{}{}", arg.0.as_str(), arg.1.span().as_str())) - .collect::>() - .join(" "); - if args.len() == 1 { - buf.pop(); // pop the ending comma - line.push_str(&buf); - } else { - buf.pop(); // pop the ending space - buf.pop(); // pop the ending comma - line.push_str(&buf); - } + let args = args.into_inner(); + line.push_str(&args.format(formatter)); } // ')' Self::close_parenthesis(line, formatter); diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 994d50192cf..4e162abbc8e 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -18,14 +18,8 @@ where .map(|pair| format!("{}{}", pair.0.span().as_str(), pair.1.span().as_str())) .collect::>() .join(" "); - if sep_pairs.len() == 1 { - buf.pop(); // pop the ending comma - formatted_code.push_str(&buf); - } else { - buf.pop(); // pop the ending space - buf.pop(); // pop the ending comma - formatted_code.push_str(&buf); - } + buf.pop(); // pop the ending comma + formatted_code.push_str(&buf); // add boxed type if let Some(final_value) = value_opt { From f3addd3ca18bd7686f90ecabb8eb0268139bfd93 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Sat, 25 Jun 2022 00:32:50 -0500 Subject: [PATCH 07/17] add fmt params to string --- sway-fmt-v2/src/utils/generics.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sway-fmt-v2/src/utils/generics.rs b/sway-fmt-v2/src/utils/generics.rs index ccf98930b9f..3c793357a24 100644 --- a/sway-fmt-v2/src/utils/generics.rs +++ b/sway-fmt-v2/src/utils/generics.rs @@ -17,7 +17,7 @@ impl Format for GenericParams { // `<` Self::open_angle_bracket(self.clone(), &mut formatted_code, formatter); // format and add parameters - params.format(formatter); + formatted_code.push_str(¶ms.format(formatter)); // `>` Self::close_angle_bracket(self.clone(), &mut formatted_code, formatter); From a2ba347d78289a3351f6a77ad773ebf75d1bca1c Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Sat, 25 Jun 2022 00:37:05 -0500 Subject: [PATCH 08/17] rmv redundant vars --- sway-fmt-v2/src/utils/punctuated.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 4e162abbc8e..563caafbf81 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -9,11 +9,10 @@ where { fn format(&self, _formatter: &mut Formatter) -> FormattedCode { let mut formatted_code = FormattedCode::new(); - let sep_pairs = &self.value_separator_pairs; - let value_opt = &self.final_value_opt; // format and add Type & Punct - let mut buf = sep_pairs + let mut buf = self + .value_separator_pairs .iter() .map(|pair| format!("{}{}", pair.0.span().as_str(), pair.1.span().as_str())) .collect::>() @@ -22,7 +21,7 @@ where formatted_code.push_str(&buf); // add boxed type - if let Some(final_value) = value_opt { + if let Some(final_value) = &self.final_value_opt { formatted_code.push_str(final_value.span().as_str()); } From 26b999e7d1d5699136ffd381995e74af35113f5b Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Sun, 26 Jun 2022 18:59:13 -0500 Subject: [PATCH 09/17] fix abi test --- sway-fmt-v2/src/fmt.rs | 2 +- sway-fmt-v2/src/items/item_abi.rs | 2 +- sway-fmt-v2/src/utils/punctuated.rs | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index dd1afbfd23c..83d3cf4423e 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -254,7 +254,7 @@ abi StorageMapExample { let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - assert!(correct_sway_code == formatted_sway_code) + assert!(dbg!(correct_sway_code) == dbg!(formatted_sway_code)) } #[test] diff --git a/sway-fmt-v2/src/items/item_abi.rs b/sway-fmt-v2/src/items/item_abi.rs index f6820c773df..c634a1591bd 100644 --- a/sway-fmt-v2/src/items/item_abi.rs +++ b/sway-fmt-v2/src/items/item_abi.rs @@ -15,7 +15,7 @@ impl Format for ItemAbi { formatter: &mut Formatter, ) -> Result<(), FormatterError> { // Add enum token - writeln!(formatted_code, "{} ", self.abi_token.span().as_str())?; + write!(formatted_code, "{} ", self.abi_token.span().as_str())?; // Add name of the abi formatted_code.push_str(self.name.as_str()); diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index bded705e01f..2b93916daf0 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -27,6 +27,7 @@ where .join(" ") )?; formatted_code.pop(); // pop the ending comma + formatted_code.pop(); // add boxed type if let Some(final_value) = &self.final_value_opt { From 0701aabf70d93f1b830ec4df8e008fe416c5e8e1 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Sun, 26 Jun 2022 19:01:30 -0500 Subject: [PATCH 10/17] chng writeln to write in punctuated --- sway-fmt-v2/src/utils/punctuated.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 2b93916daf0..06884c39eb5 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -17,7 +17,7 @@ where _formatter: &mut Formatter, ) -> Result<(), FormatterError> { // format and add Type & Punct - writeln!( + write!( formatted_code, "{}", self.value_separator_pairs @@ -27,7 +27,6 @@ where .join(" ") )?; formatted_code.pop(); // pop the ending comma - formatted_code.pop(); // add boxed type if let Some(final_value) = &self.final_value_opt { From 12cc17e2ddb64c4355f61d05879fe9fa21224b25 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Sun, 26 Jun 2022 19:03:10 -0500 Subject: [PATCH 11/17] . --- sway-fmt-v2/src/utils/punctuated.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 06884c39eb5..abf7db059fb 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -30,7 +30,7 @@ where // add boxed type if let Some(final_value) = &self.final_value_opt { - writeln!(formatted_code, "{}", final_value.span().as_str())?; + write!(formatted_code, "{}", final_value.span().as_str())?; } Ok(()) From b2244eb134eab3be2cd0cafadd5a8d3df76be83d Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Mon, 27 Jun 2022 11:15:27 -0500 Subject: [PATCH 12/17] update with formatting fns with write --- sway-fmt-v2/src/items/item_enum.rs | 29 +++++++++++------ sway-fmt-v2/src/items/item_struct.rs | 48 +++++++++++++++------------- sway-fmt-v2/src/utils/attribute.rs | 9 +++--- sway-fmt-v2/src/utils/punctuated.rs | 23 +++++++------ 4 files changed, 61 insertions(+), 48 deletions(-) diff --git a/sway-fmt-v2/src/items/item_enum.rs b/sway-fmt-v2/src/items/item_enum.rs index 621c24c2351..302cc9010dd 100644 --- a/sway-fmt-v2/src/items/item_enum.rs +++ b/sway-fmt-v2/src/items/item_enum.rs @@ -5,7 +5,10 @@ use crate::{ FormatterError, }; use std::fmt::Write; -use sway_parse::{token::Delimiter, ItemEnum}; +use sway_parse::{ + token::{Delimiter, PunctKind}, + ItemEnum, +}; use sway_types::Spanned; impl Format for ItemEnum { @@ -17,13 +20,11 @@ impl Format for ItemEnum { let enum_variant_align_threshold = formatter.config.structures.enum_variant_align_threshold; if let Some(visibility_token) = &self.visibility { - formatted_code.push_str(visibility_token.span().as_str()); - formatted_code.push(' '); + write!(formatted_code, "{} ", visibility_token.span().as_str())?; } // Add enum token - formatted_code.push_str(self.enum_token.span().as_str()); - formatted_code.push(' '); + write!(formatted_code, "{} ", self.enum_token.span().as_str())?; // Add name of the enum. formatted_code.push_str(self.name.as_str()); @@ -51,8 +52,12 @@ impl Format for ItemEnum { for (index, type_field) in type_fields.iter().enumerate() { let type_field = &type_field.0; // Push the current indentation level - formatted_code.push_str(&formatter.shape.indent.to_string(formatter)); - formatted_code.push_str(type_field.name.as_str()); + write!( + formatted_code, + "{}{}", + &formatter.shape.indent.to_string(formatter), + type_field.name.as_str() + )?; // Currently does not apply custom formatting for ty, let current_variant_length = variant_length[index]; @@ -65,10 +70,14 @@ impl Format for ItemEnum { // TODO: Improve handling this formatted_code.push_str(&(0..required_alignment).map(|_| ' ').collect::()); } - formatted_code.push_str(" : "); // TODO: We are currently converting ty to string directly but we will probably need to format ty before adding. - formatted_code.push_str(type_field.ty.span().as_str()); - formatted_code.push(','); + write!( + formatted_code, + " {} {}{}", + type_field.colon_token.span().as_str(), + type_field.ty.span().as_str(), + PunctKind::Comma.as_char(), + )?; // TODO: Here we assume that next enum variant is going to be in the new line but // from the config we may understand next enum variant should be in the same line instead. diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index c6374814dc5..be28854dcbe 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -4,7 +4,11 @@ use crate::{ utils::{bracket::CurlyBrace, item_len::ItemLen}, FormatterError, }; -use sway_parse::ItemStruct; +use std::fmt::Write; +use sway_parse::{ + token::{Delimiter, PunctKind}, + ItemStruct, +}; use sway_types::Spanned; impl Format for ItemStruct { @@ -23,12 +27,11 @@ impl Format for ItemStruct { let struct_lit_single_line = formatter.config.structures.struct_lit_single_line; // Get the width limit of a struct to be formatted into single line if struct_lit_single_line is true. - let config_whitespace = formatter.config.whitespace; let width_heuristics = formatter .config .heuristics .heuristics_pref - .to_width_heuristics(&config_whitespace); + .to_width_heuristics(&formatter.config.whitespace); let struct_lit_width = width_heuristics.struct_lit_width; let multiline = !struct_lit_single_line || self.get_formatted_len() > struct_lit_width; @@ -62,12 +65,14 @@ fn format_struct( ) -> Result<(), FormatterError> { // If there is a visibility token add it to the formatted_code with a ` ` after it. if let Some(visibility) = &item_struct.visibility { - formatted_code.push_str(visibility.span().as_str()); - formatted_code.push(' '); + write!(formatted_code, "{} ", visibility.span().as_str())?; } // Add struct token - formatted_code.push_str(item_struct.struct_token.span().as_str()); - formatted_code.push(' '); + write!( + formatted_code, + "{} ", + item_struct.struct_token.span().as_str() + )?; // Add struct name formatted_code.push_str(item_struct.name.as_str()); @@ -83,12 +88,7 @@ fn format_struct( ItemStruct::open_curly_brace(formatted_code, formatter)?; formatted_code.push('\n'); } else { - // Push a single whitespace before `{` - formatted_code.push(' '); - // Push open brace - formatted_code.push('{'); - // Push a single whitespace after `{` - formatted_code.push(' '); + write!(formatted_code, " {} ", Delimiter::Brace.as_open_char())?; } let items = item_struct @@ -127,17 +127,19 @@ fn format_struct( // TODO: Improve handling this formatted_code.push_str(&(0..required_alignment).map(|_| ' ').collect::()); } - // Add `:` - formatted_code.push_str(type_field.colon_token.ident().as_str()); - formatted_code.push(' '); + // Add `:` and ty // TODO: We are currently converting ty to string directly but we will probably need to format ty before adding. - // Add ty - formatted_code.push_str(type_field.ty.span().as_str()); + write!( + formatted_code, + "{} {}", + type_field.colon_token.ident().as_str(), + type_field.ty.span().as_str() + )?; // Add `, ` if this isn't the last field. if !multiline && item_index != items.len() - 1 { - formatted_code.push_str(", "); + write!(formatted_code, "{} ", PunctKind::Comma.as_char())?; } else if multiline { - formatted_code.push_str(",\n"); + write!(formatted_code, "{}\n", PunctKind::Comma.as_char())?; } } if !multiline { @@ -168,12 +170,12 @@ impl CurlyBrace for ItemStruct { match brace_style { ItemBraceStyle::AlwaysNextLine => { // Add openning brace to the next line. - line.push_str("\n{"); + write!(line, "\n{}", Delimiter::Brace.as_open_char())?; shape = shape.block_indent(extra_width); } _ => { // Add opening brace to the same line - line.push_str(" {"); + write!(line, " {}", Delimiter::Brace.as_open_char())?; shape = shape.block_indent(extra_width); } } @@ -186,7 +188,7 @@ impl CurlyBrace for ItemStruct { line: &mut String, formatter: &mut Formatter, ) -> Result<(), FormatterError> { - line.push('}'); + line.push(Delimiter::Brace.as_close_char()); // If shape is becoming left-most alligned or - indent just have the defualt shape formatter.shape = formatter .shape diff --git a/sway-fmt-v2/src/utils/attribute.rs b/sway-fmt-v2/src/utils/attribute.rs index 136777adc7d..65ebbdb5bd3 100644 --- a/sway-fmt-v2/src/utils/attribute.rs +++ b/sway-fmt-v2/src/utils/attribute.rs @@ -2,7 +2,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, FormatterError, }; -use std::fmt::Write; use sway_parse::{ attribute::{Annotated, AttributeDecl}, token::Delimiter, @@ -63,14 +62,14 @@ impl SquareBracket for AttributeDecl { line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { - write!(line, "{}", Delimiter::Bracket.as_open_char())?; + line.push(Delimiter::Bracket.as_open_char()); Ok(()) } fn close_square_bracket( line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { - writeln!(line, "{}", Delimiter::Bracket.as_close_char())?; + line.push(Delimiter::Bracket.as_close_char()); Ok(()) } } @@ -80,14 +79,14 @@ impl Parenthesis for AttributeDecl { line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { - write!(line, "{}", Delimiter::Parenthesis.as_open_char())?; + line.push(Delimiter::Parenthesis.as_open_char()); Ok(()) } fn close_parenthesis( line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { - write!(line, "{}", Delimiter::Parenthesis.as_close_char())?; + line.push(Delimiter::Parenthesis.as_close_char()); Ok(()) } } diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index abf7db059fb..399a232b8cb 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -17,20 +17,23 @@ where _formatter: &mut Formatter, ) -> Result<(), FormatterError> { // format and add Type & Punct - write!( - formatted_code, - "{}", - self.value_separator_pairs - .iter() - .map(|pair| format!("{}{}", pair.0.span().as_str(), pair.1.span().as_str())) - .collect::>() - .join(" ") - )?; + let mut value_pairs_iter = self.value_separator_pairs.iter().peekable(); + while let Some(pair) = value_pairs_iter.next() { + write!( + formatted_code, + "{}{}", + pair.0.span().as_str(), + pair.1.span().as_str(), + )?; + if value_pairs_iter.peek().is_some() { + formatted_code.push(' ') + } + } formatted_code.pop(); // pop the ending comma // add boxed type if let Some(final_value) = &self.final_value_opt { - write!(formatted_code, "{}", final_value.span().as_str())?; + formatted_code.push_str(final_value.span().as_str()); } Ok(()) From 75c9e764784cafb520ffda41215a6808aa51f83a Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Mon, 27 Jun 2022 11:20:50 -0500 Subject: [PATCH 13/17] update tests --- sway-fmt-v2/src/items/item_struct.rs | 2 +- sway-fmt-v2/src/utils/attribute.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index be28854dcbe..c6b2836a52d 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -139,7 +139,7 @@ fn format_struct( if !multiline && item_index != items.len() - 1 { write!(formatted_code, "{} ", PunctKind::Comma.as_char())?; } else if multiline { - write!(formatted_code, "{}\n", PunctKind::Comma.as_char())?; + writeln!(formatted_code, "{}", PunctKind::Comma.as_char())?; } } if !multiline { diff --git a/sway-fmt-v2/src/utils/attribute.rs b/sway-fmt-v2/src/utils/attribute.rs index 65ebbdb5bd3..dbceaaa918d 100644 --- a/sway-fmt-v2/src/utils/attribute.rs +++ b/sway-fmt-v2/src/utils/attribute.rs @@ -2,6 +2,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, FormatterError, }; +use std::fmt::Write; use sway_parse::{ attribute::{Annotated, AttributeDecl}, token::Delimiter, @@ -69,7 +70,7 @@ impl SquareBracket for AttributeDecl { line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { - line.push(Delimiter::Bracket.as_close_char()); + writeln!(line, "{}", Delimiter::Bracket.as_close_char())?; Ok(()) } } From ee326982ed0547b8d4952e22b190daf9049f0b61 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Mon, 27 Jun 2022 11:31:42 -0500 Subject: [PATCH 14/17] test passing --- sway-fmt-v2/src/fmt.rs | 6 +++--- sway-fmt-v2/src/items/item_struct.rs | 1 - sway-fmt-v2/src/utils/generics.rs | 13 ++----------- 3 files changed, 5 insertions(+), 15 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 83d3cf4423e..65821fa99cb 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -124,14 +124,14 @@ pub struct Foo { bar: u64, baz: bool }"#; #[test] fn test_struct_multiline_line_alignment() { let sway_code_to_format = r#"contract; -pub struct Foo { +pub struct Foo { barbazfoo: u64, baz : bool, } "#; let correct_sway_code = r#"contract; -pub struct Foo { +pub struct Foo { barbazfoo: u64, baz : bool, }"#; @@ -140,7 +140,7 @@ pub struct Foo { let mut formatter = get_formatter(config, Shape::default()); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - assert!(correct_sway_code == formatted_sway_code) + assert!(dbg!(correct_sway_code) == dbg!(formatted_sway_code)) } #[test] fn test_struct_single_line() { diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index c6b2836a52d..c5c1989f131 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -79,7 +79,6 @@ fn format_struct( // Format `GenericParams`, if any if let Some(generics) = &item_struct.generics { - // Push angle brace generics.format(formatted_code, formatter)?; } diff --git a/sway-fmt-v2/src/utils/generics.rs b/sway-fmt-v2/src/utils/generics.rs index 9bfc90bee3d..0b69758476d 100644 --- a/sway-fmt-v2/src/utils/generics.rs +++ b/sway-fmt-v2/src/utils/generics.rs @@ -2,7 +2,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter, FormatterError}, utils::bracket::AngleBracket, }; -use std::fmt::Write; use sway_parse::GenericParams; use sway_types::Spanned; @@ -35,11 +34,7 @@ impl AngleBracket for GenericParams { line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { - writeln!( - line, - "{}", - self.parameters.open_angle_bracket_token.span().as_str() - )?; + line.push_str(self.parameters.open_angle_bracket_token.span().as_str()); Ok(()) } fn close_angle_bracket( @@ -47,11 +42,7 @@ impl AngleBracket for GenericParams { line: &mut String, _formatter: &mut Formatter, ) -> Result<(), FormatterError> { - writeln!( - line, - "{}", - self.parameters.close_angle_bracket_token.span().as_str() - )?; + line.push_str(self.parameters.close_angle_bracket_token.span().as_str()); Ok(()) } } From 9c5a55b2998c7d33d352443554cbe0bdb07486ea Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Mon, 27 Jun 2022 11:38:41 -0500 Subject: [PATCH 15/17] remove dbg! from tests --- sway-fmt-v2/src/fmt.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 65821fa99cb..d3aa96ceca7 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -140,7 +140,7 @@ pub struct Foo { let mut formatter = get_formatter(config, Shape::default()); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - assert!(dbg!(correct_sway_code) == dbg!(formatted_sway_code)) + assert!(correct_sway_code == formatted_sway_code) } #[test] fn test_struct_single_line() { @@ -254,7 +254,7 @@ abi StorageMapExample { let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - assert!(dbg!(correct_sway_code) == dbg!(formatted_sway_code)) + assert!(correct_sway_code == formatted_sway_code) } #[test] From 6ae3b8b86f46371cf9fa7759d71f34bf5c8567f7 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Mon, 27 Jun 2022 19:35:10 -0500 Subject: [PATCH 16/17] update handling of final_value_opt --- sway-fmt-v2/src/fmt.rs | 6 +++--- sway-fmt-v2/src/utils/punctuated.rs | 27 +++++++++++++++------------ 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index d3aa96ceca7..06d626f3d59 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -124,7 +124,7 @@ pub struct Foo { bar: u64, baz: bool }"#; #[test] fn test_struct_multiline_line_alignment() { let sway_code_to_format = r#"contract; -pub struct Foo { +pub struct Foo { barbazfoo: u64, baz : bool, } @@ -239,14 +239,14 @@ enum Color { let sway_code_to_format = r#"contract; abi StorageMapExample { - #[storage(write, read,)]fn insert_into_map1(key: u64, value: u64); + #[storage(write,)]fn insert_into_map1(key: u64, value: u64); fn hello(key: u64, value: u64); }"#; let correct_sway_code = r#"contract; abi StorageMapExample { - #[storage(write, read)] + #[storage(write)] fn insert_into_map1(key: u64, value: u64); fn hello(key: u64, value: u64); diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 399a232b8cb..b93bc61dc06 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -17,21 +17,24 @@ where _formatter: &mut Formatter, ) -> Result<(), FormatterError> { // format and add Type & Punct - let mut value_pairs_iter = self.value_separator_pairs.iter().peekable(); - while let Some(pair) = value_pairs_iter.next() { - write!( - formatted_code, - "{}{}", - pair.0.span().as_str(), - pair.1.span().as_str(), - )?; - if value_pairs_iter.peek().is_some() { - formatted_code.push(' ') + let value_pairs = &self.value_separator_pairs; + + // Later on we may want to handle trailing commas for instances where + // `value_separator_pairs.len()` > 1 and the user wants to keep the trailing comma. + if self.value_separator_pairs.len() == 1 { + formatted_code.push_str(value_pairs.get(0).unwrap().0.span().as_str()) + } else { + for pair in value_pairs.iter() { + write!( + formatted_code, + "{}{} ", + pair.0.span().as_str(), + pair.1.span().as_str(), + )?; } } - formatted_code.pop(); // pop the ending comma - // add boxed type + // add final value, if any if let Some(final_value) = &self.final_value_opt { formatted_code.push_str(final_value.span().as_str()); } From 995ae52a2cd707e6838a36380e1108c66811b194 Mon Sep 17 00:00:00 2001 From: Chris O'Brien Date: Mon, 27 Jun 2022 19:45:32 -0500 Subject: [PATCH 17/17] fix punctuated --- sway-fmt-v2/src/fmt.rs | 2 +- sway-fmt-v2/src/utils/punctuated.rs | 22 +++++++++------------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 06d626f3d59..9a552374b98 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -239,7 +239,7 @@ enum Color { let sway_code_to_format = r#"contract; abi StorageMapExample { - #[storage(write,)]fn insert_into_map1(key: u64, value: u64); + #[storage(write)]fn insert_into_map1(key: u64, value: u64); fn hello(key: u64, value: u64); }"#; diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index b93bc61dc06..1690fc0a669 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -19,19 +19,15 @@ where // format and add Type & Punct let value_pairs = &self.value_separator_pairs; - // Later on we may want to handle trailing commas for instances where - // `value_separator_pairs.len()` > 1 and the user wants to keep the trailing comma. - if self.value_separator_pairs.len() == 1 { - formatted_code.push_str(value_pairs.get(0).unwrap().0.span().as_str()) - } else { - for pair in value_pairs.iter() { - write!( - formatted_code, - "{}{} ", - pair.0.span().as_str(), - pair.1.span().as_str(), - )?; - } + // Later on we may want to handle instances + // where the user wants to keep the trailing commas. + for pair in value_pairs.iter() { + write!( + formatted_code, + "{}{} ", + pair.0.span().as_str(), + pair.1.span().as_str(), + )?; } // add final value, if any