Skip to content

Commit

Permalink
bug: Update swayfmt::Config & remove partial implementations (FuelL…
Browse files Browse the repository at this point in the history
…abs#5193)

Closes FuelLabs#3472 

What this does:
- Removes use of `Config` options that were partially implemented
- Fixes the default implementations for `Config`. This removes the match
arms in the implementations of the `CurlyBrace` trait and just handles
the default, eg `ItemBraceStyle::SameLineWhere`
- Adds tests for items with `where` clauses, ie `ItemImpl`,
`ItemStruct`, `ItemTrait`, which weren't being tested thoroughly enough
- Updates to code quality in the `Config`, and documentation for the
default config's options
  • Loading branch information
eureka-cpu authored Nov 1, 2023
1 parent 8bee783 commit c32934b
Show file tree
Hide file tree
Showing 25 changed files with 205 additions and 202 deletions.
2 changes: 1 addition & 1 deletion examples/traits/src/main.sw
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ fn main() {
// ANCHOR: trait_constraint
fn into_rectangle<T>(t: T) -> Rectangle
where
Rectangle: Convert<T>
Rectangle: Convert<T>,
{
Rectangle::from(t)
}
Expand Down
51 changes: 51 additions & 0 deletions swayfmt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,54 @@ A tool for formatting Sway code according to style guidelines.

- To use `swayfmt`, install the [forc-fmt](../forc-plugins/forc-fmt/) plugin using [fuelup](https://github.com/FuelLabs/fuelup).
- To contribute to `swayfmt`, see [CONTRIBUTING](./CONTRIBUTING.md).

## Configuration with `swayfmt.toml`

Swayfmt _is_ meant to be configurable, however currently it only supports the default configuration options.

> **Note:** Not all `Config` options are guaranteed to work
> and most are not implemented. Configuration options are
> subject to change between versions without notice.
> If you would like to see a feature implemented, or
> implement a feature please refer to the [CONTRIBUTING guide](./CONTRIBUTING.md).
The default `swayfmt.toml`:

```toml
max_width = 100
hard_tabs = false
tab_spaces = 4
newline_style = Auto
indent_style = Block
newline_threshold = 1
group_imports = Preserve
imports_granularity = Preserve
imports_indent = Block
reorder_imports = true
reorder_modules = true
reorder_impl_items = false
item_brace_style = SameLineWhere
blank_lines_upper_bound = 1
blank_lines_lower_bound = 0
empty_item_single_line = true
format_strings = false
hex_literal_case = Preserve
expr_brace_style = AlwaysSameLine
trailing_semicolon = true
space_before_colon = false
space_after_colon = false
type_combinator_layout = Wide
spaces_around_ranges = false
match_block_trailing_comma = false
match_arm_leading_pipe = Never
force_multiline_blocks = false
fn_args_layout = Tall
fn_single_line = false
heuristics_pref = Scaled
use_small_heuristics = true
field_alignment = Off
small_structures_single_line = true
wrap_comments = false
comment_width = 80
normalize_comments = false
```
25 changes: 14 additions & 11 deletions swayfmt/src/config/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};

#[derive(Debug, Copy, Clone)]
pub struct Expressions {
/////PUNCTUATION/////
// PUNCTUATION
/// Brace style for control flow constructs.
pub expr_brace_style: ExprBraceStyle,
/// Add trailing semicolon after break, continue and return.
Expand All @@ -14,19 +14,19 @@ pub struct Expressions {
/// Leave a space after the colon.
pub space_after_colon: bool,

/////OPERATORS/////
// OPERATORS
/// Determines if `+` or `=` are wrapped in spaces in the punctuation of types.
pub type_combinator_layout: TypeCombinatorLayout,
/// Put spaces around the `..` and `..=` range operators.
pub spaces_around_ranges: bool,

/////MATCH EXPR/////
// MATCH EXPR
/// Put a trailing comma after a block based match arm (non-block arms are not affected).
pub match_block_trailing_comma: bool,
/// Determines whether leading pipes are emitted on match arms.
pub match_arm_leading_pipe: MatchArmLeadingPipe,

/////FUNCTIONS/////
// FUNCTIONS
/// Force multiline closure bodies and match arms to be wrapped in a block.
pub force_multiline_blocks: bool,
/// Control the layout of arguments in a function.
Expand All @@ -38,16 +38,16 @@ pub struct Expressions {
impl Default for Expressions {
fn default() -> Self {
Self {
expr_brace_style: ExprBraceStyle::AlwaysSameLine,
expr_brace_style: Default::default(),
trailing_semicolon: true,
space_before_colon: false,
space_after_colon: false,
type_combinator_layout: TypeCombinatorLayout::Wide,
type_combinator_layout: Default::default(),
spaces_around_ranges: false,
match_block_trailing_comma: false,
match_arm_leading_pipe: MatchArmLeadingPipe::Never,
match_arm_leading_pipe: Default::default(),
force_multiline_blocks: false,
fn_args_layout: ItemsLayout::Tall,
fn_args_layout: Default::default(),
fn_single_line: false,
}
}
Expand Down Expand Up @@ -90,9 +90,10 @@ impl Expressions {

/// Where to put the opening brace of conditional expressions (`if`, `match`, etc.).
#[allow(clippy::enum_variant_names)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum ExprBraceStyle {
/// K&R style, Rust community default
#[default]
AlwaysSameLine,
/// Stroustrup style
ClosingNextLine,
Expand All @@ -101,22 +102,24 @@ pub enum ExprBraceStyle {
}

/// Spacing around type combinators.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum TypeCombinatorLayout {
/// No spaces around "=" and "+"
Compressed,
/// Spaces around " = " and " + "
#[default]
Wide,
}

/////MATCH EXPR/////

/// Controls how swayfmt should handle leading pipes on match arms.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum MatchArmLeadingPipe {
/// Place leading pipes on all match arms
Always,
/// Never emit leading pipes on match arms
#[default]
Never,
/// Preserve any existing leading pipes
Preserve,
Expand Down
5 changes: 3 additions & 2 deletions swayfmt/src/config/heuristics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub struct Heuristics {
impl Default for Heuristics {
fn default() -> Self {
Self {
heuristics_pref: HeuristicsPreferences::Scaled,
heuristics_pref: Default::default(),
use_small_heuristics: true,
}
}
Expand All @@ -42,13 +42,14 @@ impl Heuristics {
/// Heuristic settings that can be used to simplify
/// the configuration of the granular width configurations
/// like `struct_lit_width`, `array_width`, etc.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum HeuristicsPreferences {
/// Turn off any heuristics
Off,
/// Turn on max heuristics
Max,
/// Use scaled values based on the value of `max_width`
#[default]
Scaled,
}

Expand Down
18 changes: 5 additions & 13 deletions swayfmt/src/config/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use crate::config::{user_opts::ImportsOptions, whitespace::IndentStyle};
use serde::{Deserialize, Serialize};

#[derive(Debug, Copy, Clone)]
#[derive(Debug, Copy, Clone, Default)]
pub struct Imports {
/// Controls the strategy for how imports are grouped together.
pub group_imports: GroupImports,
Expand All @@ -12,16 +12,6 @@ pub struct Imports {
pub imports_indent: IndentStyle,
}

impl Default for Imports {
fn default() -> Self {
Self {
group_imports: GroupImports::Preserve,
imports_granularity: ImportGranularity::Preserve,
imports_indent: IndentStyle::Block,
}
}
}

impl Imports {
pub fn from_opts(opts: &ImportsOptions) -> Self {
let default = Self::default();
Expand All @@ -36,9 +26,10 @@ impl Imports {
}

/// Configuration for import groups, i.e. sets of imports separated by newlines.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum GroupImports {
/// Keep groups as they are.
#[default]
Preserve,
/// Discard existing groups, and create new groups for
/// 1. `std` / `core` / `alloc` imports
Expand All @@ -50,9 +41,10 @@ pub enum GroupImports {
}

/// How to merge imports.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum ImportGranularity {
/// Do not merge imports.
#[default]
Preserve,
/// Use one `use` statement per crate.
Crate,
Expand Down
13 changes: 10 additions & 3 deletions swayfmt/src/config/items.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Configuration options related to item formatting.
use crate::{
config::user_opts::ItemsOptions,
constants::{DEFAULT_BLANK_LINES_LOWER_BOUND, DEFAULT_BLANK_LINES_UPPER_BOUND},
Expand All @@ -20,7 +21,7 @@ pub struct Items {
impl Default for Items {
fn default() -> Self {
Self {
item_brace_style: ItemBraceStyle::SameLineWhere,
item_brace_style: Default::default(),
blank_lines_upper_bound: DEFAULT_BLANK_LINES_UPPER_BOUND,
blank_lines_lower_bound: DEFAULT_BLANK_LINES_LOWER_BOUND,
empty_item_single_line: true,
Expand All @@ -47,24 +48,30 @@ impl Items {
}

/// Preference of how list-like items are displayed.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
///
/// Defaults to `Tall`.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum ItemsLayout {
/// Fit as much on one line as possible.
Compressed,
/// Items are placed horizontally if sufficient space, vertically otherwise.
#[default]
Tall,
/// Place every item on a separate line.
Vertical,
}

/// Where to put the opening brace of items (`fn`, `impl`, etc.).
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
///
/// Defaults to `SameLineWhere`.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum ItemBraceStyle {
/// Put the opening brace on the next line.
AlwaysNextLine,
/// Put the opening brace on the same line, if possible.
PreferSameLine,
/// Prefer the same line except where there is a where-clause, in which
/// case force the brace to be put on the next line.
#[default]
SameLineWhere,
}
14 changes: 3 additions & 11 deletions swayfmt/src/config/literals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,14 @@
use crate::config::user_opts::LiteralsOptions;
use serde::{Deserialize, Serialize};

#[derive(Debug, Copy, Clone)]
#[derive(Debug, Copy, Clone, Default)]
pub struct Literals {
/// Format string literals where necessary.
pub format_strings: bool,
/// Format hexadecimal integer literals.
pub hex_literal_case: HexLiteralCase,
}

impl Default for Literals {
fn default() -> Self {
Self {
format_strings: false,
hex_literal_case: HexLiteralCase::Preserve,
}
}
}

impl Literals {
pub fn from_opts(opts: &LiteralsOptions) -> Self {
let default = Self::default();
Expand All @@ -30,9 +21,10 @@ impl Literals {
}

/// Controls how swayfmt should handle case in hexadecimal literals.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum HexLiteralCase {
/// Leave the literal as-is
#[default]
Preserve,
/// Ensure all literals use uppercase lettering
Upper,
Expand Down
5 changes: 3 additions & 2 deletions swayfmt/src/config/user_def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct Structures {
impl Default for Structures {
fn default() -> Self {
Self {
field_alignment: FieldAlignment::Off,
field_alignment: Default::default(),
small_structures_single_line: true,
}
}
Expand All @@ -33,8 +33,9 @@ impl Structures {
}

/// Align fields if they fit within a provided threshold.
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Default)]
pub enum FieldAlignment {
AlignFields(usize),
#[default]
Off,
}
10 changes: 6 additions & 4 deletions swayfmt/src/config/whitespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ impl Default for Whitespace {
max_width: DEFAULT_MAX_LINE_WIDTH,
hard_tabs: false,
tab_spaces: DEFAULT_TAB_SPACES,
newline_style: NewlineStyle::Auto,
indent_style: IndentStyle::Block,
newline_style: Default::default(),
indent_style: Default::default(),
newline_threshold: DEFAULT_NEWLINE_THRESHOLD,
}
}
Expand All @@ -53,19 +53,21 @@ impl Whitespace {
}

/// Handling of line indentation for expressions or items.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum IndentStyle {
/// First line on the same line as the opening brace, all lines aligned with
/// the first line.
Visual,
/// First line is on a new line and all lines align with **block** indent.
#[default]
Block,
}

/// Handling of which OS new-line style should be applied.
#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Default)]
pub enum NewlineStyle {
/// Auto-detect based on the raw source input.
#[default]
Auto,
/// Force CRLF (`\r\n`).
Windows,
Expand Down
14 changes: 2 additions & 12 deletions swayfmt/src/items/item_abi/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::{
comments::{rewrite_with_comments, write_comments},
config::items::ItemBraceStyle,
formatter::*,
utils::{
map::byte_span::{ByteSpan, LeafSpans},
Expand Down Expand Up @@ -77,19 +76,10 @@ impl CurlyBrace for ItemAbi {
line: &mut String,
formatter: &mut Formatter,
) -> Result<(), FormatterError> {
let brace_style = formatter.config.items.item_brace_style;
formatter.indent();
let open_brace = Delimiter::Brace.as_open_char();
match brace_style {
ItemBraceStyle::AlwaysNextLine => {
// Add opening brace to the next line.
write!(line, "\n{open_brace}\n")?;
}
_ => {
// Add opening brace to the same line
writeln!(line, " {open_brace}")?;
}
}
// Add opening brace to the same line
writeln!(line, " {open_brace}")?;

Ok(())
}
Expand Down
Loading

0 comments on commit c32934b

Please sign in to comment.