Skip to content

Commit

Permalink
Add brace_spacing option
Browse files Browse the repository at this point in the history
Braces, used for table construction, are typically used with spaces
inside them:

```lua
t = { "content-0" }
```

There can be another style, however, which consists in sticking the
braces to the content:

```lua
t = {"content-0"}
```

This work adds a configuration parameter `brace_spacing: BraceSpacing`
(`Always`, `Never`) to control the spacing inside table constructors and
enable the use of the second style. This is similar to [Prettier's
bracket spacing
option](https://prettier.io/docs/en/options.html#bracket-spacing).

Which style is better is debatable, of course. In my quick research, I
listed what the formatters I know do:

- rustfmt (Rust): space
- OCamlFormat (OCaml): space, configurable
- Prettier (JavaScript, TypeScript): space, configurable
- Black (Python): no space
- Clang-Format (C, C++): no space, configurable
  • Loading branch information
bbc2 committed Dec 4, 2022
1 parent ffbef7e commit 256e5e0
Show file tree
Hide file tree
Showing 5 changed files with 100 additions and 7 deletions.
12 changes: 11 additions & 1 deletion src/cli/opt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use clap::{ArgEnum, StructOpt};
use std::path::PathBuf;
use stylua_lib::{CallParenType, CollapseSimpleStatement, IndentType, LineEndings, QuoteStyle};
use stylua_lib::{
BraceSpacing, CallParenType, CollapseSimpleStatement, IndentType, LineEndings, QuoteStyle,
};

lazy_static::lazy_static! {
static ref NUM_CPUS: String = num_cpus::get().to_string();
Expand Down Expand Up @@ -169,6 +171,9 @@ pub struct FormatOpts {
/// Specify whether to collapse simple statements.
#[structopt(long, arg_enum, ignore_case = true)]
pub collapse_simple_statement: Option<ArgCollapseSimpleStatement>,
/// Specify whether to add spacing inside the curly brackets around the content of a table literal.
#[structopt(long, arg_enum, ignore_case = true)]
pub brace_spacing: Option<ArgBraceSpacing>,
}

// Convert [`stylua_lib::Config`] enums into clap-friendly enums
Expand Down Expand Up @@ -235,6 +240,11 @@ convert_enum!(CollapseSimpleStatement, ArgCollapseSimpleStatement, {
Always,
});

convert_enum!(BraceSpacing, ArgBraceSpacing, {
Never,
Always,
});

#[cfg(test)]
mod tests {
use super::Opt;
Expand Down
8 changes: 6 additions & 2 deletions src/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
shape::Shape, CallParenType, CollapseSimpleStatement, Config, IndentType, LineEndings,
Range as FormatRange,
shape::Shape, BraceSpacing, CallParenType, CollapseSimpleStatement, Config, IndentType,
LineEndings, Range as FormatRange,
};
use full_moon::{
node::Node,
Expand Down Expand Up @@ -152,6 +152,10 @@ impl Context {
CollapseSimpleStatement::ConditionalOnly | CollapseSimpleStatement::Always
)
}

pub fn should_add_brace_spacing(&self) -> bool {
matches!(self.config().brace_spacing(), BraceSpacing::Always)
}
}

/// Returns the relevant line ending string from the [`LineEndings`] enum
Expand Down
15 changes: 11 additions & 4 deletions src/formatters/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,17 @@ pub fn create_table_braces(
ContainedSpan::new(start_brace_token, end_brace_token)
}

TableType::SingleLine => ContainedSpan::new(
fmt_symbol!(ctx, start_brace, "{ ", shape),
fmt_symbol!(ctx, end_brace, " }", shape),
),
TableType::SingleLine => {
let (start_, end_) = if ctx.should_add_brace_spacing() {
("{ ", " }")
} else {
("{", "}")
};
ContainedSpan::new(
fmt_symbol!(ctx, start_brace, start_, shape),
fmt_symbol!(ctx, end_brace, end_, shape),
)
}

TableType::Empty => {
let start_brace = fmt_symbol!(ctx, start_brace, "{", shape);
Expand Down
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,24 @@ impl Default for CollapseSimpleStatement {
}
}

/// Whether we add spacing inside the curly brackets around the content of a table literal.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
#[cfg_attr(all(target_arch = "wasm32", feature = "wasm-bindgen"), wasm_bindgen)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "fromstr", derive(strum::EnumString))]
pub enum BraceSpacing {
/// Never add spaces around content in a table literal
Never,
/// Always add spaces around content in a table literal
Always,
}

impl Default for BraceSpacing {
fn default() -> Self {
BraceSpacing::Always
}
}

/// An optional formatting range.
/// If provided, only content within these boundaries (inclusive) will be formatted.
/// Both boundaries are optional, and are given as byte offsets from the beginning of the file.
Expand Down Expand Up @@ -168,6 +186,8 @@ pub struct Config {
/// if set to [`CollapseSimpleStatement::None`] structures are never collapsed.
/// if set to [`CollapseSimpleStatement::FunctionOnly`] then simple functions (i.e., functions with a single laststmt) can be collapsed
collapse_simple_statement: CollapseSimpleStatement,
/// Whether we add spacing inside the curly brackets around the content of a table literal.
brace_spacing: BraceSpacing,
}

#[cfg_attr(all(target_arch = "wasm32", feature = "wasm-bindgen"), wasm_bindgen)]
Expand Down Expand Up @@ -211,6 +231,10 @@ impl Config {
self.collapse_simple_statement
}

pub fn brace_spacing(&self) -> BraceSpacing {
self.brace_spacing
}

/// Returns a new config with the given column width
pub fn with_column_width(self, column_width: usize) -> Self {
Self {
Expand Down Expand Up @@ -275,6 +299,14 @@ impl Config {
..self
}
}

/// Returns a new config with the given bracket space configuration
pub fn with_brace_spacing(self, brace_spacing: BraceSpacing) -> Self {
Self {
brace_spacing,
..self
}
}
}

impl Default for Config {
Expand All @@ -288,6 +320,7 @@ impl Default for Config {
no_call_parentheses: false,
call_parentheses: CallParenType::default(),
collapse_simple_statement: CollapseSimpleStatement::default(),
brace_spacing: BraceSpacing::default(),
}
}
}
Expand Down
39 changes: 39 additions & 0 deletions tests/test_table_spaces.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use stylua_lib::{format_code, BraceSpacing, Config, OutputVerification};

fn format(brace_spacing: BraceSpacing, input: &str) -> String {
format_code(
input,
Config::default().with_brace_spacing(brace_spacing),
None,
OutputVerification::None,
)
.unwrap()
}

#[test]
fn test_table_oneline_with_internal_spaces() {
insta::assert_snapshot!(
format(BraceSpacing::Always,
r###"
local foo = { "content" }
"###
),
@r###"
local foo = { "content" }
"###
);
}

#[test]
fn test_table_oneline_without_internal_spaces() {
insta::assert_snapshot!(
format(BraceSpacing::Never,
r###"
local foo = { "content" }
"###
),
@r###"
local foo = {"content"}
"###
);
}

0 comments on commit 256e5e0

Please sign in to comment.