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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
18 changes: 9 additions & 9 deletions src/formatters/luau.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -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()),
Expand All @@ -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 <name> =` / `const <name> =` part of an
/// Formats a [`ConditionBinding`] node - the `local <name> =` / `const <name> =` part of an
/// `if local` / `if const` binding, as in `if local player = getPlayer() then ... end`.
/// The formatted binding is `<local|const> <name>[: <type>] = ` (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(
Expand Down
85 changes: 73 additions & 12 deletions src/formatters/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -343,11 +343,11 @@ fn should_indent_further<'a>(trivia: impl Iterator<Item = &'a Token>, 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()
Expand Down Expand Up @@ -869,35 +869,91 @@ 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 <name> =` 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()
.has_trailing_comments(CommentSearch::All)
|| 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,
};

Expand Down Expand Up @@ -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.
Expand Down
29 changes: 29 additions & 0 deletions tests/inputs-luau/while-local-while-const-comments.lua
Original file line number Diff line number Diff line change
@@ -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
42 changes: 42 additions & 0 deletions tests/inputs-luau/while-local-while-const.lua
Original file line number Diff line number Diff line change
@@ -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
41 changes: 41 additions & 0 deletions tests/snapshots/[email protected]
Original file line number Diff line number Diff line change
@@ -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

58 changes: 58 additions & 0 deletions tests/snapshots/[email protected]
Original file line number Diff line number Diff line change
@@ -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

Loading