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

feat: add basic comment context formatting #2697

Merged
merged 3 commits into from
Sep 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
28 changes: 25 additions & 3 deletions sway-fmt-v2/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,8 +627,6 @@ pub struct Foo { // Here is a comment
// 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



// Trying some ASCII art
baz: u64,
bazzz: u64,// ________ ___ ___ _______ ___ ___ ________ ________ ________
Expand Down Expand Up @@ -988,12 +986,36 @@ fn main() {}
let sway_code_to_format = r#"script;

// use statements
use std::*;"#;
use std::*;

fn main() {
// Array of integers with type ascription
let array_of_integers: [u8;
5] = [1, 2, 3, 4, 5];


// Array of strings
let array_of_strings = [ "Bob", "Jan", "Ron"];
}
"#;

let correct_sway_code = r#"script;

// use statements
use std::*;

fn main() {
// Array of integers with type ascription
let array_of_integers: [u8; 5] = [1, 2, 3, 4, 5];


// Array of strings
let array_of_strings = [
"Bob",
"Jan",
"Ron",
];
}
"#;

let mut formatter = Formatter::default();
Expand Down
18 changes: 17 additions & 1 deletion sway-fmt-v2/src/utils/map/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,22 @@ fn get_comments_between_spans(
comments_with_context
}

fn format_context(context: &str, threshold: usize) -> String {
let mut remaining_newlines = threshold;
let mut formatted_context = String::new();
for char in context.chars() {
if char == '\n' {
if remaining_newlines > 0 {
formatted_context.push('\n');
remaining_newlines -= 1;
}
} else {
formatted_context.push(char);
}
}
formatted_context
}

/// 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: &ByteSpan,
Expand All @@ -195,7 +211,7 @@ fn insert_after_span(
write!(
comment_str,
"{}{}",
comment_context,
format_context(comment_context, 2),
&format_comment(comment_value)
)?;
}
Expand Down