Skip to content
Open
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
33 changes: 28 additions & 5 deletions src/formatters/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::{
format_anonymous_function, format_call, format_function_call, FunctionCallNextNode,
},
general::{format_contained_span, format_end_token, format_token_reference, EndTokenType},
table::format_table_constructor,
table::{format_expanded_table_constructor, format_table_constructor},
trivia::{
strip_leading_trivia, strip_trivia, FormatTriviaType, UpdateLeadingTrivia,
UpdateTrailingTrivia, UpdateTrivia,
Expand Down Expand Up @@ -62,6 +62,8 @@ macro_rules! fmt_op {
enum ExpressionContext {
/// Standard expression, with no special context
Standard,
/// The enclosing call has already decided that this table argument must expand.
ExpandedTableArgument,
/// The expression originates from a [`Prefix`] node. The special context here is that the expression will
/// always be wrapped in parentheses.
Prefix,
Expand Down Expand Up @@ -191,6 +193,19 @@ pub fn format_expression(ctx: &Context, expression: &Expression, shape: Shape) -
format_expression_internal(ctx, expression, ExpressionContext::Standard, shape)
}

pub(super) fn format_expression_with_expanded_table(
ctx: &Context,
expression: &Expression,
shape: Shape,
) -> Expression {
format_expression_internal(
ctx,
expression,
ExpressionContext::ExpandedTableArgument,
shape,
)
}

/// Internal expression formatter, with access to expression context
fn format_expression_internal(
ctx: &Context,
Expand Down Expand Up @@ -222,9 +237,13 @@ fn format_expression_internal(
Expression::Symbol(token_reference) => {
Expression::Symbol(format_token_reference(ctx, token_reference, shape))
}
Expression::TableConstructor(table_constructor) => Expression::TableConstructor(Box::new(
format_table_constructor(ctx, table_constructor, shape),
)),
Expression::TableConstructor(table_constructor) => {
let format_table = match context {
ExpressionContext::ExpandedTableArgument => format_expanded_table_constructor,
_ => format_table_constructor,
};
Expression::TableConstructor(Box::new(format_table(ctx, table_constructor, shape)))
}
Expression::Var(var) => Expression::Var(format_var(ctx, var, shape)),

#[cfg(feature = "luau")]
Expand Down Expand Up @@ -261,7 +280,11 @@ fn format_expression_internal(
let (leading_comments, trailing_comments) =
contained_span_comments(ctx, contained, shape);

format_expression(ctx, expression, shape)
let context = match context {
ExpressionContext::ExpandedTableArgument => context,
_ => ExpressionContext::Standard,
};
format_expression_internal(ctx, expression, context, shape)
.update_leading_trivia(FormatTriviaType::Append(leading_comments))
.update_trailing_trivia(FormatTriviaType::Append(trailing_comments))
} else {
Expand Down
69 changes: 54 additions & 15 deletions src/formatters/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ use crate::{
fmt_symbol,
formatters::{
block::{format_block, format_last_stmt_no_trivia},
expression::{format_expression, format_prefix, format_suffix, hang_expression},
expression::{
format_expression, format_expression_with_expanded_table, format_prefix, format_suffix,
hang_expression,
},
general::{
format_contained_punctuated_multiline, format_contained_span, format_end_token,
format_punctuated, format_token_reference, EndTokenType,
Expand Down Expand Up @@ -219,6 +222,7 @@ fn function_args_multiline_heuristic(
ctx: &Context,
arguments: &Punctuated<Expression>,
shape: Shape,
expanded_tables: &mut Vec<usize>,
) -> bool {
const PAREN_LEN: usize = "(".len();
const COMMA_SPACE_LEN: usize = ", ".len();
Expand Down Expand Up @@ -259,8 +263,9 @@ fn function_args_multiline_heuristic(

// Use state values to determine the type of arguments we have seen so far
let mut current_state = ArgumentState::new();
let expanded_argument_shape = shape.reset().increment_additional_indent();

for pair in first_iter_formatted_arguments {
for (index, pair) in first_iter_formatted_arguments.enumerate() {
let argument = pair.value();
match argument {
Expression::Function(anonymous_function) => {
Expand Down Expand Up @@ -291,19 +296,35 @@ fn function_args_multiline_heuristic(
}
Expression::TableConstructor(table) => {
// Check to see whether it has been expanded (there is a newline after the start brace)
let is_expanded = trivia_util::trivia_contains_newline(
let already_expanded = trivia_util::trivia_contains_newline(
table.braces().tokens().0.trailing_trivia(),
);

if is_expanded {
let table_width = if already_expanded {
0
} else {
argument.to_string().len()
};
// Predict expansion before choosing where to place the opening brace. Compact
// input may appear to fit until formatting adds spaces between the fields.
let needs_expansion = !already_expanded
&& arguments.len() > 1
&& !table.fields().is_empty()
&& (expanded_argument_shape + table_width).over_budget();

if already_expanded || needs_expansion {
// If we have a mixture of multiline args, and other arguments
// Then the function args should be expanded
if current_state.should_hang() {
return true;
}

// Include the first brace to check if we are over the column width already
singleline_shape = singleline_shape.take_first_line(table);
singleline_shape = if needs_expansion {
expanded_tables.push(index);
singleline_shape + BRACKET_LEN
} else {
singleline_shape.take_first_line(table)
};
if singleline_shape.over_budget() {
return true;
}
Expand All @@ -314,7 +335,7 @@ fn function_args_multiline_heuristic(
singleline_shape = singleline_shape.reset() + BRACKET_LEN;
} else {
// Update the shape with the size of the collapsed table constructor
singleline_shape = singleline_shape + argument.to_string().len();
singleline_shape = singleline_shape + table_width;
}
}
// TODO: Parentheses/UnOp, do we need to do more checking?
Expand Down Expand Up @@ -375,15 +396,18 @@ fn function_args_multiline_heuristic(
fn format_argument_multiline(ctx: &Context, argument: &Expression, shape: Shape) -> Expression {
// First format the argument assuming infinite width
let infinite_width_argument = format_expression(ctx, argument, shape.with_infinite_width());
let over_budget = shape
.add_width(strip_trivia(&infinite_width_argument).to_string().len())
.over_budget();

// If the argument fits, great! Otherwise, see if we can hang the expression
// If we can, use that instead (as it provides a nicer output). If not, format normally without infinite width
// Also: if the argument contains comments, it should be multilined
if argument.has_inline_comments()
|| shape
.add_width(strip_trivia(&infinite_width_argument).to_string().len())
.over_budget()
if over_budget
&& matches!(&infinite_width_argument, Expression::TableConstructor(table) if !table.fields().is_empty())
{
format_expression_with_expanded_table(ctx, argument, shape)
} else if argument.has_inline_comments() || over_budget {
if trivia_util::can_hang_expression(argument) {
hang_expression(ctx, argument, shape, Some(1))
} else {
Expand Down Expand Up @@ -461,8 +485,9 @@ pub fn format_function_args(
// If there is a comment present anywhere in between the start parentheses and end parentheses, we should keep it multiline
let force_mutliline = function_args_contains_comments(parentheses, arguments);

let is_multiline =
force_mutliline || function_args_multiline_heuristic(ctx, arguments, shape);
let mut expanded_tables = Vec::new();
let is_multiline = force_mutliline
|| function_args_multiline_heuristic(ctx, arguments, shape, &mut expanded_tables);

// Handle special case: we want to go multiline, but we have a single argument which is a table constructor
// In this case, we want to hug the table braces with the parentheses.
Expand Down Expand Up @@ -504,8 +529,22 @@ pub fn format_function_args(
let end_parens = format_token_reference(ctx, end_parens, shape);
let parentheses = ContainedSpan::new(start_parens, end_parens);

let mut arguments =
format_punctuated(ctx, arguments, shape + shape_increment, format_expression);
let argument_shape = shape + shape_increment;
let mut arguments = if expanded_tables.is_empty() {
format_punctuated(ctx, arguments, argument_shape, format_expression)
} else {
let mut expanded_tables = expanded_tables.into_iter().peekable();
let mut index = 0;
format_punctuated(ctx, arguments, argument_shape, |ctx, argument, shape| {
let expand_table = expanded_tables.next_if_eq(&index).is_some();
index += 1;
if expand_table {
format_expression_with_expanded_table(ctx, argument, shape)
} else {
format_expression(ctx, argument, shape)
}
})
};

// HACK: if there was more than one newline before each argument, then it will be incorrectly preserved
// leading to weird formatting (https://github.com/JohnnyMorganz/StyLua/issues/290#issuecomment-964428535)
Expand Down
4 changes: 2 additions & 2 deletions src/formatters/general.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,11 +396,11 @@ pub fn format_punctuated<T, F>(
ctx: &Context,
old: &Punctuated<T>,
shape: Shape,
value_formatter: F,
mut value_formatter: F,
) -> Punctuated<T>
where
T: std::fmt::Display,
F: Fn(&Context, &T, Shape) -> T,
F: FnMut(&Context, &T, Shape) -> T,
{
let mut list: Punctuated<T> = Punctuated::new();
let mut shape = shape;
Expand Down
28 changes: 21 additions & 7 deletions src/formatters/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,16 +590,30 @@ pub fn format_table_constructor(
format_field,
shape,
),
TableType::MultiLine => format_multiline_table(
ctx,
table_constructor.braces(),
table_constructor.fields(),
format_field,
shape,
),
TableType::MultiLine => {
return format_expanded_table_constructor(ctx, table_constructor, shape)
}
};

TableConstructor::new()
.with_braces(braces)
.with_fields(fields)
}

pub(super) fn format_expanded_table_constructor(
ctx: &Context,
table_constructor: &TableConstructor,
shape: Shape,
) -> TableConstructor {
let (braces, fields) = format_multiline_table(
ctx,
table_constructor.braces(),
table_constructor.fields(),
format_field,
shape,
);

TableConstructor::new()
.with_braces(braces)
.with_fields(fields)
}
59 changes: 59 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,65 @@ fn test_standard() {
})
}

#[test]
fn test_function_call_hugs_long_table_on_first_pass() {
const EXPANDED_TABLE: &str =
"f(x, {\n\ta,\n\tb,\n\tc,\n\td,\n\te,\n\tf,\n\tg,\n\th,\n\ti,\n})\n";

for (column_width, input, expected) in [
(
120,
r#"assert.are.same({ true, false, false, false },
{ forms.keeps("heading", "identifier"), forms.keeps("heading", "style"),
forms.keeps("div", "identifier"), forms.keeps("span", "identifier") })"#,
concat!(
"assert.are.same({ true, false, false, false }, {\n",
"\tforms.keeps(\"heading\", \"identifier\"),\n",
"\tforms.keeps(\"heading\", \"style\"),\n",
"\tforms.keeps(\"div\", \"identifier\"),\n",
"\tforms.keeps(\"span\", \"identifier\"),\n",
"})\n"
),
),
(30, "f(x, {a,b,c,d,e,f,g,h,i})", EXPANDED_TABLE),
(30, "f(x, ({a,b,c,d,e,f,g,h,i}))", EXPANDED_TABLE),
] {
let config = Config {
column_width,
..Config::default()
};
let first = format_code(input, config, None, OutputVerification::Full).unwrap();
let second = format_code(&first, config, None, OutputVerification::Full).unwrap();
assert_eq!(first, expected);
assert_eq!(first, second);
}
}

#[test]
fn test_multiline_function_call_expands_wide_table_on_first_pass() {
let config = Config {
column_width: 46,
..Config::default()
};
let input =
"render_table_with_all_the_detailed_defaults(x, {alpha=11,beta=22,gamma=33,delta=44})";
let expected = concat!(
"render_table_with_all_the_detailed_defaults(\n",
"\tx,\n",
"\t{\n",
"\t\talpha = 11,\n",
"\t\tbeta = 22,\n",
"\t\tgamma = 33,\n",
"\t\tdelta = 44,\n",
"\t}\n",
")\n"
);
let first = format_code(input, config, None, OutputVerification::Full).unwrap();
let second = format_code(&first, config, None, OutputVerification::Full).unwrap();
assert_eq!(first, expected);
assert_eq!(first, second);
}

#[test]
fn test_full_moon_test_suite() {
insta::glob!("inputs-full_moon/*.lua", |path| {
Expand Down