Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix fmt whitespaces between comments and doc comments #5178

Merged
merged 3 commits into from
Oct 9, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 38 additions & 16 deletions swayfmt/src/utils/map/newline.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::Result;
use ropey::Rope;
use std::{collections::BTreeMap, fmt::Write, path::PathBuf, sync::Arc};
use std::{collections::BTreeMap, path::PathBuf, sync::Arc};
use sway_ast::Module;
use sway_types::SourceEngine;

Expand Down Expand Up @@ -102,6 +102,20 @@ pub fn handle_newlines(
)?;
Ok(())
}

#[inline]
/// Tiny function that safely calculates the offset where the offset is a i64
/// (it may be negative). If the offset is a negative number and the result of
/// doing the offset would have panic (because usize cannot be negative) the
/// unmodified base would be returned
fn calculate_offset(base: usize, offset: i64) -> usize {
offset
.checked_add(base as i64)
.unwrap_or(base as i64)
.try_into()
.unwrap_or(base)
}

/// Adds the newlines from newline_map to correct places in the formatted code. This requires us
/// both the unformatted and formatted code's modules as they will have different spans for their
/// visitable positions. While traversing the unformatted module, `add_newlines` searches for newline sequences. If there is a newline sequence found
Expand Down Expand Up @@ -172,9 +186,8 @@ fn add_newlines(
},
&newline_map,
) {
let at = previous_formatted_newline_span.end + offset;
offset += insert_after_span(
at,
calculate_offset(previous_formatted_newline_span.end, offset),
newline_sequence,
formatted_code,
newline_threshold,
Expand All @@ -195,9 +208,8 @@ fn add_newlines(
},
&newline_map,
) {
let at = previous_formatted_newline_span.end + offset;
offset += insert_after_span(
at,
calculate_offset(previous_formatted_newline_span.end, offset),
newline_sequence,
formatted_code,
newline_threshold,
Expand Down Expand Up @@ -235,9 +247,10 @@ fn add_newlines(
&newline_map,
) {
offset += insert_after_span(
previous_formatted_newline_span.end
+ end_of_last_comment
+ offset,
calculate_offset(
previous_formatted_newline_span.end + end_of_last_comment,
offset,
),
newline_sequence,
formatted_code,
newline_threshold,
Expand Down Expand Up @@ -270,22 +283,31 @@ fn insert_after_span(
newline_sequence: NewlineSequence,
formatted_code: &mut FormattedCode,
threshold: usize,
) -> Result<usize, FormatterError> {
let mut sequence_string = String::new();
write!(
sequence_string,
"{}",
format_newline_sequence(&newline_sequence, threshold)
)?;
) -> Result<i64, FormatterError> {
let sequence_string = format_newline_sequence(&newline_sequence, threshold);
let mut len = sequence_string.len() as i64;
let mut src_rope = Rope::from_str(formatted_code);

// Remove the previous sequence_length, that will be replaced in the next statement
let mut remove_until = at;
for i in at..at + newline_sequence.sequence_length {
if src_rope.get_char(i) != Some('\n') {
eureka-cpu marked this conversation as resolved.
Show resolved Hide resolved
break;
}
remove_until = i;
}
if remove_until > at {
let _ = src_rope.try_remove(at..remove_until);
eureka-cpu marked this conversation as resolved.
Show resolved Hide resolved
len -= (remove_until - at) as i64;
}

src_rope
.try_insert(at, &sequence_string)
.map_err(|_| FormatterError::NewlineSequenceError)?;

formatted_code.clear();
formatted_code.push_str(&src_rope.to_string());
Ok(sequence_string.len())
Ok(len)
}

/// Returns the first newline sequence contained in a span.
Expand Down
100 changes: 100 additions & 0 deletions swayfmt/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1602,3 +1602,103 @@ impl MyContract for Contract {
"#,
);
}

#[test]
fn empty_fn() {
check(
r#"
library;
fn test() {
}
"#,
r#"library;
fn test() {}
"#,
);
}

#[test]
fn empty_if() {
check(
r#"
library;
fn test() {
if ( something ( ) ) {
}
}
"#,
r#"library;
fn test() {
if (something()) {}
}
"#,
);
}

#[test]
fn bug_whitespace_added_after_comment() {
check(
r#"
library;
// GTF Opcode const selectors
//
pub const GTF_OUTPUT_TYPE = 0x201;
pub const GTF_OUTPUT_COIN_TO = 0x202;
pub const GTF_OUTPUT_COIN_AMOUNT = 0x203;
pub const GTF_OUTPUT_COIN_ASSET_ID = 0x204;
// pub const GTF_OUTPUT_CONTRACT_INPUT_INDEX = 0x205;
// pub const GTF_OUTPUT_CONTRACT_BALANCE_ROOT = 0x206;
// pub const GTF_OUTPUT_CONTRACT_STATE_ROOT = 0x207;
// pub const GTF_OUTPUT_CONTRACT_CREATED_CONTRACT_ID = 0x208;
// pub const GTF_OUTPUT_CONTRACT_CREATED_STATE_ROOT = 0x209;



/// The output type for a transaction.
pub enum Output {
/// A coin output.
Coin: (), /// A contract output.
Contract: (),
/// Remaining "change" from spending of a coin.
Change: (),
/// A variable output.
Variable: (),
}
/// The output type for a transaction.
pub enum Input {
/// A variable output.
Variable: (),
}
"#,
r#"library;
// GTF Opcode const selectors
//
pub const GTF_OUTPUT_TYPE = 0x201;
pub const GTF_OUTPUT_COIN_TO = 0x202;
pub const GTF_OUTPUT_COIN_AMOUNT = 0x203;
pub const GTF_OUTPUT_COIN_ASSET_ID = 0x204;
// pub const GTF_OUTPUT_CONTRACT_INPUT_INDEX = 0x205;
// pub const GTF_OUTPUT_CONTRACT_BALANCE_ROOT = 0x206;
// pub const GTF_OUTPUT_CONTRACT_STATE_ROOT = 0x207;
// pub const GTF_OUTPUT_CONTRACT_CREATED_CONTRACT_ID = 0x208;
// pub const GTF_OUTPUT_CONTRACT_CREATED_STATE_ROOT = 0x209;

/// The output type for a transaction.
pub enum Output {
/// A coin output.
Coin: (),
/// A contract output.
Contract: (),
/// Remaining "change" from spending of a coin.
Change: (),
/// A variable output.
Variable: (),
}
/// The output type for a transaction.
pub enum Input {
/// A variable output.
Variable: (),
}
"#,
);
}
Loading