diff --git a/swayfmt/src/items/item_fn/mod.rs b/swayfmt/src/items/item_fn/mod.rs index 4a6760175f5..615b207111c 100644 --- a/swayfmt/src/items/item_fn/mod.rs +++ b/swayfmt/src/items/item_fn/mod.rs @@ -1,4 +1,5 @@ use crate::{ + comments::{has_comments, maybe_write_comments_from_map}, config::items::ItemBraceStyle, formatter::{ shape::{ExprKind, LineStyle}, @@ -9,7 +10,7 @@ use crate::{ {CurlyBrace, Parenthesis}, }, }; -use std::fmt::Write; +use std::{fmt::Write, ops::Range}; use sway_ast::{ keywords::{MutToken, RefToken, SelfToken, Token}, token::Delimiter, @@ -35,10 +36,18 @@ impl Format for ItemFn { let body = self.body.get(); if !body.statements.is_empty() || body.final_expr_opt.is_some() { Self::open_curly_brace(formatted_code, formatter)?; + formatter.shape.block_indent(&formatter.config); body.format(formatted_code, formatter)?; Self::close_curly_brace(formatted_code, formatter)?; } else { - write!(formatted_code, " {{}}")?; + Self::open_curly_brace(formatted_code, formatter)?; + let range: Range = self.span().into(); + let comments = formatter.comment_map.comments_between(&range); + if has_comments(comments) { + formatter.shape.block_indent(&formatter.config); + maybe_write_comments_from_map(formatted_code, range, formatter)?; + } + Self::close_curly_brace(formatted_code, formatter)?; } Ok(()) @@ -60,23 +69,19 @@ impl CurlyBrace for ItemFn { ItemBraceStyle::AlwaysNextLine => { // Add openning brace to the next line. writeln!(line, "\n{open_brace}")?; - formatter.shape.block_indent(&formatter.config); } ItemBraceStyle::SameLineWhere => match formatter.shape.code_line.has_where_clause { true => { write!(line, "{open_brace}")?; formatter.shape.code_line.update_where_clause(false); - formatter.shape.block_indent(&formatter.config); } false => { write!(line, " {open_brace}")?; - formatter.shape.block_indent(&formatter.config); } }, _ => { // TODO: implement PreferSameLine writeln!(line, " {open_brace}")?; - formatter.shape.block_indent(&formatter.config); } } diff --git a/swayfmt/tests/mod.rs b/swayfmt/tests/mod.rs index e9086399209..2f433e0266a 100644 --- a/swayfmt/tests/mod.rs +++ b/swayfmt/tests/mod.rs @@ -570,6 +570,41 @@ trait AlignMyComments { ); } +#[test] +fn comments_empty_fns() { + check( + r#"contract; + +fn single_comment_same_line() { /* a comment */ } + +fn single_comment() -> bool { + // TODO: This is a TODO +} + +fn multiline_comments() { + // Multi + // line +// comment +}"#, + r#"contract; + +fn single_comment_same_line() { + /* a comment */ +} + +fn single_comment() -> bool { + // TODO: This is a TODO +} + +fn multiline_comments() { + // Multi + // line + // comment +} +"#, + ); +} + #[test] fn enum_comments() { check(