Skip to content

Commit

Permalink
refactor insert_after_span
Browse files Browse the repository at this point in the history
  • Loading branch information
kayagokalp committed Jul 21, 2022
1 parent 9ae7aa8 commit fd62f6d
Showing 1 changed file with 17 additions and 24 deletions.
41 changes: 17 additions & 24 deletions sway-fmt-v2/src/utils/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,31 +336,25 @@ fn get_comments_between_spans(
unformatted_code: &Arc<str>,
) -> Vec<CommentWithContext> {
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
}

Expand All @@ -371,20 +365,19 @@ fn insert_after_span(
offset: usize,
formatted_code: &mut FormattedCode,
) -> Result<usize, FormatterError> {
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.
Expand Down

0 comments on commit fd62f6d

Please sign in to comment.