From dbbca465a5bcc0b62bf236d250ac954cf7087057 Mon Sep 17 00:00:00 2001 From: Boulea7 <145515129+Boulea7@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:19:39 +0800 Subject: [PATCH] Fix first-pass layout of wide table arguments Carry the table expansion decision from function call layout into final formatting. Exercise the reported layout and a compact table whose normalized width exceeds its budget. --- src/formatters/expression.rs | 33 ++++++++++++++--- src/formatters/functions.rs | 69 ++++++++++++++++++++++++++++-------- src/formatters/general.rs | 4 +-- src/formatters/table.rs | 28 +++++++++++---- tests/tests.rs | 59 ++++++++++++++++++++++++++++++ 5 files changed, 164 insertions(+), 29 deletions(-) diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs index 6291eedd..e13db5ac 100644 --- a/src/formatters/expression.rs +++ b/src/formatters/expression.rs @@ -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, @@ -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, @@ -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, @@ -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")] @@ -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 { diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs index ab3244e1..4c366155 100644 --- a/src/formatters/functions.rs +++ b/src/formatters/functions.rs @@ -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, @@ -219,6 +222,7 @@ fn function_args_multiline_heuristic( ctx: &Context, arguments: &Punctuated, shape: Shape, + expanded_tables: &mut Vec, ) -> bool { const PAREN_LEN: usize = "(".len(); const COMMA_SPACE_LEN: usize = ", ".len(); @@ -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) => { @@ -291,11 +296,22 @@ 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() { @@ -303,7 +319,12 @@ fn function_args_multiline_heuristic( } // 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; } @@ -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? @@ -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 { @@ -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. @@ -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) diff --git a/src/formatters/general.rs b/src/formatters/general.rs index 72d5fe09..c3a7cf3b 100644 --- a/src/formatters/general.rs +++ b/src/formatters/general.rs @@ -396,11 +396,11 @@ pub fn format_punctuated( ctx: &Context, old: &Punctuated, shape: Shape, - value_formatter: F, + mut value_formatter: F, ) -> Punctuated where T: std::fmt::Display, - F: Fn(&Context, &T, Shape) -> T, + F: FnMut(&Context, &T, Shape) -> T, { let mut list: Punctuated = Punctuated::new(); let mut shape = shape; diff --git a/src/formatters/table.rs b/src/formatters/table.rs index da949bee..25ef345a 100644 --- a/src/formatters/table.rs +++ b/src/formatters/table.rs @@ -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) +} diff --git a/tests/tests.rs b/tests/tests.rs index 908a390f..b0a80ae8 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -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| {