From fd62f6d4a7f7c3ace8a9cec7d6747d09d2905eb7 Mon Sep 17 00:00:00 2001 From: kayagokalp Date: Thu, 21 Jul 2022 15:37:11 +0300 Subject: [PATCH] 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.