diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ac6dc18..2cb18414 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Luau: Added support for `while local` / `while const` condition bindings in `while` loops (e.g. `while local line = reader:nextLine() do ... end`) + ## [2.6.0] - 2026-10-10 ### Added diff --git a/Cargo.lock b/Cargo.lock index 1db0b7ab..d278d4a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -395,9 +395,9 @@ dependencies = [ [[package]] name = "full_moon" -version = "3.0.0" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bc70b300f9b09c409fa0a68a9f0c3e6b43573e47680d16932a0f8dade11a193" +checksum = "e93b034e105ab618e1834ee44b734e4012c66e687d673b6754a2d676b38b6ac3" dependencies = [ "bytecount", "cfg-if", diff --git a/Cargo.toml b/Cargo.toml index b459ef35..b4a3d2f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,7 +43,7 @@ console = "0.15.7" crossbeam-channel = "0.5.15" ec4rs = { version = "1.0.2", optional = true } env_logger = { version = "0.10.0", default-features = false } -full_moon = "3.0.0" +full_moon = "3.1.0" globset = "0.4.13" ignore = "0.4.20" lazy_static = "1.4.0" diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs index d6bc3328..1c68a648 100644 --- a/src/formatters/luau.rs +++ b/src/formatters/luau.rs @@ -26,10 +26,10 @@ use crate::{ }; use full_moon::ast::{ luau::{ - ExportedTypeDeclaration, ExportedTypeFunction, GenericDeclaration, - GenericDeclarationParameter, GenericParameterInfo, IfConditionBinding, IndexedTypeInfo, - LuauAttribute, TypeArgument, TypeAssertion, TypeDeclaration, TypeField, TypeFieldKey, - TypeFunction, TypeInfo, TypeInstantiation, TypeIntersection, TypeSpecifier, TypeUnion, + ConditionBinding, ExportedTypeDeclaration, ExportedTypeFunction, GenericDeclaration, + GenericDeclarationParameter, GenericParameterInfo, IndexedTypeInfo, LuauAttribute, + TypeArgument, TypeAssertion, TypeDeclaration, TypeField, TypeFieldKey, TypeFunction, + TypeInfo, TypeInstantiation, TypeIntersection, TypeSpecifier, TypeUnion, }, punctuated::Pair, }; @@ -1516,8 +1516,8 @@ pub fn format_type_specifier( .with_type_info(type_info) } -/// The width of the last line of an [`IfConditionBinding`], ignoring comments. -pub fn if_condition_binding_width(binding: &IfConditionBinding) -> usize { +/// The width of the last line of a [`ConditionBinding`], ignoring comments. +pub fn if_condition_binding_width(binding: &ConditionBinding) -> usize { let text = format!( "{} {}{} =", strip_trivia(binding.local_token()), @@ -1532,15 +1532,15 @@ pub fn if_condition_binding_width(binding: &IfConditionBinding) -> usize { text.lines().last().map_or(0, |line| line.chars().count()) } -/// Formats an [`IfConditionBinding`] node - the `local =` / `const =` part of an +/// Formats a [`ConditionBinding`] node - the `local =` / `const =` part of an /// `if local` / `if const` binding, as in `if local player = getPlayer() then ... end`. /// The formatted binding is ` [: ] = ` (with a trailing space), so it /// slots directly between the `if `/`elseif ` token and the condition expression. pub fn format_if_condition_binding( ctx: &Context, - binding: &IfConditionBinding, + binding: &ConditionBinding, shape: Shape, -) -> IfConditionBinding { +) -> ConditionBinding { // Preserve the keyword (`local` or `const`), normalising to a single trailing space let local_token = format_token_reference(ctx, binding.local_token(), shape) .update_trailing_trivia(FormatTriviaType::Append(vec![Token::new( diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs index 1f2b2a6d..475175f0 100644 --- a/src/formatters/stmt.rs +++ b/src/formatters/stmt.rs @@ -37,7 +37,7 @@ use crate::{ shape::Shape, }; #[cfg(feature = "luau")] -use full_moon::ast::luau::IfConditionBinding; +use full_moon::ast::luau::ConditionBinding; use full_moon::{ ast::{ punctuated::Punctuated, Block, Call, Do, ElseIf, Expression, FunctionArgs, FunctionCall, @@ -343,11 +343,11 @@ fn should_indent_further<'a>(trivia: impl Iterator, shape: Sha #[cfg(feature = "luau")] fn hang_if_condition_binding( ctx: &Context, - binding: IfConditionBinding, + binding: ConditionBinding, shape: Shape, hang_condition: bool, keyword_has_comments: bool, -) -> IfConditionBinding { +) -> ConditionBinding { let newline = vec![create_newline_trivia(ctx)]; let equal_token = if !hang_condition { binding.equal_token().to_owned() @@ -869,12 +869,29 @@ pub fn format_while_block(ctx: &Context, while_block: &While, shape: Shape) -> W // Remove parentheses around the condition let condition = remove_condition_parentheses(while_block.condition().to_owned()); + // Format the `local =` binding (`while local` / `while const`), if present + #[cfg(feature = "luau")] + let binding_has_comments = while_block + .binding() + .is_some_and(trivia_util::contains_comments); + #[cfg(not(feature = "luau"))] + let binding_has_comments = false; + #[cfg(feature = "luau")] + let binding = while_block + .binding() + .map(|binding| format_if_condition_binding(ctx, binding, shape)); + #[cfg(feature = "luau")] + let binding_width = binding.as_ref().map_or(0, if_condition_binding_width); + #[cfg(not(feature = "luau"))] + let binding_width = 0; + let singleline_while_token = fmt_symbol!(ctx, while_block.while_token(), "while ", shape); - let singleline_condition = format_expression(ctx, &condition, shape + 6); + let singleline_condition = format_expression(ctx, &condition, shape + 6 + binding_width); let singleline_do_token = fmt_symbol!(ctx, while_block.do_token(), " do", shape); // Determine if we need to hang the condition - let singleline_shape = shape + (6 + 3 + strip_trivia(&singleline_condition).to_string().len()); // 6 = "while ", 3 = " do" + let singleline_shape = + shape + (6 + 3 + binding_width + strip_trivia(&singleline_condition).to_string().len()); // 6 = "while ", 3 = " do" let require_multiline_expression = singleline_shape.over_budget() || while_block .while_token() @@ -882,22 +899,61 @@ pub fn format_while_block(ctx: &Context, while_block: &While, shape: Shape) -> W || while_block .do_token() .has_leading_comments(CommentSearch::All) + || binding_has_comments || trivia_util::contains_comments(&condition); - let while_token = match require_multiline_expression { - true => fmt_symbol!(ctx, while_block.while_token(), "while", shape) - .update_trailing_trivia(FormatTriviaType::Append(vec![create_newline_trivia(ctx)])), - false => singleline_while_token, + // When multilining with a binding, the binding stays on the `while` line and the condition + // hangs below it, so the newline goes after the binding rather than after `while`. + #[cfg(feature = "luau")] + let while_token_has_comments = while_block + .while_token() + .has_trailing_comments(CommentSearch::All); + #[cfg(not(feature = "luau"))] + let while_token_has_comments = false; + + #[cfg(feature = "luau")] + let hang_condition = require_multiline_expression + && (binding.is_none() + || singleline_shape.over_budget() + || binding_has_comments + || trivia_util::contains_comments(&condition)); + #[cfg(not(feature = "luau"))] + let hang_condition = require_multiline_expression; + + #[cfg(feature = "luau")] + let binding = binding.map(|binding| { + hang_if_condition_binding( + ctx, + binding, + shape, + hang_condition, + while_token_has_comments, + ) + }); + + #[cfg(feature = "luau")] + let has_binding = binding.is_some(); + #[cfg(not(feature = "luau"))] + let has_binding = false; + + let while_token = if require_multiline_expression && (!has_binding || while_token_has_comments) + { + fmt_symbol!(ctx, while_block.while_token(), "while", shape) + .update_trailing_trivia(FormatTriviaType::Append(vec![create_newline_trivia(ctx)])) + } else { + singleline_while_token } .update_leading_trivia(FormatTriviaType::Append(leading_trivia.to_owned())); - let condition = match require_multiline_expression { + let condition = match hang_condition { true => { let shape = shape.reset().increment_additional_indent(); hang_expression_trailing_newline(ctx, &condition, shape, None).update_leading_trivia( FormatTriviaType::Append(vec![create_indent_trivia(ctx, shape)]), ) } + false if require_multiline_expression => singleline_condition + .update_trailing_trivia(FormatTriviaType::Append(vec![create_newline_trivia(ctx)])), false => singleline_condition, }; @@ -927,13 +983,18 @@ pub fn format_while_block(ctx: &Context, while_block: &While, shape: Shape) -> W FormatTriviaType::Append(trailing_trivia), ); - while_block + let while_block = while_block .to_owned() .with_while_token(while_token) .with_condition(condition) .with_do_token(do_token) .with_block(block) - .with_end_token(end_token) + .with_end_token(end_token); + + #[cfg(feature = "luau")] + let while_block = while_block.with_binding(binding); + + while_block } /// Wrapper around `format_function_call`, but also handles adding the trivia around the function call. diff --git a/tests/inputs-luau/while-local-while-const-comments.lua b/tests/inputs-luau/while-local-while-const-comments.lua new file mode 100644 index 00000000..0d34df7f --- /dev/null +++ b/tests/inputs-luau/while-local-while-const-comments.lua @@ -0,0 +1,29 @@ +while -- note + local x = f() do + print(x) +end + +while local x = -- why + getValue() do + print(x) +end + +while local x --[[ inline ]] = getValue() do + print(x) +end + +while local x = getValue() +-- before do +do + print(x) +end + +while -- note + const x = f() do + print(x) +end + +while const x = -- why + getValue() do + print(x) +end diff --git a/tests/inputs-luau/while-local-while-const.lua b/tests/inputs-luau/while-local-while-const.lua new file mode 100644 index 00000000..e061b215 --- /dev/null +++ b/tests/inputs-luau/while-local-while-const.lua @@ -0,0 +1,42 @@ +while local line = reader:nextLine() do +process(line) +end + +while const item = queue:pop() do print(item) end + +while local x : number? = getValue() do + print(x) +end + +while const name : string? = getName() do + print(name) +end + +while local value = (getNext()) do + print(value) +end + +while local someLongBindingName = resolveSomethingWithAVeryLongFunctionName(argumentNumberOne, argumentNumberTwo, argumentNumberThree) do + print(someLongBindingName) +end + +while local someLongBindingName: SomeVeryLongTypeName = resolveSomethingWithLongName(argumentOne) and fallbackValueForBinding do + print(someLongBindingName) +end + +while local nextNode = getNodeWithAVeryLongFunctionName(currentNodeIdentifier) or getFallbackNodeForTheTraversalOfTheGraph(rootNode) do + print(nextNode) +end + +local function drain(queue) + while local item = queue:pop() do + while const child = item:nextChildWithAVeryLongMethodName(childFilterPredicate) or item:fallbackChild(defaultChildValue) do + print(child) + end + end +end + +local const = true +while const do + const = false +end diff --git a/tests/snapshots/tests__luau@while-local-while-const-comments.lua.snap b/tests/snapshots/tests__luau@while-local-while-const-comments.lua.snap new file mode 100644 index 00000000..932496f2 --- /dev/null +++ b/tests/snapshots/tests__luau@while-local-while-const-comments.lua.snap @@ -0,0 +1,41 @@ +--- +source: tests/tests.rs +expression: "format(&contents, LuaVersion::Luau)" +input_file: tests/inputs-luau/while-local-while-const-comments.lua +--- +while -- note + local x = f() +do + print(x) +end + +while local x = -- why + getValue() +do + print(x) +end + +while local x --[[ inline ]] = + getValue() +do + print(x) +end + +while local x = getValue() + -- before do +do + print(x) +end + +while -- note + const x = f() +do + print(x) +end + +while const x = -- why + getValue() +do + print(x) +end + diff --git a/tests/snapshots/tests__luau@while-local-while-const.lua.snap b/tests/snapshots/tests__luau@while-local-while-const.lua.snap new file mode 100644 index 00000000..37a0d42f --- /dev/null +++ b/tests/snapshots/tests__luau@while-local-while-const.lua.snap @@ -0,0 +1,58 @@ +--- +source: tests/tests.rs +expression: "format(&contents, LuaVersion::Luau)" +input_file: tests/inputs-luau/while-local-while-const.lua +--- +while local line = reader:nextLine() do + process(line) +end + +while const item = queue:pop() do + print(item) +end + +while local x: number? = getValue() do + print(x) +end + +while const name: string? = getName() do + print(name) +end + +while local value = getNext() do + print(value) +end + +while local someLongBindingName = + resolveSomethingWithAVeryLongFunctionName(argumentNumberOne, argumentNumberTwo, argumentNumberThree) +do + print(someLongBindingName) +end + +while local someLongBindingName: SomeVeryLongTypeName = + resolveSomethingWithLongName(argumentOne) and fallbackValueForBinding +do + print(someLongBindingName) +end + +while local nextNode = + getNodeWithAVeryLongFunctionName(currentNodeIdentifier) or getFallbackNodeForTheTraversalOfTheGraph(rootNode) +do + print(nextNode) +end + +local function drain(queue) + while local item = queue:pop() do + while const child = + item:nextChildWithAVeryLongMethodName(childFilterPredicate) or item:fallbackChild(defaultChildValue) + do + print(child) + end + end +end + +local const = true +while const do + const = false +end +