From ee9abdbdcc3fa85a84e9fb46f8481f16974a6b56 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Tue, 5 Jul 2022 15:50:02 +0300 Subject: [PATCH 01/44] CommentedTokenTree::Comment case for span comment map implemented --- sway-fmt-v2/src/utils.rs | 1 + sway-fmt-v2/src/utils/comments.rs | 78 +++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 sway-fmt-v2/src/utils/comments.rs diff --git a/sway-fmt-v2/src/utils.rs b/sway-fmt-v2/src/utils.rs index 8d97a0a8c28..a0273d39956 100644 --- a/sway-fmt-v2/src/utils.rs +++ b/sway-fmt-v2/src/utils.rs @@ -1,5 +1,6 @@ pub(crate) mod attribute; pub(crate) mod bracket; +pub(crate) mod comments; pub(crate) mod generics; pub(crate) mod indent_style; pub(crate) mod item; diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs new file mode 100644 index 00000000000..522bc25a2e2 --- /dev/null +++ b/sway-fmt-v2/src/utils/comments.rs @@ -0,0 +1,78 @@ +use anyhow::Result; +use std::{cmp::Ordering, collections::BTreeMap, sync::Arc}; +use sway_parse::token::{lex_commented, Comment, CommentedTokenTree}; + +/// Represents a span for the comments in a spesific file +/// A stripped down version of sway-types::src::Span +#[derive(PartialEq, Eq, Debug)] +pub struct CommentSpan { + // The byte position in the string of the start of the span. + start: usize, + // The byte position in the string of the end of the span. + end: usize, +} + +impl Ord for CommentSpan { + fn cmp(&self, other: &Self) -> Ordering { + self.start.cmp(&other.start) + } +} + +impl PartialOrd for CommentSpan { + fn partial_cmp(&self, other: &CommentSpan) -> Option { + Some(self.cmp(other)) + } +} + +pub type CommentMap = BTreeMap; + +/// Get the CommentedTokenStream and collect the spans -> Comment mapping for the input source +/// code. +pub fn construct_comment_map(input: Arc) -> Result { + let mut comment_map = BTreeMap::new(); + + // pass the input through lexer + let commented_token_stream = lex_commented(&input, 0, input.len(), None)?; + let tts = commented_token_stream.token_trees().iter(); + + for comment in tts { + if let CommentedTokenTree::Comment(comment) = comment { + let comment_span = CommentSpan { + start: comment.span.start(), + end: comment.span.end(), + }; + comment_map.insert(comment_span, comment.clone()); + } + // TODO: implement CommentedTokenTree::Tree case for getting the comments inside code + // blocks + } + Ok(comment_map) +} + +#[cfg(test)] +mod tests { + use super::{construct_comment_map, CommentSpan}; + use std::{ops::Bound::Included, sync::Arc}; + + #[test] + fn test_comment_span_map() { + let input = r#" + // Single-line comment. + struct Foo { + /* multi- + * line- + * comment */ + bar: i32, + } + "#; + let map = construct_comment_map(Arc::from(input)).unwrap(); + assert!(map.len() != 0); + let range_start_span = CommentSpan { start: 0, end: 32 }; + let range_end_span = CommentSpan { start: 33, end: 34 }; + let found_comment = map + .range((Included(range_start_span), Included(range_end_span))) + .last() + .unwrap(); + assert_eq!(found_comment.1.span.as_str(), "// Single-line comment."); + } +} From 6b6681a48da8559daa88fabf5f9ebb1aa564813c Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 6 Jul 2022 15:44:15 +0300 Subject: [PATCH 02/44] CommentSpan ordering fix and test added --- sway-fmt-v2/src/utils/comments.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 522bc25a2e2..f49b00b809a 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -4,7 +4,7 @@ use sway_parse::token::{lex_commented, Comment, CommentedTokenTree}; /// Represents a span for the comments in a spesific file /// A stripped down version of sway-types::src::Span -#[derive(PartialEq, Eq, Debug)] +#[derive(PartialEq, Eq, Debug, Clone)] pub struct CommentSpan { // The byte position in the string of the start of the span. start: usize, @@ -14,7 +14,12 @@ pub struct CommentSpan { impl Ord for CommentSpan { fn cmp(&self, other: &Self) -> Ordering { - self.start.cmp(&other.start) + // If the starting position is the same encapsulatig span (i.e, wider one) should come + // first + match self.start.cmp(&other.start) { + Ordering::Equal => self.end.cmp(&other.end), + ord => ord, + } } } @@ -54,6 +59,21 @@ mod tests { use super::{construct_comment_map, CommentSpan}; use std::{ops::Bound::Included, sync::Arc}; + #[test] + fn test_comment_span_ordering() { + let first_span = CommentSpan { start: 2, end: 4 }; + let second_span = CommentSpan { start: 2, end: 6 }; + let third_span = CommentSpan { start: 4, end: 7 }; + + let mut vec = vec![second_span.clone(), third_span.clone(), first_span.clone()]; + vec.sort(); + + assert_eq!(vec[0], first_span); + assert_eq!(vec[1], second_span); + assert_eq!(vec[2], third_span); + + } + #[test] fn test_comment_span_map() { let input = r#" From be4511cb7e554dc54e1bf6abb7fe7cc241cd9d7c Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 6 Jul 2022 15:45:43 +0300 Subject: [PATCH 03/44] clippy --- sway-fmt-v2/src/utils/comments.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index f49b00b809a..d8d0549b4a8 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -86,7 +86,7 @@ mod tests { } "#; let map = construct_comment_map(Arc::from(input)).unwrap(); - assert!(map.len() != 0); + assert!(!map.is_empty()); let range_start_span = CommentSpan { start: 0, end: 32 }; let range_end_span = CommentSpan { start: 33, end: 34 }; let found_comment = map From 9dc606a9721b5ff1fe25c58e85e409687727410a Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 6 Jul 2022 16:35:41 +0300 Subject: [PATCH 04/44] Handle in-block and next-to item cases for comment map generation --- sway-fmt-v2/src/utils/comments.rs | 89 +++++++++++++++++++++++++++---- 1 file changed, 80 insertions(+), 9 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index d8d0549b4a8..832e910150d 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -1,6 +1,6 @@ use anyhow::Result; use std::{cmp::Ordering, collections::BTreeMap, sync::Arc}; -use sway_parse::token::{lex_commented, Comment, CommentedTokenTree}; +use sway_parse::token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}; /// Represents a span for the comments in a spesific file /// A stripped down version of sway-types::src::Span @@ -41,17 +41,32 @@ pub fn construct_comment_map(input: Arc) -> Result { let tts = commented_token_stream.token_trees().iter(); for comment in tts { - if let CommentedTokenTree::Comment(comment) = comment { + get_comment_from_token_stream(comment, &mut comment_map); + } + Ok(comment_map) +} + +/// Get `Comment` from the token stream and insert it with its span to the `CommentMap`. +/// Handles both the standalone and in-block comments. +fn get_comment_from_token_stream( + commented_token_tree: &CommentedTokenTree, + comment_map: &mut CommentMap, +) { + match commented_token_tree { + CommentedTokenTree::Comment(comment) => { let comment_span = CommentSpan { start: comment.span.start(), end: comment.span.end(), }; comment_map.insert(comment_span, comment.clone()); } - // TODO: implement CommentedTokenTree::Tree case for getting the comments inside code - // blocks + CommentedTokenTree::Tree(CommentedTree::Group(group)) => { + for item in group.token_stream.token_trees().iter() { + get_comment_from_token_stream(item, comment_map); + } + } + _ => {} } - Ok(comment_map) } #[cfg(test)] @@ -62,8 +77,8 @@ mod tests { #[test] fn test_comment_span_ordering() { let first_span = CommentSpan { start: 2, end: 4 }; - let second_span = CommentSpan { start: 2, end: 6 }; - let third_span = CommentSpan { start: 4, end: 7 }; + let second_span = CommentSpan { start: 2, end: 6 }; + let third_span = CommentSpan { start: 4, end: 7 }; let mut vec = vec![second_span.clone(), third_span.clone(), first_span.clone()]; vec.sort(); @@ -71,13 +86,13 @@ mod tests { assert_eq!(vec[0], first_span); assert_eq!(vec[1], second_span); assert_eq!(vec[2], third_span); - } #[test] - fn test_comment_span_map() { + fn test_comment_span_map_standalone_comment() { let input = r#" // Single-line comment. + let var = 256; // This is a comment. struct Foo { /* multi- * line- @@ -95,4 +110,60 @@ mod tests { .unwrap(); assert_eq!(found_comment.1.span.as_str(), "// Single-line comment."); } + #[test] + fn test_comment_span_map_standalone_next_to_item() { + let input = r#" + // Single-line comment. + let var = 256; // This is a comment. + struct Foo { + /* multi- + * line- + * comment */ + bar: i32, + } + "#; + let map = construct_comment_map(Arc::from(input)).unwrap(); + assert!(!map.is_empty()); + let range_start_span = CommentSpan { start: 40, end: 54 }; + let range_end_span = CommentSpan { + start: 100, + end: 115, + }; + let found_comment = map + .range((Included(range_start_span), Included(range_end_span))) + .last() + .unwrap(); + assert_eq!(found_comment.1.span.as_str(), "// This is a comment."); + } + #[test] + fn test_comment_span_map_standalone_inside_block() { + let input = r#" + // Single-line comment. + let var = 256; // This is a comment. + struct Foo { + /* multi- + * line- + * comment */ + bar: i32, + } + "#; + let map = construct_comment_map(Arc::from(input)).unwrap(); + assert!(!map.is_empty()); + let range_start_span = CommentSpan { + start: 110, + end: 116, + }; + let range_end_span = CommentSpan { + start: 200, + end: 201, + }; + let found_comment = map + .range((Included(range_start_span), Included(range_end_span))) + .last() + .unwrap(); + assert_eq!( + found_comment.1.span.as_str(), + "/* multi-\n * line-\n * comment *" + ); + } } From ddfb0076af052a058d21ea3ccc1c08819b39eebe Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 6 Jul 2022 17:27:08 +0300 Subject: [PATCH 05/44] Comments in between items are added correctly. --- sway-fmt-v2/src/error.rs | 2 ++ sway-fmt-v2/src/fmt.rs | 34 ++++++++++++++++++++++++++++--- sway-fmt-v2/src/utils/comments.rs | 25 +++++++++++++++++------ 3 files changed, 52 insertions(+), 9 deletions(-) diff --git a/sway-fmt-v2/src/error.rs b/sway-fmt-v2/src/error.rs index d1b021c871b..d9b37cc5728 100644 --- a/sway-fmt-v2/src/error.rs +++ b/sway-fmt-v2/src/error.rs @@ -7,6 +7,8 @@ pub enum FormatterError { ParseFileError(#[from] sway_parse::ParseFileError), #[error("Error formatting a message into a stream: {0}")] FormatError(#[from] std::fmt::Error), + #[error("Error while lexing file: {0}")] + LexError(#[from] sway_parse::LexError), } #[derive(Debug, Error)] diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 34e12ab81a3..1bde4415ed0 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -1,8 +1,16 @@ use crate::utils::{ - indent_style::Shape, newline_style::apply_newline_style, program_type::insert_program_type, + comments::{construct_comment_map, CommentSpan, FormatComment}, + indent_style::Shape, + newline_style::apply_newline_style, + program_type::insert_program_type, +}; +use std::{ + ops::Bound::{Excluded, Included}, + path::Path, + sync::Arc, }; -use std::{path::Path, sync::Arc}; use sway_core::BuildConfig; +use sway_types::Spanned; pub use crate::{ config::manifest::Config, @@ -42,7 +50,7 @@ impl Formatter { ) -> Result { let path = build_config.map(|build_config| build_config.canonical_root_module()); let src_len = src.len(); - let module = sway_parse::parse_file(src, path)?; + let module = sway_parse::parse_file(src.clone(), path)?; // Get parsed items let items = module.items; // Get the program type (script, predicate, contract or library) @@ -57,14 +65,34 @@ impl Formatter { // Insert program type to the formatted code. insert_program_type(&mut raw_formatted_code, program_type); + // Get the span-comment map + let comment_map = construct_comment_map(src)?; + + // Start with default span where start and end is 0. + let mut previous_item_span = CommentSpan::default(); // Insert parsed & formatted items into the formatted code. let mut iter = items.iter().peekable(); while let Some(item) = iter.next() { + // get current item span + // TODO create a util for this in comments.rs + let current_item_span = CommentSpan { + start: item.span().start(), + end: item.span().end(), + }; + // Check between previous item and current item for a comment + let comments = + comment_map.range((Included(&previous_item_span), Excluded(¤t_item_span))); + // Format each comment in between the previous formatted item and current item + for comment in comments { + comment.1.format(&mut raw_formatted_code, self)?; + raw_formatted_code.push('\n'); + } // format Annotated item.format(&mut raw_formatted_code, self)?; if iter.peek().is_some() { raw_formatted_code.push('\n'); } + previous_item_span = current_item_span; } let mut formatted_code = String::from(&raw_formatted_code); diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 832e910150d..de7ca17c909 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -1,15 +1,15 @@ -use anyhow::Result; -use std::{cmp::Ordering, collections::BTreeMap, sync::Arc}; +use crate::fmt::{Formatter, FormatterError}; +use std::{cmp::Ordering, collections::BTreeMap, fmt::Write, sync::Arc}; use sway_parse::token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}; /// Represents a span for the comments in a spesific file /// A stripped down version of sway-types::src::Span -#[derive(PartialEq, Eq, Debug, Clone)] +#[derive(PartialEq, Eq, Debug, Clone, Default)] pub struct CommentSpan { // The byte position in the string of the start of the span. - start: usize, + pub start: usize, // The byte position in the string of the end of the span. - end: usize, + pub end: usize, } impl Ord for CommentSpan { @@ -33,7 +33,7 @@ pub type CommentMap = BTreeMap; /// Get the CommentedTokenStream and collect the spans -> Comment mapping for the input source /// code. -pub fn construct_comment_map(input: Arc) -> Result { +pub fn construct_comment_map(input: Arc) -> Result { let mut comment_map = BTreeMap::new(); // pass the input through lexer @@ -69,6 +69,19 @@ fn get_comment_from_token_stream( } } +pub trait FormatComment { + fn format(&self, line: &mut String, formatter: &mut Formatter) -> Result<(), FormatterError>; +} + +// Currently we are not formatting the comment itself. We are simply pushing the comment to the +// line when it is called. +impl FormatComment for Comment { + fn format(&self, line: &mut String, _formatter: &mut Formatter) -> Result<(), FormatterError> { + write!(line, "{}", self.span.as_str())?; + Ok(()) + } +} + #[cfg(test)] mod tests { use super::{construct_comment_map, CommentSpan}; From fe5c851102c4fae73837d5e228ddb1f92a7575ce Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 7 Jul 2022 18:42:23 +0300 Subject: [PATCH 06/44] remove premature comment addition --- sway-fmt-v2/src/fmt.rs | 34 +++------------------------------- 1 file changed, 3 insertions(+), 31 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 1bde4415ed0..34e12ab81a3 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -1,16 +1,8 @@ use crate::utils::{ - comments::{construct_comment_map, CommentSpan, FormatComment}, - indent_style::Shape, - newline_style::apply_newline_style, - program_type::insert_program_type, -}; -use std::{ - ops::Bound::{Excluded, Included}, - path::Path, - sync::Arc, + indent_style::Shape, newline_style::apply_newline_style, program_type::insert_program_type, }; +use std::{path::Path, sync::Arc}; use sway_core::BuildConfig; -use sway_types::Spanned; pub use crate::{ config::manifest::Config, @@ -50,7 +42,7 @@ impl Formatter { ) -> Result { let path = build_config.map(|build_config| build_config.canonical_root_module()); let src_len = src.len(); - let module = sway_parse::parse_file(src.clone(), path)?; + let module = sway_parse::parse_file(src, path)?; // Get parsed items let items = module.items; // Get the program type (script, predicate, contract or library) @@ -65,34 +57,14 @@ impl Formatter { // Insert program type to the formatted code. insert_program_type(&mut raw_formatted_code, program_type); - // Get the span-comment map - let comment_map = construct_comment_map(src)?; - - // Start with default span where start and end is 0. - let mut previous_item_span = CommentSpan::default(); // Insert parsed & formatted items into the formatted code. let mut iter = items.iter().peekable(); while let Some(item) = iter.next() { - // get current item span - // TODO create a util for this in comments.rs - let current_item_span = CommentSpan { - start: item.span().start(), - end: item.span().end(), - }; - // Check between previous item and current item for a comment - let comments = - comment_map.range((Included(&previous_item_span), Excluded(¤t_item_span))); - // Format each comment in between the previous formatted item and current item - for comment in comments { - comment.1.format(&mut raw_formatted_code, self)?; - raw_formatted_code.push('\n'); - } // format Annotated item.format(&mut raw_formatted_code, self)?; if iter.peek().is_some() { raw_formatted_code.push('\n'); } - previous_item_span = current_item_span; } let mut formatted_code = String::from(&raw_formatted_code); From 06b5968c61187c882f681179290e5bb74d1196e6 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Fri, 8 Jul 2022 13:30:24 +0300 Subject: [PATCH 07/44] removed FormatComment trait --- sway-fmt-v2/src/utils/comments.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index de7ca17c909..931576df83a 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -69,19 +69,6 @@ fn get_comment_from_token_stream( } } -pub trait FormatComment { - fn format(&self, line: &mut String, formatter: &mut Formatter) -> Result<(), FormatterError>; -} - -// Currently we are not formatting the comment itself. We are simply pushing the comment to the -// line when it is called. -impl FormatComment for Comment { - fn format(&self, line: &mut String, _formatter: &mut Formatter) -> Result<(), FormatterError> { - write!(line, "{}", self.span.as_str())?; - Ok(()) - } -} - #[cfg(test)] mod tests { use super::{construct_comment_map, CommentSpan}; From d9cb274435190e309b1b3753687b00f1abf23fe1 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Fri, 8 Jul 2022 13:38:50 +0300 Subject: [PATCH 08/44] rename: get_comment_from_token_stream to collect_comments_from_token_stream, rename: construct_comment_map to comment_map_from_src --- sway-fmt-v2/src/utils/comments.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 931576df83a..375cdc80f53 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -1,5 +1,5 @@ -use crate::fmt::{Formatter, FormatterError}; -use std::{cmp::Ordering, collections::BTreeMap, fmt::Write, sync::Arc}; +use crate::fmt::FormatterError; +use std::{cmp::Ordering, collections::BTreeMap, sync::Arc}; use sway_parse::token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}; /// Represents a span for the comments in a spesific file @@ -33,7 +33,7 @@ pub type CommentMap = BTreeMap; /// Get the CommentedTokenStream and collect the spans -> Comment mapping for the input source /// code. -pub fn construct_comment_map(input: Arc) -> Result { +pub fn comment_map_from_src(input: Arc) -> Result { let mut comment_map = BTreeMap::new(); // pass the input through lexer @@ -41,14 +41,14 @@ pub fn construct_comment_map(input: Arc) -> Result { for item in group.token_stream.token_trees().iter() { - get_comment_from_token_stream(item, comment_map); + collect_comments_from_token_stream(item, comment_map); } } _ => {} @@ -71,7 +71,7 @@ fn get_comment_from_token_stream( #[cfg(test)] mod tests { - use super::{construct_comment_map, CommentSpan}; + use super::{comment_map_from_src, CommentSpan}; use std::{ops::Bound::Included, sync::Arc}; #[test] @@ -100,7 +100,7 @@ mod tests { bar: i32, } "#; - let map = construct_comment_map(Arc::from(input)).unwrap(); + let map = comment_map_from_src(Arc::from(input)).unwrap(); assert!(!map.is_empty()); let range_start_span = CommentSpan { start: 0, end: 32 }; let range_end_span = CommentSpan { start: 33, end: 34 }; @@ -122,7 +122,7 @@ mod tests { bar: i32, } "#; - let map = construct_comment_map(Arc::from(input)).unwrap(); + let map = comment_map_from_src(Arc::from(input)).unwrap(); assert!(!map.is_empty()); let range_start_span = CommentSpan { start: 40, end: 54 }; let range_end_span = CommentSpan { @@ -147,7 +147,7 @@ mod tests { bar: i32, } "#; - let map = construct_comment_map(Arc::from(input)).unwrap(); + let map = comment_map_from_src(Arc::from(input)).unwrap(); assert!(!map.is_empty()); let range_start_span = CommentSpan { start: 110, From bf9dcce30051ebc9837f9c95ac61b966167eb480 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Tue, 12 Jul 2022 13:03:16 +0300 Subject: [PATCH 09/44] comment ordering corrected --- sway-fmt-v2/src/utils/comments.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 375cdc80f53..b412f4bfaab 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -17,7 +17,7 @@ impl Ord for CommentSpan { // If the starting position is the same encapsulatig span (i.e, wider one) should come // first match self.start.cmp(&other.start) { - Ordering::Equal => self.end.cmp(&other.end), + Ordering::Equal => other.end.cmp(&self.end), ord => ord, } } @@ -76,8 +76,8 @@ mod tests { #[test] fn test_comment_span_ordering() { - let first_span = CommentSpan { start: 2, end: 4 }; - let second_span = CommentSpan { start: 2, end: 6 }; + let first_span = CommentSpan { start: 2, end: 6 }; + let second_span = CommentSpan { start: 2, end: 4 }; let third_span = CommentSpan { start: 4, end: 7 }; let mut vec = vec![second_span.clone(), third_span.clone(), first_span.clone()]; From 0f6d01ec24784f70ccecd2d5f5f6a1926b6864ed Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Tue, 12 Jul 2022 16:12:56 +0300 Subject: [PATCH 10/44] Comment handling for inside Struct block implemented --- Cargo.lock | 1 + sway-fmt-v2/Cargo.toml | 1 + sway-fmt-v2/src/error.rs | 2 + sway-fmt-v2/src/fmt.rs | 12 +- sway-fmt-v2/src/items/item_struct.rs | 27 ++++- sway-fmt-v2/src/utils/comments.rs | 165 ++++++++++++++++++++++++++- sway-fmt-v2/src/utils/item.rs | 23 +++- sway-fmt-v2/src/utils/punctuated.rs | 17 +++ 8 files changed, 240 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5eef4c0f10c..838c0cd4b67 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3659,6 +3659,7 @@ version = "0.18.0" dependencies = [ "anyhow", "forc-util", + "ropey", "serde", "serde_ignored", "sway-core", diff --git a/sway-fmt-v2/Cargo.toml b/sway-fmt-v2/Cargo.toml index 2913eb3eecb..67f97060a03 100644 --- a/sway-fmt-v2/Cargo.toml +++ b/sway-fmt-v2/Cargo.toml @@ -12,6 +12,7 @@ description = "Sway sway-fmt-v2." [dependencies] anyhow = "1" forc-util = { version = "0.18.0", path = "../forc-util" } +ropey = "1.5" serde = { version = "1.0", features = ["derive"] } serde_ignored = "0.1" sway-core = { version = "0.18.0", path = "../sway-core" } diff --git a/sway-fmt-v2/src/error.rs b/sway-fmt-v2/src/error.rs index d9b37cc5728..5fda59ad932 100644 --- a/sway-fmt-v2/src/error.rs +++ b/sway-fmt-v2/src/error.rs @@ -9,6 +9,8 @@ pub enum FormatterError { FormatError(#[from] std::fmt::Error), #[error("Error while lexing file: {0}")] LexError(#[from] sway_parse::LexError), + #[error("Error while adding comments")] + CommentError, } #[derive(Debug, Error)] diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 62511699a33..1a3e2941229 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -1,5 +1,6 @@ use crate::utils::{ - indent_style::Shape, newline_style::apply_newline_style, program_type::insert_program_type, + comments::handle_comments, indent_style::Shape, newline_style::apply_newline_style, + program_type::insert_program_type, }; use std::{path::Path, sync::Arc}; use sway_core::BuildConfig; @@ -42,7 +43,7 @@ impl Formatter { ) -> Result { let path = build_config.map(|build_config| build_config.canonical_root_module()); let src_len = src.len(); - let module = sway_parse::parse_file(src, path)?; + let module = sway_parse::parse_file(src.clone(), path.clone())?; // Get parsed items let items = module.items; // Get the program type (script, predicate, contract or library) @@ -68,6 +69,13 @@ impl Formatter { } let mut formatted_code = String::from(&raw_formatted_code); + // Add comments + handle_comments( + src, + Arc::from(formatted_code.clone()), + path, + &mut formatted_code, + )?; // Replace newlines with specified `NewlineStyle` apply_newline_style( self.config.whitespace.newline_style, diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index 883caa0f223..da82f0f116b 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -1,7 +1,11 @@ use crate::{ config::{items::ItemBraceStyle, user_def::FieldAlignment}, fmt::{Format, FormattedCode, Formatter}, - utils::{bracket::CurlyBrace, item::ItemLenChars}, + utils::{ + bracket::CurlyBrace, + comments::{CommentSpan, CommentVisitor}, + item::ItemLenChars, + }, FormatterError, }; use std::fmt::Write; @@ -240,3 +244,24 @@ impl CurlyBrace for ItemStruct { Ok(()) } } + +impl CommentVisitor for ItemStruct { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + // Add visibility token's span if it exists + if let Some(visibility) = &self.visibility { + collected_spans.push(CommentSpan::from_span(visibility.span())); + } + // Add struct_token's span + collected_spans.push(CommentSpan::from_span(self.struct_token.span())); + // Add name's span + collected_spans.push(CommentSpan::from_span(self.name.span())); + // Add generics' span if it exist + if let Some(generics) = &self.generics { + collected_spans.push(CommentSpan::from_span(generics.parameters.span())) + } + // Collect fields' spans. + collected_spans.append(&mut self.fields.collect_spans()); + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index b412f4bfaab..f373c222f79 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -1,7 +1,18 @@ -use crate::fmt::FormatterError; -use std::{cmp::Ordering, collections::BTreeMap, sync::Arc}; -use sway_parse::token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}; - +use crate::fmt::{FormattedCode, FormatterError}; +use ropey::Rope; +use std::{ + cmp::Ordering, + collections::BTreeMap, + fmt::Write, + ops::Bound::{Excluded, Included}, + path::PathBuf, + sync::Arc, +}; +use sway_parse::{ + token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, + Braces, Module, +}; +use sway_types::{Span, Spanned}; /// Represents a span for the comments in a spesific file /// A stripped down version of sway-types::src::Span #[derive(PartialEq, Eq, Debug, Clone, Default)] @@ -12,6 +23,16 @@ pub struct CommentSpan { pub end: usize, } +impl CommentSpan { + /// Takes `start` and `end` from `sway::types::Span` and constructs a `CommentSpan` + pub fn from_span(span: Span) -> CommentSpan { + CommentSpan { + start: span.start(), + end: span.end(), + } + } +} + impl Ord for CommentSpan { fn cmp(&self, other: &Self) -> Ordering { // If the starting position is the same encapsulatig span (i.e, wider one) should come @@ -69,6 +90,142 @@ fn collect_comments_from_token_stream( } } +impl CommentVisitor for Braces +where + T: CommentVisitor + Clone, +{ + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + let mut opening_brace_span = CommentSpan::from_span(self.span()); + opening_brace_span.end = opening_brace_span.start + 1; + // Add opening brace's CommentSpan + collected_spans.push(opening_brace_span); + // Add T's collected CommentSpan + collected_spans.append(&mut self.clone().into_inner().collect_spans()); + // Add closing brace's CommentSpan + let mut closing_brace_span = CommentSpan::from_span(self.span()); + closing_brace_span.start = closing_brace_span.end - 1; + collected_spans + } +} + +/// Handles comments by first creating the CommentMap which is used for fast seaching comments. +/// Traverses items for finding a comment in unformatted input and placing it in correct place in formatted output. +pub fn handle_comments( + unformatted_input: Arc, + formatted_input: Arc, + path: Option>, + formatted_code: &mut FormattedCode, +) -> Result<(), FormatterError> { + // Collect Span -> Comment mapping from unformatted input + let comment_map = comment_map_from_src(unformatted_input.clone())?; + + // Parse unformatted code so that we can get the spans of items in their original places. + // This is required since we collected the spans in from unformatted source file. + let unformatted_module = sway_parse::parse_file(unformatted_input, path.clone())?; + // After the formatting items should be the same but their spans will be changed since we applied formatting to them. + let formatted_module = sway_parse::parse_file(formatted_input, path)?; + // Actually insert the comments + add_comments( + comment_map, + &unformatted_module, + &formatted_module, + formatted_code, + )?; + Ok(()) +} + +/// Adds the comments from comment_map to correct places in the formatted code. This requires us +/// both the unformatted and formatted code's AST as they will have different spans for their +/// nodes. While traversing the unformatted AST, `add_comments` searches for comments. If there is a comment found +/// simply find the corresponding node from the formatted ast to retrieve the correct span to place +/// the comment. +fn add_comments( + comment_map: CommentMap, + unformatted_module: &Module, + formatted_module: &Module, + formatted_code: &mut FormattedCode, +) -> Result<(), FormatterError> { + let unformatted_items = &unformatted_module.items; + let formatted_items = &formatted_module.items; + + for (unformatted_item, formatted_item) in unformatted_items.iter().zip(formatted_items.iter()) { + // Search comments for possible places inside the item. + let unformatted_item_spans = unformatted_item.collect_spans(); + let formatted_item_spans = formatted_item.collect_spans(); + + // We will definetly have a span in the collected span since for a source code to be parsed as an item there should be some tokens present. + let mut previous_unformatted_span = unformatted_item_spans + .first() + .ok_or(FormatterError::CommentError)?; + let mut previous_formatted_span = formatted_item_spans + .first() + .ok_or(FormatterError::CommentError)?; + // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted + // as the total length of comments we added in previous iterations. + let mut offset = 0; + // Iterate over the possible spans to check for a comment + for (unformatted_cur_span, formatted_cur_span) in unformatted_item_spans + .iter() + .zip(formatted_item_spans.iter()) + { + let comments_found = get_comments_between_spans( + previous_unformatted_span, + unformatted_cur_span, + &comment_map, + ); + if !comments_found.is_empty() { + offset += insert_after_span( + previous_formatted_span, + comments_found, + offset, + formatted_code, + )?; + } + previous_unformatted_span = unformatted_cur_span; + previous_formatted_span = formatted_cur_span; + } + } + Ok(()) +} + +/// Returns a list of comments between given spans +fn get_comments_between_spans( + from: &CommentSpan, + to: &CommentSpan, + comment_map: &CommentMap, +) -> Vec { + comment_map + .range((Included(from), Excluded(to))) + .map(|comment_tuple| comment_tuple.1.clone()) + .collect() +} + +/// Inserts after given span and returns the offset. +fn insert_after_span( + from: &CommentSpan, + comments_to_insert: Vec, + offset: usize, + formatted_code: &mut FormattedCode, +) -> Result { + let mut src_rope = Rope::from_str(formatted_code); + // prepare the comment str + let mut comment_str = String::from(comments_to_insert[0].span.as_str()); + for comment in comments_to_insert.iter().skip(1) { + write!(comment_str, "\n{}", comment.span.as_str())?; + } + src_rope.insert(from.end + offset, &comment_str); + formatted_code.clear(); + formatted_code.push_str(&src_rope.to_string()); + Ok(comment_str.chars().count()) +} + +/// While searching for a comment we need the possible places a comment can be placed in a structure +/// `collect_spans` collects all field's spans so that we can check in between them. +pub trait CommentVisitor { + fn collect_spans(&self) -> Vec; +} + #[cfg(test)] mod tests { use super::{comment_map_from_src, CommentSpan}; diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index fbcc270e141..52ba0ffa4b1 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -1,6 +1,27 @@ -use crate::fmt::{Format, FormattedCode, Formatter, FormatterError}; +use crate::{ + fmt::{Format, FormattedCode, Formatter, FormatterError}, + utils::comments::{CommentSpan, CommentVisitor}, +}; use sway_parse::{Item, ItemKind::*}; +impl CommentVisitor for Item { + fn collect_spans(&self) -> Vec { + match &self.value { + Use(_) => todo!(), + Struct(item_struct) => item_struct.collect_spans(), + Enum(_) => todo!(), + Fn(_) => todo!(), + Trait(_) => todo!(), + Impl(_) => todo!(), + Abi(_) => todo!(), + Const(_) => todo!(), + Storage(_) => todo!(), + Break(_) => todo!(), + Continue(_) => todo!(), + } + } +} + impl Format for Item { fn format( &self, diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 3115bfc972b..8bd78a9a8cb 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -1,11 +1,28 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, + utils::comments::{CommentSpan, CommentVisitor}, FormatterError, }; use std::fmt::Write; use sway_parse::{keywords::CommaToken, punctuated::Punctuated, StorageField, TypeField}; use sway_types::{Ident, Spanned}; +impl CommentVisitor for Punctuated +where + T: Spanned, + P: Spanned, +{ + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + let value_pairs = &self.value_separator_pairs; + for pair in value_pairs.iter() { + collected_spans.push(CommentSpan::from_span(pair.0.span())); + collected_spans.push(CommentSpan::from_span(pair.1.span())); + } + collected_spans + } +} + impl Format for Punctuated where T: Format, From f8774ae4593eeb99bacfd43b53e813adc9045b07 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 02:30:35 +0300 Subject: [PATCH 11/44] More context collected for whitespace preserving --- sway-fmt-v2/src/utils/comments.rs | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index f373c222f79..af1beee1a5b 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -102,9 +102,10 @@ where collected_spans.push(opening_brace_span); // Add T's collected CommentSpan collected_spans.append(&mut self.clone().into_inner().collect_spans()); - // Add closing brace's CommentSpan let mut closing_brace_span = CommentSpan::from_span(self.span()); closing_brace_span.start = closing_brace_span.end - 1; + // Add closing brace's CommentSpan + collected_spans.push(closing_brace_span); collected_spans } } @@ -189,30 +190,44 @@ fn add_comments( Ok(()) } -/// Returns a list of comments between given spans +/// Returns a list of comments between given spans. For each comment returns the offset from the last item fn get_comments_between_spans( from: &CommentSpan, to: &CommentSpan, comment_map: &CommentMap, -) -> Vec { +) -> Vec<(Comment, usize)> { comment_map .range((Included(from), Excluded(to))) - .map(|comment_tuple| comment_tuple.1.clone()) + .map(|comment_tuple| { + ( + comment_tuple.1.clone(), + comment_tuple.1.span.start() - from.end, + ) + }) .collect() } /// Inserts after given span and returns the offset. fn insert_after_span( from: &CommentSpan, - comments_to_insert: Vec, + comments_to_insert: Vec<(Comment, usize)>, offset: usize, formatted_code: &mut FormattedCode, ) -> Result { let mut src_rope = Rope::from_str(formatted_code); // prepare the comment str - let mut comment_str = String::from(comments_to_insert[0].span.as_str()); + let mut comment_str = format!( + "{}{}", + &(0..comments_to_insert[0].1) + .map(|_| ' ') + .collect::(), + comments_to_insert[0].0.span.as_str() + ); for comment in comments_to_insert.iter().skip(1) { - write!(comment_str, "\n{}", comment.span.as_str())?; + let whitespaces = (0..(comment.1 - comment_str.len() - 1)) + .map(|_| ' ') + .collect::(); + write!(comment_str, "\n{}{}", whitespaces, comment.0.span.as_str())?; } src_rope.insert(from.end + offset, &comment_str); formatted_code.clear(); From 3bdc20bbf02b2b7223fdccb25f59e08a277dfec6 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 02:37:33 +0300 Subject: [PATCH 12/44] test for comments added --- sway-fmt-v2/src/fmt.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 1a3e2941229..7ce160a7f8b 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -399,6 +399,41 @@ where { let greeting = 42; greeting.to_string() +}"#; + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + assert_eq!(correct_sway_code, formatted_sway_code) + } + #[test] + fn test_comments() { + let sway_code_to_format = r#"contract; + +struct Foo { // Here I am 0 + + + + + // Here I am 1 + barasdd: u64, // Here i am 2 + // ----------------------- + // ---this is comment----- + // ----------------------- + + + + baz: bool, // Here i am 3 +}"#; + + let correct_sway_code = r#"contract; + +struct Foo { // Here I am 0 + // Here I am 1 + barasdd: u64, // Here i am 2 + // ----------------------- + // ---this is comment----- + // ----------------------- + baz: bool, // Here i am 3 }"#; let mut formatter = Formatter::default(); let formatted_sway_code = From 86b4786d485323802f8ca7ce722f52ee3fbf07d5 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 03:01:46 +0300 Subject: [PATCH 13/44] Added forgetten final value for punctuated --- sway-fmt-v2/src/utils/punctuated.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 8bd78a9a8cb..65c99410869 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -19,6 +19,9 @@ where collected_spans.push(CommentSpan::from_span(pair.0.span())); collected_spans.push(CommentSpan::from_span(pair.1.span())); } + if let Some(final_value) = &self.final_value_opt { + collected_spans.push(CommentSpan::from_span(final_value.span())); + } collected_spans } } From d603a8f3a354f11f3661fbad471bb66bf8001f17 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 03:03:43 +0300 Subject: [PATCH 14/44] removed test since it requires all item types to implement CommentVisitor --- sway-fmt-v2/src/fmt.rs | 35 ----------------------------------- 1 file changed, 35 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 7ce160a7f8b..1a3e2941229 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -399,41 +399,6 @@ where { let greeting = 42; greeting.to_string() -}"#; - let mut formatter = Formatter::default(); - let formatted_sway_code = - Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - assert_eq!(correct_sway_code, formatted_sway_code) - } - #[test] - fn test_comments() { - let sway_code_to_format = r#"contract; - -struct Foo { // Here I am 0 - - - - - // Here I am 1 - barasdd: u64, // Here i am 2 - // ----------------------- - // ---this is comment----- - // ----------------------- - - - - baz: bool, // Here i am 3 -}"#; - - let correct_sway_code = r#"contract; - -struct Foo { // Here I am 0 - // Here I am 1 - barasdd: u64, // Here i am 2 - // ----------------------- - // ---this is comment----- - // ----------------------- - baz: bool, // Here i am 3 }"#; let mut formatter = Formatter::default(); let formatted_sway_code = From 934fb84900652780e287972dc566e26e05257ff8 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 03:25:50 +0300 Subject: [PATCH 15/44] Until CommentVisitor implemented another check added for tests to pass --- sway-fmt-v2/src/utils/comments.rs | 5 +++++ sway-fmt-v2/src/utils/item.rs | 11 +---------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index af1beee1a5b..8d0f6026730 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -155,6 +155,10 @@ fn add_comments( let unformatted_item_spans = unformatted_item.collect_spans(); let formatted_item_spans = formatted_item.collect_spans(); + // TODO: Remove this once every item implements CommentVisitor. This is added to turn tests green + if unformatted_item_spans.first().is_none() || formatted_item_spans.first().is_none() { + return Ok(()); + } // We will definetly have a span in the collected span since for a source code to be parsed as an item there should be some tokens present. let mut previous_unformatted_span = unformatted_item_spans .first() @@ -162,6 +166,7 @@ fn add_comments( let mut previous_formatted_span = formatted_item_spans .first() .ok_or(FormatterError::CommentError)?; + // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted // as the total length of comments we added in previous iterations. let mut offset = 0; diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 52ba0ffa4b1..f33b7935339 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -7,17 +7,8 @@ use sway_parse::{Item, ItemKind::*}; impl CommentVisitor for Item { fn collect_spans(&self) -> Vec { match &self.value { - Use(_) => todo!(), Struct(item_struct) => item_struct.collect_spans(), - Enum(_) => todo!(), - Fn(_) => todo!(), - Trait(_) => todo!(), - Impl(_) => todo!(), - Abi(_) => todo!(), - Const(_) => todo!(), - Storage(_) => todo!(), - Break(_) => todo!(), - Continue(_) => todo!(), + _ => Vec::new(), } } } From d518b6741c2a88712e400aa12f0721b0cb74b1d7 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 14:32:11 +0300 Subject: [PATCH 16/44] CommentVisitor implemented for ItemEnum --- sway-fmt-v2/src/items/item_enum.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/sway-fmt-v2/src/items/item_enum.rs b/sway-fmt-v2/src/items/item_enum.rs index 3d869a7e407..09ebc0be692 100644 --- a/sway-fmt-v2/src/items/item_enum.rs +++ b/sway-fmt-v2/src/items/item_enum.rs @@ -1,7 +1,7 @@ use crate::{ config::{items::ItemBraceStyle, user_def::FieldAlignment}, fmt::{Format, FormattedCode, Formatter}, - utils::{bracket::CurlyBrace, item::ItemLenChars}, + utils::{bracket::CurlyBrace, item::ItemLenChars, comments::{CommentVisitor, CommentSpan}}, FormatterError, }; use std::fmt::Write; @@ -235,3 +235,23 @@ impl CurlyBrace for ItemEnum { Ok(()) } } +impl CommentVisitor for ItemEnum { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + // Add visibility token's span if it exists + if let Some(visibility) = &self.visibility { + collected_spans.push(CommentSpan::from_span(visibility.span())); + } + // Add enum_token's span + collected_spans.push(CommentSpan::from_span(self.enum_token.span())); + // Add name's span + collected_spans.push(CommentSpan::from_span(self.name.span())); + // Add generics' span if it exist + if let Some(generics) = &self.generics { + collected_spans.push(CommentSpan::from_span(generics.parameters.span())) + } + // Collect fields' spans. + collected_spans.append(&mut self.fields.collect_spans()); + collected_spans + } +} From 018effdc06c29e2258cc49a101761ee19618428a Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 15:00:36 +0300 Subject: [PATCH 17/44] Add comment test --- sway-fmt-v2/src/fmt.rs | 40 +++++++++++++++++++++++++++++ sway-fmt-v2/src/items/item_enum.rs | 6 ++++- sway-fmt-v2/src/utils/punctuated.rs | 2 +- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 1a3e2941229..93919aecfa3 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -405,4 +405,44 @@ where Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); assert_eq!(correct_sway_code, formatted_sway_code) } + #[test] + fn test_comments() { + let sway_code_to_format = r#"contract; + +pub struct Foo { // Here is a comment + // Trying some ASCII art + baz:u64, + + + + + bazzz:u64// ________ ___ ___ _______ ___ ___ ________ ________ ________ + // |\ _____\\ \|\ \|\ ___ \ |\ \ |\ \ |\ __ \|\ __ \|\ ____\ + // \ \ \__/\ \ \\\ \ \ __/|\ \ \ \ \ \ \ \ \|\ \ \ \|\ /\ \ \___|_ + // \ \ __\\ \ \\\ \ \ \_|/_\ \ \ \ \ \ \ \ __ \ \ __ \ \_____ \ + // \ \ \_| \ \ \\\ \ \ \_|\ \ \ \____ \ \ \____\ \ \ \ \ \ \|\ \|____|\ \ + // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ + // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ + // \|_________| +}"#; + let correct_sway_code = r#"contract; + +pub struct Foo { // Here is a comment + // Trying some ASCII art + baz: u64, + bazzz: u64,// ________ ___ ___ _______ ___ ___ ________ ________ ________ + // |\ _____\\ \|\ \|\ ___ \ |\ \ |\ \ |\ __ \|\ __ \|\ ____\ + // \ \ \__/\ \ \\\ \ \ __/|\ \ \ \ \ \ \ \ \|\ \ \ \|\ /\ \ \___|_ + // \ \ __\\ \ \\\ \ \ \_|/_\ \ \ \ \ \ \ \ __ \ \ __ \ \_____ \ + // \ \ \_| \ \ \\\ \ \ \_|\ \ \ \____ \ \ \____\ \ \ \ \ \ \|\ \|____|\ \ + // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ + // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ + // \|_________| +}"#; + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + println!("{}", formatted_sway_code); + assert_eq!(correct_sway_code, formatted_sway_code) + } } diff --git a/sway-fmt-v2/src/items/item_enum.rs b/sway-fmt-v2/src/items/item_enum.rs index 09ebc0be692..51adfaf41f8 100644 --- a/sway-fmt-v2/src/items/item_enum.rs +++ b/sway-fmt-v2/src/items/item_enum.rs @@ -1,7 +1,11 @@ use crate::{ config::{items::ItemBraceStyle, user_def::FieldAlignment}, fmt::{Format, FormattedCode, Formatter}, - utils::{bracket::CurlyBrace, item::ItemLenChars, comments::{CommentVisitor, CommentSpan}}, + utils::{ + bracket::CurlyBrace, + comments::{CommentSpan, CommentVisitor}, + item::ItemLenChars, + }, FormatterError, }; use std::fmt::Write; diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 65c99410869..76e557edf3e 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -16,7 +16,7 @@ where let mut collected_spans = Vec::new(); let value_pairs = &self.value_separator_pairs; for pair in value_pairs.iter() { - collected_spans.push(CommentSpan::from_span(pair.0.span())); + //collected_spans.push(CommentSpan::from_span(pair.0.span())); collected_spans.push(CommentSpan::from_span(pair.1.span())); } if let Some(final_value) = &self.final_value_opt { From 6cfc34ee8f7e2b5c98df222b332853de7b9eea58 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Wed, 13 Jul 2022 15:09:58 +0300 Subject: [PATCH 18/44] test extended to include enum --- sway-fmt-v2/src/fmt.rs | 28 ++++++++++++++++++++++++++++ sway-fmt-v2/src/utils/comments.rs | 13 ++++++------- sway-fmt-v2/src/utils/item.rs | 1 + 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 93919aecfa3..0b11cdec7bc 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -424,6 +424,22 @@ pub struct Foo { // Here is a comment // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ // \|_________| +} +pub enum Bazz { // Here is a comment + // Trying some ASCII art + baz: (), + + + + + bazzz: (),// ________ ___ ___ _______ ___ ___ ________ ________ ________ + // |\ _____\\ \|\ \|\ ___ \ |\ \ |\ \ |\ __ \|\ __ \|\ ____\ + // \ \ \__/\ \ \\\ \ \ __/|\ \ \ \ \ \ \ \ \|\ \ \ \|\ /\ \ \___|_ + // \ \ __\\ \ \\\ \ \ \_|/_\ \ \ \ \ \ \ \ __ \ \ __ \ \_____ \ + // \ \ \_| \ \ \\\ \ \ \_|\ \ \ \____ \ \ \____\ \ \ \ \ \ \|\ \|____|\ \ + // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ + // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ + // \|_________| }"#; let correct_sway_code = r#"contract; @@ -438,6 +454,18 @@ pub struct Foo { // Here is a comment // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ // \|_________| +} +pub enum Bazz { // Here is a comment + // Trying some ASCII art + baz: (), + bazzz: (),// ________ ___ ___ _______ ___ ___ ________ ________ ________ + // |\ _____\\ \|\ \|\ ___ \ |\ \ |\ \ |\ __ \|\ __ \|\ ____\ + // \ \ \__/\ \ \\\ \ \ __/|\ \ \ \ \ \ \ \ \|\ \ \ \|\ /\ \ \___|_ + // \ \ __\\ \ \\\ \ \ \_|/_\ \ \ \ \ \ \ \ __ \ \ __ \ \_____ \ + // \ \ \_| \ \ \\\ \ \ \_|\ \ \ \____ \ \ \____\ \ \ \ \ \ \|\ \|____|\ \ + // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ + // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ + // \|_________| }"#; let mut formatter = Formatter::default(); let formatted_sway_code = diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 8d0f6026730..303d6a8acd1 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -137,10 +137,9 @@ pub fn handle_comments( } /// Adds the comments from comment_map to correct places in the formatted code. This requires us -/// both the unformatted and formatted code's AST as they will have different spans for their -/// nodes. While traversing the unformatted AST, `add_comments` searches for comments. If there is a comment found -/// simply find the corresponding node from the formatted ast to retrieve the correct span to place -/// the comment. +/// both the unformatted and formatted code's items as they will have different spans for their +/// nodes. While traversing the unformatted items, `add_comments` searches for comments. If there is a comment found +/// place the comment. fn add_comments( comment_map: CommentMap, unformatted_module: &Module, @@ -150,6 +149,9 @@ fn add_comments( let unformatted_items = &unformatted_module.items; let formatted_items = &formatted_module.items; + // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted + // as the total length of comments we added in previous iterations. + let mut offset = 0; for (unformatted_item, formatted_item) in unformatted_items.iter().zip(formatted_items.iter()) { // Search comments for possible places inside the item. let unformatted_item_spans = unformatted_item.collect_spans(); @@ -167,9 +169,6 @@ fn add_comments( .first() .ok_or(FormatterError::CommentError)?; - // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted - // as the total length of comments we added in previous iterations. - let mut offset = 0; // Iterate over the possible spans to check for a comment for (unformatted_cur_span, formatted_cur_span) in unformatted_item_spans .iter() diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index f33b7935339..401749361dd 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -8,6 +8,7 @@ impl CommentVisitor for Item { fn collect_spans(&self) -> Vec { match &self.value { Struct(item_struct) => item_struct.collect_spans(), + Enum(item_enum) => item_enum.collect_spans(), _ => Vec::new(), } } From 40bb4162b5ebfd73591210135b62dd0f8b9ce06a Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 14 Jul 2022 21:16:46 +0300 Subject: [PATCH 19/44] CommentVisitor for ItemFn implemendted --- sway-fmt-v2/src/items/item_fn.rs | 70 ++++++++++++++++++++++++- sway-fmt-v2/src/utils/comments.rs | 35 ++++++++++++- sway-fmt-v2/src/utils/pattern.rs | 81 ++++++++++++++++++++++++++++- sway-fmt-v2/src/utils/punctuated.rs | 10 ++-- 4 files changed, 188 insertions(+), 8 deletions(-) diff --git a/sway-fmt-v2/src/items/item_fn.rs b/sway-fmt-v2/src/items/item_fn.rs index 10ecbe18205..7d2700c37ee 100644 --- a/sway-fmt-v2/src/items/item_fn.rs +++ b/sway-fmt-v2/src/items/item_fn.rs @@ -1,7 +1,10 @@ use crate::{ config::items::ItemBraceStyle, fmt::{Format, FormattedCode, Formatter, FormatterError}, - utils::bracket::{CurlyBrace, Parenthesis}, + utils::{ + bracket::{CurlyBrace, Parenthesis}, + comments::{CommentSpan, CommentVisitor}, + }, }; use std::fmt::Write; use sway_parse::{token::Delimiter, CodeBlockContents, FnArg, FnArgs, FnSignature, ItemFn}; @@ -204,3 +207,68 @@ impl Format for FnArg { Ok(()) } } + +impl CommentVisitor for FnSignature { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + // Add visibility token if it exists + if let Some(visibility) = &self.visibility { + collected_spans.push(CommentSpan::from_span(visibility.span())); + } + // Add fn_token + collected_spans.push(CommentSpan::from_span(self.fn_token.span())); + // Add name + collected_spans.push(CommentSpan::from_span(self.name.span())); + // Add generics if it exists + if let Some(generics) = &self.generics { + collected_spans.push(CommentSpan::from_span(generics.parameters.span())); + } + // Add spans for parameters + collected_spans.append(&mut self.arguments.collect_spans()); + // Add return type if it exists + if let Some((right_arrow_token, ty)) = &self.return_type_opt { + collected_spans.push(CommentSpan::from_span(right_arrow_token.span())); + collected_spans.push(CommentSpan::from_span(ty.span())); + } + // TODO add where, I will add where for all items at once. + collected_spans + } +} + +impl CommentVisitor for FnArgs { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + match &self { + FnArgs::Static(arg_static) => { + collected_spans.append(&mut arg_static.collect_spans()); + } + FnArgs::NonStatic { + self_token, + mutable_self, + args_opt, + } => { + collected_spans.push(CommentSpan::from_span(self_token.span())); + if let Some(mutable) = mutable_self { + collected_spans.push(CommentSpan::from_span(mutable.span())); + } + if let Some(args) = args_opt { + collected_spans.push(CommentSpan::from_span(args.0.span())); + collected_spans.append(&mut args.1.collect_spans()); + } + } + }; + collected_spans + } +} + +impl CommentVisitor for FnArg { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + collected_spans.append(&mut self.pattern.collect_spans()); + // Add ColonToken + collected_spans.push(CommentSpan::from_span(self.colon_token.span())); + // Add ty + collected_spans.push(CommentSpan::from_span(self.ty.span())); + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 303d6a8acd1..64fd415a9f5 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -9,8 +9,10 @@ use std::{ sync::Arc, }; use sway_parse::{ + brackets::Parens, + keywords::CommaToken, token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, - Braces, Module, + Braces, Module, TypeField, }; use sway_types::{Span, Spanned}; /// Represents a span for the comments in a spesific file @@ -110,6 +112,37 @@ where } } +impl CommentVisitor for Parens +where + T: CommentVisitor + Clone, +{ + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + let mut opening_paren_span = CommentSpan::from_span(self.span()); + opening_paren_span.end = opening_paren_span.start + 1; + // Add opening paren's span + collected_spans.push(opening_paren_span); + // Add T's collected CommentSpan + collected_spans.append(&mut self.clone().into_inner().collect_spans()); + let mut closing_paren_span = CommentSpan::from_span(self.span()); + closing_paren_span.start = closing_paren_span.end - 1; + // Add closing paren's CommentSpan + collected_spans.push(closing_paren_span); + collected_spans + } +} + +impl CommentVisitor for CommaToken { + fn collect_spans(&self) -> Vec { + vec![(CommentSpan::from_span(self.span()))] + } +} + +impl CommentVisitor for TypeField { + fn collect_spans(&self) -> Vec { + vec![(CommentSpan::from_span(self.span()))] + } +} /// Handles comments by first creating the CommentMap which is used for fast seaching comments. /// Traverses items for finding a comment in unformatted input and placing it in correct place in formatted output. pub fn handle_comments( diff --git a/sway-fmt-v2/src/utils/pattern.rs b/sway-fmt-v2/src/utils/pattern.rs index 8f5ed66ae49..b0157acacf1 100644 --- a/sway-fmt-v2/src/utils/pattern.rs +++ b/sway-fmt-v2/src/utils/pattern.rs @@ -1,4 +1,7 @@ -use crate::fmt::*; +use crate::{ + fmt::*, + utils::comments::{CommentSpan, CommentVisitor}, +}; use std::fmt::Write; use sway_parse::{token::Delimiter, Pattern, PatternStructField}; use sway_types::Spanned; @@ -114,3 +117,79 @@ impl Format for PatternStructField { Ok(()) } } + +impl CommentVisitor for Pattern { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + match self { + Pattern::Wildcard { underscore_token } => { + collected_spans.push(CommentSpan::from_span(underscore_token.span())); + } + Pattern::Var { mutable, name } => { + // Add mutable if it exists + if let Some(mutable) = mutable { + collected_spans.push(CommentSpan::from_span(mutable.span())); + } + // Add name + collected_spans.push(CommentSpan::from_span(name.span())); + } + Pattern::Literal(literal) => { + collected_spans.push(CommentSpan::from_span(literal.span())); + } + Pattern::Constant(constant) => { + // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr + // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted + // root::parent/* i am a comment*/::child + // I am not sure if this is something the language will allow. + collected_spans.push(CommentSpan::from_span(constant.span())); + todo!(); + } + Pattern::Constructor { path, args } => { + // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr + // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted + // root::parent/* i am a comment*/::child + // I am not sure if this is something the language will allow. + collected_spans.push(CommentSpan::from_span(path.span())); + collected_spans.append(&mut args.collect_spans()); + } + Pattern::Struct { path, fields } => { + // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr + // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted + // root::parent/* i am a comment*/::child + // I am not sure if this is something the language will allow. + collected_spans.push(CommentSpan::from_span(path.span())); + collected_spans.append(&mut fields.collect_spans()); + } + Pattern::Tuple(tuple) => { + collected_spans.append(&mut tuple.collect_spans()); + } + } + collected_spans + } +} + +impl CommentVisitor for PatternStructField { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + match self { + PatternStructField::Rest { token } => { + collected_spans.push(CommentSpan::from_span(token.span())); + } + PatternStructField::Field { + field_name, + pattern_opt, + } => { + // Add field name CommentSpan + collected_spans.push(CommentSpan::from_span(field_name.span())); + // Add patern CommentSpan's if it exists + if let Some(pattern) = pattern_opt { + // Add ColonToken's CommentSpan + collected_spans.push(CommentSpan::from_span(pattern.0.span())); + // Add patterns CommentSpan + collected_spans.append(&mut pattern.1.collect_spans()); + } + } + } + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 76e557edf3e..e1cd42be620 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -9,18 +9,18 @@ use sway_types::{Ident, Spanned}; impl CommentVisitor for Punctuated where - T: Spanned, - P: Spanned, + T: CommentVisitor + Clone, + P: CommentVisitor + Clone, { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); let value_pairs = &self.value_separator_pairs; for pair in value_pairs.iter() { - //collected_spans.push(CommentSpan::from_span(pair.0.span())); - collected_spans.push(CommentSpan::from_span(pair.1.span())); + collected_spans.append(&mut pair.0.collect_spans()); + collected_spans.append(&mut pair.1.collect_spans()); } if let Some(final_value) = &self.final_value_opt { - collected_spans.push(CommentSpan::from_span(final_value.span())); + collected_spans.append(&mut final_value.collect_spans()); } collected_spans } From be4ed24b1e5459a8129358491e3a32247799da82 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 14 Jul 2022 23:39:40 +0300 Subject: [PATCH 20/44] Do not search or insert comment between Punctuated's T and P. --- sway-fmt-v2/src/utils/comments.rs | 4 ++++ sway-fmt-v2/src/utils/punctuated.rs | 16 ++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 64fd415a9f5..2a25926212b 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -33,6 +33,10 @@ impl CommentSpan { end: span.end(), } } + + pub fn len(&self) -> usize { + self.end - self.start + } } impl Ord for CommentSpan { diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index e1cd42be620..d352be3232b 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -16,8 +16,20 @@ where let mut collected_spans = Vec::new(); let value_pairs = &self.value_separator_pairs; for pair in value_pairs.iter() { - collected_spans.append(&mut pair.0.collect_spans()); - collected_spans.append(&mut pair.1.collect_spans()); + // Since we do not want to have comments between T and P we are extending the CommentSpans coming from T with spans coming from P + // Since formatter can insert a trailing comma after a field, comments next to a field can be falsely inserted between the comma and the field + // So we shouldn't allow inserting comments (or searching for one) between T and P as in Punctuated scenerio this can/will result in formattings that breaks the build process + let mut comment_spans = pair + .0 + .collect_spans() + .iter_mut() + .zip(pair.1.collect_spans()) + .map(|comment_map| { + comment_map.0.end += comment_map.1.len(); + comment_map.0.clone() + }) + .collect(); + collected_spans.append(&mut comment_spans) } if let Some(final_value) = &self.final_value_opt { collected_spans.append(&mut final_value.collect_spans()); From 120d601bf11792a26a34c19eb62b3e050954264d Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Fri, 15 Jul 2022 13:51:57 +0300 Subject: [PATCH 21/44] Literal visitor implemented, pattern visitor updated --- sway-fmt-v2/src/utils/literal.rs | 16 +++++++++++++++- sway-fmt-v2/src/utils/pattern.rs | 3 +-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/sway-fmt-v2/src/utils/literal.rs b/sway-fmt-v2/src/utils/literal.rs index 732e334063c..6269f02a4fc 100644 --- a/sway-fmt-v2/src/utils/literal.rs +++ b/sway-fmt-v2/src/utils/literal.rs @@ -1,4 +1,7 @@ -use crate::fmt::*; +use crate::{ + fmt::*, + utils::comments::{CommentSpan, CommentVisitor}, +}; use std::fmt::Write; use sway_parse::Literal; @@ -18,3 +21,14 @@ impl Format for Literal { Ok(()) } } + +impl CommentVisitor for Literal { + fn collect_spans(&self) -> Vec { + match self { + Literal::String(str_lit) => vec![CommentSpan::from_span(str_lit.span.clone())], + Literal::Char(chr_lit) => vec![CommentSpan::from_span(chr_lit.span.clone())], + Literal::Int(int_lit) => vec![CommentSpan::from_span(int_lit.span.clone())], + Literal::Bool(bool_lit) => vec![CommentSpan::from_span(bool_lit.span.clone())], + } + } +} diff --git a/sway-fmt-v2/src/utils/pattern.rs b/sway-fmt-v2/src/utils/pattern.rs index b0157acacf1..1bd31c54ac3 100644 --- a/sway-fmt-v2/src/utils/pattern.rs +++ b/sway-fmt-v2/src/utils/pattern.rs @@ -134,7 +134,7 @@ impl CommentVisitor for Pattern { collected_spans.push(CommentSpan::from_span(name.span())); } Pattern::Literal(literal) => { - collected_spans.push(CommentSpan::from_span(literal.span())); + collected_spans.append(&mut literal.collect_spans()); } Pattern::Constant(constant) => { // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr @@ -142,7 +142,6 @@ impl CommentVisitor for Pattern { // root::parent/* i am a comment*/::child // I am not sure if this is something the language will allow. collected_spans.push(CommentSpan::from_span(constant.span())); - todo!(); } Pattern::Constructor { path, args } => { // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr From 6c34f10a190ba3412a7f12d3c86aa40d303577fa Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Fri, 15 Jul 2022 14:02:52 +0300 Subject: [PATCH 22/44] statement visitor implemented --- sway-fmt-v2/src/utils/statement.rs | 40 +++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/sway-fmt-v2/src/utils/statement.rs b/sway-fmt-v2/src/utils/statement.rs index dc1da828f84..499fa853fcb 100644 --- a/sway-fmt-v2/src/utils/statement.rs +++ b/sway-fmt-v2/src/utils/statement.rs @@ -1,4 +1,7 @@ -use crate::fmt::*; +use crate::{ + fmt::*, + utils::comments::{CommentSpan, CommentVisitor}, +}; use std::fmt::Write; use sway_parse::{Statement, StatementLet}; use sway_types::Spanned; @@ -56,3 +59,38 @@ impl Format for StatementLet { Ok(()) } } + +impl CommentVisitor for Statement { + fn collect_spans(&self) -> Vec { + match self { + Statement::Let(statement_let) => statement_let.collect_spans(), + Statement::Item(item) => item.collect_spans(), + Statement::Expr { + expr, + semicolon_token_opt, + } => todo!(), + } + } +} + +impl CommentVisitor for StatementLet { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + // Add let token's CommentSpan + collected_spans.push(CommentSpan::from_span(self.let_token.span())); + // Add pattern's CommentSpan + collected_spans.append(&mut self.pattern.collect_spans()); + // Add ty's CommentSpan if it exists + if let Some(ty) = &self.ty_opt { + collected_spans.push(CommentSpan::from_span(ty.0.span())); + // TODO: determine if we are allowing comments between `:` and ty + collected_spans.push(CommentSpan::from_span(ty.1.span())); + } + // Add eq token's CommentSpan + collected_spans.push(CommentSpan::from_span(self.eq_token.span())); + // Add Expr's CommentSpan + // collected_spans.append(&mut self.expr.collect_spans()); + collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans + } +} From 3f59e9f9e13c265e400b64ba318e30638c4ce210 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Sat, 16 Jul 2022 01:37:59 +0300 Subject: [PATCH 23/44] Visitor for ItemFn implemented recursively, we can now insert comments anywhere possible in a ItemFn, a simple test added --- sway-fmt-v2/src/fmt.rs | 9 +- sway-fmt-v2/src/items/item_fn.rs | 24 ++ sway-fmt-v2/src/utils/comments.rs | 53 ++- sway-fmt-v2/src/utils/expr.rs | 595 ++++++++++++++++++++++++++++- sway-fmt-v2/src/utils/item.rs | 1 + sway-fmt-v2/src/utils/path.rs | 25 +- sway-fmt-v2/src/utils/pattern.rs | 18 +- sway-fmt-v2/src/utils/statement.rs | 15 +- sway-fmt-v2/src/utils/ty.rs | 55 ++- 9 files changed, 764 insertions(+), 31 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 0b11cdec7bc..fde33983c02 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -440,6 +440,10 @@ pub enum Bazz { // Here is a comment // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ // \|_________| +} + +fn hello_world( baz: /* this is a comment */ u64) { + }"#; let correct_sway_code = r#"contract; @@ -466,11 +470,14 @@ pub enum Bazz { // Here is a comment // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ // \|_________| +} +fn hello_world(baz: /* this is a comment */ u64) { }"#; let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - println!("{}", formatted_sway_code); + println!("{}\n\n\n", formatted_sway_code); + println!("\n\n\n{}", correct_sway_code); assert_eq!(correct_sway_code, formatted_sway_code) } } diff --git a/sway-fmt-v2/src/items/item_fn.rs b/sway-fmt-v2/src/items/item_fn.rs index 7d2700c37ee..4c084a134a7 100644 --- a/sway-fmt-v2/src/items/item_fn.rs +++ b/sway-fmt-v2/src/items/item_fn.rs @@ -208,6 +208,30 @@ impl Format for FnArg { } } +impl CommentVisitor for ItemFn { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + collected_spans.append(&mut self.fn_signature.collect_spans()); + collected_spans.append(&mut self.body.collect_spans()); + collected_spans + } +} + +impl CommentVisitor for CodeBlockContents { + fn collect_spans(&self) -> Vec { + let mut collected_span = Vec::new(); + // Collect statements' CommentSpans + for statement in self.statements.iter() { + collected_span.append(&mut statement.collect_spans()); + } + // Collect expr's CommentSpans if it exists + if let Some(expr) = &self.final_expr_opt { + collected_span.append(&mut expr.collect_spans()); + } + collected_span + } +} + impl CommentVisitor for FnSignature { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 2a25926212b..38b668a78d1 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -9,7 +9,7 @@ use std::{ sync::Arc, }; use sway_parse::{ - brackets::Parens, + brackets::{Parens, SquareBrackets}, keywords::CommaToken, token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, Braces, Module, TypeField, @@ -136,6 +136,38 @@ where } } +impl CommentVisitor for SquareBrackets +where + T: CommentVisitor + Clone, +{ + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + let mut opening_bracket_span = CommentSpan::from_span(self.span()); + opening_bracket_span.end = opening_bracket_span.start + 1; + // Add opening bracket's span + collected_spans.push(opening_bracket_span); + // Add T's collected CommentSpan + collected_spans.append(&mut self.clone().into_inner().collect_spans()); + let mut closing_bracket_span = CommentSpan::from_span(self.span()); + closing_bracket_span.start = closing_bracket_span.end - 1; + // Add closing bracket's CommentSpan + collected_spans.push(closing_bracket_span); + collected_spans + } +} + +impl CommentVisitor for Vec +where + T: CommentVisitor, +{ + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + for t in self { + collected_spans.append(&mut t.collect_spans()); + } + collected_spans + } +} impl CommentVisitor for CommaToken { fn collect_spans(&self) -> Vec { vec![(CommentSpan::from_span(self.span()))] @@ -157,7 +189,6 @@ pub fn handle_comments( ) -> Result<(), FormatterError> { // Collect Span -> Comment mapping from unformatted input let comment_map = comment_map_from_src(unformatted_input.clone())?; - // Parse unformatted code so that we can get the spans of items in their original places. // This is required since we collected the spans in from unformatted source file. let unformatted_module = sway_parse::parse_file(unformatted_input, path.clone())?; @@ -262,13 +293,18 @@ fn insert_after_span( &(0..comments_to_insert[0].1) .map(|_| ' ') .collect::(), - comments_to_insert[0].0.span.as_str() + format_comment(&comments_to_insert[0].0) ); for comment in comments_to_insert.iter().skip(1) { let whitespaces = (0..(comment.1 - comment_str.len() - 1)) .map(|_| ' ') .collect::(); - write!(comment_str, "\n{}{}", whitespaces, comment.0.span.as_str())?; + write!( + comment_str, + "\n{}{}", + whitespaces, + &format_comment(&comment.0) + )?; } src_rope.insert(from.end + offset, &comment_str); formatted_code.clear(); @@ -276,6 +312,15 @@ fn insert_after_span( Ok(comment_str.chars().count()) } +/// Applies formatting to the comment. +/// Currently just checks if it is a multiline comment, if that is the case it adds a trailing `/` to the end. +fn format_comment(comment: &Comment) -> String { + if comment.span().str().starts_with("/*") { + format!("{}/", comment.span().str()) + } else { + String::from(comment.span().str()) + } +} /// While searching for a comment we need the possible places a comment can be placed in a structure /// `collect_spans` collects all field's spans so that we can check in between them. pub trait CommentVisitor { diff --git a/sway-fmt-v2/src/utils/expr.rs b/sway-fmt-v2/src/utils/expr.rs index 3ec225dfc48..090e2e6f2e2 100644 --- a/sway-fmt-v2/src/utils/expr.rs +++ b/sway-fmt-v2/src/utils/expr.rs @@ -1,6 +1,14 @@ -use crate::fmt::*; -use std::fmt::Write; -use sway_parse::Expr; +use crate::{ + fmt::*, + utils::comments::{CommentSpan, CommentVisitor}, +}; +use std::{fmt::Write, vec}; +use sway_parse::{ + expr::asm::{AsmBlockContents, AsmFinalExpr}, + AbiCastArgs, AsmBlock, AsmRegisterDeclaration, Assignable, Expr, ExprArrayDescriptor, + ExprStructField, ExprTupleDescriptor, IfCondition, IfExpr, Instruction, MatchBranch, + MatchBranchKind, +}; use sway_types::Spanned; #[allow(unused_variables)] @@ -160,3 +168,584 @@ impl Format for Expr { Ok(()) } } +// TODO: Find a better way of handling Boxed version +impl CommentVisitor for Box { + fn collect_spans(&self) -> Vec { + visit_expr(self) + } +} + +impl CommentVisitor for Expr { + fn collect_spans(&self) -> Vec { + visit_expr(self) + } +} + +pub fn visit_expr(expr: &Expr) -> Vec { + match expr { + Expr::Path(path) => path.collect_spans(), + Expr::Literal(literal) => literal.collect_spans(), + Expr::AbiCast { abi_token, args } => { + let mut collected_spans = vec![CommentSpan::from_span(abi_token.span())]; + collected_spans.append(&mut args.collect_spans()); + collected_spans + } + Expr::Struct { path, fields } => { + let mut collected_spans = path.collect_spans(); + collected_spans.append(&mut fields.collect_spans()); + collected_spans + } + Expr::Tuple(tuple) => tuple.collect_spans(), + Expr::Parens(parens) => parens.collect_spans(), + Expr::Block(block) => block.collect_spans(), + Expr::Array(array) => array.collect_spans(), + Expr::Asm(asm) => asm.collect_spans(), + Expr::Return { + return_token, + expr_opt, + } => { + let mut collected_spans = vec![CommentSpan::from_span(return_token.span())]; + if let Some(expr) = expr_opt { + collected_spans.append(&mut expr.collect_spans()); + } + collected_spans + } + Expr::If(expr_if) => expr_if.collect_spans(), + Expr::Match { + match_token, + value, + branches, + } => { + let mut collected_spans = vec![CommentSpan::from_span(match_token.span())]; + // Collect value's CommentSpans + collected_spans.append(&mut value.collect_spans()); + // Collect branches' CommentSpans + collected_spans.append(&mut branches.collect_spans()); + collected_spans + } + Expr::While { + while_token, + condition, + block, + } => { + let mut collected_spans = vec![CommentSpan::from_span(while_token.span())]; + // Collect condition's CommentSpans + collected_spans.append(&mut condition.collect_spans()); + // Colelct block's CommentSpans + collected_spans.append(&mut block.collect_spans()); + collected_spans + } + Expr::FuncApp { func, args } => { + let mut collected_spans = Vec::new(); + // Collect func's CommentSpans + collected_spans.append(&mut func.collect_spans()); + // Collect args' CommentSpans + collected_spans.append(&mut args.collect_spans()); + collected_spans + } + Expr::Index { target, arg } => { + let mut collected_spans = Vec::new(); + // Collect target's CommentSpans + collected_spans.append(&mut target.collect_spans()); + // Collect arg's CommentSpans + collected_spans.append(&mut arg.collect_spans()); + collected_spans + } + Expr::MethodCall { + target, + dot_token, + name, + contract_args_opt, + args, + } => { + let mut collected_spans = Vec::new(); + // Collect target's CommentSpans + collected_spans.append(&mut target.collect_spans()); + // Add dot_token's CommentSpan + collected_spans.push(CommentSpan::from_span(dot_token.span())); + // Add name's CommentSpan + collected_spans.push(CommentSpan::from_span(name.span())); + // Collect contract args if it exists + if let Some(contract_args) = contract_args_opt { + collected_spans.append(&mut contract_args.collect_spans()); + } + // Collect args CommentSpans + collected_spans.append(&mut args.collect_spans()); + collected_spans + } + Expr::FieldProjection { + target, + dot_token, + name, + } => { + let mut collected_spans = Vec::new(); + // Collect target's CommentSpans + collected_spans.append(&mut target.collect_spans()); + // Add dot_token's CommentSpan + collected_spans.push(CommentSpan::from_span(dot_token.span())); + // Add name's CommentSpan + collected_spans.push(CommentSpan::from_span(name.span())); + collected_spans + } + Expr::TupleFieldProjection { + target, + dot_token, + field: _field, + field_span, + } => { + let mut collected_spans = Vec::new(); + // Collect target CommentSpans + collected_spans.append(&mut target.collect_spans()); + // Add dot_token's CommentSpan + collected_spans.push(CommentSpan::from_span(dot_token.span())); + // Add field's CommentSpan + collected_spans.push(CommentSpan::from_span(field_span.clone())); + collected_spans + } + Expr::Ref { ref_token, expr } => { + let mut collected_spans = vec![CommentSpan::from_span(ref_token.span())]; + collected_spans.append(&mut expr.collect_spans()); + collected_spans + } + Expr::Deref { deref_token, expr } => { + let mut collected_spans = vec![CommentSpan::from_span(deref_token.span())]; + collected_spans.append(&mut expr.collect_spans()); + collected_spans + } + Expr::Not { bang_token, expr } => { + let mut collected_spans = vec![CommentSpan::from_span(bang_token.span())]; + collected_spans.append(&mut expr.collect_spans()); + collected_spans + } + Expr::Mul { + lhs, + star_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(star_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Div { + lhs, + forward_slash_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(forward_slash_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Modulo { + lhs, + percent_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(percent_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Add { + lhs, + add_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(add_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Sub { + lhs, + sub_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(sub_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Shl { + lhs, + shl_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(shl_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Shr { + lhs, + shr_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(shr_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::BitAnd { + lhs, + ampersand_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(ampersand_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::BitXor { + lhs, + caret_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(caret_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::BitOr { + lhs, + pipe_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(pipe_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Equal { + lhs, + double_eq_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(double_eq_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::NotEqual { + lhs, + bang_eq_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(bang_eq_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::LessThan { + lhs, + less_than_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(less_than_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::GreaterThan { + lhs, + greater_than_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(greater_than_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::LessThanEq { + lhs, + less_than_eq_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(less_than_eq_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::GreaterThanEq { + lhs, + greater_than_eq_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(greater_than_eq_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::LogicalAnd { + lhs, + double_ampersand_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(double_ampersand_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::LogicalOr { + lhs, + double_pipe_token, + rhs, + } => { + let mut collected_spans = lhs.collect_spans(); + collected_spans.push(CommentSpan::from_span(double_pipe_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + Expr::Reassignment { + assignable, + reassignment_op, + expr, + } => { + let mut collected_spans = assignable.collect_spans(); + collected_spans.push(CommentSpan::from_span(reassignment_op.span.clone())); + collected_spans.append(&mut expr.collect_spans()); + collected_spans + } + } +} + +impl CommentVisitor for AbiCastArgs { + fn collect_spans(&self) -> Vec { + // Add name's CommentSpan + let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; + // Add comma_token's CommentSpan + collected_spans.push(CommentSpan::from_span(self.comma_token.span())); + // Add address CommentSpan + collected_spans.append(&mut self.address.collect_spans()); + collected_spans + } +} + +impl CommentVisitor for ExprStructField { + fn collect_spans(&self) -> Vec { + // Add field name's CommentSpan + let mut collected_spans = vec![CommentSpan::from_span(self.field_name.span())]; + // Add expr's CommentSpan if it exists + if let Some(expr) = &self.expr_opt { + collected_spans.push(CommentSpan::from_span(expr.0.span())); + // TODO: determine if we are allowing comments between `:` and expr + collected_spans.append(&mut expr.1.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for ExprTupleDescriptor { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + if let ExprTupleDescriptor::Cons { + head, + comma_token, + tail, + } = self + { + // Collect head's CommentSpans + collected_spans.append(&mut head.collect_spans()); + // Add comma_token's CommentSpan + collected_spans.push(CommentSpan::from_span(comma_token.span())); + // Collect tail's CommentSpans + collected_spans.append(&mut tail.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for ExprArrayDescriptor { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + if let ExprArrayDescriptor::Repeat { + value, + semicolon_token, + length, + } = self + { + // Collect value's CommentSpans + collected_spans.append(&mut value.collect_spans()); + // Add semicolon_token's CommentSpan + collected_spans.push(CommentSpan::from_span(semicolon_token.span())); + // Collect length's CommentSpans + collected_spans.append(&mut length.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for AsmBlock { + fn collect_spans(&self) -> Vec { + // Add asm_token's CommentSpan + let mut collected_spans = vec![CommentSpan::from_span(self.asm_token.span())]; + // Collect registers' CommentSpans + collected_spans.append(&mut self.registers.collect_spans()); + // Collect contents' CommentSpans + collected_spans.append(&mut self.contents.collect_spans()); + collected_spans + } +} + +impl CommentVisitor for AsmRegisterDeclaration { + fn collect_spans(&self) -> Vec { + // Add register's CommentSpan + let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; + // Add value's CommentSpan if it exists + if let Some(value) = &self.value_opt { + collected_spans.push(CommentSpan::from_span(value.0.span())); + // TODO: determine if we are allowing comments between `:` and expr + collected_spans.append(&mut value.1.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for AsmBlockContents { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + for instruction in &self.instructions { + // Add instruction's CommentSpan + collected_spans.append(&mut instruction.0.collect_spans()); + // Add SemicolonToken's CommentSpan + // TODO: probably we shouldn't allow for comments in between the instruction and comma since it may/will result in build failure after formatting + collected_spans.push(CommentSpan::from_span(instruction.1.span())); + } + collected_spans + } +} + +impl CommentVisitor for Instruction { + fn collect_spans(&self) -> Vec { + // Visit instructions as a whole unit, meaning we cannot insert comments inside an instruction. + vec![CommentSpan::from_span(self.span())] + } +} + +impl CommentVisitor for AsmFinalExpr { + fn collect_spans(&self) -> Vec { + // Add register's CommentSpan + let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; + // Add ty's CommentSpan if it exists + if let Some(ty) = &self.ty_opt { + collected_spans.push(CommentSpan::from_span(ty.0.span())); + // TODO: determine if we are allowing comments between `:` and ty + collected_spans.append(&mut ty.1.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for IfExpr { + fn collect_spans(&self) -> Vec { + // Add if_token's CommentSpan + let mut collected_spans = vec![CommentSpan::from_span(self.if_token.span())]; + // Collect condition's CommentSpan + collected_spans.append(&mut self.condition.collect_spans()); + // Collect then block + collected_spans.append(&mut self.then_block.collect_spans()); + // Collect else if it exists + if let Some(else_block) = &self.else_opt { + // Add ElseToken's CommentSpan + collected_spans.push(CommentSpan::from_span(else_block.0.span())); + // Collect else & else if blocks' CommentSpans + let mut else_body_spans = match &else_block.1 { + std::ops::ControlFlow::Continue(if_expr) => if_expr.collect_spans(), + std::ops::ControlFlow::Break(else_body) => else_body.collect_spans(), + }; + collected_spans.append(&mut else_body_spans); + } + collected_spans + } +} + +impl CommentVisitor for IfCondition { + fn collect_spans(&self) -> Vec { + match self { + IfCondition::Expr(expr) => expr.collect_spans(), + IfCondition::Let { + let_token, + lhs, + eq_token, + rhs, + } => { + let mut collected_spans = vec![CommentSpan::from_span(let_token.span())]; + collected_spans.append(&mut lhs.collect_spans()); + collected_spans.push(CommentSpan::from_span(eq_token.span())); + collected_spans.append(&mut rhs.collect_spans()); + collected_spans + } + } + } +} + +impl CommentVisitor for MatchBranch { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + // Collect Pattern's CommentSpans + collected_spans.append(&mut self.pattern.collect_spans()); + // Add fat_right_arrow_token's CommentSpan + collected_spans.push(CommentSpan::from_span(self.fat_right_arrow_token.span())); + // Collect kind's CommentSpans + collected_spans.append(&mut self.kind.collect_spans()); + collected_spans + } +} + +impl CommentVisitor for MatchBranchKind { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + match self { + MatchBranchKind::Block { + block, + comma_token_opt, + } => { + collected_spans.append(&mut block.collect_spans()); + // TODO: determine if we allow comments between block and comma_token + if let Some(comma_token) = comma_token_opt { + collected_spans.push(CommentSpan::from_span(comma_token.span())); + } + } + MatchBranchKind::Expr { expr, comma_token } => { + collected_spans.append(&mut expr.collect_spans()); + // TODO: determine if we allow comments between expr and comma_token + collected_spans.push(CommentSpan::from_span(comma_token.span())); + } + }; + collected_spans + } +} + +impl CommentVisitor for Assignable { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + match self { + Assignable::Var(var) => collected_spans.push(CommentSpan::from_span(var.span())), + Assignable::Index { target, arg } => { + collected_spans.append(&mut target.collect_spans()); + collected_spans.append(&mut arg.collect_spans()); + } + Assignable::FieldProjection { + target, + dot_token, + name, + } => { + collected_spans.append(&mut target.collect_spans()); + collected_spans.push(CommentSpan::from_span(dot_token.span())); + collected_spans.push(CommentSpan::from_span(name.span())); + } + Assignable::TupleFieldProjection { + target, + dot_token, + field: _field, + field_span, + } => { + collected_spans.append(&mut target.collect_spans()); + collected_spans.push(CommentSpan::from_span(dot_token.span())); + collected_spans.push(CommentSpan::from_span(field_span.clone())); + } + }; + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 401749361dd..8064ff7c906 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -9,6 +9,7 @@ impl CommentVisitor for Item { match &self.value { Struct(item_struct) => item_struct.collect_spans(), Enum(item_enum) => item_enum.collect_spans(), + Fn(item_fn) => item_fn.collect_spans(), _ => Vec::new(), } } diff --git a/sway-fmt-v2/src/utils/path.rs b/sway-fmt-v2/src/utils/path.rs index f71205ee10a..5f59d4024bb 100644 --- a/sway-fmt-v2/src/utils/path.rs +++ b/sway-fmt-v2/src/utils/path.rs @@ -1,5 +1,8 @@ -use crate::fmt::*; -use std::fmt::Write; +use crate::{ + fmt::*, + utils::comments::{CommentSpan, CommentVisitor}, +}; +use std::{fmt::Write, vec}; use sway_parse::{PathExpr, PathExprSegment, PathType, PathTypeSegment, QualifiedPathRoot}; use sway_types::Spanned; @@ -132,3 +135,21 @@ impl Format for PathTypeSegment { Ok(()) } } + +impl CommentVisitor for PathExpr { + fn collect_spans(&self) -> Vec { + // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr + // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted + // root::parent/* i am a comment*/::child + // I am not sure if this is something the language will allow. + vec![CommentSpan::from_span(self.span())] + } +} + +impl CommentVisitor for PathType { + fn collect_spans(&self) -> Vec { + // TODO: Should we look for a comment inside the path type? if so we will need to implement CommentVisitor for PathType + // For now we are assuming there will be no comments inside the PathType so we are visiting it as a single unit. + vec![CommentSpan::from_span(self.span())] + } +} diff --git a/sway-fmt-v2/src/utils/pattern.rs b/sway-fmt-v2/src/utils/pattern.rs index 1bd31c54ac3..6f90719b53b 100644 --- a/sway-fmt-v2/src/utils/pattern.rs +++ b/sway-fmt-v2/src/utils/pattern.rs @@ -137,26 +137,14 @@ impl CommentVisitor for Pattern { collected_spans.append(&mut literal.collect_spans()); } Pattern::Constant(constant) => { - // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr - // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted - // root::parent/* i am a comment*/::child - // I am not sure if this is something the language will allow. - collected_spans.push(CommentSpan::from_span(constant.span())); + collected_spans.append(&mut constant.collect_spans()); } Pattern::Constructor { path, args } => { - // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr - // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted - // root::parent/* i am a comment*/::child - // I am not sure if this is something the language will allow. - collected_spans.push(CommentSpan::from_span(path.span())); + collected_spans.append(&mut path.collect_spans()); collected_spans.append(&mut args.collect_spans()); } Pattern::Struct { path, fields } => { - // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr - // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted - // root::parent/* i am a comment*/::child - // I am not sure if this is something the language will allow. - collected_spans.push(CommentSpan::from_span(path.span())); + collected_spans.append(&mut path.collect_spans()); collected_spans.append(&mut fields.collect_spans()); } Pattern::Tuple(tuple) => { diff --git a/sway-fmt-v2/src/utils/statement.rs b/sway-fmt-v2/src/utils/statement.rs index 499fa853fcb..24501cc087f 100644 --- a/sway-fmt-v2/src/utils/statement.rs +++ b/sway-fmt-v2/src/utils/statement.rs @@ -68,28 +68,33 @@ impl CommentVisitor for Statement { Statement::Expr { expr, semicolon_token_opt, - } => todo!(), + } => { + let mut collected_spans = expr.collect_spans(); + if let Some(semicolon_token) = semicolon_token_opt { + collected_spans.push(CommentSpan::from_span(semicolon_token.span())); + } + collected_spans + } } } } impl CommentVisitor for StatementLet { fn collect_spans(&self) -> Vec { - let mut collected_spans = Vec::new(); // Add let token's CommentSpan - collected_spans.push(CommentSpan::from_span(self.let_token.span())); + let mut collected_spans = vec![CommentSpan::from_span(self.let_token.span())]; // Add pattern's CommentSpan collected_spans.append(&mut self.pattern.collect_spans()); // Add ty's CommentSpan if it exists if let Some(ty) = &self.ty_opt { collected_spans.push(CommentSpan::from_span(ty.0.span())); // TODO: determine if we are allowing comments between `:` and ty - collected_spans.push(CommentSpan::from_span(ty.1.span())); + collected_spans.append(&mut ty.1.collect_spans()); } // Add eq token's CommentSpan collected_spans.push(CommentSpan::from_span(self.eq_token.span())); // Add Expr's CommentSpan - // collected_spans.append(&mut self.expr.collect_spans()); + collected_spans.append(&mut self.expr.collect_spans()); collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); collected_spans } diff --git a/sway-fmt-v2/src/utils/ty.rs b/sway-fmt-v2/src/utils/ty.rs index db370c793b3..fa8a8e8cce1 100644 --- a/sway-fmt-v2/src/utils/ty.rs +++ b/sway-fmt-v2/src/utils/ty.rs @@ -1,4 +1,7 @@ -use crate::fmt::{Format, FormattedCode, Formatter, FormatterError}; +use crate::{ + fmt::{Format, FormattedCode, Formatter, FormatterError}, + utils::comments::{CommentSpan, CommentVisitor}, +}; use std::fmt::Write; use sway_parse::{ brackets::SquareBrackets, @@ -58,6 +61,7 @@ impl Format for TyArrayDescriptor { formatter: &mut Formatter, ) -> Result<(), FormatterError> { self.ty.format(formatted_code, formatter)?; + // TODO: once expr formatting is completly implemented switch this to use the actual formatting rather than the raw str coming from span write!( formatted_code, "{} {}", @@ -103,3 +107,52 @@ impl Format for TyTupleDescriptor { Ok(()) } } + +impl CommentVisitor for Ty { + fn collect_spans(&self) -> Vec { + match self { + Ty::Path(path) => path.collect_spans(), + Ty::Tuple(tuple) => tuple.collect_spans(), + Ty::Array(array) => array.collect_spans(), + Ty::Str { str_token, length } => { + let mut collected_spans = vec![CommentSpan::from_span(str_token.span())]; + collected_spans.append(&mut length.collect_spans()); + collected_spans + } + Ty::Infer { underscore_token } => vec![CommentSpan::from_span(underscore_token.span())], + } + } +} + +impl CommentVisitor for TyTupleDescriptor { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + if let TyTupleDescriptor::Cons { + head, + comma_token, + tail, + } = self + { + // Collect head's CommentSpans + collected_spans.append(&mut head.collect_spans()); + // Add comma_token's CommentSpan + collected_spans.push(CommentSpan::from_span(comma_token.span())); + // Collect tail's CommentSpans + collected_spans.append(&mut tail.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for TyArrayDescriptor { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + // Collect ty's CommentSpans + collected_spans.append(&mut self.ty.collect_spans()); + // Add semicolon token's CommentSpan + collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + // Collect length's CommentSpans + collected_spans.append(&mut self.length.collect_spans()); + collected_spans + } +} From 68d4f028668c695d3efe987dba455d16476885b9 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Sat, 16 Jul 2022 01:44:02 +0300 Subject: [PATCH 24/44] comment tests simplified --- sway-fmt-v2/src/fmt.rs | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index fde33983c02..263348769b0 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -432,18 +432,12 @@ pub enum Bazz { // Here is a comment - bazzz: (),// ________ ___ ___ _______ ___ ___ ________ ________ ________ - // |\ _____\\ \|\ \|\ ___ \ |\ \ |\ \ |\ __ \|\ __ \|\ ____\ - // \ \ \__/\ \ \\\ \ \ __/|\ \ \ \ \ \ \ \ \|\ \ \ \|\ /\ \ \___|_ - // \ \ __\\ \ \\\ \ \ \_|/_\ \ \ \ \ \ \ \ __ \ \ __ \ \_____ \ - // \ \ \_| \ \ \\\ \ \ \_|\ \ \ \____ \ \ \____\ \ \ \ \ \ \|\ \|____|\ \ - // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ - // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ - // \|_________| + bazzz: (),//----- + //--D-- + //----- } -fn hello_world( baz: /* this is a comment */ u64) { - +fn hello_world( baz: /* this is a comment */ u64) { // This is a comment inside the block }"#; let correct_sway_code = r#"contract; @@ -462,16 +456,11 @@ pub struct Foo { // Here is a comment pub enum Bazz { // Here is a comment // Trying some ASCII art baz: (), - bazzz: (),// ________ ___ ___ _______ ___ ___ ________ ________ ________ - // |\ _____\\ \|\ \|\ ___ \ |\ \ |\ \ |\ __ \|\ __ \|\ ____\ - // \ \ \__/\ \ \\\ \ \ __/|\ \ \ \ \ \ \ \ \|\ \ \ \|\ /\ \ \___|_ - // \ \ __\\ \ \\\ \ \ \_|/_\ \ \ \ \ \ \ \ __ \ \ __ \ \_____ \ - // \ \ \_| \ \ \\\ \ \ \_|\ \ \ \____ \ \ \____\ \ \ \ \ \ \|\ \|____|\ \ - // \ \__\ \ \_______\ \_______\ \_______\ \ \_______\ \__\ \__\ \_______\____\_\ \ - // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ - // \|_________| + bazzz: (),//----- + //--D-- + //----- } -fn hello_world(baz: /* this is a comment */ u64) { +fn hello_world(baz: /* this is a comment */ u64) { // This is a comment inside the block }"#; let mut formatter = Formatter::default(); let formatted_sway_code = From f2a3ab10b5210979926c3acc3b1789fa3ed727ba Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Sat, 16 Jul 2022 02:14:07 +0300 Subject: [PATCH 25/44] fix storage initializers for comment handler to parse formatted code correctly --- sway-fmt-v2/src/fmt.rs | 12 ++++++++---- sway-fmt-v2/src/items/item_storage.rs | 11 ++++++++++- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index cd08a5e8868..5a21842e833 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -345,8 +345,10 @@ storage { let correct_sway_code = r#"contract; storage { - long_var_name : Type1, - var2 : Type2, + long_var_name : Type1 = Type1 { + }, + var2 : Type2 = Type2 { + }, }"#; let mut formatter = Formatter::default(); @@ -366,10 +368,12 @@ storage { "#; let correct_sway_code = r#"contract; -storage { long_var_name: Type1, var2: Type2 }"#; +storage { long_var_name: Type1 = Type1 { + }, var2: Type2 = Type2 { + } }"#; let mut formatter = Formatter::default(); formatter.config.structures.small_structures_single_line = true; - formatter.config.whitespace.max_width = 300; + formatter.config.whitespace.max_width = 700; let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); assert_eq!(correct_sway_code, formatted_sway_code) diff --git a/sway-fmt-v2/src/items/item_storage.rs b/sway-fmt-v2/src/items/item_storage.rs index cd8208d2a1d..d5d55323323 100644 --- a/sway-fmt-v2/src/items/item_storage.rs +++ b/sway-fmt-v2/src/items/item_storage.rs @@ -111,6 +111,14 @@ fn format_storage( storage_field.colon_token.ident().as_str(), )?; storage_field.ty.format(formatted_code, formatter)?; + write!( + formatted_code, + " {} ", + storage_field.eq_token.ident().as_str() + )?; + storage_field + .initializer + .format(formatted_code, formatter)?; if value_pairs_iter.peek().is_some() { writeln!(formatted_code, "{}", field.1.span().as_str())?; } else if let Some(final_value) = &fields.final_value_opt { @@ -157,7 +165,8 @@ fn format_storage( field.0.colon_token.span().as_str(), )?; field.0.ty.format(formatted_code, formatter)?; - + write!(formatted_code, " {} ", field.0.eq_token.ident().as_str())?; + field.0.initializer.format(formatted_code, formatter)?; if value_pairs_iter.peek().is_some() { write!(formatted_code, "{} ", field.1.span().as_str())?; } From 8a995f7d081df7a2ca0875ef7eac9fb836565a15 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Sat, 16 Jul 2022 02:25:34 +0300 Subject: [PATCH 26/44] clippy --- sway-fmt-v2/src/utils/comments.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 38b668a78d1..359c7ceec85 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -318,7 +318,7 @@ fn format_comment(comment: &Comment) -> String { if comment.span().str().starts_with("/*") { format!("{}/", comment.span().str()) } else { - String::from(comment.span().str()) + comment.span().str() } } /// While searching for a comment we need the possible places a comment can be placed in a structure From bdcfc4b02380b17cda6ec07c19e6c0677845987a Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Mon, 18 Jul 2022 01:07:27 +0300 Subject: [PATCH 27/44] Collecting more context for comments --- sway-fmt-v2/src/fmt.rs | 6 +++ sway-fmt-v2/src/utils/comments.rs | 61 ++++++++++++++++++------------- 2 files changed, 42 insertions(+), 25 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 5a21842e833..8599ae2c44b 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -501,6 +501,9 @@ trait CompSciStudent: Programmer + Student { let sway_code_to_format = r#"contract; pub struct Foo { // Here is a comment + + + // Trying some ASCII art baz:u64, @@ -533,6 +536,9 @@ fn hello_world( baz: /* this is a comment */ u64) { // This is a comment inside let correct_sway_code = r#"contract; pub struct Foo { // Here is a comment + + + // Trying some ASCII art baz: u64, bazzz: u64,// ________ ___ ___ _______ ___ ___ ________ ________ ________ diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 359c7ceec85..b8cac50bb10 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -191,7 +191,7 @@ pub fn handle_comments( let comment_map = comment_map_from_src(unformatted_input.clone())?; // Parse unformatted code so that we can get the spans of items in their original places. // This is required since we collected the spans in from unformatted source file. - let unformatted_module = sway_parse::parse_file(unformatted_input, path.clone())?; + let unformatted_module = sway_parse::parse_file(unformatted_input.clone(), path.clone())?; // After the formatting items should be the same but their spans will be changed since we applied formatting to them. let formatted_module = sway_parse::parse_file(formatted_input, path)?; // Actually insert the comments @@ -200,6 +200,7 @@ pub fn handle_comments( &unformatted_module, &formatted_module, formatted_code, + unformatted_input, )?; Ok(()) } @@ -207,12 +208,13 @@ pub fn handle_comments( /// Adds the comments from comment_map to correct places in the formatted code. This requires us /// both the unformatted and formatted code's items as they will have different spans for their /// nodes. While traversing the unformatted items, `add_comments` searches for comments. If there is a comment found -/// place the comment. +/// places the comment. fn add_comments( comment_map: CommentMap, unformatted_module: &Module, formatted_module: &Module, formatted_code: &mut FormattedCode, + unformatted_code: Arc, ) -> Result<(), FormatterError> { let unformatted_items = &unformatted_module.items; let formatted_items = &formatted_module.items; @@ -246,6 +248,7 @@ fn add_comments( previous_unformatted_span, unformatted_cur_span, &comment_map, + &unformatted_code, ); if !comments_found.is_empty() { offset += insert_after_span( @@ -262,27 +265,45 @@ fn add_comments( Ok(()) } -/// Returns a list of comments between given spans. For each comment returns the offset from the last item +// A CommentWithContext is the Comment and the offset before it. The offset can be between the (from) item we searched for this comment or from the last comment inside range +type CommentWithContext = (Comment, String); + +/// Returns a list of comments between given spans. For each comment returns the Context +/// Context of a comment is basically the offset (the characters between the last item/comment) to the current comment fn get_comments_between_spans( from: &CommentSpan, to: &CommentSpan, comment_map: &CommentMap, -) -> Vec<(Comment, usize)> { - comment_map + unformatted_code: &Arc, +) -> Vec { + let mut comments_with_context = Vec::new(); + for (index, comment_tuple) in comment_map .range((Included(from), Excluded(to))) - .map(|comment_tuple| { - ( + .enumerate() + { + if comments_with_context.is_empty() { + // This is the first comment in the current range the context should be collected between from's end and comment's beginning + comments_with_context.push(( + comment_tuple.1.clone(), + unformatted_code[from.end..comment_tuple.0.start].to_string(), + )); + } else { + // There is a comment before this one, so we should get the context starting from the last comment's end to the beginning of the current comment + comments_with_context.push(( comment_tuple.1.clone(), - comment_tuple.1.span.start() - from.end, - ) - }) - .collect() + unformatted_code + [comments_with_context[index - 1].0.span.end()..comment_tuple.0.start] + .to_string(), + )); + } + } + comments_with_context } -/// Inserts after given span and returns the offset. +/// Inserts after given span and returns the offset. While inserting comments this also inserts Context of the comments so that the alignment whitespaces/newlines are intact fn insert_after_span( from: &CommentSpan, - comments_to_insert: Vec<(Comment, usize)>, + comments_to_insert: Vec, offset: usize, formatted_code: &mut FormattedCode, ) -> Result { @@ -290,21 +311,11 @@ fn insert_after_span( // prepare the comment str let mut comment_str = format!( "{}{}", - &(0..comments_to_insert[0].1) - .map(|_| ' ') - .collect::(), + comments_to_insert[0].1, format_comment(&comments_to_insert[0].0) ); for comment in comments_to_insert.iter().skip(1) { - let whitespaces = (0..(comment.1 - comment_str.len() - 1)) - .map(|_| ' ') - .collect::(); - write!( - comment_str, - "\n{}{}", - whitespaces, - &format_comment(&comment.0) - )?; + write!(comment_str, "{}{}", comment.1, &format_comment(&comment.0))?; } src_rope.insert(from.end + offset, &comment_str); formatted_code.clear(); From 47bffb30cc7eb55aa7e7ad621f60c88e37802a8a Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Mon, 18 Jul 2022 02:46:20 +0300 Subject: [PATCH 28/44] Added in-between item comments --- sway-fmt-v2/src/fmt.rs | 44 +++++++++++++++++++++++++++++-- sway-fmt-v2/src/utils/comments.rs | 41 ++++++++++++++++++++++++++-- 2 files changed, 81 insertions(+), 4 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 8599ae2c44b..2ef637a139e 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -499,7 +499,7 @@ trait CompSciStudent: Programmer + Student { #[test] fn test_comments() { let sway_code_to_format = r#"contract; - +// This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implemented pub struct Foo { // Here is a comment @@ -519,6 +519,10 @@ pub struct Foo { // Here is a comment // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ // \|_________| } +// This is a comment + + + pub enum Bazz { // Here is a comment // Trying some ASCII art baz: (), @@ -530,10 +534,28 @@ pub enum Bazz { // Here is a comment //--D-- //----- } - +// This is a comment before a fn +// This is another comment before a fn fn hello_world( baz: /* this is a comment */ u64) { // This is a comment inside the block + if baz < 10 { + // Baz is smaller than 10 + + // return 0 because of blah blah + return 0; // 0 is an interesting number + }else if bax < 20 { + // Baz is between 10 and 20 + + // return 1 because of blah blah + return 1; // 1 is an interesting number + }else { + // Baz is bigger than 20 + + // return 2 because of blah blah + return 2; // 2 is the perfect number to return + } }"#; let correct_sway_code = r#"contract; +// This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implementedcontract; pub struct Foo { // Here is a comment @@ -550,6 +572,7 @@ pub struct Foo { // Here is a comment // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ // \|_________| } +// This is a comment pub enum Bazz { // Here is a comment // Trying some ASCII art baz: (), @@ -557,7 +580,24 @@ pub enum Bazz { // Here is a comment //--D-- //----- } +// This is a comment before a fn fn hello_world(baz: /* this is a comment */ u64) { // This is a comment inside the block + if baz < 10 { + // Baz is smaller than 10 + + // return 0 because of blah blah + return 0; // 0 is an interesting number + }else if bax < 20 { + // Baz is between 10 and 20 + + // return 1 because of blah blah + return 1; // 1 is an interesting number + }else { + // Baz is bigger than 20 + + // return 2 because of blah blah + return 2; // 2 is the perfect number to return + } }"#; let mut formatter = Formatter::default(); let formatted_sway_code = diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index b8cac50bb10..e11696aa249 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -219,11 +219,14 @@ fn add_comments( let unformatted_items = &unformatted_module.items; let formatted_items = &formatted_module.items; + // Once CommentVisitor for ModuleKind is implemented start search from there + let mut prev_unformatted_item_last_span = CommentSpan { start: 0, end: 0 }; + let mut prev_formatted_item_last_span = CommentSpan { start: 0, end: 0 }; + // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted // as the total length of comments we added in previous iterations. let mut offset = 0; for (unformatted_item, formatted_item) in unformatted_items.iter().zip(formatted_items.iter()) { - // Search comments for possible places inside the item. let unformatted_item_spans = unformatted_item.collect_spans(); let formatted_item_spans = formatted_item.collect_spans(); @@ -231,6 +234,32 @@ fn add_comments( if unformatted_item_spans.first().is_none() || formatted_item_spans.first().is_none() { return Ok(()); } + // Search comment between the last item and this one + + // Get first span of the current item from unformatted code + let curr_unformatted_item_first_span = unformatted_item_spans + .first() + .ok_or(FormatterError::CommentError)?; + // Search for comments + + let comments_found = get_comments_between_spans( + &prev_unformatted_item_last_span, + curr_unformatted_item_first_span, + &comment_map, + &unformatted_code, + ); + // If there are some comments in between given spans insert them into the formatted code and increment offset with the length of the inserted comment(s) + if !comments_found.is_empty() { + offset += insert_after_span( + &prev_formatted_item_last_span, + comments_found, + offset, + formatted_code, + )?; + } + + // Search comments for possible places inside the item. + // We will definetly have a span in the collected span since for a source code to be parsed as an item there should be some tokens present. let mut previous_unformatted_span = unformatted_item_spans .first() @@ -261,6 +290,14 @@ fn add_comments( previous_unformatted_span = unformatted_cur_span; previous_formatted_span = formatted_cur_span; } + prev_unformatted_item_last_span = unformatted_item_spans + .last() + .ok_or(FormatterError::CommentError)? + .clone(); + prev_formatted_item_last_span = formatted_item_spans + .last() + .ok_or(FormatterError::CommentError)? + .clone(); } Ok(()) } @@ -320,7 +357,7 @@ fn insert_after_span( src_rope.insert(from.end + offset, &comment_str); formatted_code.clear(); formatted_code.push_str(&src_rope.to_string()); - Ok(comment_str.chars().count()) + Ok(comment_str.len()) } /// Applies formatting to the comment. From b4cc1cbec5799f8171b0fa5f53e446bd3e471667 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Mon, 18 Jul 2022 03:02:54 +0300 Subject: [PATCH 29/44] comments inside expr removed since formatter already includes them by default (it is not implemented yet) --- sway-fmt-v2/src/fmt.rs | 34 +--------------------------------- 1 file changed, 1 insertion(+), 33 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 2ef637a139e..9362a04dbc1 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -537,22 +537,6 @@ pub enum Bazz { // Here is a comment // This is a comment before a fn // This is another comment before a fn fn hello_world( baz: /* this is a comment */ u64) { // This is a comment inside the block - if baz < 10 { - // Baz is smaller than 10 - - // return 0 because of blah blah - return 0; // 0 is an interesting number - }else if bax < 20 { - // Baz is between 10 and 20 - - // return 1 because of blah blah - return 1; // 1 is an interesting number - }else { - // Baz is bigger than 20 - - // return 2 because of blah blah - return 2; // 2 is the perfect number to return - } }"#; let correct_sway_code = r#"contract; // This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implementedcontract; @@ -581,28 +565,12 @@ pub enum Bazz { // Here is a comment //----- } // This is a comment before a fn +// This is another comment before a fn fn hello_world(baz: /* this is a comment */ u64) { // This is a comment inside the block - if baz < 10 { - // Baz is smaller than 10 - - // return 0 because of blah blah - return 0; // 0 is an interesting number - }else if bax < 20 { - // Baz is between 10 and 20 - - // return 1 because of blah blah - return 1; // 1 is an interesting number - }else { - // Baz is bigger than 20 - - // return 2 because of blah blah - return 2; // 2 is the perfect number to return - } }"#; let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - println!("{formatted_sway_code}"); println!("{correct_sway_code}"); assert_eq!(correct_sway_code, formatted_sway_code) From fd6595ecaafc1a9038966848c9acc92fac5e9cd4 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Mon, 18 Jul 2022 13:51:52 +0300 Subject: [PATCH 30/44] ItemAbi CommentVisitor implemented --- sway-fmt-v2/src/fmt.rs | 17 +++++++++++++++ sway-fmt-v2/src/items/item_abi.rs | 34 +++++++++++++++++++++++++++-- sway-fmt-v2/src/utils/comments.rs | 36 +++++++++++++++++++++++++++++-- sway-fmt-v2/src/utils/expr.rs | 3 ++- sway-fmt-v2/src/utils/item.rs | 1 + 5 files changed, 86 insertions(+), 5 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 9362a04dbc1..03194fbbd92 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -537,6 +537,14 @@ pub enum Bazz { // Here is a comment // This is a comment before a fn // This is another comment before a fn fn hello_world( baz: /* this is a comment */ u64) { // This is a comment inside the block +} +// This is a storage map +abi StorageMapExample { + // insert_into_map is blah blah + #[storage(write)] // this is some other comment + fn insert_into_map1(key: u64, value: u64); // this is the last comment inside the StorageMapExample + + fn hello(key: u64, value: u64); }"#; let correct_sway_code = r#"contract; // This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implementedcontract; @@ -567,6 +575,15 @@ pub enum Bazz { // Here is a comment // This is a comment before a fn // This is another comment before a fn fn hello_world(baz: /* this is a comment */ u64) { // This is a comment inside the block +} +// This is a storage map + +abi StorageMapExample { + // insert_into_map is blah blah + #[storage(write)] // this is some other comment + fn insert_into_map1(key: u64, value: u64); // this is the last comment inside the StorageMapExample + + fn hello(key: u64, value: u64); }"#; let mut formatter = Formatter::default(); let formatted_sway_code = diff --git a/sway-fmt-v2/src/items/item_abi.rs b/sway-fmt-v2/src/items/item_abi.rs index 3113bdfff7e..1320674205d 100644 --- a/sway-fmt-v2/src/items/item_abi.rs +++ b/sway-fmt-v2/src/items/item_abi.rs @@ -1,11 +1,17 @@ use crate::{ config::items::ItemBraceStyle, fmt::{Format, FormattedCode, Formatter}, - utils::{attribute::FormatDecl, bracket::CurlyBrace}, + utils::{ + attribute::FormatDecl, + bracket::CurlyBrace, + comments::{CommentSpan, CommentVisitor}, + }, FormatterError, }; use std::fmt::Write; -use sway_parse::{token::Delimiter, ItemAbi}; +use sway_parse::{ + attribute::Annotated, keywords::SemicolonToken, token::Delimiter, FnSignature, ItemAbi, +}; use sway_types::Spanned; impl Format for ItemAbi { @@ -130,3 +136,27 @@ impl CurlyBrace for ItemAbi { Ok(()) } } + +impl CommentVisitor for ItemAbi { + fn collect_spans(&self) -> Vec { + // Add abi_token's CommentSpan + let mut collected_spans = vec![CommentSpan::from_span(self.abi_token.span())]; + // Add name's CommentSpan + collected_spans.push(CommentSpan::from_span(self.name.span())); + // Collect abi_items + collected_spans.append(&mut self.abi_items.collect_spans()); + // Collect abi_defs if it exists + if let Some(abi_defs) = &self.abi_defs_opt { + collected_spans.append(&mut abi_defs.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for (Annotated, SemicolonToken) { + fn collect_spans(&self) -> Vec { + let mut collected_spans = self.0.collect_spans(); + collected_spans.push(CommentSpan::from_span(self.1.span())); + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index e11696aa249..e9eaa04e627 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -9,12 +9,13 @@ use std::{ sync::Arc, }; use sway_parse::{ + attribute::{Annotated, Attribute}, brackets::{Parens, SquareBrackets}, keywords::CommaToken, token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, - Braces, Module, TypeField, + AttributeDecl, Braces, Module, Parse, TypeField, }; -use sway_types::{Span, Spanned}; +use sway_types::{Ident, Span, Spanned}; /// Represents a span for the comments in a spesific file /// A stripped down version of sway-types::src::Span #[derive(PartialEq, Eq, Debug, Clone, Default)] @@ -168,6 +169,37 @@ where collected_spans } } +impl CommentVisitor for Annotated +where + T: CommentVisitor + Parse, +{ + fn collect_spans(&self) -> Vec { + let mut collected_spans = self.attribute_list.collect_spans(); + collected_spans.append(&mut self.value.collect_spans()); + collected_spans + } +} +impl CommentVisitor for AttributeDecl { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.hash_token.span())]; + collected_spans.append(&mut self.attribute.collect_spans()); + collected_spans + } +} +impl CommentVisitor for Attribute { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; + if let Some(args) = &self.args { + collected_spans.append(&mut args.collect_spans()); + } + collected_spans + } +} +impl CommentVisitor for Ident { + fn collect_spans(&self) -> Vec { + vec![CommentSpan::from_span(self.span())] + } +} impl CommentVisitor for CommaToken { fn collect_spans(&self) -> Vec { vec![(CommentSpan::from_span(self.span()))] diff --git a/sway-fmt-v2/src/utils/expr.rs b/sway-fmt-v2/src/utils/expr.rs index 9c9c56b3dee..57bf78ff64f 100644 --- a/sway-fmt-v2/src/utils/expr.rs +++ b/sway-fmt-v2/src/utils/expr.rs @@ -271,7 +271,8 @@ impl CommentVisitor for Expr { } } -pub fn visit_expr(expr: &Expr) -> Vec { +/// Collects various expr field's CommentSpans. +fn visit_expr(expr: &Expr) -> Vec { match expr { Expr::Path(path) => path.collect_spans(), Expr::Literal(literal) => literal.collect_spans(), diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 8064ff7c906..28c647b7626 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -10,6 +10,7 @@ impl CommentVisitor for Item { Struct(item_struct) => item_struct.collect_spans(), Enum(item_enum) => item_enum.collect_spans(), Fn(item_fn) => item_fn.collect_spans(), + Abi(item_abi) => item_abi.collect_spans(), _ => Vec::new(), } } From e163d1faa4497bfe8b7eb6b4f8769946fea353e5 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Mon, 18 Jul 2022 14:56:26 +0300 Subject: [PATCH 31/44] CommentVisitor for ItemConst implemented & removed unnecessary comments for other CommentVisitor implementations --- sway-fmt-v2/src/fmt.rs | 6 ++-- sway-fmt-v2/src/items/item_const.rs | 21 ++++++++++++ sway-fmt-v2/src/items/item_enum.rs | 5 --- sway-fmt-v2/src/items/item_fn.rs | 10 ------ sway-fmt-v2/src/items/item_struct.rs | 5 --- sway-fmt-v2/src/utils/attribute.rs | 23 +++++++++++-- sway-fmt-v2/src/utils/comments.rs | 21 ++---------- sway-fmt-v2/src/utils/expr.rs | 48 ---------------------------- sway-fmt-v2/src/utils/item.rs | 1 + sway-fmt-v2/src/utils/ty.rs | 6 ---- 10 files changed, 50 insertions(+), 96 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 03194fbbd92..229854f3574 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -545,7 +545,8 @@ abi StorageMapExample { fn insert_into_map1(key: u64, value: u64); // this is the last comment inside the StorageMapExample fn hello(key: u64, value: u64); -}"#; +} +pub const /* TEST: blah blah tests */ TEST: u16 = 10;"#; let correct_sway_code = r#"contract; // This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implementedcontract; @@ -584,7 +585,8 @@ abi StorageMapExample { fn insert_into_map1(key: u64, value: u64); // this is the last comment inside the StorageMapExample fn hello(key: u64, value: u64); -}"#; +} +pub const /* TEST: blah blah tests */ TEST: u16 = 10;"#; let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); diff --git a/sway-fmt-v2/src/items/item_const.rs b/sway-fmt-v2/src/items/item_const.rs index 17f2d9d6661..bb72ce16a62 100644 --- a/sway-fmt-v2/src/items/item_const.rs +++ b/sway-fmt-v2/src/items/item_const.rs @@ -1,5 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, + utils::comments::{CommentSpan, CommentVisitor}, FormatterError, }; use std::fmt::Write; @@ -44,3 +45,23 @@ impl Format for ItemConst { Ok(()) } } + +impl CommentVisitor for ItemConst { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + if let Some(visibility) = &self.visibility { + collected_spans.push(CommentSpan::from_span(visibility.span())); + } + collected_spans.push(CommentSpan::from_span(self.const_token.span())); + collected_spans.push(CommentSpan::from_span(self.name.span())); + if let Some(ty) = &self.ty_opt { + collected_spans.push(CommentSpan::from_span(ty.0.span())); + // TODO: determine if we allow comments in between `:` and ty + collected_spans.append(&mut ty.1.collect_spans()); + } + collected_spans.push(CommentSpan::from_span(self.eq_token.span())); + collected_spans.append(&mut self.expr.collect_spans()); + collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans + } +} diff --git a/sway-fmt-v2/src/items/item_enum.rs b/sway-fmt-v2/src/items/item_enum.rs index 51adfaf41f8..f032c6a2e1a 100644 --- a/sway-fmt-v2/src/items/item_enum.rs +++ b/sway-fmt-v2/src/items/item_enum.rs @@ -242,19 +242,14 @@ impl CurlyBrace for ItemEnum { impl CommentVisitor for ItemEnum { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - // Add visibility token's span if it exists if let Some(visibility) = &self.visibility { collected_spans.push(CommentSpan::from_span(visibility.span())); } - // Add enum_token's span collected_spans.push(CommentSpan::from_span(self.enum_token.span())); - // Add name's span collected_spans.push(CommentSpan::from_span(self.name.span())); - // Add generics' span if it exist if let Some(generics) = &self.generics { collected_spans.push(CommentSpan::from_span(generics.parameters.span())) } - // Collect fields' spans. collected_spans.append(&mut self.fields.collect_spans()); collected_spans } diff --git a/sway-fmt-v2/src/items/item_fn.rs b/sway-fmt-v2/src/items/item_fn.rs index 6a2a47fa9e9..8d52c5ca6eb 100644 --- a/sway-fmt-v2/src/items/item_fn.rs +++ b/sway-fmt-v2/src/items/item_fn.rs @@ -219,11 +219,9 @@ impl CommentVisitor for ItemFn { impl CommentVisitor for CodeBlockContents { fn collect_spans(&self) -> Vec { let mut collected_span = Vec::new(); - // Collect statements' CommentSpans for statement in self.statements.iter() { collected_span.append(&mut statement.collect_spans()); } - // Collect expr's CommentSpans if it exists if let Some(expr) = &self.final_expr_opt { collected_span.append(&mut expr.collect_spans()); } @@ -234,21 +232,15 @@ impl CommentVisitor for CodeBlockContents { impl CommentVisitor for FnSignature { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - // Add visibility token if it exists if let Some(visibility) = &self.visibility { collected_spans.push(CommentSpan::from_span(visibility.span())); } - // Add fn_token collected_spans.push(CommentSpan::from_span(self.fn_token.span())); - // Add name collected_spans.push(CommentSpan::from_span(self.name.span())); - // Add generics if it exists if let Some(generics) = &self.generics { collected_spans.push(CommentSpan::from_span(generics.parameters.span())); } - // Add spans for parameters collected_spans.append(&mut self.arguments.collect_spans()); - // Add return type if it exists if let Some((right_arrow_token, ty)) = &self.return_type_opt { collected_spans.push(CommentSpan::from_span(right_arrow_token.span())); collected_spans.push(CommentSpan::from_span(ty.span())); @@ -288,9 +280,7 @@ impl CommentVisitor for FnArg { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.pattern.collect_spans()); - // Add ColonToken collected_spans.push(CommentSpan::from_span(self.colon_token.span())); - // Add ty collected_spans.push(CommentSpan::from_span(self.ty.span())); collected_spans } diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index da82f0f116b..3649350baa5 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -248,19 +248,14 @@ impl CurlyBrace for ItemStruct { impl CommentVisitor for ItemStruct { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - // Add visibility token's span if it exists if let Some(visibility) = &self.visibility { collected_spans.push(CommentSpan::from_span(visibility.span())); } - // Add struct_token's span collected_spans.push(CommentSpan::from_span(self.struct_token.span())); - // Add name's span collected_spans.push(CommentSpan::from_span(self.name.span())); - // Add generics' span if it exist if let Some(generics) = &self.generics { collected_spans.push(CommentSpan::from_span(generics.parameters.span())) } - // Collect fields' spans. collected_spans.append(&mut self.fields.collect_spans()); collected_spans } diff --git a/sway-fmt-v2/src/utils/attribute.rs b/sway-fmt-v2/src/utils/attribute.rs index 7e10cfd1775..dfaf2f3d7a9 100644 --- a/sway-fmt-v2/src/utils/attribute.rs +++ b/sway-fmt-v2/src/utils/attribute.rs @@ -4,13 +4,16 @@ use crate::{ }; use std::fmt::Write; use sway_parse::{ - attribute::{Annotated, AttributeDecl}, + attribute::{Annotated, Attribute, AttributeDecl}, token::Delimiter, Parse, }; use sway_types::Spanned; -use super::bracket::{Parenthesis, SquareBracket}; +use super::{ + bracket::{Parenthesis, SquareBracket}, + comments::{CommentSpan, CommentVisitor}, +}; impl Format for Annotated { fn format( @@ -91,3 +94,19 @@ impl Parenthesis for AttributeDecl { Ok(()) } } +impl CommentVisitor for AttributeDecl { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.hash_token.span())]; + collected_spans.append(&mut self.attribute.collect_spans()); + collected_spans + } +} +impl CommentVisitor for Attribute { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; + if let Some(args) = &self.args { + collected_spans.append(&mut args.collect_spans()); + } + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index e9eaa04e627..f2139b12ced 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -9,11 +9,11 @@ use std::{ sync::Arc, }; use sway_parse::{ - attribute::{Annotated, Attribute}, + attribute::Annotated, brackets::{Parens, SquareBrackets}, keywords::CommaToken, token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, - AttributeDecl, Braces, Module, Parse, TypeField, + Braces, Module, Parse, TypeField, }; use sway_types::{Ident, Span, Spanned}; /// Represents a span for the comments in a spesific file @@ -179,22 +179,7 @@ where collected_spans } } -impl CommentVisitor for AttributeDecl { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.hash_token.span())]; - collected_spans.append(&mut self.attribute.collect_spans()); - collected_spans - } -} -impl CommentVisitor for Attribute { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; - if let Some(args) = &self.args { - collected_spans.append(&mut args.collect_spans()); - } - collected_spans - } -} + impl CommentVisitor for Ident { fn collect_spans(&self) -> Vec { vec![CommentSpan::from_span(self.span())] diff --git a/sway-fmt-v2/src/utils/expr.rs b/sway-fmt-v2/src/utils/expr.rs index 57bf78ff64f..a2494ca1bc0 100644 --- a/sway-fmt-v2/src/utils/expr.rs +++ b/sway-fmt-v2/src/utils/expr.rs @@ -308,9 +308,7 @@ fn visit_expr(expr: &Expr) -> Vec { branches, } => { let mut collected_spans = vec![CommentSpan::from_span(match_token.span())]; - // Collect value's CommentSpans collected_spans.append(&mut value.collect_spans()); - // Collect branches' CommentSpans collected_spans.append(&mut branches.collect_spans()); collected_spans } @@ -320,25 +318,19 @@ fn visit_expr(expr: &Expr) -> Vec { block, } => { let mut collected_spans = vec![CommentSpan::from_span(while_token.span())]; - // Collect condition's CommentSpans collected_spans.append(&mut condition.collect_spans()); - // Colelct block's CommentSpans collected_spans.append(&mut block.collect_spans()); collected_spans } Expr::FuncApp { func, args } => { let mut collected_spans = Vec::new(); - // Collect func's CommentSpans collected_spans.append(&mut func.collect_spans()); - // Collect args' CommentSpans collected_spans.append(&mut args.collect_spans()); collected_spans } Expr::Index { target, arg } => { let mut collected_spans = Vec::new(); - // Collect target's CommentSpans collected_spans.append(&mut target.collect_spans()); - // Collect arg's CommentSpans collected_spans.append(&mut arg.collect_spans()); collected_spans } @@ -350,17 +342,12 @@ fn visit_expr(expr: &Expr) -> Vec { args, } => { let mut collected_spans = Vec::new(); - // Collect target's CommentSpans collected_spans.append(&mut target.collect_spans()); - // Add dot_token's CommentSpan collected_spans.push(CommentSpan::from_span(dot_token.span())); - // Add name's CommentSpan collected_spans.push(CommentSpan::from_span(name.span())); - // Collect contract args if it exists if let Some(contract_args) = contract_args_opt { collected_spans.append(&mut contract_args.collect_spans()); } - // Collect args CommentSpans collected_spans.append(&mut args.collect_spans()); collected_spans } @@ -370,11 +357,8 @@ fn visit_expr(expr: &Expr) -> Vec { name, } => { let mut collected_spans = Vec::new(); - // Collect target's CommentSpans collected_spans.append(&mut target.collect_spans()); - // Add dot_token's CommentSpan collected_spans.push(CommentSpan::from_span(dot_token.span())); - // Add name's CommentSpan collected_spans.push(CommentSpan::from_span(name.span())); collected_spans } @@ -385,11 +369,8 @@ fn visit_expr(expr: &Expr) -> Vec { field_span, } => { let mut collected_spans = Vec::new(); - // Collect target CommentSpans collected_spans.append(&mut target.collect_spans()); - // Add dot_token's CommentSpan collected_spans.push(CommentSpan::from_span(dot_token.span())); - // Add field's CommentSpan collected_spans.push(CommentSpan::from_span(field_span.clone())); collected_spans } @@ -603,11 +584,8 @@ fn visit_expr(expr: &Expr) -> Vec { impl CommentVisitor for AbiCastArgs { fn collect_spans(&self) -> Vec { - // Add name's CommentSpan let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; - // Add comma_token's CommentSpan collected_spans.push(CommentSpan::from_span(self.comma_token.span())); - // Add address CommentSpan collected_spans.append(&mut self.address.collect_spans()); collected_spans } @@ -615,9 +593,7 @@ impl CommentVisitor for AbiCastArgs { impl CommentVisitor for ExprStructField { fn collect_spans(&self) -> Vec { - // Add field name's CommentSpan let mut collected_spans = vec![CommentSpan::from_span(self.field_name.span())]; - // Add expr's CommentSpan if it exists if let Some(expr) = &self.expr_opt { collected_spans.push(CommentSpan::from_span(expr.0.span())); // TODO: determine if we are allowing comments between `:` and expr @@ -636,11 +612,8 @@ impl CommentVisitor for ExprTupleDescriptor { tail, } = self { - // Collect head's CommentSpans collected_spans.append(&mut head.collect_spans()); - // Add comma_token's CommentSpan collected_spans.push(CommentSpan::from_span(comma_token.span())); - // Collect tail's CommentSpans collected_spans.append(&mut tail.collect_spans()); } collected_spans @@ -656,11 +629,8 @@ impl CommentVisitor for ExprArrayDescriptor { length, } = self { - // Collect value's CommentSpans collected_spans.append(&mut value.collect_spans()); - // Add semicolon_token's CommentSpan collected_spans.push(CommentSpan::from_span(semicolon_token.span())); - // Collect length's CommentSpans collected_spans.append(&mut length.collect_spans()); } collected_spans @@ -669,11 +639,8 @@ impl CommentVisitor for ExprArrayDescriptor { impl CommentVisitor for AsmBlock { fn collect_spans(&self) -> Vec { - // Add asm_token's CommentSpan let mut collected_spans = vec![CommentSpan::from_span(self.asm_token.span())]; - // Collect registers' CommentSpans collected_spans.append(&mut self.registers.collect_spans()); - // Collect contents' CommentSpans collected_spans.append(&mut self.contents.collect_spans()); collected_spans } @@ -681,9 +648,7 @@ impl CommentVisitor for AsmBlock { impl CommentVisitor for AsmRegisterDeclaration { fn collect_spans(&self) -> Vec { - // Add register's CommentSpan let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; - // Add value's CommentSpan if it exists if let Some(value) = &self.value_opt { collected_spans.push(CommentSpan::from_span(value.0.span())); // TODO: determine if we are allowing comments between `:` and expr @@ -697,9 +662,7 @@ impl CommentVisitor for AsmBlockContents { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); for instruction in &self.instructions { - // Add instruction's CommentSpan collected_spans.append(&mut instruction.0.collect_spans()); - // Add SemicolonToken's CommentSpan // TODO: probably we shouldn't allow for comments in between the instruction and comma since it may/will result in build failure after formatting collected_spans.push(CommentSpan::from_span(instruction.1.span())); } @@ -716,9 +679,7 @@ impl CommentVisitor for Instruction { impl CommentVisitor for AsmFinalExpr { fn collect_spans(&self) -> Vec { - // Add register's CommentSpan let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; - // Add ty's CommentSpan if it exists if let Some(ty) = &self.ty_opt { collected_spans.push(CommentSpan::from_span(ty.0.span())); // TODO: determine if we are allowing comments between `:` and ty @@ -730,17 +691,11 @@ impl CommentVisitor for AsmFinalExpr { impl CommentVisitor for IfExpr { fn collect_spans(&self) -> Vec { - // Add if_token's CommentSpan let mut collected_spans = vec![CommentSpan::from_span(self.if_token.span())]; - // Collect condition's CommentSpan collected_spans.append(&mut self.condition.collect_spans()); - // Collect then block collected_spans.append(&mut self.then_block.collect_spans()); - // Collect else if it exists if let Some(else_block) = &self.else_opt { - // Add ElseToken's CommentSpan collected_spans.push(CommentSpan::from_span(else_block.0.span())); - // Collect else & else if blocks' CommentSpans let mut else_body_spans = match &else_block.1 { std::ops::ControlFlow::Continue(if_expr) => if_expr.collect_spans(), std::ops::ControlFlow::Break(else_body) => else_body.collect_spans(), @@ -774,11 +729,8 @@ impl CommentVisitor for IfCondition { impl CommentVisitor for MatchBranch { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - // Collect Pattern's CommentSpans collected_spans.append(&mut self.pattern.collect_spans()); - // Add fat_right_arrow_token's CommentSpan collected_spans.push(CommentSpan::from_span(self.fat_right_arrow_token.span())); - // Collect kind's CommentSpans collected_spans.append(&mut self.kind.collect_spans()); collected_spans } diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 28c647b7626..a4321822c14 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -11,6 +11,7 @@ impl CommentVisitor for Item { Enum(item_enum) => item_enum.collect_spans(), Fn(item_fn) => item_fn.collect_spans(), Abi(item_abi) => item_abi.collect_spans(), + Const(item_const) => item_const.collect_spans(), _ => Vec::new(), } } diff --git a/sway-fmt-v2/src/utils/ty.rs b/sway-fmt-v2/src/utils/ty.rs index fa8a8e8cce1..8e9f8187312 100644 --- a/sway-fmt-v2/src/utils/ty.rs +++ b/sway-fmt-v2/src/utils/ty.rs @@ -133,11 +133,8 @@ impl CommentVisitor for TyTupleDescriptor { tail, } = self { - // Collect head's CommentSpans collected_spans.append(&mut head.collect_spans()); - // Add comma_token's CommentSpan collected_spans.push(CommentSpan::from_span(comma_token.span())); - // Collect tail's CommentSpans collected_spans.append(&mut tail.collect_spans()); } collected_spans @@ -147,11 +144,8 @@ impl CommentVisitor for TyTupleDescriptor { impl CommentVisitor for TyArrayDescriptor { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - // Collect ty's CommentSpans collected_spans.append(&mut self.ty.collect_spans()); - // Add semicolon token's CommentSpan collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); - // Collect length's CommentSpans collected_spans.append(&mut self.length.collect_spans()); collected_spans } From e452fada9de1d448519d2b720a359a13bb01a4fa Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Mon, 18 Jul 2022 16:23:51 +0300 Subject: [PATCH 32/44] CommentVisitor implemented for ItemStorage, Fixed a bug for Punctuated visiting, couple more comment refactoring --- sway-fmt-v2/src/fmt.rs | 19 +++++++++++++++++-- sway-fmt-v2/src/items/item_abi.rs | 4 ---- sway-fmt-v2/src/items/item_storage.rs | 27 +++++++++++++++++++++++++-- sway-fmt-v2/src/utils/comments.rs | 1 - sway-fmt-v2/src/utils/item.rs | 1 + sway-fmt-v2/src/utils/pattern.rs | 6 ------ sway-fmt-v2/src/utils/punctuated.rs | 9 ++++++--- 7 files changed, 49 insertions(+), 18 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 229854f3574..4662f8b44d0 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -546,7 +546,14 @@ abi StorageMapExample { fn hello(key: u64, value: u64); } -pub const /* TEST: blah blah tests */ TEST: u16 = 10;"#; +pub const /* TEST: blah blah tests */ TEST: u16 = 10; // This is a comment next to a const + +storage { + // Testig a comment inside storage + long_var_name: Type1=Type1{}, + // Testing another comment + var2: Type2=Type2{} // This is the last comment, + }"#; let correct_sway_code = r#"contract; // This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implementedcontract; @@ -586,7 +593,15 @@ abi StorageMapExample { fn hello(key: u64, value: u64); } -pub const /* TEST: blah blah tests */ TEST: u16 = 10;"#; +pub const /* TEST: blah blah tests */ TEST: u16 = 10; // This is a comment next to a const +storage { + // Testig a comment inside storage + long_var_name: Type1 = Type1 { + }, + // Testing another comment + var2: Type2 = Type2 { + }, // This is the last comment, +}"#; let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); diff --git a/sway-fmt-v2/src/items/item_abi.rs b/sway-fmt-v2/src/items/item_abi.rs index 1320674205d..d3d624608cb 100644 --- a/sway-fmt-v2/src/items/item_abi.rs +++ b/sway-fmt-v2/src/items/item_abi.rs @@ -139,13 +139,9 @@ impl CurlyBrace for ItemAbi { impl CommentVisitor for ItemAbi { fn collect_spans(&self) -> Vec { - // Add abi_token's CommentSpan let mut collected_spans = vec![CommentSpan::from_span(self.abi_token.span())]; - // Add name's CommentSpan collected_spans.push(CommentSpan::from_span(self.name.span())); - // Collect abi_items collected_spans.append(&mut self.abi_items.collect_spans()); - // Collect abi_defs if it exists if let Some(abi_defs) = &self.abi_defs_opt { collected_spans.append(&mut abi_defs.collect_spans()); } diff --git a/sway-fmt-v2/src/items/item_storage.rs b/sway-fmt-v2/src/items/item_storage.rs index d5d55323323..55826ad7d85 100644 --- a/sway-fmt-v2/src/items/item_storage.rs +++ b/sway-fmt-v2/src/items/item_storage.rs @@ -1,13 +1,17 @@ use crate::{ config::{items::ItemBraceStyle, user_def::FieldAlignment}, fmt::{Format, FormattedCode, Formatter}, - utils::{bracket::CurlyBrace, item::ItemLenChars}, + utils::{ + bracket::CurlyBrace, + comments::{CommentSpan, CommentVisitor}, + item::ItemLenChars, + }, FormatterError, }; use std::fmt::Write; use sway_parse::{ token::{Delimiter, PunctKind}, - ItemStorage, + ItemStorage, StorageField, }; use sway_types::Spanned; @@ -225,3 +229,22 @@ impl CurlyBrace for ItemStorage { Ok(()) } } + +impl CommentVisitor for ItemStorage { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.storage_token.span())]; + collected_spans.append(&mut self.fields.collect_spans()); + collected_spans + } +} + +impl CommentVisitor for StorageField { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; + collected_spans.push(CommentSpan::from_span(self.colon_token.span())); + collected_spans.append(&mut self.ty.collect_spans()); + collected_spans.push(CommentSpan::from_span(self.eq_token.span())); + collected_spans.append(&mut self.initializer.collect_spans()); + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index f2139b12ced..b33f4895429 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -246,7 +246,6 @@ fn add_comments( for (unformatted_item, formatted_item) in unformatted_items.iter().zip(formatted_items.iter()) { let unformatted_item_spans = unformatted_item.collect_spans(); let formatted_item_spans = formatted_item.collect_spans(); - // TODO: Remove this once every item implements CommentVisitor. This is added to turn tests green if unformatted_item_spans.first().is_none() || formatted_item_spans.first().is_none() { return Ok(()); diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index a4321822c14..31526468537 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -12,6 +12,7 @@ impl CommentVisitor for Item { Fn(item_fn) => item_fn.collect_spans(), Abi(item_abi) => item_abi.collect_spans(), Const(item_const) => item_const.collect_spans(), + Storage(item_storage) => item_storage.collect_spans(), _ => Vec::new(), } } diff --git a/sway-fmt-v2/src/utils/pattern.rs b/sway-fmt-v2/src/utils/pattern.rs index 6f90719b53b..3135fed7376 100644 --- a/sway-fmt-v2/src/utils/pattern.rs +++ b/sway-fmt-v2/src/utils/pattern.rs @@ -126,11 +126,9 @@ impl CommentVisitor for Pattern { collected_spans.push(CommentSpan::from_span(underscore_token.span())); } Pattern::Var { mutable, name } => { - // Add mutable if it exists if let Some(mutable) = mutable { collected_spans.push(CommentSpan::from_span(mutable.span())); } - // Add name collected_spans.push(CommentSpan::from_span(name.span())); } Pattern::Literal(literal) => { @@ -166,13 +164,9 @@ impl CommentVisitor for PatternStructField { field_name, pattern_opt, } => { - // Add field name CommentSpan collected_spans.push(CommentSpan::from_span(field_name.span())); - // Add patern CommentSpan's if it exists if let Some(pattern) = pattern_opt { - // Add ColonToken's CommentSpan collected_spans.push(CommentSpan::from_span(pattern.0.span())); - // Add patterns CommentSpan collected_spans.append(&mut pattern.1.collect_spans()); } } diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index e5e68da90e6..01949e81b5b 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -16,6 +16,7 @@ where let mut collected_spans = Vec::new(); let value_pairs = &self.value_separator_pairs; for pair in value_pairs.iter() { + let p_comment_spans = pair.1.collect_spans(); // Since we do not want to have comments between T and P we are extending the CommentSpans coming from T with spans coming from P // Since formatter can insert a trailing comma after a field, comments next to a field can be falsely inserted between the comma and the field // So we shouldn't allow inserting comments (or searching for one) between T and P as in Punctuated scenerio this can/will result in formattings that breaks the build process @@ -23,10 +24,12 @@ where .0 .collect_spans() .iter_mut() - .zip(pair.1.collect_spans()) .map(|comment_map| { - comment_map.0.end += comment_map.1.len(); - comment_map.0.clone() + // Since the length of P' CommentSpan is same for each pair we are using the first one's length for all of the pairs. + // This assumtion always holds because for each pair P is formatted to same str so the length is going to be the same. + // For example when P is CommaToken, the length of P is always 1. + comment_map.end += p_comment_spans[0].len(); + comment_map.clone() }) .collect(); collected_spans.append(&mut comment_spans) From b63c955cf37bff0fac1d1ebe9e74bf96084a920f Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Mon, 18 Jul 2022 17:29:50 +0300 Subject: [PATCH 33/44] CommentVisitor implemented for ItemTrait, Tuple visitor implemented for refactoring --- sway-fmt-v2/src/fmt.rs | 13 ++++++++- sway-fmt-v2/src/items/item_abi.rs | 12 +-------- sway-fmt-v2/src/items/item_const.rs | 3 +-- sway-fmt-v2/src/items/item_fn.rs | 8 +++--- sway-fmt-v2/src/items/item_trait.rs | 36 ++++++++++++++++++++++++- sway-fmt-v2/src/utils/comments.rs | 42 +++++++++++++++++++++++++++-- sway-fmt-v2/src/utils/expr.rs | 9 +++---- sway-fmt-v2/src/utils/item.rs | 1 + 8 files changed, 96 insertions(+), 28 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 4662f8b44d0..1c2a3cc789e 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -553,7 +553,12 @@ storage { long_var_name: Type1=Type1{}, // Testing another comment var2: Type2=Type2{} // This is the last comment, - }"#; + } +// This is the programmer trait +trait Programmer { + // Returns fav languages of this Programmer. + fn fav_language(self) -> String; +}"#; let correct_sway_code = r#"contract; // This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implementedcontract; @@ -601,7 +606,13 @@ storage { // Testing another comment var2: Type2 = Type2 { }, // This is the last comment, +} +// This is the programmer trait +trait Programmer { + // Returns fav languages of this Programmer. + fn fav_language(self) -> String; }"#; + let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); diff --git a/sway-fmt-v2/src/items/item_abi.rs b/sway-fmt-v2/src/items/item_abi.rs index d3d624608cb..65bec3f5b5c 100644 --- a/sway-fmt-v2/src/items/item_abi.rs +++ b/sway-fmt-v2/src/items/item_abi.rs @@ -9,9 +9,7 @@ use crate::{ FormatterError, }; use std::fmt::Write; -use sway_parse::{ - attribute::Annotated, keywords::SemicolonToken, token::Delimiter, FnSignature, ItemAbi, -}; +use sway_parse::{token::Delimiter, ItemAbi}; use sway_types::Spanned; impl Format for ItemAbi { @@ -148,11 +146,3 @@ impl CommentVisitor for ItemAbi { collected_spans } } - -impl CommentVisitor for (Annotated, SemicolonToken) { - fn collect_spans(&self) -> Vec { - let mut collected_spans = self.0.collect_spans(); - collected_spans.push(CommentSpan::from_span(self.1.span())); - collected_spans - } -} diff --git a/sway-fmt-v2/src/items/item_const.rs b/sway-fmt-v2/src/items/item_const.rs index bb72ce16a62..d20d91a4279 100644 --- a/sway-fmt-v2/src/items/item_const.rs +++ b/sway-fmt-v2/src/items/item_const.rs @@ -55,9 +55,8 @@ impl CommentVisitor for ItemConst { collected_spans.push(CommentSpan::from_span(self.const_token.span())); collected_spans.push(CommentSpan::from_span(self.name.span())); if let Some(ty) = &self.ty_opt { - collected_spans.push(CommentSpan::from_span(ty.0.span())); + collected_spans.append(&mut ty.collect_spans()); // TODO: determine if we allow comments in between `:` and ty - collected_spans.append(&mut ty.1.collect_spans()); } collected_spans.push(CommentSpan::from_span(self.eq_token.span())); collected_spans.append(&mut self.expr.collect_spans()); diff --git a/sway-fmt-v2/src/items/item_fn.rs b/sway-fmt-v2/src/items/item_fn.rs index 8d52c5ca6eb..eb86dd13fbf 100644 --- a/sway-fmt-v2/src/items/item_fn.rs +++ b/sway-fmt-v2/src/items/item_fn.rs @@ -241,9 +241,8 @@ impl CommentVisitor for FnSignature { collected_spans.push(CommentSpan::from_span(generics.parameters.span())); } collected_spans.append(&mut self.arguments.collect_spans()); - if let Some((right_arrow_token, ty)) = &self.return_type_opt { - collected_spans.push(CommentSpan::from_span(right_arrow_token.span())); - collected_spans.push(CommentSpan::from_span(ty.span())); + if let Some(return_type) = &self.return_type_opt { + collected_spans.append(&mut return_type.collect_spans()); } // TODO add where, I will add where for all items at once. collected_spans @@ -267,8 +266,7 @@ impl CommentVisitor for FnArgs { collected_spans.push(CommentSpan::from_span(mutable.span())); } if let Some(args) = args_opt { - collected_spans.push(CommentSpan::from_span(args.0.span())); - collected_spans.append(&mut args.1.collect_spans()); + collected_spans.append(&mut args.collect_spans()); } } }; diff --git a/sway-fmt-v2/src/items/item_trait.rs b/sway-fmt-v2/src/items/item_trait.rs index 882067e654d..bf41ba694ce 100644 --- a/sway-fmt-v2/src/items/item_trait.rs +++ b/sway-fmt-v2/src/items/item_trait.rs @@ -1,4 +1,11 @@ -use crate::{config::items::ItemBraceStyle, fmt::*, utils::bracket::CurlyBrace}; +use crate::{ + config::items::ItemBraceStyle, + fmt::*, + utils::{ + bracket::CurlyBrace, + comments::{CommentSpan, CommentVisitor}, + }, +}; use std::fmt::Write; use sway_parse::{token::Delimiter, ItemTrait, Traits}; use sway_types::Spanned; @@ -113,3 +120,30 @@ impl Format for Traits { Ok(()) } } + +impl CommentVisitor for ItemTrait { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + if let Some(visibility) = &self.visibility { + collected_spans.push(CommentSpan::from_span(visibility.span())); + } + collected_spans.push(CommentSpan::from_span(self.trait_token.span())); + collected_spans.push(CommentSpan::from_span(self.name.span())); + if let Some(super_traits) = &self.super_traits { + collected_spans.append(&mut super_traits.collect_spans()); + } + collected_spans.append(&mut self.trait_items.collect_spans()); + if let Some(trait_defs) = &self.trait_defs_opt { + collected_spans.append(&mut trait_defs.collect_spans()); + } + collected_spans + } +} + +impl CommentVisitor for Traits { + fn collect_spans(&self) -> Vec { + let mut collected_spans = self.prefix.collect_spans(); + collected_spans.append(&mut self.suffixes.collect_spans()); + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index b33f4895429..1850151d56e 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -11,7 +11,7 @@ use std::{ use sway_parse::{ attribute::Annotated, brackets::{Parens, SquareBrackets}, - keywords::CommaToken, + keywords::{AddToken, ColonToken, CommaToken, RightArrowToken, SemicolonToken}, token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, Braces, Module, Parse, TypeField, }; @@ -157,6 +157,17 @@ where } } +impl CommentVisitor for (T, P) +where + T: CommentVisitor, + P: CommentVisitor, +{ + fn collect_spans(&self) -> Vec { + let mut collected_spans = self.0.collect_spans(); + collected_spans.append(&mut self.1.collect_spans()); + collected_spans + } +} impl CommentVisitor for Vec where T: CommentVisitor, @@ -193,7 +204,34 @@ impl CommentVisitor for CommaToken { impl CommentVisitor for TypeField { fn collect_spans(&self) -> Vec { - vec![(CommentSpan::from_span(self.span()))] + let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; + collected_spans.push(CommentSpan::from_span(self.colon_token.span())); + collected_spans.append(&mut self.ty.collect_spans()); + collected_spans + } +} + +impl CommentVisitor for AddToken { + fn collect_spans(&self) -> Vec { + vec![CommentSpan::from_span(self.span())] + } +} + +impl CommentVisitor for SemicolonToken { + fn collect_spans(&self) -> Vec { + vec![CommentSpan::from_span(self.span())] + } +} + +impl CommentVisitor for ColonToken { + fn collect_spans(&self) -> Vec { + vec![CommentSpan::from_span(self.span())] + } +} + +impl CommentVisitor for RightArrowToken { + fn collect_spans(&self) -> Vec { + vec![CommentSpan::from_span(self.span())] } } /// Handles comments by first creating the CommentMap which is used for fast seaching comments. diff --git a/sway-fmt-v2/src/utils/expr.rs b/sway-fmt-v2/src/utils/expr.rs index a2494ca1bc0..84fef79304a 100644 --- a/sway-fmt-v2/src/utils/expr.rs +++ b/sway-fmt-v2/src/utils/expr.rs @@ -650,9 +650,8 @@ impl CommentVisitor for AsmRegisterDeclaration { fn collect_spans(&self) -> Vec { let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; if let Some(value) = &self.value_opt { - collected_spans.push(CommentSpan::from_span(value.0.span())); + collected_spans.append(&mut value.collect_spans()); // TODO: determine if we are allowing comments between `:` and expr - collected_spans.append(&mut value.1.collect_spans()); } collected_spans } @@ -662,9 +661,8 @@ impl CommentVisitor for AsmBlockContents { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); for instruction in &self.instructions { - collected_spans.append(&mut instruction.0.collect_spans()); + collected_spans.append(&mut instruction.collect_spans()); // TODO: probably we shouldn't allow for comments in between the instruction and comma since it may/will result in build failure after formatting - collected_spans.push(CommentSpan::from_span(instruction.1.span())); } collected_spans } @@ -681,9 +679,8 @@ impl CommentVisitor for AsmFinalExpr { fn collect_spans(&self) -> Vec { let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; if let Some(ty) = &self.ty_opt { - collected_spans.push(CommentSpan::from_span(ty.0.span())); + collected_spans.append(&mut ty.collect_spans()); // TODO: determine if we are allowing comments between `:` and ty - collected_spans.append(&mut ty.1.collect_spans()); } collected_spans } diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 31526468537..0954c208f33 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -13,6 +13,7 @@ impl CommentVisitor for Item { Abi(item_abi) => item_abi.collect_spans(), Const(item_const) => item_const.collect_spans(), Storage(item_storage) => item_storage.collect_spans(), + Trait(item_trait) => item_trait.collect_spans(), _ => Vec::new(), } } From 92d815dd54f87c63d6fb0ed5aa5e062fd173511e Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Tue, 19 Jul 2022 14:32:23 +0300 Subject: [PATCH 34/44] CommentVisitor for ItemImpl implemented --- sway-fmt-v2/src/items/item_impl.rs | 17 +++++++++++++++++ sway-fmt-v2/src/utils/comments.rs | 8 +++++++- sway-fmt-v2/src/utils/item.rs | 1 + 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/sway-fmt-v2/src/items/item_impl.rs b/sway-fmt-v2/src/items/item_impl.rs index a14aedad852..59d24e062be 100644 --- a/sway-fmt-v2/src/items/item_impl.rs +++ b/sway-fmt-v2/src/items/item_impl.rs @@ -1,8 +1,10 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, + utils::comments::{CommentSpan, CommentVisitor}, FormatterError, }; use sway_parse::ItemImpl; +use sway_types::Spanned; impl Format for ItemImpl { fn format( @@ -13,3 +15,18 @@ impl Format for ItemImpl { todo!() } } +impl CommentVisitor for ItemImpl { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.impl_token.span())]; + if let Some(generic) = &self.generic_params_opt { + collected_spans.push(CommentSpan::from_span(generic.parameters.span())); + } + if let Some(trait_tuple) = &self.trait_opt { + collected_spans.append(&mut trait_tuple.collect_spans()); + } + collected_spans.append(&mut self.ty.collect_spans()); + // TODO add where + collected_spans.append(&mut self.contents.collect_spans()); + collected_spans + } +} diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 1850151d56e..e11236ce78c 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -11,7 +11,7 @@ use std::{ use sway_parse::{ attribute::Annotated, brackets::{Parens, SquareBrackets}, - keywords::{AddToken, ColonToken, CommaToken, RightArrowToken, SemicolonToken}, + keywords::{AddToken, ColonToken, CommaToken, ForToken, RightArrowToken, SemicolonToken}, token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, Braces, Module, Parse, TypeField, }; @@ -234,6 +234,12 @@ impl CommentVisitor for RightArrowToken { vec![CommentSpan::from_span(self.span())] } } + +impl CommentVisitor for ForToken { + fn collect_spans(&self) -> Vec { + vec![CommentSpan::from_span(self.span())] + } +} /// Handles comments by first creating the CommentMap which is used for fast seaching comments. /// Traverses items for finding a comment in unformatted input and placing it in correct place in formatted output. pub fn handle_comments( diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 0954c208f33..8e290b6c615 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -14,6 +14,7 @@ impl CommentVisitor for Item { Const(item_const) => item_const.collect_spans(), Storage(item_storage) => item_storage.collect_spans(), Trait(item_trait) => item_trait.collect_spans(), + Impl(item_impl) => item_impl.collect_spans(), _ => Vec::new(), } } From 356d3c26f7439665b96f91c3b7c569722904105c Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Tue, 19 Jul 2022 15:36:41 +0300 Subject: [PATCH 35/44] CommentVisitor implemented for ItemUse --- sway-fmt-v2/src/items/item_use.rs | 51 ++++++++++++++++++++++++++++++- sway-fmt-v2/src/utils/item.rs | 4 ++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/items/item_use.rs b/sway-fmt-v2/src/items/item_use.rs index cf23ebc89dd..e9ee4d1d1aa 100644 --- a/sway-fmt-v2/src/items/item_use.rs +++ b/sway-fmt-v2/src/items/item_use.rs @@ -1,8 +1,12 @@ +use std::vec; + use crate::{ fmt::{Format, FormattedCode, Formatter}, + utils::comments::{CommentSpan, CommentVisitor}, FormatterError, }; -use sway_parse::ItemUse; +use sway_parse::{ItemUse, UseTree}; +use sway_types::Spanned; impl Format for ItemUse { fn format( @@ -13,3 +17,48 @@ impl Format for ItemUse { todo!() } } + +impl CommentVisitor for ItemUse { + fn collect_spans(&self) -> Vec { + let mut collected_spans = Vec::new(); + if let Some(visibility) = &self.visibility { + collected_spans.push(CommentSpan::from_span(visibility.span())); + } + collected_spans.push(CommentSpan::from_span(self.use_token.span())); + if let Some(root_import) = &self.root_import { + collected_spans.push(CommentSpan::from_span(root_import.span())); + } + collected_spans.append(&mut self.tree.collect_spans()); + collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans + } +} + +impl CommentVisitor for UseTree { + fn collect_spans(&self) -> Vec { + match self { + UseTree::Group { imports } => imports.collect_spans(), + UseTree::Name { name } => vec![CommentSpan::from_span(name.span())], + UseTree::Rename { + name, + as_token, + alias, + } => vec![ + CommentSpan::from_span(name.span()), + CommentSpan::from_span(as_token.span()), + CommentSpan::from_span(alias.span()), + ], + UseTree::Glob { star_token } => vec![CommentSpan::from_span(star_token.span())], + UseTree::Path { + prefix, + double_colon_token, + suffix, + } => { + let mut collected_spans = vec![CommentSpan::from_span(prefix.span())]; + collected_spans.push(CommentSpan::from_span(double_colon_token.span())); + collected_spans.append(&mut suffix.collect_spans()); + collected_spans + } + } + } +} diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 8e290b6c615..69af358c0bb 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -15,7 +15,9 @@ impl CommentVisitor for Item { Storage(item_storage) => item_storage.collect_spans(), Trait(item_trait) => item_trait.collect_spans(), Impl(item_impl) => item_impl.collect_spans(), - _ => Vec::new(), + Use(item_use) => item_use.collect_spans(), + Break(_) => todo!(), + Continue(_) => todo!(), } } } From dfcf38ab0d1a5bbb56b4a178539ff7c2394c3393 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Tue, 19 Jul 2022 16:17:28 +0300 Subject: [PATCH 36/44] CommentVisitor for Module implemented, refactoring around add_comments --- sway-fmt-v2/src/fmt.rs | 2 +- sway-fmt-v2/src/utils/comments.rs | 101 +++++++++----------------- sway-fmt-v2/src/utils/program_type.rs | 56 +++++++++++++- 3 files changed, 90 insertions(+), 69 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 1c2a3cc789e..afc6fb1b5ef 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -560,7 +560,7 @@ trait Programmer { fn fav_language(self) -> String; }"#; let correct_sway_code = r#"contract; -// This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implementedcontract; +// This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implemented pub struct Foo { // Here is a comment diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index e11236ce78c..dfa37423d77 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -11,7 +11,10 @@ use std::{ use sway_parse::{ attribute::Annotated, brackets::{Parens, SquareBrackets}, - keywords::{AddToken, ColonToken, CommaToken, ForToken, RightArrowToken, SemicolonToken}, + keywords::{ + AddToken, ColonToken, CommaToken, ForToken, ForwardSlashToken, RightArrowToken, + SemicolonToken, + }, token::{lex_commented, Comment, CommentedTokenTree, CommentedTree}, Braces, Module, Parse, TypeField, }; @@ -240,6 +243,12 @@ impl CommentVisitor for ForToken { vec![CommentSpan::from_span(self.span())] } } + +impl CommentVisitor for ForwardSlashToken { + fn collect_spans(&self) -> Vec { + vec![CommentSpan::from_span(self.span())] + } +} /// Handles comments by first creating the CommentMap which is used for fast seaching comments. /// Traverses items for finding a comment in unformatted input and placing it in correct place in formatted output. pub fn handle_comments( @@ -265,7 +274,6 @@ pub fn handle_comments( )?; Ok(()) } - /// Adds the comments from comment_map to correct places in the formatted code. This requires us /// both the unformatted and formatted code's items as they will have different spans for their /// nodes. While traversing the unformatted items, `add_comments` searches for comments. If there is a comment found @@ -277,87 +285,41 @@ fn add_comments( formatted_code: &mut FormattedCode, unformatted_code: Arc, ) -> Result<(), FormatterError> { - let unformatted_items = &unformatted_module.items; - let formatted_items = &formatted_module.items; - - // Once CommentVisitor for ModuleKind is implemented start search from there - let mut prev_unformatted_item_last_span = CommentSpan { start: 0, end: 0 }; - let mut prev_formatted_item_last_span = CommentSpan { start: 0, end: 0 }; + let unformatted_comment_spans = unformatted_module.collect_spans(); + let formatted_comment_spans = formatted_module.collect_spans(); // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted // as the total length of comments we added in previous iterations. let mut offset = 0; - for (unformatted_item, formatted_item) in unformatted_items.iter().zip(formatted_items.iter()) { - let unformatted_item_spans = unformatted_item.collect_spans(); - let formatted_item_spans = formatted_item.collect_spans(); - // TODO: Remove this once every item implements CommentVisitor. This is added to turn tests green - if unformatted_item_spans.first().is_none() || formatted_item_spans.first().is_none() { - return Ok(()); - } - // Search comment between the last item and this one - - // Get first span of the current item from unformatted code - let curr_unformatted_item_first_span = unformatted_item_spans - .first() - .ok_or(FormatterError::CommentError)?; - // Search for comments + // We will definetly have a span in the collected span since for a source code to be parsed there should be some tokens present. + let mut previous_unformatted_comment_span = unformatted_comment_spans + .first() + .ok_or(FormatterError::CommentError)?; + let mut previous_formatted_comment_span = formatted_comment_spans + .first() + .ok_or(FormatterError::CommentError)?; + for (unformatted_comment_span, formatted_comment_span) in unformatted_comment_spans + .iter() + .skip(1) + .zip(formatted_comment_spans.iter().skip(1)) + { let comments_found = get_comments_between_spans( - &prev_unformatted_item_last_span, - curr_unformatted_item_first_span, + previous_unformatted_comment_span, + unformatted_comment_span, &comment_map, &unformatted_code, ); - // If there are some comments in between given spans insert them into the formatted code and increment offset with the length of the inserted comment(s) if !comments_found.is_empty() { offset += insert_after_span( - &prev_formatted_item_last_span, + previous_formatted_comment_span, comments_found, offset, formatted_code, )?; } - - // Search comments for possible places inside the item. - - // We will definetly have a span in the collected span since for a source code to be parsed as an item there should be some tokens present. - let mut previous_unformatted_span = unformatted_item_spans - .first() - .ok_or(FormatterError::CommentError)?; - let mut previous_formatted_span = formatted_item_spans - .first() - .ok_or(FormatterError::CommentError)?; - - // Iterate over the possible spans to check for a comment - for (unformatted_cur_span, formatted_cur_span) in unformatted_item_spans - .iter() - .zip(formatted_item_spans.iter()) - { - let comments_found = get_comments_between_spans( - previous_unformatted_span, - unformatted_cur_span, - &comment_map, - &unformatted_code, - ); - if !comments_found.is_empty() { - offset += insert_after_span( - previous_formatted_span, - comments_found, - offset, - formatted_code, - )?; - } - previous_unformatted_span = unformatted_cur_span; - previous_formatted_span = formatted_cur_span; - } - prev_unformatted_item_last_span = unformatted_item_spans - .last() - .ok_or(FormatterError::CommentError)? - .clone(); - prev_formatted_item_last_span = formatted_item_spans - .last() - .ok_or(FormatterError::CommentError)? - .clone(); + previous_unformatted_comment_span = unformatted_comment_span; + previous_formatted_comment_span = formatted_comment_span; } Ok(()) } @@ -384,6 +346,7 @@ fn get_comments_between_spans( comment_tuple.1.clone(), unformatted_code[from.end..comment_tuple.0.start].to_string(), )); + println!("this"); } else { // There is a comment before this one, so we should get the context starting from the last comment's end to the beginning of the current comment comments_with_context.push(( @@ -394,6 +357,10 @@ fn get_comments_between_spans( )); } } + println!( + " found {:?} between {:?} and {:?} \n\n", + comments_with_context, from, to + ); comments_with_context } diff --git a/sway-fmt-v2/src/utils/program_type.rs b/sway-fmt-v2/src/utils/program_type.rs index e7eab15083c..edee84514ab 100644 --- a/sway-fmt-v2/src/utils/program_type.rs +++ b/sway-fmt-v2/src/utils/program_type.rs @@ -1,9 +1,11 @@ use std::fmt::Write; -use sway_parse::{token::PunctKind, ModuleKind}; +use sway_parse::{dependency::DependencyPath, token::PunctKind, Dependency, Module, ModuleKind}; use sway_types::Spanned; use crate::FormatterError; +use super::comments::{CommentSpan, CommentVisitor}; + /// Insert the program type without applying a formatting to it. /// /// Possible list of program types: @@ -40,3 +42,55 @@ pub(crate) fn insert_program_type( Ok(()) } + +impl CommentVisitor for ModuleKind { + fn collect_spans(&self) -> Vec { + match self { + ModuleKind::Script { script_token } => { + vec![CommentSpan::from_span(script_token.span())] + } + ModuleKind::Contract { contract_token } => { + vec![CommentSpan::from_span(contract_token.span())] + } + ModuleKind::Predicate { predicate_token } => { + vec![CommentSpan::from_span(predicate_token.span())] + } + ModuleKind::Library { + library_token, + name, + } => { + vec![ + CommentSpan::from_span(library_token.span()), + CommentSpan::from_span(name.span()), + ] + } + } + } +} + +impl CommentVisitor for Module { + fn collect_spans(&self) -> Vec { + let mut collected_spans = self.kind.collect_spans(); + collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans.append(&mut self.dependencies.collect_spans()); + collected_spans.append(&mut self.items.collect_spans()); + collected_spans + } +} + +impl CommentVisitor for Dependency { + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![CommentSpan::from_span(self.dep_token.span())]; + collected_spans.append(&mut self.path.collect_spans()); + collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans + } +} + +impl CommentVisitor for DependencyPath { + fn collect_spans(&self) -> Vec { + let mut collected_spans = self.prefix.collect_spans(); + collected_spans.append(&mut self.suffixes.collect_spans()); + collected_spans + } +} From 1c35627f7e7aedab035efa6538dff171d4a0adcd Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 21 Jul 2022 15:09:41 +0300 Subject: [PATCH 37/44] CommentSpan -> ByteSpan renamed --- sway-fmt-v2/src/items/item_abi.rs | 8 +- sway-fmt-v2/src/items/item_const.rs | 14 +-- sway-fmt-v2/src/items/item_enum.rs | 12 +-- sway-fmt-v2/src/items/item_fn.rs | 28 ++--- sway-fmt-v2/src/items/item_impl.rs | 8 +- sway-fmt-v2/src/items/item_storage.rs | 14 +-- sway-fmt-v2/src/items/item_struct.rs | 12 +-- sway-fmt-v2/src/items/item_trait.rs | 12 +-- sway-fmt-v2/src/items/item_use.rs | 28 ++--- sway-fmt-v2/src/utils/attribute.rs | 10 +- sway-fmt-v2/src/utils/comments.rs | 124 +++++++++++----------- sway-fmt-v2/src/utils/expr.rs | 146 +++++++++++++------------- sway-fmt-v2/src/utils/item.rs | 4 +- sway-fmt-v2/src/utils/literal.rs | 12 +-- sway-fmt-v2/src/utils/path.rs | 10 +- sway-fmt-v2/src/utils/pattern.rs | 18 ++-- sway-fmt-v2/src/utils/program_type.rs | 26 ++--- sway-fmt-v2/src/utils/punctuated.rs | 8 +- sway-fmt-v2/src/utils/statement.rs | 26 ++--- sway-fmt-v2/src/utils/ty.rs | 16 +-- 20 files changed, 268 insertions(+), 268 deletions(-) diff --git a/sway-fmt-v2/src/items/item_abi.rs b/sway-fmt-v2/src/items/item_abi.rs index 65bec3f5b5c..f3e7d29b2e6 100644 --- a/sway-fmt-v2/src/items/item_abi.rs +++ b/sway-fmt-v2/src/items/item_abi.rs @@ -4,7 +4,7 @@ use crate::{ utils::{ attribute::FormatDecl, bracket::CurlyBrace, - comments::{CommentSpan, CommentVisitor}, + comments::{ByteSpan, CommentVisitor}, }, FormatterError, }; @@ -136,9 +136,9 @@ impl CurlyBrace for ItemAbi { } impl CommentVisitor for ItemAbi { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.abi_token.span())]; - collected_spans.push(CommentSpan::from_span(self.name.span())); + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.abi_token.span())]; + collected_spans.push(ByteSpan::from_span(self.name.span())); collected_spans.append(&mut self.abi_items.collect_spans()); if let Some(abi_defs) = &self.abi_defs_opt { collected_spans.append(&mut abi_defs.collect_spans()); diff --git a/sway-fmt-v2/src/items/item_const.rs b/sway-fmt-v2/src/items/item_const.rs index d20d91a4279..b9520811c0a 100644 --- a/sway-fmt-v2/src/items/item_const.rs +++ b/sway-fmt-v2/src/items/item_const.rs @@ -1,6 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, FormatterError, }; use std::fmt::Write; @@ -47,20 +47,20 @@ impl Format for ItemConst { } impl CommentVisitor for ItemConst { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(CommentSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from_span(visibility.span())); } - collected_spans.push(CommentSpan::from_span(self.const_token.span())); - collected_spans.push(CommentSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from_span(self.const_token.span())); + collected_spans.push(ByteSpan::from_span(self.name.span())); if let Some(ty) = &self.ty_opt { collected_spans.append(&mut ty.collect_spans()); // TODO: determine if we allow comments in between `:` and ty } - collected_spans.push(CommentSpan::from_span(self.eq_token.span())); + collected_spans.push(ByteSpan::from_span(self.eq_token.span())); collected_spans.append(&mut self.expr.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_enum.rs b/sway-fmt-v2/src/items/item_enum.rs index f032c6a2e1a..1bfab77e80f 100644 --- a/sway-fmt-v2/src/items/item_enum.rs +++ b/sway-fmt-v2/src/items/item_enum.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, utils::{ bracket::CurlyBrace, - comments::{CommentSpan, CommentVisitor}, + comments::{ByteSpan, CommentVisitor}, item::ItemLenChars, }, FormatterError, @@ -240,15 +240,15 @@ impl CurlyBrace for ItemEnum { } } impl CommentVisitor for ItemEnum { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(CommentSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from_span(visibility.span())); } - collected_spans.push(CommentSpan::from_span(self.enum_token.span())); - collected_spans.push(CommentSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from_span(self.enum_token.span())); + collected_spans.push(ByteSpan::from_span(self.name.span())); if let Some(generics) = &self.generics { - collected_spans.push(CommentSpan::from_span(generics.parameters.span())) + collected_spans.push(ByteSpan::from_span(generics.parameters.span())) } collected_spans.append(&mut self.fields.collect_spans()); collected_spans diff --git a/sway-fmt-v2/src/items/item_fn.rs b/sway-fmt-v2/src/items/item_fn.rs index eb86dd13fbf..3b87dc3fbbf 100644 --- a/sway-fmt-v2/src/items/item_fn.rs +++ b/sway-fmt-v2/src/items/item_fn.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter, FormatterError}, utils::{ bracket::{CurlyBrace, Parenthesis}, - comments::{CommentSpan, CommentVisitor}, + comments::{ByteSpan, CommentVisitor}, }, }; use std::fmt::Write; @@ -208,7 +208,7 @@ impl Format for FnArg { } impl CommentVisitor for ItemFn { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.fn_signature.collect_spans()); collected_spans.append(&mut self.body.collect_spans()); @@ -217,7 +217,7 @@ impl CommentVisitor for ItemFn { } impl CommentVisitor for CodeBlockContents { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_span = Vec::new(); for statement in self.statements.iter() { collected_span.append(&mut statement.collect_spans()); @@ -230,15 +230,15 @@ impl CommentVisitor for CodeBlockContents { } impl CommentVisitor for FnSignature { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(CommentSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from_span(visibility.span())); } - collected_spans.push(CommentSpan::from_span(self.fn_token.span())); - collected_spans.push(CommentSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from_span(self.fn_token.span())); + collected_spans.push(ByteSpan::from_span(self.name.span())); if let Some(generics) = &self.generics { - collected_spans.push(CommentSpan::from_span(generics.parameters.span())); + collected_spans.push(ByteSpan::from_span(generics.parameters.span())); } collected_spans.append(&mut self.arguments.collect_spans()); if let Some(return_type) = &self.return_type_opt { @@ -250,7 +250,7 @@ impl CommentVisitor for FnSignature { } impl CommentVisitor for FnArgs { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match &self { FnArgs::Static(arg_static) => { @@ -261,9 +261,9 @@ impl CommentVisitor for FnArgs { mutable_self, args_opt, } => { - collected_spans.push(CommentSpan::from_span(self_token.span())); + collected_spans.push(ByteSpan::from_span(self_token.span())); if let Some(mutable) = mutable_self { - collected_spans.push(CommentSpan::from_span(mutable.span())); + collected_spans.push(ByteSpan::from_span(mutable.span())); } if let Some(args) = args_opt { collected_spans.append(&mut args.collect_spans()); @@ -275,11 +275,11 @@ impl CommentVisitor for FnArgs { } impl CommentVisitor for FnArg { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.pattern.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.colon_token.span())); - collected_spans.push(CommentSpan::from_span(self.ty.span())); + collected_spans.push(ByteSpan::from_span(self.colon_token.span())); + collected_spans.push(ByteSpan::from_span(self.ty.span())); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_impl.rs b/sway-fmt-v2/src/items/item_impl.rs index 59d24e062be..4ca6adee29d 100644 --- a/sway-fmt-v2/src/items/item_impl.rs +++ b/sway-fmt-v2/src/items/item_impl.rs @@ -1,6 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, FormatterError, }; use sway_parse::ItemImpl; @@ -16,10 +16,10 @@ impl Format for ItemImpl { } } impl CommentVisitor for ItemImpl { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.impl_token.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.impl_token.span())]; if let Some(generic) = &self.generic_params_opt { - collected_spans.push(CommentSpan::from_span(generic.parameters.span())); + collected_spans.push(ByteSpan::from_span(generic.parameters.span())); } if let Some(trait_tuple) = &self.trait_opt { collected_spans.append(&mut trait_tuple.collect_spans()); diff --git a/sway-fmt-v2/src/items/item_storage.rs b/sway-fmt-v2/src/items/item_storage.rs index 55826ad7d85..6d1997aaaab 100644 --- a/sway-fmt-v2/src/items/item_storage.rs +++ b/sway-fmt-v2/src/items/item_storage.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, utils::{ bracket::CurlyBrace, - comments::{CommentSpan, CommentVisitor}, + comments::{ByteSpan, CommentVisitor}, item::ItemLenChars, }, FormatterError, @@ -231,19 +231,19 @@ impl CurlyBrace for ItemStorage { } impl CommentVisitor for ItemStorage { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.storage_token.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.storage_token.span())]; collected_spans.append(&mut self.fields.collect_spans()); collected_spans } } impl CommentVisitor for StorageField { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; - collected_spans.push(CommentSpan::from_span(self.colon_token.span())); + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; + collected_spans.push(ByteSpan::from_span(self.colon_token.span())); collected_spans.append(&mut self.ty.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.eq_token.span())); + collected_spans.push(ByteSpan::from_span(self.eq_token.span())); collected_spans.append(&mut self.initializer.collect_spans()); collected_spans } diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index 3649350baa5..003f0fc2efa 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, utils::{ bracket::CurlyBrace, - comments::{CommentSpan, CommentVisitor}, + comments::{ByteSpan, CommentVisitor}, item::ItemLenChars, }, FormatterError, @@ -246,15 +246,15 @@ impl CurlyBrace for ItemStruct { } impl CommentVisitor for ItemStruct { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(CommentSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from_span(visibility.span())); } - collected_spans.push(CommentSpan::from_span(self.struct_token.span())); - collected_spans.push(CommentSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from_span(self.struct_token.span())); + collected_spans.push(ByteSpan::from_span(self.name.span())); if let Some(generics) = &self.generics { - collected_spans.push(CommentSpan::from_span(generics.parameters.span())) + collected_spans.push(ByteSpan::from_span(generics.parameters.span())) } collected_spans.append(&mut self.fields.collect_spans()); collected_spans diff --git a/sway-fmt-v2/src/items/item_trait.rs b/sway-fmt-v2/src/items/item_trait.rs index bf41ba694ce..318e1dc3694 100644 --- a/sway-fmt-v2/src/items/item_trait.rs +++ b/sway-fmt-v2/src/items/item_trait.rs @@ -3,7 +3,7 @@ use crate::{ fmt::*, utils::{ bracket::CurlyBrace, - comments::{CommentSpan, CommentVisitor}, + comments::{ByteSpan, CommentVisitor}, }, }; use std::fmt::Write; @@ -122,13 +122,13 @@ impl Format for Traits { } impl CommentVisitor for ItemTrait { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(CommentSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from_span(visibility.span())); } - collected_spans.push(CommentSpan::from_span(self.trait_token.span())); - collected_spans.push(CommentSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from_span(self.trait_token.span())); + collected_spans.push(ByteSpan::from_span(self.name.span())); if let Some(super_traits) = &self.super_traits { collected_spans.append(&mut super_traits.collect_spans()); } @@ -141,7 +141,7 @@ impl CommentVisitor for ItemTrait { } impl CommentVisitor for Traits { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = self.prefix.collect_spans(); collected_spans.append(&mut self.suffixes.collect_spans()); collected_spans diff --git a/sway-fmt-v2/src/items/item_use.rs b/sway-fmt-v2/src/items/item_use.rs index e9ee4d1d1aa..6453774a522 100644 --- a/sway-fmt-v2/src/items/item_use.rs +++ b/sway-fmt-v2/src/items/item_use.rs @@ -2,7 +2,7 @@ use std::vec; use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, FormatterError, }; use sway_parse::{ItemUse, UseTree}; @@ -19,43 +19,43 @@ impl Format for ItemUse { } impl CommentVisitor for ItemUse { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(CommentSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from_span(visibility.span())); } - collected_spans.push(CommentSpan::from_span(self.use_token.span())); + collected_spans.push(ByteSpan::from_span(self.use_token.span())); if let Some(root_import) = &self.root_import { - collected_spans.push(CommentSpan::from_span(root_import.span())); + collected_spans.push(ByteSpan::from_span(root_import.span())); } collected_spans.append(&mut self.tree.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); collected_spans } } impl CommentVisitor for UseTree { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { match self { UseTree::Group { imports } => imports.collect_spans(), - UseTree::Name { name } => vec![CommentSpan::from_span(name.span())], + UseTree::Name { name } => vec![ByteSpan::from_span(name.span())], UseTree::Rename { name, as_token, alias, } => vec![ - CommentSpan::from_span(name.span()), - CommentSpan::from_span(as_token.span()), - CommentSpan::from_span(alias.span()), + ByteSpan::from_span(name.span()), + ByteSpan::from_span(as_token.span()), + ByteSpan::from_span(alias.span()), ], - UseTree::Glob { star_token } => vec![CommentSpan::from_span(star_token.span())], + UseTree::Glob { star_token } => vec![ByteSpan::from_span(star_token.span())], UseTree::Path { prefix, double_colon_token, suffix, } => { - let mut collected_spans = vec![CommentSpan::from_span(prefix.span())]; - collected_spans.push(CommentSpan::from_span(double_colon_token.span())); + let mut collected_spans = vec![ByteSpan::from_span(prefix.span())]; + collected_spans.push(ByteSpan::from_span(double_colon_token.span())); collected_spans.append(&mut suffix.collect_spans()); collected_spans } diff --git a/sway-fmt-v2/src/utils/attribute.rs b/sway-fmt-v2/src/utils/attribute.rs index dfaf2f3d7a9..8b7bf6d0bd6 100644 --- a/sway-fmt-v2/src/utils/attribute.rs +++ b/sway-fmt-v2/src/utils/attribute.rs @@ -12,7 +12,7 @@ use sway_types::Spanned; use super::{ bracket::{Parenthesis, SquareBracket}, - comments::{CommentSpan, CommentVisitor}, + comments::{ByteSpan, CommentVisitor}, }; impl Format for Annotated { @@ -95,15 +95,15 @@ impl Parenthesis for AttributeDecl { } } impl CommentVisitor for AttributeDecl { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.hash_token.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.hash_token.span())]; collected_spans.append(&mut self.attribute.collect_spans()); collected_spans } } impl CommentVisitor for Attribute { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; if let Some(args) = &self.args { collected_spans.append(&mut args.collect_spans()); } diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index dfa37423d77..923525bd360 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -22,17 +22,17 @@ use sway_types::{Ident, Span, Spanned}; /// Represents a span for the comments in a spesific file /// A stripped down version of sway-types::src::Span #[derive(PartialEq, Eq, Debug, Clone, Default)] -pub struct CommentSpan { +pub struct ByteSpan { // The byte position in the string of the start of the span. pub start: usize, // The byte position in the string of the end of the span. pub end: usize, } -impl CommentSpan { - /// Takes `start` and `end` from `sway::types::Span` and constructs a `CommentSpan` - pub fn from_span(span: Span) -> CommentSpan { - CommentSpan { +impl ByteSpan { + /// Takes `start` and `end` from `sway::types::Span` and constructs a `ByteSpan` + pub fn from_span(span: Span) -> ByteSpan { + ByteSpan { start: span.start(), end: span.end(), } @@ -43,7 +43,7 @@ impl CommentSpan { } } -impl Ord for CommentSpan { +impl Ord for ByteSpan { fn cmp(&self, other: &Self) -> Ordering { // If the starting position is the same encapsulatig span (i.e, wider one) should come // first @@ -54,13 +54,13 @@ impl Ord for CommentSpan { } } -impl PartialOrd for CommentSpan { - fn partial_cmp(&self, other: &CommentSpan) -> Option { +impl PartialOrd for ByteSpan { + fn partial_cmp(&self, other: &ByteSpan) -> Option { Some(self.cmp(other)) } } -pub type CommentMap = BTreeMap; +pub type CommentMap = BTreeMap; /// Get the CommentedTokenStream and collect the spans -> Comment mapping for the input source /// code. @@ -85,7 +85,7 @@ fn collect_comments_from_token_stream( ) { match commented_token_tree { CommentedTokenTree::Comment(comment) => { - let comment_span = CommentSpan { + let comment_span = ByteSpan { start: comment.span.start(), end: comment.span.end(), }; @@ -104,17 +104,17 @@ impl CommentVisitor for Braces where T: CommentVisitor + Clone, { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - let mut opening_brace_span = CommentSpan::from_span(self.span()); + let mut opening_brace_span = ByteSpan::from_span(self.span()); opening_brace_span.end = opening_brace_span.start + 1; - // Add opening brace's CommentSpan + // Add opening brace's ByteSpan collected_spans.push(opening_brace_span); - // Add T's collected CommentSpan + // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().collect_spans()); - let mut closing_brace_span = CommentSpan::from_span(self.span()); + let mut closing_brace_span = ByteSpan::from_span(self.span()); closing_brace_span.start = closing_brace_span.end - 1; - // Add closing brace's CommentSpan + // Add closing brace's ByteSpan collected_spans.push(closing_brace_span); collected_spans } @@ -124,17 +124,17 @@ impl CommentVisitor for Parens where T: CommentVisitor + Clone, { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - let mut opening_paren_span = CommentSpan::from_span(self.span()); + let mut opening_paren_span = ByteSpan::from_span(self.span()); opening_paren_span.end = opening_paren_span.start + 1; // Add opening paren's span collected_spans.push(opening_paren_span); - // Add T's collected CommentSpan + // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().collect_spans()); - let mut closing_paren_span = CommentSpan::from_span(self.span()); + let mut closing_paren_span = ByteSpan::from_span(self.span()); closing_paren_span.start = closing_paren_span.end - 1; - // Add closing paren's CommentSpan + // Add closing paren's ByteSpan collected_spans.push(closing_paren_span); collected_spans } @@ -144,17 +144,17 @@ impl CommentVisitor for SquareBrackets where T: CommentVisitor + Clone, { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - let mut opening_bracket_span = CommentSpan::from_span(self.span()); + let mut opening_bracket_span = ByteSpan::from_span(self.span()); opening_bracket_span.end = opening_bracket_span.start + 1; // Add opening bracket's span collected_spans.push(opening_bracket_span); - // Add T's collected CommentSpan + // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().collect_spans()); - let mut closing_bracket_span = CommentSpan::from_span(self.span()); + let mut closing_bracket_span = ByteSpan::from_span(self.span()); closing_bracket_span.start = closing_bracket_span.end - 1; - // Add closing bracket's CommentSpan + // Add closing bracket's ByteSpan collected_spans.push(closing_bracket_span); collected_spans } @@ -165,7 +165,7 @@ where T: CommentVisitor, P: CommentVisitor, { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = self.0.collect_spans(); collected_spans.append(&mut self.1.collect_spans()); collected_spans @@ -175,7 +175,7 @@ impl CommentVisitor for Vec where T: CommentVisitor, { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); for t in self { collected_spans.append(&mut t.collect_spans()); @@ -187,7 +187,7 @@ impl CommentVisitor for Annotated where T: CommentVisitor + Parse, { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = self.attribute_list.collect_spans(); collected_spans.append(&mut self.value.collect_spans()); collected_spans @@ -195,58 +195,58 @@ where } impl CommentVisitor for Ident { - fn collect_spans(&self) -> Vec { - vec![CommentSpan::from_span(self.span())] + fn collect_spans(&self) -> Vec { + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for CommaToken { - fn collect_spans(&self) -> Vec { - vec![(CommentSpan::from_span(self.span()))] + fn collect_spans(&self) -> Vec { + vec![(ByteSpan::from_span(self.span()))] } } impl CommentVisitor for TypeField { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; - collected_spans.push(CommentSpan::from_span(self.colon_token.span())); + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; + collected_spans.push(ByteSpan::from_span(self.colon_token.span())); collected_spans.append(&mut self.ty.collect_spans()); collected_spans } } impl CommentVisitor for AddToken { - fn collect_spans(&self) -> Vec { - vec![CommentSpan::from_span(self.span())] + fn collect_spans(&self) -> Vec { + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for SemicolonToken { - fn collect_spans(&self) -> Vec { - vec![CommentSpan::from_span(self.span())] + fn collect_spans(&self) -> Vec { + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for ColonToken { - fn collect_spans(&self) -> Vec { - vec![CommentSpan::from_span(self.span())] + fn collect_spans(&self) -> Vec { + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for RightArrowToken { - fn collect_spans(&self) -> Vec { - vec![CommentSpan::from_span(self.span())] + fn collect_spans(&self) -> Vec { + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for ForToken { - fn collect_spans(&self) -> Vec { - vec![CommentSpan::from_span(self.span())] + fn collect_spans(&self) -> Vec { + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for ForwardSlashToken { - fn collect_spans(&self) -> Vec { - vec![CommentSpan::from_span(self.span())] + fn collect_spans(&self) -> Vec { + vec![ByteSpan::from_span(self.span())] } } /// Handles comments by first creating the CommentMap which is used for fast seaching comments. @@ -330,8 +330,8 @@ type CommentWithContext = (Comment, String); /// Returns a list of comments between given spans. For each comment returns the Context /// Context of a comment is basically the offset (the characters between the last item/comment) to the current comment fn get_comments_between_spans( - from: &CommentSpan, - to: &CommentSpan, + from: &ByteSpan, + to: &ByteSpan, comment_map: &CommentMap, unformatted_code: &Arc, ) -> Vec { @@ -366,7 +366,7 @@ fn get_comments_between_spans( /// Inserts after given span and returns the offset. While inserting comments this also inserts Context of the comments so that the alignment whitespaces/newlines are intact fn insert_after_span( - from: &CommentSpan, + from: &ByteSpan, comments_to_insert: Vec, offset: usize, formatted_code: &mut FormattedCode, @@ -399,19 +399,19 @@ fn format_comment(comment: &Comment) -> String { /// While searching for a comment we need the possible places a comment can be placed in a structure /// `collect_spans` collects all field's spans so that we can check in between them. pub trait CommentVisitor { - fn collect_spans(&self) -> Vec; + fn collect_spans(&self) -> Vec; } #[cfg(test)] mod tests { - use super::{comment_map_from_src, CommentSpan}; + use super::{comment_map_from_src, ByteSpan}; use std::{ops::Bound::Included, sync::Arc}; #[test] fn test_comment_span_ordering() { - let first_span = CommentSpan { start: 2, end: 6 }; - let second_span = CommentSpan { start: 2, end: 4 }; - let third_span = CommentSpan { start: 4, end: 7 }; + let first_span = ByteSpan { start: 2, end: 6 }; + let second_span = ByteSpan { start: 2, end: 4 }; + let third_span = ByteSpan { start: 4, end: 7 }; let mut vec = vec![second_span.clone(), third_span.clone(), first_span.clone()]; vec.sort(); @@ -435,8 +435,8 @@ mod tests { "#; let map = comment_map_from_src(Arc::from(input)).unwrap(); assert!(!map.is_empty()); - let range_start_span = CommentSpan { start: 0, end: 32 }; - let range_end_span = CommentSpan { start: 33, end: 34 }; + let range_start_span = ByteSpan { start: 0, end: 32 }; + let range_end_span = ByteSpan { start: 33, end: 34 }; let found_comment = map .range((Included(range_start_span), Included(range_end_span))) .last() @@ -457,8 +457,8 @@ mod tests { "#; let map = comment_map_from_src(Arc::from(input)).unwrap(); assert!(!map.is_empty()); - let range_start_span = CommentSpan { start: 40, end: 54 }; - let range_end_span = CommentSpan { + let range_start_span = ByteSpan { start: 40, end: 54 }; + let range_end_span = ByteSpan { start: 100, end: 115, }; @@ -482,11 +482,11 @@ mod tests { "#; let map = comment_map_from_src(Arc::from(input)).unwrap(); assert!(!map.is_empty()); - let range_start_span = CommentSpan { + let range_start_span = ByteSpan { start: 110, end: 116, }; - let range_end_span = CommentSpan { + let range_end_span = ByteSpan { start: 200, end: 201, }; diff --git a/sway-fmt-v2/src/utils/expr.rs b/sway-fmt-v2/src/utils/expr.rs index 84fef79304a..b788235d4f9 100644 --- a/sway-fmt-v2/src/utils/expr.rs +++ b/sway-fmt-v2/src/utils/expr.rs @@ -1,7 +1,7 @@ use crate::{ config::items::ItemBraceStyle, fmt::*, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, }; use std::{fmt::Write, vec}; use sway_parse::{ @@ -260,24 +260,24 @@ impl CurlyBrace for ExprStructField { // TODO: Find a better way of handling Boxed version impl CommentVisitor for Box { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { visit_expr(self) } } impl CommentVisitor for Expr { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { visit_expr(self) } } -/// Collects various expr field's CommentSpans. -fn visit_expr(expr: &Expr) -> Vec { +/// Collects various expr field's ByteSpans. +fn visit_expr(expr: &Expr) -> Vec { match expr { Expr::Path(path) => path.collect_spans(), Expr::Literal(literal) => literal.collect_spans(), Expr::AbiCast { abi_token, args } => { - let mut collected_spans = vec![CommentSpan::from_span(abi_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(abi_token.span())]; collected_spans.append(&mut args.collect_spans()); collected_spans } @@ -295,7 +295,7 @@ fn visit_expr(expr: &Expr) -> Vec { return_token, expr_opt, } => { - let mut collected_spans = vec![CommentSpan::from_span(return_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(return_token.span())]; if let Some(expr) = expr_opt { collected_spans.append(&mut expr.collect_spans()); } @@ -307,7 +307,7 @@ fn visit_expr(expr: &Expr) -> Vec { value, branches, } => { - let mut collected_spans = vec![CommentSpan::from_span(match_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(match_token.span())]; collected_spans.append(&mut value.collect_spans()); collected_spans.append(&mut branches.collect_spans()); collected_spans @@ -317,7 +317,7 @@ fn visit_expr(expr: &Expr) -> Vec { condition, block, } => { - let mut collected_spans = vec![CommentSpan::from_span(while_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(while_token.span())]; collected_spans.append(&mut condition.collect_spans()); collected_spans.append(&mut block.collect_spans()); collected_spans @@ -343,8 +343,8 @@ fn visit_expr(expr: &Expr) -> Vec { } => { let mut collected_spans = Vec::new(); collected_spans.append(&mut target.collect_spans()); - collected_spans.push(CommentSpan::from_span(dot_token.span())); - collected_spans.push(CommentSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from_span(dot_token.span())); + collected_spans.push(ByteSpan::from_span(name.span())); if let Some(contract_args) = contract_args_opt { collected_spans.append(&mut contract_args.collect_spans()); } @@ -358,8 +358,8 @@ fn visit_expr(expr: &Expr) -> Vec { } => { let mut collected_spans = Vec::new(); collected_spans.append(&mut target.collect_spans()); - collected_spans.push(CommentSpan::from_span(dot_token.span())); - collected_spans.push(CommentSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from_span(dot_token.span())); + collected_spans.push(ByteSpan::from_span(name.span())); collected_spans } Expr::TupleFieldProjection { @@ -370,22 +370,22 @@ fn visit_expr(expr: &Expr) -> Vec { } => { let mut collected_spans = Vec::new(); collected_spans.append(&mut target.collect_spans()); - collected_spans.push(CommentSpan::from_span(dot_token.span())); - collected_spans.push(CommentSpan::from_span(field_span.clone())); + collected_spans.push(ByteSpan::from_span(dot_token.span())); + collected_spans.push(ByteSpan::from_span(field_span.clone())); collected_spans } Expr::Ref { ref_token, expr } => { - let mut collected_spans = vec![CommentSpan::from_span(ref_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(ref_token.span())]; collected_spans.append(&mut expr.collect_spans()); collected_spans } Expr::Deref { deref_token, expr } => { - let mut collected_spans = vec![CommentSpan::from_span(deref_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(deref_token.span())]; collected_spans.append(&mut expr.collect_spans()); collected_spans } Expr::Not { bang_token, expr } => { - let mut collected_spans = vec![CommentSpan::from_span(bang_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(bang_token.span())]; collected_spans.append(&mut expr.collect_spans()); collected_spans } @@ -395,7 +395,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(star_token.span())); + collected_spans.push(ByteSpan::from_span(star_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -405,7 +405,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(forward_slash_token.span())); + collected_spans.push(ByteSpan::from_span(forward_slash_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -415,7 +415,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(percent_token.span())); + collected_spans.push(ByteSpan::from_span(percent_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -425,7 +425,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(add_token.span())); + collected_spans.push(ByteSpan::from_span(add_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -435,7 +435,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(sub_token.span())); + collected_spans.push(ByteSpan::from_span(sub_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -445,7 +445,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(shl_token.span())); + collected_spans.push(ByteSpan::from_span(shl_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -455,7 +455,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(shr_token.span())); + collected_spans.push(ByteSpan::from_span(shr_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -465,7 +465,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(ampersand_token.span())); + collected_spans.push(ByteSpan::from_span(ampersand_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -475,7 +475,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(caret_token.span())); + collected_spans.push(ByteSpan::from_span(caret_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -485,7 +485,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(pipe_token.span())); + collected_spans.push(ByteSpan::from_span(pipe_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -495,7 +495,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(double_eq_token.span())); + collected_spans.push(ByteSpan::from_span(double_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -505,7 +505,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(bang_eq_token.span())); + collected_spans.push(ByteSpan::from_span(bang_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -515,7 +515,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(less_than_token.span())); + collected_spans.push(ByteSpan::from_span(less_than_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -525,7 +525,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(greater_than_token.span())); + collected_spans.push(ByteSpan::from_span(greater_than_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -535,7 +535,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(less_than_eq_token.span())); + collected_spans.push(ByteSpan::from_span(less_than_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -545,7 +545,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(greater_than_eq_token.span())); + collected_spans.push(ByteSpan::from_span(greater_than_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -555,7 +555,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(double_ampersand_token.span())); + collected_spans.push(ByteSpan::from_span(double_ampersand_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -565,7 +565,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(CommentSpan::from_span(double_pipe_token.span())); + collected_spans.push(ByteSpan::from_span(double_pipe_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -575,7 +575,7 @@ fn visit_expr(expr: &Expr) -> Vec { expr, } => { let mut collected_spans = assignable.collect_spans(); - collected_spans.push(CommentSpan::from_span(reassignment_op.span.clone())); + collected_spans.push(ByteSpan::from_span(reassignment_op.span.clone())); collected_spans.append(&mut expr.collect_spans()); collected_spans } @@ -583,19 +583,19 @@ fn visit_expr(expr: &Expr) -> Vec { } impl CommentVisitor for AbiCastArgs { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.name.span())]; - collected_spans.push(CommentSpan::from_span(self.comma_token.span())); + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; + collected_spans.push(ByteSpan::from_span(self.comma_token.span())); collected_spans.append(&mut self.address.collect_spans()); collected_spans } } impl CommentVisitor for ExprStructField { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.field_name.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.field_name.span())]; if let Some(expr) = &self.expr_opt { - collected_spans.push(CommentSpan::from_span(expr.0.span())); + collected_spans.push(ByteSpan::from_span(expr.0.span())); // TODO: determine if we are allowing comments between `:` and expr collected_spans.append(&mut expr.1.collect_spans()); } @@ -604,7 +604,7 @@ impl CommentVisitor for ExprStructField { } impl CommentVisitor for ExprTupleDescriptor { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let ExprTupleDescriptor::Cons { head, @@ -613,7 +613,7 @@ impl CommentVisitor for ExprTupleDescriptor { } = self { collected_spans.append(&mut head.collect_spans()); - collected_spans.push(CommentSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from_span(comma_token.span())); collected_spans.append(&mut tail.collect_spans()); } collected_spans @@ -621,7 +621,7 @@ impl CommentVisitor for ExprTupleDescriptor { } impl CommentVisitor for ExprArrayDescriptor { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let ExprArrayDescriptor::Repeat { value, @@ -630,7 +630,7 @@ impl CommentVisitor for ExprArrayDescriptor { } = self { collected_spans.append(&mut value.collect_spans()); - collected_spans.push(CommentSpan::from_span(semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(semicolon_token.span())); collected_spans.append(&mut length.collect_spans()); } collected_spans @@ -638,8 +638,8 @@ impl CommentVisitor for ExprArrayDescriptor { } impl CommentVisitor for AsmBlock { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.asm_token.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.asm_token.span())]; collected_spans.append(&mut self.registers.collect_spans()); collected_spans.append(&mut self.contents.collect_spans()); collected_spans @@ -647,8 +647,8 @@ impl CommentVisitor for AsmBlock { } impl CommentVisitor for AsmRegisterDeclaration { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.register.span())]; if let Some(value) = &self.value_opt { collected_spans.append(&mut value.collect_spans()); // TODO: determine if we are allowing comments between `:` and expr @@ -658,7 +658,7 @@ impl CommentVisitor for AsmRegisterDeclaration { } impl CommentVisitor for AsmBlockContents { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); for instruction in &self.instructions { collected_spans.append(&mut instruction.collect_spans()); @@ -669,15 +669,15 @@ impl CommentVisitor for AsmBlockContents { } impl CommentVisitor for Instruction { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { // Visit instructions as a whole unit, meaning we cannot insert comments inside an instruction. - vec![CommentSpan::from_span(self.span())] + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for AsmFinalExpr { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.register.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.register.span())]; if let Some(ty) = &self.ty_opt { collected_spans.append(&mut ty.collect_spans()); // TODO: determine if we are allowing comments between `:` and ty @@ -687,12 +687,12 @@ impl CommentVisitor for AsmFinalExpr { } impl CommentVisitor for IfExpr { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.if_token.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.if_token.span())]; collected_spans.append(&mut self.condition.collect_spans()); collected_spans.append(&mut self.then_block.collect_spans()); if let Some(else_block) = &self.else_opt { - collected_spans.push(CommentSpan::from_span(else_block.0.span())); + collected_spans.push(ByteSpan::from_span(else_block.0.span())); let mut else_body_spans = match &else_block.1 { std::ops::ControlFlow::Continue(if_expr) => if_expr.collect_spans(), std::ops::ControlFlow::Break(else_body) => else_body.collect_spans(), @@ -704,7 +704,7 @@ impl CommentVisitor for IfExpr { } impl CommentVisitor for IfCondition { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { match self { IfCondition::Expr(expr) => expr.collect_spans(), IfCondition::Let { @@ -713,9 +713,9 @@ impl CommentVisitor for IfCondition { eq_token, rhs, } => { - let mut collected_spans = vec![CommentSpan::from_span(let_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(let_token.span())]; collected_spans.append(&mut lhs.collect_spans()); - collected_spans.push(CommentSpan::from_span(eq_token.span())); + collected_spans.push(ByteSpan::from_span(eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -724,17 +724,17 @@ impl CommentVisitor for IfCondition { } impl CommentVisitor for MatchBranch { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.pattern.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.fat_right_arrow_token.span())); + collected_spans.push(ByteSpan::from_span(self.fat_right_arrow_token.span())); collected_spans.append(&mut self.kind.collect_spans()); collected_spans } } impl CommentVisitor for MatchBranchKind { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { MatchBranchKind::Block { @@ -744,13 +744,13 @@ impl CommentVisitor for MatchBranchKind { collected_spans.append(&mut block.collect_spans()); // TODO: determine if we allow comments between block and comma_token if let Some(comma_token) = comma_token_opt { - collected_spans.push(CommentSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from_span(comma_token.span())); } } MatchBranchKind::Expr { expr, comma_token } => { collected_spans.append(&mut expr.collect_spans()); // TODO: determine if we allow comments between expr and comma_token - collected_spans.push(CommentSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from_span(comma_token.span())); } }; collected_spans @@ -758,10 +758,10 @@ impl CommentVisitor for MatchBranchKind { } impl CommentVisitor for Assignable { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { - Assignable::Var(var) => collected_spans.push(CommentSpan::from_span(var.span())), + Assignable::Var(var) => collected_spans.push(ByteSpan::from_span(var.span())), Assignable::Index { target, arg } => { collected_spans.append(&mut target.collect_spans()); collected_spans.append(&mut arg.collect_spans()); @@ -772,8 +772,8 @@ impl CommentVisitor for Assignable { name, } => { collected_spans.append(&mut target.collect_spans()); - collected_spans.push(CommentSpan::from_span(dot_token.span())); - collected_spans.push(CommentSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from_span(dot_token.span())); + collected_spans.push(ByteSpan::from_span(name.span())); } Assignable::TupleFieldProjection { target, @@ -782,8 +782,8 @@ impl CommentVisitor for Assignable { field_span, } => { collected_spans.append(&mut target.collect_spans()); - collected_spans.push(CommentSpan::from_span(dot_token.span())); - collected_spans.push(CommentSpan::from_span(field_span.clone())); + collected_spans.push(ByteSpan::from_span(dot_token.span())); + collected_spans.push(ByteSpan::from_span(field_span.clone())); } }; collected_spans diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 69af358c0bb..580f494f8bb 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -1,11 +1,11 @@ use crate::{ fmt::{Format, FormattedCode, Formatter, FormatterError}, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, }; use sway_parse::{Item, ItemKind::*}; impl CommentVisitor for Item { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { match &self.value { Struct(item_struct) => item_struct.collect_spans(), Enum(item_enum) => item_enum.collect_spans(), diff --git a/sway-fmt-v2/src/utils/literal.rs b/sway-fmt-v2/src/utils/literal.rs index 6269f02a4fc..3e44d302ec9 100644 --- a/sway-fmt-v2/src/utils/literal.rs +++ b/sway-fmt-v2/src/utils/literal.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, }; use std::fmt::Write; use sway_parse::Literal; @@ -23,12 +23,12 @@ impl Format for Literal { } impl CommentVisitor for Literal { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { match self { - Literal::String(str_lit) => vec![CommentSpan::from_span(str_lit.span.clone())], - Literal::Char(chr_lit) => vec![CommentSpan::from_span(chr_lit.span.clone())], - Literal::Int(int_lit) => vec![CommentSpan::from_span(int_lit.span.clone())], - Literal::Bool(bool_lit) => vec![CommentSpan::from_span(bool_lit.span.clone())], + Literal::String(str_lit) => vec![ByteSpan::from_span(str_lit.span.clone())], + Literal::Char(chr_lit) => vec![ByteSpan::from_span(chr_lit.span.clone())], + Literal::Int(int_lit) => vec![ByteSpan::from_span(int_lit.span.clone())], + Literal::Bool(bool_lit) => vec![ByteSpan::from_span(bool_lit.span.clone())], } } } diff --git a/sway-fmt-v2/src/utils/path.rs b/sway-fmt-v2/src/utils/path.rs index 5f59d4024bb..958741776be 100644 --- a/sway-fmt-v2/src/utils/path.rs +++ b/sway-fmt-v2/src/utils/path.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, }; use std::{fmt::Write, vec}; use sway_parse::{PathExpr, PathExprSegment, PathType, PathTypeSegment, QualifiedPathRoot}; @@ -137,19 +137,19 @@ impl Format for PathTypeSegment { } impl CommentVisitor for PathExpr { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted // root::parent/* i am a comment*/::child // I am not sure if this is something the language will allow. - vec![CommentSpan::from_span(self.span())] + vec![ByteSpan::from_span(self.span())] } } impl CommentVisitor for PathType { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { // TODO: Should we look for a comment inside the path type? if so we will need to implement CommentVisitor for PathType // For now we are assuming there will be no comments inside the PathType so we are visiting it as a single unit. - vec![CommentSpan::from_span(self.span())] + vec![ByteSpan::from_span(self.span())] } } diff --git a/sway-fmt-v2/src/utils/pattern.rs b/sway-fmt-v2/src/utils/pattern.rs index 3135fed7376..945c0c65476 100644 --- a/sway-fmt-v2/src/utils/pattern.rs +++ b/sway-fmt-v2/src/utils/pattern.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, }; use std::fmt::Write; use sway_parse::{token::Delimiter, Pattern, PatternStructField}; @@ -119,17 +119,17 @@ impl Format for PatternStructField { } impl CommentVisitor for Pattern { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { Pattern::Wildcard { underscore_token } => { - collected_spans.push(CommentSpan::from_span(underscore_token.span())); + collected_spans.push(ByteSpan::from_span(underscore_token.span())); } Pattern::Var { mutable, name } => { if let Some(mutable) = mutable { - collected_spans.push(CommentSpan::from_span(mutable.span())); + collected_spans.push(ByteSpan::from_span(mutable.span())); } - collected_spans.push(CommentSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from_span(name.span())); } Pattern::Literal(literal) => { collected_spans.append(&mut literal.collect_spans()); @@ -154,19 +154,19 @@ impl CommentVisitor for Pattern { } impl CommentVisitor for PatternStructField { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { PatternStructField::Rest { token } => { - collected_spans.push(CommentSpan::from_span(token.span())); + collected_spans.push(ByteSpan::from_span(token.span())); } PatternStructField::Field { field_name, pattern_opt, } => { - collected_spans.push(CommentSpan::from_span(field_name.span())); + collected_spans.push(ByteSpan::from_span(field_name.span())); if let Some(pattern) = pattern_opt { - collected_spans.push(CommentSpan::from_span(pattern.0.span())); + collected_spans.push(ByteSpan::from_span(pattern.0.span())); collected_spans.append(&mut pattern.1.collect_spans()); } } diff --git a/sway-fmt-v2/src/utils/program_type.rs b/sway-fmt-v2/src/utils/program_type.rs index edee84514ab..3d8d22eebdc 100644 --- a/sway-fmt-v2/src/utils/program_type.rs +++ b/sway-fmt-v2/src/utils/program_type.rs @@ -4,7 +4,7 @@ use sway_types::Spanned; use crate::FormatterError; -use super::comments::{CommentSpan, CommentVisitor}; +use super::comments::{ByteSpan, CommentVisitor}; /// Insert the program type without applying a formatting to it. /// @@ -44,24 +44,24 @@ pub(crate) fn insert_program_type( } impl CommentVisitor for ModuleKind { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { match self { ModuleKind::Script { script_token } => { - vec![CommentSpan::from_span(script_token.span())] + vec![ByteSpan::from_span(script_token.span())] } ModuleKind::Contract { contract_token } => { - vec![CommentSpan::from_span(contract_token.span())] + vec![ByteSpan::from_span(contract_token.span())] } ModuleKind::Predicate { predicate_token } => { - vec![CommentSpan::from_span(predicate_token.span())] + vec![ByteSpan::from_span(predicate_token.span())] } ModuleKind::Library { library_token, name, } => { vec![ - CommentSpan::from_span(library_token.span()), - CommentSpan::from_span(name.span()), + ByteSpan::from_span(library_token.span()), + ByteSpan::from_span(name.span()), ] } } @@ -69,9 +69,9 @@ impl CommentVisitor for ModuleKind { } impl CommentVisitor for Module { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = self.kind.collect_spans(); - collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); collected_spans.append(&mut self.dependencies.collect_spans()); collected_spans.append(&mut self.items.collect_spans()); collected_spans @@ -79,16 +79,16 @@ impl CommentVisitor for Module { } impl CommentVisitor for Dependency { - fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![CommentSpan::from_span(self.dep_token.span())]; + fn collect_spans(&self) -> Vec { + let mut collected_spans = vec![ByteSpan::from_span(self.dep_token.span())]; collected_spans.append(&mut self.path.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); collected_spans } } impl CommentVisitor for DependencyPath { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = self.prefix.collect_spans(); collected_spans.append(&mut self.suffixes.collect_spans()); collected_spans diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index 01949e81b5b..f208cc19ff9 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -1,6 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, FormatterError, }; use std::fmt::Write; @@ -12,12 +12,12 @@ where T: CommentVisitor + Clone, P: CommentVisitor + Clone, { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); let value_pairs = &self.value_separator_pairs; for pair in value_pairs.iter() { let p_comment_spans = pair.1.collect_spans(); - // Since we do not want to have comments between T and P we are extending the CommentSpans coming from T with spans coming from P + // Since we do not want to have comments between T and P we are extending the ByteSpans coming from T with spans coming from P // Since formatter can insert a trailing comma after a field, comments next to a field can be falsely inserted between the comma and the field // So we shouldn't allow inserting comments (or searching for one) between T and P as in Punctuated scenerio this can/will result in formattings that breaks the build process let mut comment_spans = pair @@ -25,7 +25,7 @@ where .collect_spans() .iter_mut() .map(|comment_map| { - // Since the length of P' CommentSpan is same for each pair we are using the first one's length for all of the pairs. + // Since the length of P' ByteSpan is same for each pair we are using the first one's length for all of the pairs. // This assumtion always holds because for each pair P is formatted to same str so the length is going to be the same. // For example when P is CommaToken, the length of P is always 1. comment_map.end += p_comment_spans[0].len(); diff --git a/sway-fmt-v2/src/utils/statement.rs b/sway-fmt-v2/src/utils/statement.rs index 24501cc087f..9cdd7f43efd 100644 --- a/sway-fmt-v2/src/utils/statement.rs +++ b/sway-fmt-v2/src/utils/statement.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, }; use std::fmt::Write; use sway_parse::{Statement, StatementLet}; @@ -61,7 +61,7 @@ impl Format for StatementLet { } impl CommentVisitor for Statement { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { match self { Statement::Let(statement_let) => statement_let.collect_spans(), Statement::Item(item) => item.collect_spans(), @@ -71,7 +71,7 @@ impl CommentVisitor for Statement { } => { let mut collected_spans = expr.collect_spans(); if let Some(semicolon_token) = semicolon_token_opt { - collected_spans.push(CommentSpan::from_span(semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(semicolon_token.span())); } collected_spans } @@ -80,22 +80,22 @@ impl CommentVisitor for Statement { } impl CommentVisitor for StatementLet { - fn collect_spans(&self) -> Vec { - // Add let token's CommentSpan - let mut collected_spans = vec![CommentSpan::from_span(self.let_token.span())]; - // Add pattern's CommentSpan + fn collect_spans(&self) -> Vec { + // Add let token's ByteSpan + let mut collected_spans = vec![ByteSpan::from_span(self.let_token.span())]; + // Add pattern's ByteSpan collected_spans.append(&mut self.pattern.collect_spans()); - // Add ty's CommentSpan if it exists + // Add ty's ByteSpan if it exists if let Some(ty) = &self.ty_opt { - collected_spans.push(CommentSpan::from_span(ty.0.span())); + collected_spans.push(ByteSpan::from_span(ty.0.span())); // TODO: determine if we are allowing comments between `:` and ty collected_spans.append(&mut ty.1.collect_spans()); } - // Add eq token's CommentSpan - collected_spans.push(CommentSpan::from_span(self.eq_token.span())); - // Add Expr's CommentSpan + // Add eq token's ByteSpan + collected_spans.push(ByteSpan::from_span(self.eq_token.span())); + // Add Expr's ByteSpan collected_spans.append(&mut self.expr.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); collected_spans } } diff --git a/sway-fmt-v2/src/utils/ty.rs b/sway-fmt-v2/src/utils/ty.rs index 8e9f8187312..be3be69875c 100644 --- a/sway-fmt-v2/src/utils/ty.rs +++ b/sway-fmt-v2/src/utils/ty.rs @@ -1,6 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter, FormatterError}, - utils::comments::{CommentSpan, CommentVisitor}, + utils::comments::{ByteSpan, CommentVisitor}, }; use std::fmt::Write; use sway_parse::{ @@ -109,23 +109,23 @@ impl Format for TyTupleDescriptor { } impl CommentVisitor for Ty { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { match self { Ty::Path(path) => path.collect_spans(), Ty::Tuple(tuple) => tuple.collect_spans(), Ty::Array(array) => array.collect_spans(), Ty::Str { str_token, length } => { - let mut collected_spans = vec![CommentSpan::from_span(str_token.span())]; + let mut collected_spans = vec![ByteSpan::from_span(str_token.span())]; collected_spans.append(&mut length.collect_spans()); collected_spans } - Ty::Infer { underscore_token } => vec![CommentSpan::from_span(underscore_token.span())], + Ty::Infer { underscore_token } => vec![ByteSpan::from_span(underscore_token.span())], } } } impl CommentVisitor for TyTupleDescriptor { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let TyTupleDescriptor::Cons { head, @@ -134,7 +134,7 @@ impl CommentVisitor for TyTupleDescriptor { } = self { collected_spans.append(&mut head.collect_spans()); - collected_spans.push(CommentSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from_span(comma_token.span())); collected_spans.append(&mut tail.collect_spans()); } collected_spans @@ -142,10 +142,10 @@ impl CommentVisitor for TyTupleDescriptor { } impl CommentVisitor for TyArrayDescriptor { - fn collect_spans(&self) -> Vec { + fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.ty.collect_spans()); - collected_spans.push(CommentSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); collected_spans.append(&mut self.length.collect_spans()); collected_spans } From 13b3bec86a8a333d0dc8c62e11b02a3f933a78d8 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 21 Jul 2022 15:13:48 +0300 Subject: [PATCH 38/44] from_span() removed in favor of From --- sway-fmt-v2/src/items/item_abi.rs | 4 +- sway-fmt-v2/src/items/item_const.rs | 10 +-- sway-fmt-v2/src/items/item_enum.rs | 8 +- sway-fmt-v2/src/items/item_fn.rs | 16 ++-- sway-fmt-v2/src/items/item_impl.rs | 4 +- sway-fmt-v2/src/items/item_storage.rs | 8 +- sway-fmt-v2/src/items/item_struct.rs | 8 +- sway-fmt-v2/src/items/item_trait.rs | 6 +- sway-fmt-v2/src/items/item_use.rs | 22 +++--- sway-fmt-v2/src/utils/attribute.rs | 4 +- sway-fmt-v2/src/utils/comments.rs | 38 ++++----- sway-fmt-v2/src/utils/expr.rs | 108 +++++++++++++------------- sway-fmt-v2/src/utils/literal.rs | 8 +- sway-fmt-v2/src/utils/path.rs | 4 +- sway-fmt-v2/src/utils/pattern.rs | 12 +-- sway-fmt-v2/src/utils/program_type.rs | 16 ++-- sway-fmt-v2/src/utils/statement.rs | 10 +-- sway-fmt-v2/src/utils/ty.rs | 8 +- 18 files changed, 148 insertions(+), 146 deletions(-) diff --git a/sway-fmt-v2/src/items/item_abi.rs b/sway-fmt-v2/src/items/item_abi.rs index f3e7d29b2e6..359652c8bad 100644 --- a/sway-fmt-v2/src/items/item_abi.rs +++ b/sway-fmt-v2/src/items/item_abi.rs @@ -137,8 +137,8 @@ impl CurlyBrace for ItemAbi { impl CommentVisitor for ItemAbi { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.abi_token.span())]; - collected_spans.push(ByteSpan::from_span(self.name.span())); + let mut collected_spans = vec![ByteSpan::from(self.abi_token.span())]; + collected_spans.push(ByteSpan::from(self.name.span())); collected_spans.append(&mut self.abi_items.collect_spans()); if let Some(abi_defs) = &self.abi_defs_opt { collected_spans.append(&mut abi_defs.collect_spans()); diff --git a/sway-fmt-v2/src/items/item_const.rs b/sway-fmt-v2/src/items/item_const.rs index b9520811c0a..f02493adf80 100644 --- a/sway-fmt-v2/src/items/item_const.rs +++ b/sway-fmt-v2/src/items/item_const.rs @@ -50,17 +50,17 @@ impl CommentVisitor for ItemConst { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(ByteSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from(visibility.span())); } - collected_spans.push(ByteSpan::from_span(self.const_token.span())); - collected_spans.push(ByteSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from(self.const_token.span())); + collected_spans.push(ByteSpan::from(self.name.span())); if let Some(ty) = &self.ty_opt { collected_spans.append(&mut ty.collect_spans()); // TODO: determine if we allow comments in between `:` and ty } - collected_spans.push(ByteSpan::from_span(self.eq_token.span())); + collected_spans.push(ByteSpan::from(self.eq_token.span())); collected_spans.append(&mut self.expr.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_enum.rs b/sway-fmt-v2/src/items/item_enum.rs index 1bfab77e80f..571ae52628e 100644 --- a/sway-fmt-v2/src/items/item_enum.rs +++ b/sway-fmt-v2/src/items/item_enum.rs @@ -243,12 +243,12 @@ impl CommentVisitor for ItemEnum { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(ByteSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from(visibility.span())); } - collected_spans.push(ByteSpan::from_span(self.enum_token.span())); - collected_spans.push(ByteSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from(self.enum_token.span())); + collected_spans.push(ByteSpan::from(self.name.span())); if let Some(generics) = &self.generics { - collected_spans.push(ByteSpan::from_span(generics.parameters.span())) + collected_spans.push(ByteSpan::from(generics.parameters.span())) } collected_spans.append(&mut self.fields.collect_spans()); collected_spans diff --git a/sway-fmt-v2/src/items/item_fn.rs b/sway-fmt-v2/src/items/item_fn.rs index 3b87dc3fbbf..1080de20eee 100644 --- a/sway-fmt-v2/src/items/item_fn.rs +++ b/sway-fmt-v2/src/items/item_fn.rs @@ -233,12 +233,12 @@ impl CommentVisitor for FnSignature { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(ByteSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from(visibility.span())); } - collected_spans.push(ByteSpan::from_span(self.fn_token.span())); - collected_spans.push(ByteSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from(self.fn_token.span())); + collected_spans.push(ByteSpan::from(self.name.span())); if let Some(generics) = &self.generics { - collected_spans.push(ByteSpan::from_span(generics.parameters.span())); + collected_spans.push(ByteSpan::from(generics.parameters.span())); } collected_spans.append(&mut self.arguments.collect_spans()); if let Some(return_type) = &self.return_type_opt { @@ -261,9 +261,9 @@ impl CommentVisitor for FnArgs { mutable_self, args_opt, } => { - collected_spans.push(ByteSpan::from_span(self_token.span())); + collected_spans.push(ByteSpan::from(self_token.span())); if let Some(mutable) = mutable_self { - collected_spans.push(ByteSpan::from_span(mutable.span())); + collected_spans.push(ByteSpan::from(mutable.span())); } if let Some(args) = args_opt { collected_spans.append(&mut args.collect_spans()); @@ -278,8 +278,8 @@ impl CommentVisitor for FnArg { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.pattern.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.colon_token.span())); - collected_spans.push(ByteSpan::from_span(self.ty.span())); + collected_spans.push(ByteSpan::from(self.colon_token.span())); + collected_spans.push(ByteSpan::from(self.ty.span())); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_impl.rs b/sway-fmt-v2/src/items/item_impl.rs index 4ca6adee29d..16bab28eccb 100644 --- a/sway-fmt-v2/src/items/item_impl.rs +++ b/sway-fmt-v2/src/items/item_impl.rs @@ -17,9 +17,9 @@ impl Format for ItemImpl { } impl CommentVisitor for ItemImpl { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.impl_token.span())]; + let mut collected_spans = vec![ByteSpan::from(self.impl_token.span())]; if let Some(generic) = &self.generic_params_opt { - collected_spans.push(ByteSpan::from_span(generic.parameters.span())); + collected_spans.push(ByteSpan::from(generic.parameters.span())); } if let Some(trait_tuple) = &self.trait_opt { collected_spans.append(&mut trait_tuple.collect_spans()); diff --git a/sway-fmt-v2/src/items/item_storage.rs b/sway-fmt-v2/src/items/item_storage.rs index 6d1997aaaab..df69c817cd9 100644 --- a/sway-fmt-v2/src/items/item_storage.rs +++ b/sway-fmt-v2/src/items/item_storage.rs @@ -232,7 +232,7 @@ impl CurlyBrace for ItemStorage { impl CommentVisitor for ItemStorage { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.storage_token.span())]; + let mut collected_spans = vec![ByteSpan::from(self.storage_token.span())]; collected_spans.append(&mut self.fields.collect_spans()); collected_spans } @@ -240,10 +240,10 @@ impl CommentVisitor for ItemStorage { impl CommentVisitor for StorageField { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; - collected_spans.push(ByteSpan::from_span(self.colon_token.span())); + let mut collected_spans = vec![ByteSpan::from(self.name.span())]; + collected_spans.push(ByteSpan::from(self.colon_token.span())); collected_spans.append(&mut self.ty.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.eq_token.span())); + collected_spans.push(ByteSpan::from(self.eq_token.span())); collected_spans.append(&mut self.initializer.collect_spans()); collected_spans } diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index 003f0fc2efa..59ce9e157cc 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -249,12 +249,12 @@ impl CommentVisitor for ItemStruct { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(ByteSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from(visibility.span())); } - collected_spans.push(ByteSpan::from_span(self.struct_token.span())); - collected_spans.push(ByteSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from(self.struct_token.span())); + collected_spans.push(ByteSpan::from(self.name.span())); if let Some(generics) = &self.generics { - collected_spans.push(ByteSpan::from_span(generics.parameters.span())) + collected_spans.push(ByteSpan::from(generics.parameters.span())) } collected_spans.append(&mut self.fields.collect_spans()); collected_spans diff --git a/sway-fmt-v2/src/items/item_trait.rs b/sway-fmt-v2/src/items/item_trait.rs index 318e1dc3694..74091201ad1 100644 --- a/sway-fmt-v2/src/items/item_trait.rs +++ b/sway-fmt-v2/src/items/item_trait.rs @@ -125,10 +125,10 @@ impl CommentVisitor for ItemTrait { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(ByteSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from(visibility.span())); } - collected_spans.push(ByteSpan::from_span(self.trait_token.span())); - collected_spans.push(ByteSpan::from_span(self.name.span())); + collected_spans.push(ByteSpan::from(self.trait_token.span())); + collected_spans.push(ByteSpan::from(self.name.span())); if let Some(super_traits) = &self.super_traits { collected_spans.append(&mut super_traits.collect_spans()); } diff --git a/sway-fmt-v2/src/items/item_use.rs b/sway-fmt-v2/src/items/item_use.rs index 6453774a522..f0f6f87c9c3 100644 --- a/sway-fmt-v2/src/items/item_use.rs +++ b/sway-fmt-v2/src/items/item_use.rs @@ -22,14 +22,14 @@ impl CommentVisitor for ItemUse { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { - collected_spans.push(ByteSpan::from_span(visibility.span())); + collected_spans.push(ByteSpan::from(visibility.span())); } - collected_spans.push(ByteSpan::from_span(self.use_token.span())); + collected_spans.push(ByteSpan::from(self.use_token.span())); if let Some(root_import) = &self.root_import { - collected_spans.push(ByteSpan::from_span(root_import.span())); + collected_spans.push(ByteSpan::from(root_import.span())); } collected_spans.append(&mut self.tree.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } } @@ -38,24 +38,24 @@ impl CommentVisitor for UseTree { fn collect_spans(&self) -> Vec { match self { UseTree::Group { imports } => imports.collect_spans(), - UseTree::Name { name } => vec![ByteSpan::from_span(name.span())], + UseTree::Name { name } => vec![ByteSpan::from(name.span())], UseTree::Rename { name, as_token, alias, } => vec![ - ByteSpan::from_span(name.span()), - ByteSpan::from_span(as_token.span()), - ByteSpan::from_span(alias.span()), + ByteSpan::from(name.span()), + ByteSpan::from(as_token.span()), + ByteSpan::from(alias.span()), ], - UseTree::Glob { star_token } => vec![ByteSpan::from_span(star_token.span())], + UseTree::Glob { star_token } => vec![ByteSpan::from(star_token.span())], UseTree::Path { prefix, double_colon_token, suffix, } => { - let mut collected_spans = vec![ByteSpan::from_span(prefix.span())]; - collected_spans.push(ByteSpan::from_span(double_colon_token.span())); + let mut collected_spans = vec![ByteSpan::from(prefix.span())]; + collected_spans.push(ByteSpan::from(double_colon_token.span())); collected_spans.append(&mut suffix.collect_spans()); collected_spans } diff --git a/sway-fmt-v2/src/utils/attribute.rs b/sway-fmt-v2/src/utils/attribute.rs index 8b7bf6d0bd6..0852d6b77e6 100644 --- a/sway-fmt-v2/src/utils/attribute.rs +++ b/sway-fmt-v2/src/utils/attribute.rs @@ -96,14 +96,14 @@ impl Parenthesis for AttributeDecl { } impl CommentVisitor for AttributeDecl { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.hash_token.span())]; + let mut collected_spans = vec![ByteSpan::from(self.hash_token.span())]; collected_spans.append(&mut self.attribute.collect_spans()); collected_spans } } impl CommentVisitor for Attribute { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; + let mut collected_spans = vec![ByteSpan::from(self.name.span())]; if let Some(args) = &self.args { collected_spans.append(&mut args.collect_spans()); } diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 923525bd360..3f31f82095b 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -29,15 +29,17 @@ pub struct ByteSpan { pub end: usize, } -impl ByteSpan { +impl From for ByteSpan { /// Takes `start` and `end` from `sway::types::Span` and constructs a `ByteSpan` - pub fn from_span(span: Span) -> ByteSpan { + fn from(span: Span) -> Self { ByteSpan { start: span.start(), end: span.end(), } } +} +impl ByteSpan { pub fn len(&self) -> usize { self.end - self.start } @@ -106,13 +108,13 @@ where { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - let mut opening_brace_span = ByteSpan::from_span(self.span()); + let mut opening_brace_span = ByteSpan::from(self.span()); opening_brace_span.end = opening_brace_span.start + 1; // Add opening brace's ByteSpan collected_spans.push(opening_brace_span); // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().collect_spans()); - let mut closing_brace_span = ByteSpan::from_span(self.span()); + let mut closing_brace_span = ByteSpan::from(self.span()); closing_brace_span.start = closing_brace_span.end - 1; // Add closing brace's ByteSpan collected_spans.push(closing_brace_span); @@ -126,13 +128,13 @@ where { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - let mut opening_paren_span = ByteSpan::from_span(self.span()); + let mut opening_paren_span = ByteSpan::from(self.span()); opening_paren_span.end = opening_paren_span.start + 1; // Add opening paren's span collected_spans.push(opening_paren_span); // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().collect_spans()); - let mut closing_paren_span = ByteSpan::from_span(self.span()); + let mut closing_paren_span = ByteSpan::from(self.span()); closing_paren_span.start = closing_paren_span.end - 1; // Add closing paren's ByteSpan collected_spans.push(closing_paren_span); @@ -146,13 +148,13 @@ where { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - let mut opening_bracket_span = ByteSpan::from_span(self.span()); + let mut opening_bracket_span = ByteSpan::from(self.span()); opening_bracket_span.end = opening_bracket_span.start + 1; // Add opening bracket's span collected_spans.push(opening_bracket_span); // Add T's collected ByteSpan collected_spans.append(&mut self.clone().into_inner().collect_spans()); - let mut closing_bracket_span = ByteSpan::from_span(self.span()); + let mut closing_bracket_span = ByteSpan::from(self.span()); closing_bracket_span.start = closing_bracket_span.end - 1; // Add closing bracket's ByteSpan collected_spans.push(closing_bracket_span); @@ -196,19 +198,19 @@ where impl CommentVisitor for Ident { fn collect_spans(&self) -> Vec { - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } impl CommentVisitor for CommaToken { fn collect_spans(&self) -> Vec { - vec![(ByteSpan::from_span(self.span()))] + vec![(ByteSpan::from(self.span()))] } } impl CommentVisitor for TypeField { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; - collected_spans.push(ByteSpan::from_span(self.colon_token.span())); + let mut collected_spans = vec![ByteSpan::from(self.name.span())]; + collected_spans.push(ByteSpan::from(self.colon_token.span())); collected_spans.append(&mut self.ty.collect_spans()); collected_spans } @@ -216,37 +218,37 @@ impl CommentVisitor for TypeField { impl CommentVisitor for AddToken { fn collect_spans(&self) -> Vec { - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } impl CommentVisitor for SemicolonToken { fn collect_spans(&self) -> Vec { - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } impl CommentVisitor for ColonToken { fn collect_spans(&self) -> Vec { - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } impl CommentVisitor for RightArrowToken { fn collect_spans(&self) -> Vec { - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } impl CommentVisitor for ForToken { fn collect_spans(&self) -> Vec { - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } impl CommentVisitor for ForwardSlashToken { fn collect_spans(&self) -> Vec { - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } /// Handles comments by first creating the CommentMap which is used for fast seaching comments. diff --git a/sway-fmt-v2/src/utils/expr.rs b/sway-fmt-v2/src/utils/expr.rs index b788235d4f9..d93d400699a 100644 --- a/sway-fmt-v2/src/utils/expr.rs +++ b/sway-fmt-v2/src/utils/expr.rs @@ -277,7 +277,7 @@ fn visit_expr(expr: &Expr) -> Vec { Expr::Path(path) => path.collect_spans(), Expr::Literal(literal) => literal.collect_spans(), Expr::AbiCast { abi_token, args } => { - let mut collected_spans = vec![ByteSpan::from_span(abi_token.span())]; + let mut collected_spans = vec![ByteSpan::from(abi_token.span())]; collected_spans.append(&mut args.collect_spans()); collected_spans } @@ -295,7 +295,7 @@ fn visit_expr(expr: &Expr) -> Vec { return_token, expr_opt, } => { - let mut collected_spans = vec![ByteSpan::from_span(return_token.span())]; + let mut collected_spans = vec![ByteSpan::from(return_token.span())]; if let Some(expr) = expr_opt { collected_spans.append(&mut expr.collect_spans()); } @@ -307,7 +307,7 @@ fn visit_expr(expr: &Expr) -> Vec { value, branches, } => { - let mut collected_spans = vec![ByteSpan::from_span(match_token.span())]; + let mut collected_spans = vec![ByteSpan::from(match_token.span())]; collected_spans.append(&mut value.collect_spans()); collected_spans.append(&mut branches.collect_spans()); collected_spans @@ -317,7 +317,7 @@ fn visit_expr(expr: &Expr) -> Vec { condition, block, } => { - let mut collected_spans = vec![ByteSpan::from_span(while_token.span())]; + let mut collected_spans = vec![ByteSpan::from(while_token.span())]; collected_spans.append(&mut condition.collect_spans()); collected_spans.append(&mut block.collect_spans()); collected_spans @@ -343,8 +343,8 @@ fn visit_expr(expr: &Expr) -> Vec { } => { let mut collected_spans = Vec::new(); collected_spans.append(&mut target.collect_spans()); - collected_spans.push(ByteSpan::from_span(dot_token.span())); - collected_spans.push(ByteSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from(dot_token.span())); + collected_spans.push(ByteSpan::from(name.span())); if let Some(contract_args) = contract_args_opt { collected_spans.append(&mut contract_args.collect_spans()); } @@ -358,8 +358,8 @@ fn visit_expr(expr: &Expr) -> Vec { } => { let mut collected_spans = Vec::new(); collected_spans.append(&mut target.collect_spans()); - collected_spans.push(ByteSpan::from_span(dot_token.span())); - collected_spans.push(ByteSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from(dot_token.span())); + collected_spans.push(ByteSpan::from(name.span())); collected_spans } Expr::TupleFieldProjection { @@ -370,22 +370,22 @@ fn visit_expr(expr: &Expr) -> Vec { } => { let mut collected_spans = Vec::new(); collected_spans.append(&mut target.collect_spans()); - collected_spans.push(ByteSpan::from_span(dot_token.span())); - collected_spans.push(ByteSpan::from_span(field_span.clone())); + collected_spans.push(ByteSpan::from(dot_token.span())); + collected_spans.push(ByteSpan::from(field_span.clone())); collected_spans } Expr::Ref { ref_token, expr } => { - let mut collected_spans = vec![ByteSpan::from_span(ref_token.span())]; + let mut collected_spans = vec![ByteSpan::from(ref_token.span())]; collected_spans.append(&mut expr.collect_spans()); collected_spans } Expr::Deref { deref_token, expr } => { - let mut collected_spans = vec![ByteSpan::from_span(deref_token.span())]; + let mut collected_spans = vec![ByteSpan::from(deref_token.span())]; collected_spans.append(&mut expr.collect_spans()); collected_spans } Expr::Not { bang_token, expr } => { - let mut collected_spans = vec![ByteSpan::from_span(bang_token.span())]; + let mut collected_spans = vec![ByteSpan::from(bang_token.span())]; collected_spans.append(&mut expr.collect_spans()); collected_spans } @@ -395,7 +395,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(star_token.span())); + collected_spans.push(ByteSpan::from(star_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -405,7 +405,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(forward_slash_token.span())); + collected_spans.push(ByteSpan::from(forward_slash_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -415,7 +415,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(percent_token.span())); + collected_spans.push(ByteSpan::from(percent_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -425,7 +425,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(add_token.span())); + collected_spans.push(ByteSpan::from(add_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -435,7 +435,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(sub_token.span())); + collected_spans.push(ByteSpan::from(sub_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -445,7 +445,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(shl_token.span())); + collected_spans.push(ByteSpan::from(shl_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -455,7 +455,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(shr_token.span())); + collected_spans.push(ByteSpan::from(shr_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -465,7 +465,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(ampersand_token.span())); + collected_spans.push(ByteSpan::from(ampersand_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -475,7 +475,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(caret_token.span())); + collected_spans.push(ByteSpan::from(caret_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -485,7 +485,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(pipe_token.span())); + collected_spans.push(ByteSpan::from(pipe_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -495,7 +495,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(double_eq_token.span())); + collected_spans.push(ByteSpan::from(double_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -505,7 +505,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(bang_eq_token.span())); + collected_spans.push(ByteSpan::from(bang_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -515,7 +515,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(less_than_token.span())); + collected_spans.push(ByteSpan::from(less_than_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -525,7 +525,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(greater_than_token.span())); + collected_spans.push(ByteSpan::from(greater_than_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -535,7 +535,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(less_than_eq_token.span())); + collected_spans.push(ByteSpan::from(less_than_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -545,7 +545,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(greater_than_eq_token.span())); + collected_spans.push(ByteSpan::from(greater_than_eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -555,7 +555,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(double_ampersand_token.span())); + collected_spans.push(ByteSpan::from(double_ampersand_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -565,7 +565,7 @@ fn visit_expr(expr: &Expr) -> Vec { rhs, } => { let mut collected_spans = lhs.collect_spans(); - collected_spans.push(ByteSpan::from_span(double_pipe_token.span())); + collected_spans.push(ByteSpan::from(double_pipe_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -575,7 +575,7 @@ fn visit_expr(expr: &Expr) -> Vec { expr, } => { let mut collected_spans = assignable.collect_spans(); - collected_spans.push(ByteSpan::from_span(reassignment_op.span.clone())); + collected_spans.push(ByteSpan::from(reassignment_op.span.clone())); collected_spans.append(&mut expr.collect_spans()); collected_spans } @@ -584,8 +584,8 @@ fn visit_expr(expr: &Expr) -> Vec { impl CommentVisitor for AbiCastArgs { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.name.span())]; - collected_spans.push(ByteSpan::from_span(self.comma_token.span())); + let mut collected_spans = vec![ByteSpan::from(self.name.span())]; + collected_spans.push(ByteSpan::from(self.comma_token.span())); collected_spans.append(&mut self.address.collect_spans()); collected_spans } @@ -593,9 +593,9 @@ impl CommentVisitor for AbiCastArgs { impl CommentVisitor for ExprStructField { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.field_name.span())]; + let mut collected_spans = vec![ByteSpan::from(self.field_name.span())]; if let Some(expr) = &self.expr_opt { - collected_spans.push(ByteSpan::from_span(expr.0.span())); + collected_spans.push(ByteSpan::from(expr.0.span())); // TODO: determine if we are allowing comments between `:` and expr collected_spans.append(&mut expr.1.collect_spans()); } @@ -613,7 +613,7 @@ impl CommentVisitor for ExprTupleDescriptor { } = self { collected_spans.append(&mut head.collect_spans()); - collected_spans.push(ByteSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from(comma_token.span())); collected_spans.append(&mut tail.collect_spans()); } collected_spans @@ -630,7 +630,7 @@ impl CommentVisitor for ExprArrayDescriptor { } = self { collected_spans.append(&mut value.collect_spans()); - collected_spans.push(ByteSpan::from_span(semicolon_token.span())); + collected_spans.push(ByteSpan::from(semicolon_token.span())); collected_spans.append(&mut length.collect_spans()); } collected_spans @@ -639,7 +639,7 @@ impl CommentVisitor for ExprArrayDescriptor { impl CommentVisitor for AsmBlock { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.asm_token.span())]; + let mut collected_spans = vec![ByteSpan::from(self.asm_token.span())]; collected_spans.append(&mut self.registers.collect_spans()); collected_spans.append(&mut self.contents.collect_spans()); collected_spans @@ -648,7 +648,7 @@ impl CommentVisitor for AsmBlock { impl CommentVisitor for AsmRegisterDeclaration { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.register.span())]; + let mut collected_spans = vec![ByteSpan::from(self.register.span())]; if let Some(value) = &self.value_opt { collected_spans.append(&mut value.collect_spans()); // TODO: determine if we are allowing comments between `:` and expr @@ -671,13 +671,13 @@ impl CommentVisitor for AsmBlockContents { impl CommentVisitor for Instruction { fn collect_spans(&self) -> Vec { // Visit instructions as a whole unit, meaning we cannot insert comments inside an instruction. - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } impl CommentVisitor for AsmFinalExpr { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.register.span())]; + let mut collected_spans = vec![ByteSpan::from(self.register.span())]; if let Some(ty) = &self.ty_opt { collected_spans.append(&mut ty.collect_spans()); // TODO: determine if we are allowing comments between `:` and ty @@ -688,11 +688,11 @@ impl CommentVisitor for AsmFinalExpr { impl CommentVisitor for IfExpr { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.if_token.span())]; + let mut collected_spans = vec![ByteSpan::from(self.if_token.span())]; collected_spans.append(&mut self.condition.collect_spans()); collected_spans.append(&mut self.then_block.collect_spans()); if let Some(else_block) = &self.else_opt { - collected_spans.push(ByteSpan::from_span(else_block.0.span())); + collected_spans.push(ByteSpan::from(else_block.0.span())); let mut else_body_spans = match &else_block.1 { std::ops::ControlFlow::Continue(if_expr) => if_expr.collect_spans(), std::ops::ControlFlow::Break(else_body) => else_body.collect_spans(), @@ -713,9 +713,9 @@ impl CommentVisitor for IfCondition { eq_token, rhs, } => { - let mut collected_spans = vec![ByteSpan::from_span(let_token.span())]; + let mut collected_spans = vec![ByteSpan::from(let_token.span())]; collected_spans.append(&mut lhs.collect_spans()); - collected_spans.push(ByteSpan::from_span(eq_token.span())); + collected_spans.push(ByteSpan::from(eq_token.span())); collected_spans.append(&mut rhs.collect_spans()); collected_spans } @@ -727,7 +727,7 @@ impl CommentVisitor for MatchBranch { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.pattern.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.fat_right_arrow_token.span())); + collected_spans.push(ByteSpan::from(self.fat_right_arrow_token.span())); collected_spans.append(&mut self.kind.collect_spans()); collected_spans } @@ -744,13 +744,13 @@ impl CommentVisitor for MatchBranchKind { collected_spans.append(&mut block.collect_spans()); // TODO: determine if we allow comments between block and comma_token if let Some(comma_token) = comma_token_opt { - collected_spans.push(ByteSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from(comma_token.span())); } } MatchBranchKind::Expr { expr, comma_token } => { collected_spans.append(&mut expr.collect_spans()); // TODO: determine if we allow comments between expr and comma_token - collected_spans.push(ByteSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from(comma_token.span())); } }; collected_spans @@ -761,7 +761,7 @@ impl CommentVisitor for Assignable { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { - Assignable::Var(var) => collected_spans.push(ByteSpan::from_span(var.span())), + Assignable::Var(var) => collected_spans.push(ByteSpan::from(var.span())), Assignable::Index { target, arg } => { collected_spans.append(&mut target.collect_spans()); collected_spans.append(&mut arg.collect_spans()); @@ -772,8 +772,8 @@ impl CommentVisitor for Assignable { name, } => { collected_spans.append(&mut target.collect_spans()); - collected_spans.push(ByteSpan::from_span(dot_token.span())); - collected_spans.push(ByteSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from(dot_token.span())); + collected_spans.push(ByteSpan::from(name.span())); } Assignable::TupleFieldProjection { target, @@ -782,8 +782,8 @@ impl CommentVisitor for Assignable { field_span, } => { collected_spans.append(&mut target.collect_spans()); - collected_spans.push(ByteSpan::from_span(dot_token.span())); - collected_spans.push(ByteSpan::from_span(field_span.clone())); + collected_spans.push(ByteSpan::from(dot_token.span())); + collected_spans.push(ByteSpan::from(field_span.clone())); } }; collected_spans diff --git a/sway-fmt-v2/src/utils/literal.rs b/sway-fmt-v2/src/utils/literal.rs index 3e44d302ec9..ccc0da81423 100644 --- a/sway-fmt-v2/src/utils/literal.rs +++ b/sway-fmt-v2/src/utils/literal.rs @@ -25,10 +25,10 @@ impl Format for Literal { impl CommentVisitor for Literal { fn collect_spans(&self) -> Vec { match self { - Literal::String(str_lit) => vec![ByteSpan::from_span(str_lit.span.clone())], - Literal::Char(chr_lit) => vec![ByteSpan::from_span(chr_lit.span.clone())], - Literal::Int(int_lit) => vec![ByteSpan::from_span(int_lit.span.clone())], - Literal::Bool(bool_lit) => vec![ByteSpan::from_span(bool_lit.span.clone())], + Literal::String(str_lit) => vec![ByteSpan::from(str_lit.span.clone())], + Literal::Char(chr_lit) => vec![ByteSpan::from(chr_lit.span.clone())], + Literal::Int(int_lit) => vec![ByteSpan::from(int_lit.span.clone())], + Literal::Bool(bool_lit) => vec![ByteSpan::from(bool_lit.span.clone())], } } } diff --git a/sway-fmt-v2/src/utils/path.rs b/sway-fmt-v2/src/utils/path.rs index 958741776be..97b9ef9cac7 100644 --- a/sway-fmt-v2/src/utils/path.rs +++ b/sway-fmt-v2/src/utils/path.rs @@ -142,7 +142,7 @@ impl CommentVisitor for PathExpr { // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted // root::parent/* i am a comment*/::child // I am not sure if this is something the language will allow. - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } @@ -150,6 +150,6 @@ impl CommentVisitor for PathType { fn collect_spans(&self) -> Vec { // TODO: Should we look for a comment inside the path type? if so we will need to implement CommentVisitor for PathType // For now we are assuming there will be no comments inside the PathType so we are visiting it as a single unit. - vec![ByteSpan::from_span(self.span())] + vec![ByteSpan::from(self.span())] } } diff --git a/sway-fmt-v2/src/utils/pattern.rs b/sway-fmt-v2/src/utils/pattern.rs index 945c0c65476..dea698de2aa 100644 --- a/sway-fmt-v2/src/utils/pattern.rs +++ b/sway-fmt-v2/src/utils/pattern.rs @@ -123,13 +123,13 @@ impl CommentVisitor for Pattern { let mut collected_spans = Vec::new(); match self { Pattern::Wildcard { underscore_token } => { - collected_spans.push(ByteSpan::from_span(underscore_token.span())); + collected_spans.push(ByteSpan::from(underscore_token.span())); } Pattern::Var { mutable, name } => { if let Some(mutable) = mutable { - collected_spans.push(ByteSpan::from_span(mutable.span())); + collected_spans.push(ByteSpan::from(mutable.span())); } - collected_spans.push(ByteSpan::from_span(name.span())); + collected_spans.push(ByteSpan::from(name.span())); } Pattern::Literal(literal) => { collected_spans.append(&mut literal.collect_spans()); @@ -158,15 +158,15 @@ impl CommentVisitor for PatternStructField { let mut collected_spans = Vec::new(); match self { PatternStructField::Rest { token } => { - collected_spans.push(ByteSpan::from_span(token.span())); + collected_spans.push(ByteSpan::from(token.span())); } PatternStructField::Field { field_name, pattern_opt, } => { - collected_spans.push(ByteSpan::from_span(field_name.span())); + collected_spans.push(ByteSpan::from(field_name.span())); if let Some(pattern) = pattern_opt { - collected_spans.push(ByteSpan::from_span(pattern.0.span())); + collected_spans.push(ByteSpan::from(pattern.0.span())); collected_spans.append(&mut pattern.1.collect_spans()); } } diff --git a/sway-fmt-v2/src/utils/program_type.rs b/sway-fmt-v2/src/utils/program_type.rs index 3d8d22eebdc..58cf2f61473 100644 --- a/sway-fmt-v2/src/utils/program_type.rs +++ b/sway-fmt-v2/src/utils/program_type.rs @@ -47,21 +47,21 @@ impl CommentVisitor for ModuleKind { fn collect_spans(&self) -> Vec { match self { ModuleKind::Script { script_token } => { - vec![ByteSpan::from_span(script_token.span())] + vec![ByteSpan::from(script_token.span())] } ModuleKind::Contract { contract_token } => { - vec![ByteSpan::from_span(contract_token.span())] + vec![ByteSpan::from(contract_token.span())] } ModuleKind::Predicate { predicate_token } => { - vec![ByteSpan::from_span(predicate_token.span())] + vec![ByteSpan::from(predicate_token.span())] } ModuleKind::Library { library_token, name, } => { vec![ - ByteSpan::from_span(library_token.span()), - ByteSpan::from_span(name.span()), + ByteSpan::from(library_token.span()), + ByteSpan::from(name.span()), ] } } @@ -71,7 +71,7 @@ impl CommentVisitor for ModuleKind { impl CommentVisitor for Module { fn collect_spans(&self) -> Vec { let mut collected_spans = self.kind.collect_spans(); - collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans.append(&mut self.dependencies.collect_spans()); collected_spans.append(&mut self.items.collect_spans()); collected_spans @@ -80,9 +80,9 @@ impl CommentVisitor for Module { impl CommentVisitor for Dependency { fn collect_spans(&self) -> Vec { - let mut collected_spans = vec![ByteSpan::from_span(self.dep_token.span())]; + let mut collected_spans = vec![ByteSpan::from(self.dep_token.span())]; collected_spans.append(&mut self.path.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } } diff --git a/sway-fmt-v2/src/utils/statement.rs b/sway-fmt-v2/src/utils/statement.rs index 9cdd7f43efd..6fd1f455572 100644 --- a/sway-fmt-v2/src/utils/statement.rs +++ b/sway-fmt-v2/src/utils/statement.rs @@ -71,7 +71,7 @@ impl CommentVisitor for Statement { } => { let mut collected_spans = expr.collect_spans(); if let Some(semicolon_token) = semicolon_token_opt { - collected_spans.push(ByteSpan::from_span(semicolon_token.span())); + collected_spans.push(ByteSpan::from(semicolon_token.span())); } collected_spans } @@ -82,20 +82,20 @@ impl CommentVisitor for Statement { impl CommentVisitor for StatementLet { fn collect_spans(&self) -> Vec { // Add let token's ByteSpan - let mut collected_spans = vec![ByteSpan::from_span(self.let_token.span())]; + let mut collected_spans = vec![ByteSpan::from(self.let_token.span())]; // Add pattern's ByteSpan collected_spans.append(&mut self.pattern.collect_spans()); // Add ty's ByteSpan if it exists if let Some(ty) = &self.ty_opt { - collected_spans.push(ByteSpan::from_span(ty.0.span())); + collected_spans.push(ByteSpan::from(ty.0.span())); // TODO: determine if we are allowing comments between `:` and ty collected_spans.append(&mut ty.1.collect_spans()); } // Add eq token's ByteSpan - collected_spans.push(ByteSpan::from_span(self.eq_token.span())); + collected_spans.push(ByteSpan::from(self.eq_token.span())); // Add Expr's ByteSpan collected_spans.append(&mut self.expr.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } } diff --git a/sway-fmt-v2/src/utils/ty.rs b/sway-fmt-v2/src/utils/ty.rs index be3be69875c..776c77b481d 100644 --- a/sway-fmt-v2/src/utils/ty.rs +++ b/sway-fmt-v2/src/utils/ty.rs @@ -115,11 +115,11 @@ impl CommentVisitor for Ty { Ty::Tuple(tuple) => tuple.collect_spans(), Ty::Array(array) => array.collect_spans(), Ty::Str { str_token, length } => { - let mut collected_spans = vec![ByteSpan::from_span(str_token.span())]; + let mut collected_spans = vec![ByteSpan::from(str_token.span())]; collected_spans.append(&mut length.collect_spans()); collected_spans } - Ty::Infer { underscore_token } => vec![ByteSpan::from_span(underscore_token.span())], + Ty::Infer { underscore_token } => vec![ByteSpan::from(underscore_token.span())], } } } @@ -134,7 +134,7 @@ impl CommentVisitor for TyTupleDescriptor { } = self { collected_spans.append(&mut head.collect_spans()); - collected_spans.push(ByteSpan::from_span(comma_token.span())); + collected_spans.push(ByteSpan::from(comma_token.span())); collected_spans.append(&mut tail.collect_spans()); } collected_spans @@ -145,7 +145,7 @@ impl CommentVisitor for TyArrayDescriptor { fn collect_spans(&self) -> Vec { let mut collected_spans = Vec::new(); collected_spans.append(&mut self.ty.collect_spans()); - collected_spans.push(ByteSpan::from_span(self.semicolon_token.span())); + collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans.append(&mut self.length.collect_spans()); collected_spans } From 9ae7aa8356536bf7368e428e7e977b8dba851773 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 21 Jul 2022 15:19:35 +0300 Subject: [PATCH 39/44] Prevent reparsing the unformatted_code as we already did it before formatting --- sway-fmt-v2/src/fmt.rs | 5 +++-- sway-fmt-v2/src/utils/comments.rs | 8 +++----- sway-fmt-v2/src/utils/program_type.rs | 2 +- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index afc6fb1b5ef..508f40c18b4 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -45,9 +45,9 @@ impl Formatter { let src_len = src.len(); let module = sway_parse::parse_file(src.clone(), path.clone())?; // Get parsed items - let items = module.items; + let items = &module.items; // Get the program type (script, predicate, contract or library) - let program_type = module.kind; + let program_type = &module.kind; // Formatted code will be pushed here with raw newline stlye. // Which means newlines are not converted into system-specific versions until `apply_newline_style()`. @@ -72,6 +72,7 @@ impl Formatter { // Add comments handle_comments( src, + &module, Arc::from(formatted_code.clone()), path, &mut formatted_code, diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 3f31f82095b..f58495d4a7d 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -255,18 +255,16 @@ impl CommentVisitor for ForwardSlashToken { /// Traverses items for finding a comment in unformatted input and placing it in correct place in formatted output. pub fn handle_comments( unformatted_input: Arc, + unformatted_module: &Module, formatted_input: Arc, path: Option>, formatted_code: &mut FormattedCode, ) -> Result<(), FormatterError> { // Collect Span -> Comment mapping from unformatted input let comment_map = comment_map_from_src(unformatted_input.clone())?; - // Parse unformatted code so that we can get the spans of items in their original places. - // This is required since we collected the spans in from unformatted source file. - let unformatted_module = sway_parse::parse_file(unformatted_input.clone(), path.clone())?; - // After the formatting items should be the same but their spans will be changed since we applied formatting to them. + // After the formatting existing items should be the same (type of the item) but their spans will be changed since we applied formatting to them. let formatted_module = sway_parse::parse_file(formatted_input, path)?; - // Actually insert the comments + // Actually find & insert the comments add_comments( comment_map, &unformatted_module, diff --git a/sway-fmt-v2/src/utils/program_type.rs b/sway-fmt-v2/src/utils/program_type.rs index 58cf2f61473..cbf92c3f237 100644 --- a/sway-fmt-v2/src/utils/program_type.rs +++ b/sway-fmt-v2/src/utils/program_type.rs @@ -15,7 +15,7 @@ use super::comments::{ByteSpan, CommentVisitor}; /// - Library pub(crate) fn insert_program_type( formatted_code: &mut String, - module_kind: ModuleKind, + module_kind: &ModuleKind, ) -> Result<(), FormatterError> { match module_kind { ModuleKind::Script { script_token } => { From fd62f6d4a7f7c3ace8a9cec7d6747d09d2905eb7 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 21 Jul 2022 15:37:11 +0300 Subject: [PATCH 40/44] refactor insert_after_span --- sway-fmt-v2/src/utils/comments.rs | 41 +++++++++++++------------------ 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index f58495d4a7d..8fb82f215b3 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -336,31 +336,25 @@ fn get_comments_between_spans( unformatted_code: &Arc, ) -> Vec { let mut comments_with_context = Vec::new(); - for (index, comment_tuple) in comment_map + for (index, (comment_span, comment)) in comment_map .range((Included(from), Excluded(to))) .enumerate() { if comments_with_context.is_empty() { // This is the first comment in the current range the context should be collected between from's end and comment's beginning comments_with_context.push(( - comment_tuple.1.clone(), - unformatted_code[from.end..comment_tuple.0.start].to_string(), + comment.clone(), + unformatted_code[from.end..comment_span.start].to_string(), )); - println!("this"); } else { // There is a comment before this one, so we should get the context starting from the last comment's end to the beginning of the current comment comments_with_context.push(( - comment_tuple.1.clone(), - unformatted_code - [comments_with_context[index - 1].0.span.end()..comment_tuple.0.start] + comment.clone(), + unformatted_code[comments_with_context[index - 1].0.span.end()..comment_span.start] .to_string(), )); } } - println!( - " found {:?} between {:?} and {:?} \n\n", - comments_with_context, from, to - ); comments_with_context } @@ -371,20 +365,19 @@ fn insert_after_span( offset: usize, formatted_code: &mut FormattedCode, ) -> Result { - let mut src_rope = Rope::from_str(formatted_code); - // prepare the comment str - let mut comment_str = format!( - "{}{}", - comments_to_insert[0].1, - format_comment(&comments_to_insert[0].0) - ); - for comment in comments_to_insert.iter().skip(1) { - write!(comment_str, "{}{}", comment.1, &format_comment(&comment.0))?; + let mut iter = comments_to_insert.iter(); + if let Some(first) = iter.next() { + let mut comment_str = format!("{}{}", first.1, format_comment(&first.0)); + for comment in iter { + write!(comment_str, "{}{}", comment.1, &format_comment(&comment.0))?; + } + let mut src_rope = Rope::from_str(formatted_code); + src_rope.insert(from.end + offset, &comment_str); + formatted_code.clear(); + formatted_code.push_str(&src_rope.to_string()); + return Ok(comment_str.len()); } - src_rope.insert(from.end + offset, &comment_str); - formatted_code.clear(); - formatted_code.push_str(&src_rope.to_string()); - Ok(comment_str.len()) + Ok(0) } /// Applies formatting to the comment. From 4424ae881b9a3ff2ef62292d24b2ea3d0120234e Mon Sep 17 00:00:00 2001 From: Kaya Gokalp Date: Thu, 21 Jul 2022 20:40:56 +0300 Subject: [PATCH 41/44] Split test_comments to seperate tests for better visibility, code refactoring around insertion --- sway-fmt-v2/src/fmt.rs | 167 ++++++++++++++++++++---------- sway-fmt-v2/src/utils/comments.rs | 82 +++++++++------ 2 files changed, 165 insertions(+), 84 deletions(-) diff --git a/sway-fmt-v2/src/fmt.rs b/sway-fmt-v2/src/fmt.rs index 508f40c18b4..f40d2d70028 100644 --- a/sway-fmt-v2/src/fmt.rs +++ b/sway-fmt-v2/src/fmt.rs @@ -498,9 +498,9 @@ trait CompSciStudent: Programmer + Student { } #[test] - fn test_comments() { + fn test_struct_comments() { let sway_code_to_format = r#"contract; -// This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implemented +// This is a comment, for this one to be placed correctly we need to have Module visitor implemented pub struct Foo { // Here is a comment @@ -521,48 +521,10 @@ pub struct Foo { // Here is a comment // \|_________| } // This is a comment - - - -pub enum Bazz { // Here is a comment - // Trying some ASCII art - baz: (), - - - - - bazzz: (),//----- - //--D-- - //----- -} -// This is a comment before a fn -// This is another comment before a fn -fn hello_world( baz: /* this is a comment */ u64) { // This is a comment inside the block -} -// This is a storage map -abi StorageMapExample { - // insert_into_map is blah blah - #[storage(write)] // this is some other comment - fn insert_into_map1(key: u64, value: u64); // this is the last comment inside the StorageMapExample - - fn hello(key: u64, value: u64); -} -pub const /* TEST: blah blah tests */ TEST: u16 = 10; // This is a comment next to a const - -storage { - // Testig a comment inside storage - long_var_name: Type1=Type1{}, - // Testing another comment - var2: Type2=Type2{} // This is the last comment, - } -// This is the programmer trait -trait Programmer { - // Returns fav languages of this Programmer. - fn fav_language(self) -> String; -}"#; +"#; let correct_sway_code = r#"contract; -// This is some other comment, for this one to be placed correclty we need to have ModuleKind visitor implemented +// This is a comment, for this one to be placed correctly we need to have Module visitor implemented pub struct Foo { // Here is a comment @@ -578,36 +540,135 @@ pub struct Foo { // Here is a comment // \|__| \|_______|\|_______|\|_______| \|_______|\|__|\|__|\|_______|\_________\ // \|_________| } -// This is a comment +// This is a comment"#; + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + assert_eq!(correct_sway_code, formatted_sway_code) + } + + #[test] + fn test_enum_comments() { + let sway_code_to_format = r#"contract; pub enum Bazz { // Here is a comment // Trying some ASCII art baz: (), + + + + + bazzz: (),//----- //--D-- //----- } +"#; + let correct_sway_code = r#"contract; + +pub enum Bazz { // Here is a comment + // Trying some ASCII art + baz: (), + bazzz: (),//----- + //--D-- + //----- +}"#; + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + assert_eq!(correct_sway_code, formatted_sway_code); + } + + #[test] + fn test_fn_comments() { + let sway_code_to_format = r#"contract; // This is a comment before a fn // This is another comment before a fn -fn hello_world(baz: /* this is a comment */ u64) { // This is a comment inside the block +fn hello_world( baz: /* this is a comment */ u64) { // This is a comment inside the block } -// This is a storage map +"#; + let correct_sway_code = r#"contract; + +// This is a comment before a fn +// This is another comment before a fn +fn hello_world(baz: /* this is a comment */ u64) { // This is a comment inside the block +}"#; + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + assert_eq!(correct_sway_code, formatted_sway_code); + } + + #[test] + fn test_abi_comments() { + let sway_code_to_format = r#"contract; +// This is an abi abi StorageMapExample { // insert_into_map is blah blah #[storage(write)] // this is some other comment - fn insert_into_map1(key: u64, value: u64); // this is the last comment inside the StorageMapExample + fn insert_into_map(key: u64, value: u64); // this is the last comment inside the StorageMapExample +}"#; + let correct_sway_code = r#"contract; + +// This is an abi +abi StorageMapExample { + // insert_into_map is blah blah + #[storage(write)] // this is some other comment + fn insert_into_map(key: u64, value: u64); // this is the last comment inside the StorageMapExample +}"#; + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + assert_eq!(correct_sway_code, formatted_sway_code); + } + + #[test] + fn test_const_comments() { + let sway_code_to_format = r#"contract; +pub const /* TEST: blah blah tests */ TEST: u16 = 10; // This is a comment next to a const"#; + let correct_sway_code = r#"contract; + +pub const /* TEST: blah blah tests */ TEST: u16 = 10;"#; // Comment next to const is not picked up by the lexer see: #2356 + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + assert_eq!(correct_sway_code, formatted_sway_code); + } + #[test] + fn test_storage_comments() { + let sway_code_to_format = r#"contract; +storage { + // Testing a comment inside storage + long_var_name: Type1=Type1{}, + // Testing another comment + var2: Type2 = Type2{} // This is the last comment +}"#; + let correct_sway_code = r#"contract; - fn hello(key: u64, value: u64); -} -pub const /* TEST: blah blah tests */ TEST: u16 = 10; // This is a comment next to a const storage { - // Testig a comment inside storage + // Testing a comment inside storage long_var_name: Type1 = Type1 { }, // Testing another comment var2: Type2 = Type2 { - }, // This is the last comment, -} + }, // This is the last comment +}"#; + let mut formatter = Formatter::default(); + let formatted_sway_code = + Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); + assert_eq!(correct_sway_code, formatted_sway_code); + } + + #[test] + fn test_trait_comments() { + let sway_code_to_format = r#"contract; +// This is the programmer trait +trait Programmer { + // Returns fav languages of this Programmer. + fn fav_language(self) -> String; +}"#; + let correct_sway_code = r#"contract; + // This is the programmer trait trait Programmer { // Returns fav languages of this Programmer. @@ -617,8 +678,6 @@ trait Programmer { let mut formatter = Formatter::default(); let formatted_sway_code = Formatter::format(&mut formatter, Arc::from(sway_code_to_format), None).unwrap(); - println!("{formatted_sway_code}"); - println!("{correct_sway_code}"); assert_eq!(correct_sway_code, formatted_sway_code) } } diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 8fb82f215b3..5ee03127082 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -267,17 +267,23 @@ pub fn handle_comments( // Actually find & insert the comments add_comments( comment_map, - &unformatted_module, + unformatted_module, &formatted_module, formatted_code, unformatted_input, )?; Ok(()) } + /// Adds the comments from comment_map to correct places in the formatted code. This requires us -/// both the unformatted and formatted code's items as they will have different spans for their -/// nodes. While traversing the unformatted items, `add_comments` searches for comments. If there is a comment found -/// places the comment. +/// both the unformatted and formatted code's modules as they will have different spans for their +/// visitable positions. While traversing the unformatted module, `add_comments` searches for comments. If there is a comment found +/// places the comment to the correct place at formatted_code. +/// +/// This requires both the unformatted_code itself and the parsed version of it, because +/// unformatted_code is used for context lookups and unformatted_module is required for actual +/// traversal. When `add_comments` is called we have already parsed the unformatted_code so there is no need +/// to parse it again. fn add_comments( comment_map: CommentMap, unformatted_module: &Module, @@ -285,8 +291,18 @@ fn add_comments( formatted_code: &mut FormattedCode, unformatted_code: Arc, ) -> Result<(), FormatterError> { - let unformatted_comment_spans = unformatted_module.collect_spans(); - let formatted_comment_spans = formatted_module.collect_spans(); + let mut unformatted_comment_spans = unformatted_module.collect_spans(); + let mut formatted_comment_spans = formatted_module.collect_spans(); + // Adding end of file to both spans so that the last comment(s) after an item would also be + // found & included + unformatted_comment_spans.push(ByteSpan { + start: unformatted_code.len(), + end: unformatted_code.len(), + }); + formatted_comment_spans.push(ByteSpan { + start: formatted_code.len(), + end: formatted_code.len(), + }); // Since we are adding comments into formatted code, in the next iteration the spans we find for the formatted code needs to be offsetted // as the total length of comments we added in previous iterations. @@ -335,25 +351,22 @@ fn get_comments_between_spans( comment_map: &CommentMap, unformatted_code: &Arc, ) -> Vec { - let mut comments_with_context = Vec::new(); + let mut comments_with_context: Vec = Vec::new(); for (index, (comment_span, comment)) in comment_map .range((Included(from), Excluded(to))) .enumerate() { - if comments_with_context.is_empty() { + let starting_position_for_context = if index == 0 { // This is the first comment in the current range the context should be collected between from's end and comment's beginning - comments_with_context.push(( - comment.clone(), - unformatted_code[from.end..comment_span.start].to_string(), - )); + from.end } else { // There is a comment before this one, so we should get the context starting from the last comment's end to the beginning of the current comment - comments_with_context.push(( - comment.clone(), - unformatted_code[comments_with_context[index - 1].0.span.end()..comment_span.start] - .to_string(), - )); - } + comments_with_context[index - 1].0.span.end() + }; + comments_with_context.push(( + comment.clone(), + unformatted_code[starting_position_for_context..comment_span.start].to_string(), + )); } comments_with_context } @@ -365,19 +378,28 @@ fn insert_after_span( offset: usize, formatted_code: &mut FormattedCode, ) -> Result { - let mut iter = comments_to_insert.iter(); - if let Some(first) = iter.next() { - let mut comment_str = format!("{}{}", first.1, format_comment(&first.0)); - for comment in iter { - write!(comment_str, "{}{}", comment.1, &format_comment(&comment.0))?; - } - let mut src_rope = Rope::from_str(formatted_code); - src_rope.insert(from.end + offset, &comment_str); - formatted_code.clear(); - formatted_code.push_str(&src_rope.to_string()); - return Ok(comment_str.len()); + let iter = comments_to_insert.iter(); + let mut offset = offset; + let mut comment_str = String::new(); + for comment_with_context in iter { + let (comment_value, comment_context) = comment_with_context; + write!( + comment_str, + "{}{}", + comment_context, + &format_comment(comment_value) + )?; + } + let mut src_rope = Rope::from_str(formatted_code); + // If the position we are going to be inserting from + 1 is a \n we are moving that \n after + // this comment so if that is the case we are inserting after the \n + if formatted_code.chars().nth(from.end + offset + 1) == Some('\n') { + offset += 1; } - Ok(0) + src_rope.insert(from.end + offset, &comment_str); + formatted_code.clear(); + formatted_code.push_str(&src_rope.to_string()); + Ok(comment_str.len()) } /// Applies formatting to the comment. From c8bc47436e749c05599027210fde5bbfc488daa3 Mon Sep 17 00:00:00 2001 From: Kaya Gokalp Date: Thu, 21 Jul 2022 20:52:21 +0300 Subject: [PATCH 42/44] removed comments regarding comments inside PathType --- sway-fmt-v2/src/utils/path.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/sway-fmt-v2/src/utils/path.rs b/sway-fmt-v2/src/utils/path.rs index 97b9ef9cac7..ed55eb67e32 100644 --- a/sway-fmt-v2/src/utils/path.rs +++ b/sway-fmt-v2/src/utils/path.rs @@ -138,18 +138,12 @@ impl Format for PathTypeSegment { impl CommentVisitor for PathExpr { fn collect_spans(&self) -> Vec { - // TODO: Should we look for a comment inside the path expression? if so we will need to implement CommentVisitor for PathExpr - // For now we are assuming there will be no comments inside the PathExpr so the following comment will be omitted - // root::parent/* i am a comment*/::child - // I am not sure if this is something the language will allow. vec![ByteSpan::from(self.span())] } } impl CommentVisitor for PathType { fn collect_spans(&self) -> Vec { - // TODO: Should we look for a comment inside the path type? if so we will need to implement CommentVisitor for PathType - // For now we are assuming there will be no comments inside the PathType so we are visiting it as a single unit. vec![ByteSpan::from(self.span())] } } From 5328b3d8757b1fda08caa8cda1a8254aa767cf43 Mon Sep 17 00:00:00 2001 From: Kaya Gokalp Date: Fri, 22 Jul 2022 14:03:29 +0300 Subject: [PATCH 43/44] CommentVisitor -> LeafSpans and comment formatting fix --- sway-fmt-v2/src/items/item_abi.rs | 10 +- sway-fmt-v2/src/items/item_const.rs | 10 +- sway-fmt-v2/src/items/item_enum.rs | 8 +- sway-fmt-v2/src/items/item_fn.rs | 40 ++--- sway-fmt-v2/src/items/item_impl.rs | 12 +- sway-fmt-v2/src/items/item_storage.rs | 16 +- sway-fmt-v2/src/items/item_struct.rs | 8 +- sway-fmt-v2/src/items/item_trait.rs | 20 +-- sway-fmt-v2/src/items/item_use.rs | 16 +- sway-fmt-v2/src/utils/attribute.rs | 14 +- sway-fmt-v2/src/utils/comments.rs | 108 ++++++----- sway-fmt-v2/src/utils/expr.rs | 250 +++++++++++++------------- sway-fmt-v2/src/utils/item.rs | 24 +-- sway-fmt-v2/src/utils/literal.rs | 6 +- sway-fmt-v2/src/utils/path.rs | 10 +- sway-fmt-v2/src/utils/pattern.rs | 26 +-- sway-fmt-v2/src/utils/program_type.rs | 30 ++-- sway-fmt-v2/src/utils/punctuated.rs | 16 +- sway-fmt-v2/src/utils/statement.rs | 22 +-- sway-fmt-v2/src/utils/ty.rs | 30 ++-- 20 files changed, 336 insertions(+), 340 deletions(-) diff --git a/sway-fmt-v2/src/items/item_abi.rs b/sway-fmt-v2/src/items/item_abi.rs index 359652c8bad..c55ae82eca8 100644 --- a/sway-fmt-v2/src/items/item_abi.rs +++ b/sway-fmt-v2/src/items/item_abi.rs @@ -4,7 +4,7 @@ use crate::{ utils::{ attribute::FormatDecl, bracket::CurlyBrace, - comments::{ByteSpan, CommentVisitor}, + comments::{ByteSpan, LeafSpans}, }, FormatterError, }; @@ -135,13 +135,13 @@ impl CurlyBrace for ItemAbi { } } -impl CommentVisitor for ItemAbi { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemAbi { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.abi_token.span())]; collected_spans.push(ByteSpan::from(self.name.span())); - collected_spans.append(&mut self.abi_items.collect_spans()); + collected_spans.append(&mut self.abi_items.leaf_spans()); if let Some(abi_defs) = &self.abi_defs_opt { - collected_spans.append(&mut abi_defs.collect_spans()); + collected_spans.append(&mut abi_defs.leaf_spans()); } collected_spans } diff --git a/sway-fmt-v2/src/items/item_const.rs b/sway-fmt-v2/src/items/item_const.rs index f02493adf80..acc589c130c 100644 --- a/sway-fmt-v2/src/items/item_const.rs +++ b/sway-fmt-v2/src/items/item_const.rs @@ -1,6 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, FormatterError, }; use std::fmt::Write; @@ -46,8 +46,8 @@ impl Format for ItemConst { } } -impl CommentVisitor for ItemConst { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemConst { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); @@ -55,11 +55,11 @@ impl CommentVisitor for ItemConst { collected_spans.push(ByteSpan::from(self.const_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(ty) = &self.ty_opt { - collected_spans.append(&mut ty.collect_spans()); + collected_spans.append(&mut ty.leaf_spans()); // TODO: determine if we allow comments in between `:` and ty } collected_spans.push(ByteSpan::from(self.eq_token.span())); - collected_spans.append(&mut self.expr.collect_spans()); + collected_spans.append(&mut self.expr.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } diff --git a/sway-fmt-v2/src/items/item_enum.rs b/sway-fmt-v2/src/items/item_enum.rs index 571ae52628e..d84a1dc06a8 100644 --- a/sway-fmt-v2/src/items/item_enum.rs +++ b/sway-fmt-v2/src/items/item_enum.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, utils::{ bracket::CurlyBrace, - comments::{ByteSpan, CommentVisitor}, + comments::{ByteSpan, LeafSpans}, item::ItemLenChars, }, FormatterError, @@ -239,8 +239,8 @@ impl CurlyBrace for ItemEnum { Ok(()) } } -impl CommentVisitor for ItemEnum { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemEnum { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); @@ -250,7 +250,7 @@ impl CommentVisitor for ItemEnum { if let Some(generics) = &self.generics { collected_spans.push(ByteSpan::from(generics.parameters.span())) } - collected_spans.append(&mut self.fields.collect_spans()); + collected_spans.append(&mut self.fields.leaf_spans()); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_fn.rs b/sway-fmt-v2/src/items/item_fn.rs index 1080de20eee..e7682ca6461 100644 --- a/sway-fmt-v2/src/items/item_fn.rs +++ b/sway-fmt-v2/src/items/item_fn.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter, FormatterError}, utils::{ bracket::{CurlyBrace, Parenthesis}, - comments::{ByteSpan, CommentVisitor}, + comments::{ByteSpan, LeafSpans}, }, }; use std::fmt::Write; @@ -207,30 +207,30 @@ impl Format for FnArg { } } -impl CommentVisitor for ItemFn { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemFn { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - collected_spans.append(&mut self.fn_signature.collect_spans()); - collected_spans.append(&mut self.body.collect_spans()); + collected_spans.append(&mut self.fn_signature.leaf_spans()); + collected_spans.append(&mut self.body.leaf_spans()); collected_spans } } -impl CommentVisitor for CodeBlockContents { - fn collect_spans(&self) -> Vec { +impl LeafSpans for CodeBlockContents { + fn leaf_spans(&self) -> Vec { let mut collected_span = Vec::new(); for statement in self.statements.iter() { - collected_span.append(&mut statement.collect_spans()); + collected_span.append(&mut statement.leaf_spans()); } if let Some(expr) = &self.final_expr_opt { - collected_span.append(&mut expr.collect_spans()); + collected_span.append(&mut expr.leaf_spans()); } collected_span } } -impl CommentVisitor for FnSignature { - fn collect_spans(&self) -> Vec { +impl LeafSpans for FnSignature { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); @@ -240,21 +240,21 @@ impl CommentVisitor for FnSignature { if let Some(generics) = &self.generics { collected_spans.push(ByteSpan::from(generics.parameters.span())); } - collected_spans.append(&mut self.arguments.collect_spans()); + collected_spans.append(&mut self.arguments.leaf_spans()); if let Some(return_type) = &self.return_type_opt { - collected_spans.append(&mut return_type.collect_spans()); + collected_spans.append(&mut return_type.leaf_spans()); } // TODO add where, I will add where for all items at once. collected_spans } } -impl CommentVisitor for FnArgs { - fn collect_spans(&self) -> Vec { +impl LeafSpans for FnArgs { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match &self { FnArgs::Static(arg_static) => { - collected_spans.append(&mut arg_static.collect_spans()); + collected_spans.append(&mut arg_static.leaf_spans()); } FnArgs::NonStatic { self_token, @@ -266,7 +266,7 @@ impl CommentVisitor for FnArgs { collected_spans.push(ByteSpan::from(mutable.span())); } if let Some(args) = args_opt { - collected_spans.append(&mut args.collect_spans()); + collected_spans.append(&mut args.leaf_spans()); } } }; @@ -274,10 +274,10 @@ impl CommentVisitor for FnArgs { } } -impl CommentVisitor for FnArg { - fn collect_spans(&self) -> Vec { +impl LeafSpans for FnArg { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - collected_spans.append(&mut self.pattern.collect_spans()); + collected_spans.append(&mut self.pattern.leaf_spans()); collected_spans.push(ByteSpan::from(self.colon_token.span())); collected_spans.push(ByteSpan::from(self.ty.span())); collected_spans diff --git a/sway-fmt-v2/src/items/item_impl.rs b/sway-fmt-v2/src/items/item_impl.rs index 16bab28eccb..07b85c6b590 100644 --- a/sway-fmt-v2/src/items/item_impl.rs +++ b/sway-fmt-v2/src/items/item_impl.rs @@ -1,6 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, FormatterError, }; use sway_parse::ItemImpl; @@ -15,18 +15,18 @@ impl Format for ItemImpl { todo!() } } -impl CommentVisitor for ItemImpl { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemImpl { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.impl_token.span())]; if let Some(generic) = &self.generic_params_opt { collected_spans.push(ByteSpan::from(generic.parameters.span())); } if let Some(trait_tuple) = &self.trait_opt { - collected_spans.append(&mut trait_tuple.collect_spans()); + collected_spans.append(&mut trait_tuple.leaf_spans()); } - collected_spans.append(&mut self.ty.collect_spans()); + collected_spans.append(&mut self.ty.leaf_spans()); // TODO add where - collected_spans.append(&mut self.contents.collect_spans()); + collected_spans.append(&mut self.contents.leaf_spans()); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_storage.rs b/sway-fmt-v2/src/items/item_storage.rs index df69c817cd9..9d4189ffd5c 100644 --- a/sway-fmt-v2/src/items/item_storage.rs +++ b/sway-fmt-v2/src/items/item_storage.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, utils::{ bracket::CurlyBrace, - comments::{ByteSpan, CommentVisitor}, + comments::{ByteSpan, LeafSpans}, item::ItemLenChars, }, FormatterError, @@ -230,21 +230,21 @@ impl CurlyBrace for ItemStorage { } } -impl CommentVisitor for ItemStorage { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemStorage { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.storage_token.span())]; - collected_spans.append(&mut self.fields.collect_spans()); + collected_spans.append(&mut self.fields.leaf_spans()); collected_spans } } -impl CommentVisitor for StorageField { - fn collect_spans(&self) -> Vec { +impl LeafSpans for StorageField { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; collected_spans.push(ByteSpan::from(self.colon_token.span())); - collected_spans.append(&mut self.ty.collect_spans()); + collected_spans.append(&mut self.ty.leaf_spans()); collected_spans.push(ByteSpan::from(self.eq_token.span())); - collected_spans.append(&mut self.initializer.collect_spans()); + collected_spans.append(&mut self.initializer.leaf_spans()); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_struct.rs b/sway-fmt-v2/src/items/item_struct.rs index 59ce9e157cc..c714fa2a37b 100644 --- a/sway-fmt-v2/src/items/item_struct.rs +++ b/sway-fmt-v2/src/items/item_struct.rs @@ -3,7 +3,7 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, utils::{ bracket::CurlyBrace, - comments::{ByteSpan, CommentVisitor}, + comments::{ByteSpan, LeafSpans}, item::ItemLenChars, }, FormatterError, @@ -245,8 +245,8 @@ impl CurlyBrace for ItemStruct { } } -impl CommentVisitor for ItemStruct { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemStruct { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); @@ -256,7 +256,7 @@ impl CommentVisitor for ItemStruct { if let Some(generics) = &self.generics { collected_spans.push(ByteSpan::from(generics.parameters.span())) } - collected_spans.append(&mut self.fields.collect_spans()); + collected_spans.append(&mut self.fields.leaf_spans()); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_trait.rs b/sway-fmt-v2/src/items/item_trait.rs index 74091201ad1..1bdc05b5392 100644 --- a/sway-fmt-v2/src/items/item_trait.rs +++ b/sway-fmt-v2/src/items/item_trait.rs @@ -3,7 +3,7 @@ use crate::{ fmt::*, utils::{ bracket::CurlyBrace, - comments::{ByteSpan, CommentVisitor}, + comments::{ByteSpan, LeafSpans}, }, }; use std::fmt::Write; @@ -121,8 +121,8 @@ impl Format for Traits { } } -impl CommentVisitor for ItemTrait { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemTrait { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); @@ -130,20 +130,20 @@ impl CommentVisitor for ItemTrait { collected_spans.push(ByteSpan::from(self.trait_token.span())); collected_spans.push(ByteSpan::from(self.name.span())); if let Some(super_traits) = &self.super_traits { - collected_spans.append(&mut super_traits.collect_spans()); + collected_spans.append(&mut super_traits.leaf_spans()); } - collected_spans.append(&mut self.trait_items.collect_spans()); + collected_spans.append(&mut self.trait_items.leaf_spans()); if let Some(trait_defs) = &self.trait_defs_opt { - collected_spans.append(&mut trait_defs.collect_spans()); + collected_spans.append(&mut trait_defs.leaf_spans()); } collected_spans } } -impl CommentVisitor for Traits { - fn collect_spans(&self) -> Vec { - let mut collected_spans = self.prefix.collect_spans(); - collected_spans.append(&mut self.suffixes.collect_spans()); +impl LeafSpans for Traits { + fn leaf_spans(&self) -> Vec { + let mut collected_spans = self.prefix.leaf_spans(); + collected_spans.append(&mut self.suffixes.leaf_spans()); collected_spans } } diff --git a/sway-fmt-v2/src/items/item_use.rs b/sway-fmt-v2/src/items/item_use.rs index f0f6f87c9c3..9448a136322 100644 --- a/sway-fmt-v2/src/items/item_use.rs +++ b/sway-fmt-v2/src/items/item_use.rs @@ -2,7 +2,7 @@ use std::vec; use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, FormatterError, }; use sway_parse::{ItemUse, UseTree}; @@ -18,8 +18,8 @@ impl Format for ItemUse { } } -impl CommentVisitor for ItemUse { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ItemUse { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let Some(visibility) = &self.visibility { collected_spans.push(ByteSpan::from(visibility.span())); @@ -28,16 +28,16 @@ impl CommentVisitor for ItemUse { if let Some(root_import) = &self.root_import { collected_spans.push(ByteSpan::from(root_import.span())); } - collected_spans.append(&mut self.tree.collect_spans()); + collected_spans.append(&mut self.tree.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } } -impl CommentVisitor for UseTree { - fn collect_spans(&self) -> Vec { +impl LeafSpans for UseTree { + fn leaf_spans(&self) -> Vec { match self { - UseTree::Group { imports } => imports.collect_spans(), + UseTree::Group { imports } => imports.leaf_spans(), UseTree::Name { name } => vec![ByteSpan::from(name.span())], UseTree::Rename { name, @@ -56,7 +56,7 @@ impl CommentVisitor for UseTree { } => { let mut collected_spans = vec![ByteSpan::from(prefix.span())]; collected_spans.push(ByteSpan::from(double_colon_token.span())); - collected_spans.append(&mut suffix.collect_spans()); + collected_spans.append(&mut suffix.leaf_spans()); collected_spans } } diff --git a/sway-fmt-v2/src/utils/attribute.rs b/sway-fmt-v2/src/utils/attribute.rs index 0852d6b77e6..eb70567a008 100644 --- a/sway-fmt-v2/src/utils/attribute.rs +++ b/sway-fmt-v2/src/utils/attribute.rs @@ -12,7 +12,7 @@ use sway_types::Spanned; use super::{ bracket::{Parenthesis, SquareBracket}, - comments::{ByteSpan, CommentVisitor}, + comments::{ByteSpan, LeafSpans}, }; impl Format for Annotated { @@ -94,18 +94,18 @@ impl Parenthesis for AttributeDecl { Ok(()) } } -impl CommentVisitor for AttributeDecl { - fn collect_spans(&self) -> Vec { +impl LeafSpans for AttributeDecl { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.hash_token.span())]; - collected_spans.append(&mut self.attribute.collect_spans()); + collected_spans.append(&mut self.attribute.leaf_spans()); collected_spans } } -impl CommentVisitor for Attribute { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Attribute { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; if let Some(args) = &self.args { - collected_spans.append(&mut args.collect_spans()); + collected_spans.append(&mut args.leaf_spans()); } collected_spans } diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index b6e0074af19..744892a5284 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -102,18 +102,18 @@ fn collect_comments_from_token_stream( } } -impl CommentVisitor for Braces +impl LeafSpans for Braces where - T: CommentVisitor + Clone, + T: LeafSpans + Clone, { - fn collect_spans(&self) -> Vec { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); let mut opening_brace_span = ByteSpan::from(self.span()); opening_brace_span.end = opening_brace_span.start + 1; // Add opening brace's ByteSpan collected_spans.push(opening_brace_span); // Add T's collected ByteSpan - collected_spans.append(&mut self.clone().into_inner().collect_spans()); + collected_spans.append(&mut self.clone().into_inner().leaf_spans()); let mut closing_brace_span = ByteSpan::from(self.span()); closing_brace_span.start = closing_brace_span.end - 1; // Add closing brace's ByteSpan @@ -122,18 +122,18 @@ where } } -impl CommentVisitor for Parens +impl LeafSpans for Parens where - T: CommentVisitor + Clone, + T: LeafSpans + Clone, { - fn collect_spans(&self) -> Vec { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); let mut opening_paren_span = ByteSpan::from(self.span()); opening_paren_span.end = opening_paren_span.start + 1; // Add opening paren's span collected_spans.push(opening_paren_span); // Add T's collected ByteSpan - collected_spans.append(&mut self.clone().into_inner().collect_spans()); + collected_spans.append(&mut self.clone().into_inner().leaf_spans()); let mut closing_paren_span = ByteSpan::from(self.span()); closing_paren_span.start = closing_paren_span.end - 1; // Add closing paren's ByteSpan @@ -142,18 +142,18 @@ where } } -impl CommentVisitor for SquareBrackets +impl LeafSpans for SquareBrackets where - T: CommentVisitor + Clone, + T: LeafSpans + Clone, { - fn collect_spans(&self) -> Vec { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); let mut opening_bracket_span = ByteSpan::from(self.span()); opening_bracket_span.end = opening_bracket_span.start + 1; // Add opening bracket's span collected_spans.push(opening_bracket_span); // Add T's collected ByteSpan - collected_spans.append(&mut self.clone().into_inner().collect_spans()); + collected_spans.append(&mut self.clone().into_inner().leaf_spans()); let mut closing_bracket_span = ByteSpan::from(self.span()); closing_bracket_span.start = closing_bracket_span.end - 1; // Add closing bracket's ByteSpan @@ -162,92 +162,92 @@ where } } -impl CommentVisitor for (T, P) +impl LeafSpans for (T, P) where - T: CommentVisitor, - P: CommentVisitor, + T: LeafSpans, + P: LeafSpans, { - fn collect_spans(&self) -> Vec { - let mut collected_spans = self.0.collect_spans(); - collected_spans.append(&mut self.1.collect_spans()); + fn leaf_spans(&self) -> Vec { + let mut collected_spans = self.0.leaf_spans(); + collected_spans.append(&mut self.1.leaf_spans()); collected_spans } } -impl CommentVisitor for Vec +impl LeafSpans for Vec where - T: CommentVisitor, + T: LeafSpans, { - fn collect_spans(&self) -> Vec { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); for t in self { - collected_spans.append(&mut t.collect_spans()); + collected_spans.append(&mut t.leaf_spans()); } collected_spans } } -impl CommentVisitor for Annotated +impl LeafSpans for Annotated where - T: CommentVisitor + Parse, + T: LeafSpans + Parse, { - fn collect_spans(&self) -> Vec { - let mut collected_spans = self.attribute_list.collect_spans(); - collected_spans.append(&mut self.value.collect_spans()); + fn leaf_spans(&self) -> Vec { + let mut collected_spans = self.attribute_list.leaf_spans(); + collected_spans.append(&mut self.value.leaf_spans()); collected_spans } } -impl CommentVisitor for Ident { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Ident { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for CommaToken { - fn collect_spans(&self) -> Vec { +impl LeafSpans for CommaToken { + fn leaf_spans(&self) -> Vec { vec![(ByteSpan::from(self.span()))] } } -impl CommentVisitor for TypeField { - fn collect_spans(&self) -> Vec { +impl LeafSpans for TypeField { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; collected_spans.push(ByteSpan::from(self.colon_token.span())); - collected_spans.append(&mut self.ty.collect_spans()); + collected_spans.append(&mut self.ty.leaf_spans()); collected_spans } } -impl CommentVisitor for AddToken { - fn collect_spans(&self) -> Vec { +impl LeafSpans for AddToken { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for SemicolonToken { - fn collect_spans(&self) -> Vec { +impl LeafSpans for SemicolonToken { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for ColonToken { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ColonToken { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for RightArrowToken { - fn collect_spans(&self) -> Vec { +impl LeafSpans for RightArrowToken { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for ForToken { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ForToken { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for ForwardSlashToken { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ForwardSlashToken { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } @@ -291,8 +291,8 @@ fn add_comments( formatted_code: &mut FormattedCode, unformatted_code: Arc, ) -> Result<(), FormatterError> { - let mut unformatted_comment_spans = unformatted_module.collect_spans(); - let mut formatted_comment_spans = formatted_module.collect_spans(); + let mut unformatted_comment_spans = unformatted_module.leaf_spans(); + let mut formatted_comment_spans = formatted_module.leaf_spans(); // Adding end of file to both spans so that the last comment(s) after an item would also be // found & included unformatted_comment_spans.push(ByteSpan { @@ -403,18 +403,14 @@ fn insert_after_span( } /// Applies formatting to the comment. -/// Currently just checks if it is a multiline comment, if that is the case it adds a trailing `/` to the end. +/// Currently does not apply any formatting and directly returns the raw comment str fn format_comment(comment: &Comment) -> String { - if comment.span().str().starts_with("/*") { - format!("{}/", comment.span().str()) - } else { comment.span().str() - } } /// While searching for a comment we need the possible places a comment can be placed in a structure -/// `collect_spans` collects all field's spans so that we can check in between them. -pub trait CommentVisitor { - fn collect_spans(&self) -> Vec; +/// `leaf_spans` collects all field's spans so that we can check in between them. +pub trait LeafSpans { + fn leaf_spans(&self) -> Vec; } #[cfg(test)] diff --git a/sway-fmt-v2/src/utils/expr.rs b/sway-fmt-v2/src/utils/expr.rs index d93d400699a..7220c91cb6f 100644 --- a/sway-fmt-v2/src/utils/expr.rs +++ b/sway-fmt-v2/src/utils/expr.rs @@ -1,7 +1,7 @@ use crate::{ config::items::ItemBraceStyle, fmt::*, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, }; use std::{fmt::Write, vec}; use sway_parse::{ @@ -259,14 +259,14 @@ impl CurlyBrace for ExprStructField { } // TODO: Find a better way of handling Boxed version -impl CommentVisitor for Box { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Box { + fn leaf_spans(&self) -> Vec { visit_expr(self) } } -impl CommentVisitor for Expr { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Expr { + fn leaf_spans(&self) -> Vec { visit_expr(self) } } @@ -274,42 +274,42 @@ impl CommentVisitor for Expr { /// Collects various expr field's ByteSpans. fn visit_expr(expr: &Expr) -> Vec { match expr { - Expr::Path(path) => path.collect_spans(), - Expr::Literal(literal) => literal.collect_spans(), + Expr::Path(path) => path.leaf_spans(), + Expr::Literal(literal) => literal.leaf_spans(), Expr::AbiCast { abi_token, args } => { let mut collected_spans = vec![ByteSpan::from(abi_token.span())]; - collected_spans.append(&mut args.collect_spans()); + collected_spans.append(&mut args.leaf_spans()); collected_spans } Expr::Struct { path, fields } => { - let mut collected_spans = path.collect_spans(); - collected_spans.append(&mut fields.collect_spans()); + let mut collected_spans = path.leaf_spans(); + collected_spans.append(&mut fields.leaf_spans()); collected_spans } - Expr::Tuple(tuple) => tuple.collect_spans(), - Expr::Parens(parens) => parens.collect_spans(), - Expr::Block(block) => block.collect_spans(), - Expr::Array(array) => array.collect_spans(), - Expr::Asm(asm) => asm.collect_spans(), + Expr::Tuple(tuple) => tuple.leaf_spans(), + Expr::Parens(parens) => parens.leaf_spans(), + Expr::Block(block) => block.leaf_spans(), + Expr::Array(array) => array.leaf_spans(), + Expr::Asm(asm) => asm.leaf_spans(), Expr::Return { return_token, expr_opt, } => { let mut collected_spans = vec![ByteSpan::from(return_token.span())]; if let Some(expr) = expr_opt { - collected_spans.append(&mut expr.collect_spans()); + collected_spans.append(&mut expr.leaf_spans()); } collected_spans } - Expr::If(expr_if) => expr_if.collect_spans(), + Expr::If(expr_if) => expr_if.leaf_spans(), Expr::Match { match_token, value, branches, } => { let mut collected_spans = vec![ByteSpan::from(match_token.span())]; - collected_spans.append(&mut value.collect_spans()); - collected_spans.append(&mut branches.collect_spans()); + collected_spans.append(&mut value.leaf_spans()); + collected_spans.append(&mut branches.leaf_spans()); collected_spans } Expr::While { @@ -318,20 +318,20 @@ fn visit_expr(expr: &Expr) -> Vec { block, } => { let mut collected_spans = vec![ByteSpan::from(while_token.span())]; - collected_spans.append(&mut condition.collect_spans()); - collected_spans.append(&mut block.collect_spans()); + collected_spans.append(&mut condition.leaf_spans()); + collected_spans.append(&mut block.leaf_spans()); collected_spans } Expr::FuncApp { func, args } => { let mut collected_spans = Vec::new(); - collected_spans.append(&mut func.collect_spans()); - collected_spans.append(&mut args.collect_spans()); + collected_spans.append(&mut func.leaf_spans()); + collected_spans.append(&mut args.leaf_spans()); collected_spans } Expr::Index { target, arg } => { let mut collected_spans = Vec::new(); - collected_spans.append(&mut target.collect_spans()); - collected_spans.append(&mut arg.collect_spans()); + collected_spans.append(&mut target.leaf_spans()); + collected_spans.append(&mut arg.leaf_spans()); collected_spans } Expr::MethodCall { @@ -342,13 +342,13 @@ fn visit_expr(expr: &Expr) -> Vec { args, } => { let mut collected_spans = Vec::new(); - collected_spans.append(&mut target.collect_spans()); + collected_spans.append(&mut target.leaf_spans()); collected_spans.push(ByteSpan::from(dot_token.span())); collected_spans.push(ByteSpan::from(name.span())); if let Some(contract_args) = contract_args_opt { - collected_spans.append(&mut contract_args.collect_spans()); + collected_spans.append(&mut contract_args.leaf_spans()); } - collected_spans.append(&mut args.collect_spans()); + collected_spans.append(&mut args.leaf_spans()); collected_spans } Expr::FieldProjection { @@ -357,7 +357,7 @@ fn visit_expr(expr: &Expr) -> Vec { name, } => { let mut collected_spans = Vec::new(); - collected_spans.append(&mut target.collect_spans()); + collected_spans.append(&mut target.leaf_spans()); collected_spans.push(ByteSpan::from(dot_token.span())); collected_spans.push(ByteSpan::from(name.span())); collected_spans @@ -369,24 +369,24 @@ fn visit_expr(expr: &Expr) -> Vec { field_span, } => { let mut collected_spans = Vec::new(); - collected_spans.append(&mut target.collect_spans()); + collected_spans.append(&mut target.leaf_spans()); collected_spans.push(ByteSpan::from(dot_token.span())); collected_spans.push(ByteSpan::from(field_span.clone())); collected_spans } Expr::Ref { ref_token, expr } => { let mut collected_spans = vec![ByteSpan::from(ref_token.span())]; - collected_spans.append(&mut expr.collect_spans()); + collected_spans.append(&mut expr.leaf_spans()); collected_spans } Expr::Deref { deref_token, expr } => { let mut collected_spans = vec![ByteSpan::from(deref_token.span())]; - collected_spans.append(&mut expr.collect_spans()); + collected_spans.append(&mut expr.leaf_spans()); collected_spans } Expr::Not { bang_token, expr } => { let mut collected_spans = vec![ByteSpan::from(bang_token.span())]; - collected_spans.append(&mut expr.collect_spans()); + collected_spans.append(&mut expr.leaf_spans()); collected_spans } Expr::Mul { @@ -394,9 +394,9 @@ fn visit_expr(expr: &Expr) -> Vec { star_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(star_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Div { @@ -404,9 +404,9 @@ fn visit_expr(expr: &Expr) -> Vec { forward_slash_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(forward_slash_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Modulo { @@ -414,9 +414,9 @@ fn visit_expr(expr: &Expr) -> Vec { percent_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(percent_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Add { @@ -424,9 +424,9 @@ fn visit_expr(expr: &Expr) -> Vec { add_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(add_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Sub { @@ -434,9 +434,9 @@ fn visit_expr(expr: &Expr) -> Vec { sub_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(sub_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Shl { @@ -444,9 +444,9 @@ fn visit_expr(expr: &Expr) -> Vec { shl_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(shl_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Shr { @@ -454,9 +454,9 @@ fn visit_expr(expr: &Expr) -> Vec { shr_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(shr_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::BitAnd { @@ -464,9 +464,9 @@ fn visit_expr(expr: &Expr) -> Vec { ampersand_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(ampersand_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::BitXor { @@ -474,9 +474,9 @@ fn visit_expr(expr: &Expr) -> Vec { caret_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(caret_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::BitOr { @@ -484,9 +484,9 @@ fn visit_expr(expr: &Expr) -> Vec { pipe_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(pipe_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Equal { @@ -494,9 +494,9 @@ fn visit_expr(expr: &Expr) -> Vec { double_eq_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(double_eq_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::NotEqual { @@ -504,9 +504,9 @@ fn visit_expr(expr: &Expr) -> Vec { bang_eq_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(bang_eq_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::LessThan { @@ -514,9 +514,9 @@ fn visit_expr(expr: &Expr) -> Vec { less_than_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(less_than_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::GreaterThan { @@ -524,9 +524,9 @@ fn visit_expr(expr: &Expr) -> Vec { greater_than_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(greater_than_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::LessThanEq { @@ -534,9 +534,9 @@ fn visit_expr(expr: &Expr) -> Vec { less_than_eq_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(less_than_eq_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::GreaterThanEq { @@ -544,9 +544,9 @@ fn visit_expr(expr: &Expr) -> Vec { greater_than_eq_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(greater_than_eq_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::LogicalAnd { @@ -554,9 +554,9 @@ fn visit_expr(expr: &Expr) -> Vec { double_ampersand_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(double_ampersand_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::LogicalOr { @@ -564,9 +564,9 @@ fn visit_expr(expr: &Expr) -> Vec { double_pipe_token, rhs, } => { - let mut collected_spans = lhs.collect_spans(); + let mut collected_spans = lhs.leaf_spans(); collected_spans.push(ByteSpan::from(double_pipe_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } Expr::Reassignment { @@ -574,37 +574,37 @@ fn visit_expr(expr: &Expr) -> Vec { reassignment_op, expr, } => { - let mut collected_spans = assignable.collect_spans(); + let mut collected_spans = assignable.leaf_spans(); collected_spans.push(ByteSpan::from(reassignment_op.span.clone())); - collected_spans.append(&mut expr.collect_spans()); + collected_spans.append(&mut expr.leaf_spans()); collected_spans } } } -impl CommentVisitor for AbiCastArgs { - fn collect_spans(&self) -> Vec { +impl LeafSpans for AbiCastArgs { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.name.span())]; collected_spans.push(ByteSpan::from(self.comma_token.span())); - collected_spans.append(&mut self.address.collect_spans()); + collected_spans.append(&mut self.address.leaf_spans()); collected_spans } } -impl CommentVisitor for ExprStructField { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ExprStructField { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.field_name.span())]; if let Some(expr) = &self.expr_opt { collected_spans.push(ByteSpan::from(expr.0.span())); // TODO: determine if we are allowing comments between `:` and expr - collected_spans.append(&mut expr.1.collect_spans()); + collected_spans.append(&mut expr.1.leaf_spans()); } collected_spans } } -impl CommentVisitor for ExprTupleDescriptor { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ExprTupleDescriptor { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let ExprTupleDescriptor::Cons { head, @@ -612,16 +612,16 @@ impl CommentVisitor for ExprTupleDescriptor { tail, } = self { - collected_spans.append(&mut head.collect_spans()); + collected_spans.append(&mut head.leaf_spans()); collected_spans.push(ByteSpan::from(comma_token.span())); - collected_spans.append(&mut tail.collect_spans()); + collected_spans.append(&mut tail.leaf_spans()); } collected_spans } } -impl CommentVisitor for ExprArrayDescriptor { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ExprArrayDescriptor { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let ExprArrayDescriptor::Repeat { value, @@ -629,73 +629,73 @@ impl CommentVisitor for ExprArrayDescriptor { length, } = self { - collected_spans.append(&mut value.collect_spans()); + collected_spans.append(&mut value.leaf_spans()); collected_spans.push(ByteSpan::from(semicolon_token.span())); - collected_spans.append(&mut length.collect_spans()); + collected_spans.append(&mut length.leaf_spans()); } collected_spans } } -impl CommentVisitor for AsmBlock { - fn collect_spans(&self) -> Vec { +impl LeafSpans for AsmBlock { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.asm_token.span())]; - collected_spans.append(&mut self.registers.collect_spans()); - collected_spans.append(&mut self.contents.collect_spans()); + collected_spans.append(&mut self.registers.leaf_spans()); + collected_spans.append(&mut self.contents.leaf_spans()); collected_spans } } -impl CommentVisitor for AsmRegisterDeclaration { - fn collect_spans(&self) -> Vec { +impl LeafSpans for AsmRegisterDeclaration { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.register.span())]; if let Some(value) = &self.value_opt { - collected_spans.append(&mut value.collect_spans()); + collected_spans.append(&mut value.leaf_spans()); // TODO: determine if we are allowing comments between `:` and expr } collected_spans } } -impl CommentVisitor for AsmBlockContents { - fn collect_spans(&self) -> Vec { +impl LeafSpans for AsmBlockContents { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); for instruction in &self.instructions { - collected_spans.append(&mut instruction.collect_spans()); + collected_spans.append(&mut instruction.leaf_spans()); // TODO: probably we shouldn't allow for comments in between the instruction and comma since it may/will result in build failure after formatting } collected_spans } } -impl CommentVisitor for Instruction { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Instruction { + fn leaf_spans(&self) -> Vec { // Visit instructions as a whole unit, meaning we cannot insert comments inside an instruction. vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for AsmFinalExpr { - fn collect_spans(&self) -> Vec { +impl LeafSpans for AsmFinalExpr { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.register.span())]; if let Some(ty) = &self.ty_opt { - collected_spans.append(&mut ty.collect_spans()); + collected_spans.append(&mut ty.leaf_spans()); // TODO: determine if we are allowing comments between `:` and ty } collected_spans } } -impl CommentVisitor for IfExpr { - fn collect_spans(&self) -> Vec { +impl LeafSpans for IfExpr { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.if_token.span())]; - collected_spans.append(&mut self.condition.collect_spans()); - collected_spans.append(&mut self.then_block.collect_spans()); + collected_spans.append(&mut self.condition.leaf_spans()); + collected_spans.append(&mut self.then_block.leaf_spans()); if let Some(else_block) = &self.else_opt { collected_spans.push(ByteSpan::from(else_block.0.span())); let mut else_body_spans = match &else_block.1 { - std::ops::ControlFlow::Continue(if_expr) => if_expr.collect_spans(), - std::ops::ControlFlow::Break(else_body) => else_body.collect_spans(), + std::ops::ControlFlow::Continue(if_expr) => if_expr.leaf_spans(), + std::ops::ControlFlow::Break(else_body) => else_body.leaf_spans(), }; collected_spans.append(&mut else_body_spans); } @@ -703,10 +703,10 @@ impl CommentVisitor for IfExpr { } } -impl CommentVisitor for IfCondition { - fn collect_spans(&self) -> Vec { +impl LeafSpans for IfCondition { + fn leaf_spans(&self) -> Vec { match self { - IfCondition::Expr(expr) => expr.collect_spans(), + IfCondition::Expr(expr) => expr.leaf_spans(), IfCondition::Let { let_token, lhs, @@ -714,41 +714,41 @@ impl CommentVisitor for IfCondition { rhs, } => { let mut collected_spans = vec![ByteSpan::from(let_token.span())]; - collected_spans.append(&mut lhs.collect_spans()); + collected_spans.append(&mut lhs.leaf_spans()); collected_spans.push(ByteSpan::from(eq_token.span())); - collected_spans.append(&mut rhs.collect_spans()); + collected_spans.append(&mut rhs.leaf_spans()); collected_spans } } } } -impl CommentVisitor for MatchBranch { - fn collect_spans(&self) -> Vec { +impl LeafSpans for MatchBranch { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - collected_spans.append(&mut self.pattern.collect_spans()); + collected_spans.append(&mut self.pattern.leaf_spans()); collected_spans.push(ByteSpan::from(self.fat_right_arrow_token.span())); - collected_spans.append(&mut self.kind.collect_spans()); + collected_spans.append(&mut self.kind.leaf_spans()); collected_spans } } -impl CommentVisitor for MatchBranchKind { - fn collect_spans(&self) -> Vec { +impl LeafSpans for MatchBranchKind { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { MatchBranchKind::Block { block, comma_token_opt, } => { - collected_spans.append(&mut block.collect_spans()); + collected_spans.append(&mut block.leaf_spans()); // TODO: determine if we allow comments between block and comma_token if let Some(comma_token) = comma_token_opt { collected_spans.push(ByteSpan::from(comma_token.span())); } } MatchBranchKind::Expr { expr, comma_token } => { - collected_spans.append(&mut expr.collect_spans()); + collected_spans.append(&mut expr.leaf_spans()); // TODO: determine if we allow comments between expr and comma_token collected_spans.push(ByteSpan::from(comma_token.span())); } @@ -757,21 +757,21 @@ impl CommentVisitor for MatchBranchKind { } } -impl CommentVisitor for Assignable { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Assignable { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { Assignable::Var(var) => collected_spans.push(ByteSpan::from(var.span())), Assignable::Index { target, arg } => { - collected_spans.append(&mut target.collect_spans()); - collected_spans.append(&mut arg.collect_spans()); + collected_spans.append(&mut target.leaf_spans()); + collected_spans.append(&mut arg.leaf_spans()); } Assignable::FieldProjection { target, dot_token, name, } => { - collected_spans.append(&mut target.collect_spans()); + collected_spans.append(&mut target.leaf_spans()); collected_spans.push(ByteSpan::from(dot_token.span())); collected_spans.push(ByteSpan::from(name.span())); } @@ -781,7 +781,7 @@ impl CommentVisitor for Assignable { field: _field, field_span, } => { - collected_spans.append(&mut target.collect_spans()); + collected_spans.append(&mut target.leaf_spans()); collected_spans.push(ByteSpan::from(dot_token.span())); collected_spans.push(ByteSpan::from(field_span.clone())); } diff --git a/sway-fmt-v2/src/utils/item.rs b/sway-fmt-v2/src/utils/item.rs index 580f494f8bb..d7a66673a69 100644 --- a/sway-fmt-v2/src/utils/item.rs +++ b/sway-fmt-v2/src/utils/item.rs @@ -1,21 +1,21 @@ use crate::{ fmt::{Format, FormattedCode, Formatter, FormatterError}, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, }; use sway_parse::{Item, ItemKind::*}; -impl CommentVisitor for Item { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Item { + fn leaf_spans(&self) -> Vec { match &self.value { - Struct(item_struct) => item_struct.collect_spans(), - Enum(item_enum) => item_enum.collect_spans(), - Fn(item_fn) => item_fn.collect_spans(), - Abi(item_abi) => item_abi.collect_spans(), - Const(item_const) => item_const.collect_spans(), - Storage(item_storage) => item_storage.collect_spans(), - Trait(item_trait) => item_trait.collect_spans(), - Impl(item_impl) => item_impl.collect_spans(), - Use(item_use) => item_use.collect_spans(), + Struct(item_struct) => item_struct.leaf_spans(), + Enum(item_enum) => item_enum.leaf_spans(), + Fn(item_fn) => item_fn.leaf_spans(), + Abi(item_abi) => item_abi.leaf_spans(), + Const(item_const) => item_const.leaf_spans(), + Storage(item_storage) => item_storage.leaf_spans(), + Trait(item_trait) => item_trait.leaf_spans(), + Impl(item_impl) => item_impl.leaf_spans(), + Use(item_use) => item_use.leaf_spans(), Break(_) => todo!(), Continue(_) => todo!(), } diff --git a/sway-fmt-v2/src/utils/literal.rs b/sway-fmt-v2/src/utils/literal.rs index ccc0da81423..2101da95163 100644 --- a/sway-fmt-v2/src/utils/literal.rs +++ b/sway-fmt-v2/src/utils/literal.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_parse::Literal; @@ -22,8 +22,8 @@ impl Format for Literal { } } -impl CommentVisitor for Literal { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Literal { + fn leaf_spans(&self) -> Vec { match self { Literal::String(str_lit) => vec![ByteSpan::from(str_lit.span.clone())], Literal::Char(chr_lit) => vec![ByteSpan::from(chr_lit.span.clone())], diff --git a/sway-fmt-v2/src/utils/path.rs b/sway-fmt-v2/src/utils/path.rs index ed55eb67e32..5d4ff00a3bf 100644 --- a/sway-fmt-v2/src/utils/path.rs +++ b/sway-fmt-v2/src/utils/path.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, }; use std::{fmt::Write, vec}; use sway_parse::{PathExpr, PathExprSegment, PathType, PathTypeSegment, QualifiedPathRoot}; @@ -136,14 +136,14 @@ impl Format for PathTypeSegment { } } -impl CommentVisitor for PathExpr { - fn collect_spans(&self) -> Vec { +impl LeafSpans for PathExpr { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } -impl CommentVisitor for PathType { - fn collect_spans(&self) -> Vec { +impl LeafSpans for PathType { + fn leaf_spans(&self) -> Vec { vec![ByteSpan::from(self.span())] } } diff --git a/sway-fmt-v2/src/utils/pattern.rs b/sway-fmt-v2/src/utils/pattern.rs index dea698de2aa..8cc7bf2e5ed 100644 --- a/sway-fmt-v2/src/utils/pattern.rs +++ b/sway-fmt-v2/src/utils/pattern.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_parse::{token::Delimiter, Pattern, PatternStructField}; @@ -118,8 +118,8 @@ impl Format for PatternStructField { } } -impl CommentVisitor for Pattern { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Pattern { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { Pattern::Wildcard { underscore_token } => { @@ -132,29 +132,29 @@ impl CommentVisitor for Pattern { collected_spans.push(ByteSpan::from(name.span())); } Pattern::Literal(literal) => { - collected_spans.append(&mut literal.collect_spans()); + collected_spans.append(&mut literal.leaf_spans()); } Pattern::Constant(constant) => { - collected_spans.append(&mut constant.collect_spans()); + collected_spans.append(&mut constant.leaf_spans()); } Pattern::Constructor { path, args } => { - collected_spans.append(&mut path.collect_spans()); - collected_spans.append(&mut args.collect_spans()); + collected_spans.append(&mut path.leaf_spans()); + collected_spans.append(&mut args.leaf_spans()); } Pattern::Struct { path, fields } => { - collected_spans.append(&mut path.collect_spans()); - collected_spans.append(&mut fields.collect_spans()); + collected_spans.append(&mut path.leaf_spans()); + collected_spans.append(&mut fields.leaf_spans()); } Pattern::Tuple(tuple) => { - collected_spans.append(&mut tuple.collect_spans()); + collected_spans.append(&mut tuple.leaf_spans()); } } collected_spans } } -impl CommentVisitor for PatternStructField { - fn collect_spans(&self) -> Vec { +impl LeafSpans for PatternStructField { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); match self { PatternStructField::Rest { token } => { @@ -167,7 +167,7 @@ impl CommentVisitor for PatternStructField { collected_spans.push(ByteSpan::from(field_name.span())); if let Some(pattern) = pattern_opt { collected_spans.push(ByteSpan::from(pattern.0.span())); - collected_spans.append(&mut pattern.1.collect_spans()); + collected_spans.append(&mut pattern.1.leaf_spans()); } } } diff --git a/sway-fmt-v2/src/utils/program_type.rs b/sway-fmt-v2/src/utils/program_type.rs index cbf92c3f237..72fdb6c976c 100644 --- a/sway-fmt-v2/src/utils/program_type.rs +++ b/sway-fmt-v2/src/utils/program_type.rs @@ -4,7 +4,7 @@ use sway_types::Spanned; use crate::FormatterError; -use super::comments::{ByteSpan, CommentVisitor}; +use super::comments::{ByteSpan, LeafSpans}; /// Insert the program type without applying a formatting to it. /// @@ -43,8 +43,8 @@ pub(crate) fn insert_program_type( Ok(()) } -impl CommentVisitor for ModuleKind { - fn collect_spans(&self) -> Vec { +impl LeafSpans for ModuleKind { + fn leaf_spans(&self) -> Vec { match self { ModuleKind::Script { script_token } => { vec![ByteSpan::from(script_token.span())] @@ -68,29 +68,29 @@ impl CommentVisitor for ModuleKind { } } -impl CommentVisitor for Module { - fn collect_spans(&self) -> Vec { - let mut collected_spans = self.kind.collect_spans(); +impl LeafSpans for Module { + fn leaf_spans(&self) -> Vec { + let mut collected_spans = self.kind.leaf_spans(); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); - collected_spans.append(&mut self.dependencies.collect_spans()); - collected_spans.append(&mut self.items.collect_spans()); + collected_spans.append(&mut self.dependencies.leaf_spans()); + collected_spans.append(&mut self.items.leaf_spans()); collected_spans } } -impl CommentVisitor for Dependency { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Dependency { + fn leaf_spans(&self) -> Vec { let mut collected_spans = vec![ByteSpan::from(self.dep_token.span())]; - collected_spans.append(&mut self.path.collect_spans()); + collected_spans.append(&mut self.path.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } } -impl CommentVisitor for DependencyPath { - fn collect_spans(&self) -> Vec { - let mut collected_spans = self.prefix.collect_spans(); - collected_spans.append(&mut self.suffixes.collect_spans()); +impl LeafSpans for DependencyPath { + fn leaf_spans(&self) -> Vec { + let mut collected_spans = self.prefix.leaf_spans(); + collected_spans.append(&mut self.suffixes.leaf_spans()); collected_spans } } diff --git a/sway-fmt-v2/src/utils/punctuated.rs b/sway-fmt-v2/src/utils/punctuated.rs index f208cc19ff9..503a6cb65e0 100644 --- a/sway-fmt-v2/src/utils/punctuated.rs +++ b/sway-fmt-v2/src/utils/punctuated.rs @@ -1,28 +1,28 @@ use crate::{ fmt::{Format, FormattedCode, Formatter}, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, FormatterError, }; use std::fmt::Write; use sway_parse::{keywords::CommaToken, punctuated::Punctuated, StorageField, TypeField}; use sway_types::{Ident, Spanned}; -impl CommentVisitor for Punctuated +impl LeafSpans for Punctuated where - T: CommentVisitor + Clone, - P: CommentVisitor + Clone, + T: LeafSpans + Clone, + P: LeafSpans + Clone, { - fn collect_spans(&self) -> Vec { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); let value_pairs = &self.value_separator_pairs; for pair in value_pairs.iter() { - let p_comment_spans = pair.1.collect_spans(); + let p_comment_spans = pair.1.leaf_spans(); // Since we do not want to have comments between T and P we are extending the ByteSpans coming from T with spans coming from P // Since formatter can insert a trailing comma after a field, comments next to a field can be falsely inserted between the comma and the field // So we shouldn't allow inserting comments (or searching for one) between T and P as in Punctuated scenerio this can/will result in formattings that breaks the build process let mut comment_spans = pair .0 - .collect_spans() + .leaf_spans() .iter_mut() .map(|comment_map| { // Since the length of P' ByteSpan is same for each pair we are using the first one's length for all of the pairs. @@ -35,7 +35,7 @@ where collected_spans.append(&mut comment_spans) } if let Some(final_value) = &self.final_value_opt { - collected_spans.append(&mut final_value.collect_spans()); + collected_spans.append(&mut final_value.leaf_spans()); } collected_spans } diff --git a/sway-fmt-v2/src/utils/statement.rs b/sway-fmt-v2/src/utils/statement.rs index 6fd1f455572..32411492d42 100644 --- a/sway-fmt-v2/src/utils/statement.rs +++ b/sway-fmt-v2/src/utils/statement.rs @@ -1,6 +1,6 @@ use crate::{ fmt::*, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_parse::{Statement, StatementLet}; @@ -60,16 +60,16 @@ impl Format for StatementLet { } } -impl CommentVisitor for Statement { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Statement { + fn leaf_spans(&self) -> Vec { match self { - Statement::Let(statement_let) => statement_let.collect_spans(), - Statement::Item(item) => item.collect_spans(), + Statement::Let(statement_let) => statement_let.leaf_spans(), + Statement::Item(item) => item.leaf_spans(), Statement::Expr { expr, semicolon_token_opt, } => { - let mut collected_spans = expr.collect_spans(); + let mut collected_spans = expr.leaf_spans(); if let Some(semicolon_token) = semicolon_token_opt { collected_spans.push(ByteSpan::from(semicolon_token.span())); } @@ -79,22 +79,22 @@ impl CommentVisitor for Statement { } } -impl CommentVisitor for StatementLet { - fn collect_spans(&self) -> Vec { +impl LeafSpans for StatementLet { + fn leaf_spans(&self) -> Vec { // Add let token's ByteSpan let mut collected_spans = vec![ByteSpan::from(self.let_token.span())]; // Add pattern's ByteSpan - collected_spans.append(&mut self.pattern.collect_spans()); + collected_spans.append(&mut self.pattern.leaf_spans()); // Add ty's ByteSpan if it exists if let Some(ty) = &self.ty_opt { collected_spans.push(ByteSpan::from(ty.0.span())); // TODO: determine if we are allowing comments between `:` and ty - collected_spans.append(&mut ty.1.collect_spans()); + collected_spans.append(&mut ty.1.leaf_spans()); } // Add eq token's ByteSpan collected_spans.push(ByteSpan::from(self.eq_token.span())); // Add Expr's ByteSpan - collected_spans.append(&mut self.expr.collect_spans()); + collected_spans.append(&mut self.expr.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); collected_spans } diff --git a/sway-fmt-v2/src/utils/ty.rs b/sway-fmt-v2/src/utils/ty.rs index 776c77b481d..8c0959960d5 100644 --- a/sway-fmt-v2/src/utils/ty.rs +++ b/sway-fmt-v2/src/utils/ty.rs @@ -1,6 +1,6 @@ use crate::{ fmt::{Format, FormattedCode, Formatter, FormatterError}, - utils::comments::{ByteSpan, CommentVisitor}, + utils::comments::{ByteSpan, LeafSpans}, }; use std::fmt::Write; use sway_parse::{ @@ -108,15 +108,15 @@ impl Format for TyTupleDescriptor { } } -impl CommentVisitor for Ty { - fn collect_spans(&self) -> Vec { +impl LeafSpans for Ty { + fn leaf_spans(&self) -> Vec { match self { - Ty::Path(path) => path.collect_spans(), - Ty::Tuple(tuple) => tuple.collect_spans(), - Ty::Array(array) => array.collect_spans(), + Ty::Path(path) => path.leaf_spans(), + Ty::Tuple(tuple) => tuple.leaf_spans(), + Ty::Array(array) => array.leaf_spans(), Ty::Str { str_token, length } => { let mut collected_spans = vec![ByteSpan::from(str_token.span())]; - collected_spans.append(&mut length.collect_spans()); + collected_spans.append(&mut length.leaf_spans()); collected_spans } Ty::Infer { underscore_token } => vec![ByteSpan::from(underscore_token.span())], @@ -124,8 +124,8 @@ impl CommentVisitor for Ty { } } -impl CommentVisitor for TyTupleDescriptor { - fn collect_spans(&self) -> Vec { +impl LeafSpans for TyTupleDescriptor { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); if let TyTupleDescriptor::Cons { head, @@ -133,20 +133,20 @@ impl CommentVisitor for TyTupleDescriptor { tail, } = self { - collected_spans.append(&mut head.collect_spans()); + collected_spans.append(&mut head.leaf_spans()); collected_spans.push(ByteSpan::from(comma_token.span())); - collected_spans.append(&mut tail.collect_spans()); + collected_spans.append(&mut tail.leaf_spans()); } collected_spans } } -impl CommentVisitor for TyArrayDescriptor { - fn collect_spans(&self) -> Vec { +impl LeafSpans for TyArrayDescriptor { + fn leaf_spans(&self) -> Vec { let mut collected_spans = Vec::new(); - collected_spans.append(&mut self.ty.collect_spans()); + collected_spans.append(&mut self.ty.leaf_spans()); collected_spans.push(ByteSpan::from(self.semicolon_token.span())); - collected_spans.append(&mut self.length.collect_spans()); + collected_spans.append(&mut self.length.leaf_spans()); collected_spans } } From c118303df24fb5afa2abb6acf653c4f0d3fdf565 Mon Sep 17 00:00:00 2001 From: Kaya Gokalp Date: Fri, 22 Jul 2022 14:05:27 +0300 Subject: [PATCH 44/44] fmt fix --- sway-fmt-v2/src/utils/comments.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sway-fmt-v2/src/utils/comments.rs b/sway-fmt-v2/src/utils/comments.rs index 744892a5284..c5f9f765488 100644 --- a/sway-fmt-v2/src/utils/comments.rs +++ b/sway-fmt-v2/src/utils/comments.rs @@ -403,9 +403,9 @@ fn insert_after_span( } /// Applies formatting to the comment. -/// Currently does not apply any formatting and directly returns the raw comment str +/// Currently does not apply any formatting and directly returns the raw comment str fn format_comment(comment: &Comment) -> String { - comment.span().str() + comment.span().str() } /// While searching for a comment we need the possible places a comment can be placed in a structure /// `leaf_spans` collects all field's spans so that we can check in between them.