Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

* add support for `const` declaration of variables and functions (e.g. `const var = true` or `const function test() end`) and add rule (`make_assignment_local`) to convert those assignments to `local` assignments ([#346](https://github.com/seaofvoices/darklua/pull/346))
* add support for type instantiation prefixes and methods (e.g. `func<<string>>()`) ([#345](https://github.com/seaofvoices/darklua/pull/345))

## 0.18.0
Expand Down
12 changes: 12 additions & 0 deletions site/content/rules/make_assignment_local.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
description: Convert Luau `const` assignments to `local` assignments
added_in: "unreleased"
parameters: []
examples:
- content: "const PI = math.pi"
- content: "const function example() end"
---

This rule converts all `const` assignments into regular `local` assignments. It is applied to variable assignments and function assignments.

**Note:** this rule is useful if you are converting Luau code into regular Lua code.
85 changes: 81 additions & 4 deletions src/ast_converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -856,7 +856,29 @@ impl<'a> AstConverter<'a> {

self.statements.push(
builder
.into_local_function_statement(name, local_token)
.into_function_assignment(name, AssignmentKind::Local, local_token)
.into(),
);
}
ConvertWork::MakeConstFunctionStatement { statement } => {
let mut builder = self.convert_function_body_attributes(
statement.body(),
self.convert_token(statement.function_token())?,
)?;

builder.set_attributes(self.convert_attributes(statement.attributes())?);

let mut name = Identifier::new(statement.name().token().to_string());
let mut const_token = None;

if self.hold_token_data {
name.set_token(self.convert_token(statement.name())?);
const_token = Some(self.convert_token(statement.const_token())?);
}

self.statements.push(
builder
.into_function_assignment(name, AssignmentKind::Const, const_token)
.into(),
);
}
Expand Down Expand Up @@ -900,14 +922,14 @@ impl<'a> AstConverter<'a> {
})
.collect::<Result<Vec<_>, _>>()?;

let mut local_assign = LocalAssignStatement::new(
let mut local_assign = VariableAssignment::new(
variables,
self.pop_expressions(statement.expressions().len())?,
);

if self.hold_token_data {
local_assign.set_tokens(LocalAssignTokens {
local: self.convert_token(statement.local_token())?,
local_assign.set_tokens(VariableAssignmentTokens {
keyword: self.convert_token(statement.local_token())?,
equal: statement
.equal_token()
.map(|token| self.convert_token(token))
Expand All @@ -920,6 +942,37 @@ impl<'a> AstConverter<'a> {
}
self.statements.push(local_assign.into());
}
ConvertWork::MakeConstAssignStatement { statement } => {
let variables = statement
.names()
.iter()
.zip(statement.type_specifiers())
.map(|(token_ref, type_specifier)| {
self.convert_typed_identifier(token_ref, type_specifier)
})
.collect::<Result<Vec<_>, _>>()?;

let mut assignment = VariableAssignment::new(
variables,
self.pop_expressions(statement.expressions().len())?,
);
assignment.set_assignment_kind(AssignmentKind::Const);

if self.hold_token_data {
assignment.set_tokens(VariableAssignmentTokens {
keyword: self.convert_token(statement.const_token())?,
equal: statement
.equal_token()
.map(|token| self.convert_token(token))
.transpose()?,
variable_commas: self
.extract_tokens_from_punctuation(statement.names())?,
value_commas: self
.extract_tokens_from_punctuation(statement.expressions())?,
})
}
self.statements.push(assignment.into());
}
ConvertWork::MakeArgumentsFromExpressions {
arguments,
parentheses,
Expand Down Expand Up @@ -1578,13 +1631,31 @@ impl<'a> AstConverter<'a> {
self.push_work(expression);
}
}
ast::Stmt::ConstAssignment(const_assignment) => {
self.work_stack.push(ConvertWork::MakeConstAssignStatement {
statement: const_assignment,
});
for type_specifier in const_assignment.type_specifiers().flatten() {
self.push_work(type_specifier.type_info());
}
for expression in const_assignment.expressions().iter() {
self.push_work(expression);
}
}
ast::Stmt::LocalFunction(local_function) => {
self.work_stack
.push(ConvertWork::MakeLocalFunctionStatement {
statement: local_function,
});
self.push_function_body_work(local_function.body());
}
ast::Stmt::ConstFunction(const_function) => {
self.work_stack
.push(ConvertWork::MakeConstFunctionStatement {
statement: const_function,
});
self.push_function_body_work(const_function.body());
}
ast::Stmt::TypeFunction(type_function) => {
self.work_stack
.push(ConvertWork::MakeTypeFunctionStatement {
Expand Down Expand Up @@ -3005,9 +3076,15 @@ enum ConvertWork<'a> {
MakeLocalFunctionStatement {
statement: &'a ast::LocalFunction,
},
MakeConstFunctionStatement {
statement: &'a ast::luau::ConstFunction,
},
MakeLocalAssignStatement {
statement: &'a ast::LocalAssignment,
},
MakeConstAssignStatement {
statement: &'a ast::luau::ConstAssignment,
},
MakeAssignStatement {
statement: &'a ast::Assignment,
},
Expand Down
53 changes: 41 additions & 12 deletions src/generator/dense.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,32 +500,58 @@ impl LuaGenerator for DenseLuaGenerator {
}
}

fn write_local_assign(&mut self, assign: &nodes::LocalAssignStatement) {
self.push_str("local");
fn write_local_assign(&mut self, assign: &nodes::VariableAssignment) {
self.push_str(assign.get_assignment_kind().as_keyword());

let variables = assign.get_variables();
let last_variable_index = variables.len().saturating_sub(1);
let variables_length = assign.variables_len();
let last_variable_index = variables_length.saturating_sub(1);

variables.iter().enumerate().for_each(|(index, variable)| {
for (index, variable) in assign.iter_variables().enumerate() {
self.write_typed_identifier(variable);

if index != last_variable_index {
self.push_char(',');
}
});
}

// const assignments must have at least one variable per value, so it may need
// additional variables
for i in 0..assign.required_new_variables() {
if i != 0 || variables_length > 0 {
self.push_char(',');
}
utils::THROWAWAY_IDENTIFIER.with(|identifier| {
self.write_typed_identifier(identifier);
});
}

// const assignments must have a value for each variable, so it may need additional
// nil values
let required_nil_values = assign.required_nil_values();

let has_values = assign.has_values();

if assign.has_values() {
if has_values || required_nil_values > 0 {
self.push_char_and_break_if('=', utils::break_equal);

let last_value_index = assign.values_len() - 1;
let last_value_index = assign.values_len().saturating_sub(1);

assign.iter_values().enumerate().for_each(|(index, value)| {
for (index, value) in assign.iter_values().enumerate() {
self.write_expression(value);

if index != last_value_index {
self.push_char(',');
}
});
}

for i in 0..required_nil_values {
if i != 0 || has_values {
self.push_char(',');
}
utils::NIL_EXPRESSION.with(|nil| {
self.write_expression(nil);
})
}
};
}

Expand All @@ -537,9 +563,12 @@ impl LuaGenerator for DenseLuaGenerator {
self.write_expression(assign.get_value());
}

fn write_local_function(&mut self, function: &nodes::LocalFunctionStatement) {
fn write_local_function(&mut self, function: &nodes::FunctionAssignment) {
self.write_attributes(function.attributes());
self.push_str("local function");
self.push_str(function.get_assignment_kind().as_keyword());
self.push_space();
self.push_str("function");
self.push_space();
self.push_str(function.get_name());

if let Some(generics) = function.get_generic_parameters() {
Expand Down
55 changes: 36 additions & 19 deletions src/generator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ pub trait LuaGenerator {
fn write_if_statement(&mut self, if_statement: &nodes::IfStatement);
fn write_function_statement(&mut self, function: &nodes::FunctionStatement);
fn write_last_statement(&mut self, statement: &nodes::LastStatement);
fn write_local_assign(&mut self, assign: &nodes::LocalAssignStatement);
fn write_local_function(&mut self, function: &nodes::LocalFunctionStatement);
fn write_local_assign(&mut self, assign: &nodes::VariableAssignment);
fn write_local_function(&mut self, function: &nodes::FunctionAssignment);
fn write_numeric_for(&mut self, numeric_for: &nodes::NumericForStatement);
fn write_repeat_statement(&mut self, repeat: &nodes::RepeatStatement);
fn write_while_statement(&mut self, while_statement: &nodes::WhileStatement);
Expand Down Expand Up @@ -674,7 +674,7 @@ mod $mod_name {
),
ambiguous_function_call_from_local_assign => Block::default()
.with_statement(
LocalAssignStatement::from_variable("name")
VariableAssignment::from_variable("name")
.with_value(
IfExpression::new(
Expression::identifier("condition"),
Expand Down Expand Up @@ -972,45 +972,62 @@ mod $mod_name {
));

snapshot_node!($mod_name, $generator, local_assign, write_statement => (
foo_unassigned => LocalAssignStatement::from_variable("foo"),
foo_typed_unassigned => LocalAssignStatement::from_variable(
foo_unassigned => VariableAssignment::from_variable("foo"),
foo_typed_unassigned => VariableAssignment::from_variable(
Identifier::new("foo").with_type(Type::from(true))
),
foo_and_bar_unassigned => LocalAssignStatement::from_variable("foo")
foo_and_bar_unassigned => VariableAssignment::from_variable("foo")
.with_variable("bar"),
foo_and_bar_typed_unassigned => LocalAssignStatement::from_variable("foo")
foo_and_bar_typed_unassigned => VariableAssignment::from_variable("foo")
.with_variable(Identifier::new("bar").with_type(Type::from(false))),
var_assign_to_false => LocalAssignStatement::from_variable("var")
var_assign_to_false => VariableAssignment::from_variable("var")
.with_value(false),
typed_generic_var_break_equal_sign => LocalAssignStatement::from_variable(
typed_generic_var_break_equal_sign => VariableAssignment::from_variable(
Identifier::new("var").with_type(
TypeName::new("List").with_type_parameter(TypeName::new("string"))
)
).with_value(false),
// const assignments
const_foo_unassigned => VariableAssignment::from_variable("foo")
.with_assignment_kind(AssignmentKind::Const),
const_foo_typed_unassigned => VariableAssignment::from_variable(
Identifier::new("foo").with_type(OptionalType::new(Type::from(true)))
).with_assignment_kind(AssignmentKind::Const),
const_foo_and_bar_unassigned => VariableAssignment::from_variable("foo")
.with_assignment_kind(AssignmentKind::Const)
.with_variable("bar")
.with_assignment_kind(AssignmentKind::Const),
const_foo_and_bar_typed_unassigned => VariableAssignment::from_variable("foo")
.with_assignment_kind(AssignmentKind::Const)
.with_variable(Identifier::new("bar").with_type(OptionalType::new(Type::from(false)))),
const_assignment_of_one_variable_with_two_values => VariableAssignment::from_variable("foo")
.with_assignment_kind(AssignmentKind::Const)
.with_value(true)
.with_value(false),
));

snapshot_node!($mod_name, $generator, local_function, write_statement => (
empty => LocalFunctionStatement::from_name("foo", Block::default()),
empty_variadic => LocalFunctionStatement::from_name("foo", Block::default())
empty => FunctionAssignment::from_name("foo", Block::default()),
empty_variadic => FunctionAssignment::from_name("foo", Block::default())
.variadic(),
empty_with_one_parameter => LocalFunctionStatement::from_name("foo", Block::default())
empty_with_one_parameter => FunctionAssignment::from_name("foo", Block::default())
.with_parameter("bar"),
empty_with_two_parameters => LocalFunctionStatement::from_name("foo", Block::default())
empty_with_two_parameters => FunctionAssignment::from_name("foo", Block::default())
.with_parameter("bar")
.with_parameter("baz"),
empty_variadic_with_one_parameter => LocalFunctionStatement::from_name("foo", Block::default())
empty_variadic_with_one_parameter => FunctionAssignment::from_name("foo", Block::default())
.with_parameter("bar")
.variadic(),
empty_with_generic_pack_return_type => LocalFunctionStatement::from_name("foo", Block::default())
empty_with_generic_pack_return_type => FunctionAssignment::from_name("foo", Block::default())
.with_return_type(GenericTypePack::new("R")),
empty_with_attribute => LocalFunctionStatement::from_name("foo", Block::default())
empty_with_attribute => FunctionAssignment::from_name("foo", Block::default())
.with_attribute(NamedAttribute::new("native")),
empty_with_attribute_in_group => LocalFunctionStatement::from_name("foo", Block::default())
empty_with_attribute_in_group => FunctionAssignment::from_name("foo", Block::default())
.with_attribute(AttributeGroupElement::new("native").with_arguments(AttributeTupleArguments::default())),
empty_with_2_attributes => LocalFunctionStatement::from_name("foo", Block::default())
empty_with_2_attributes => FunctionAssignment::from_name("foo", Block::default())
.with_attribute(NamedAttribute::new("native"))
.with_attribute(NamedAttribute::new("deprecated")),
empty_with_2_attributes_in_group => LocalFunctionStatement::from_name("foo", Block::default())
empty_with_2_attributes_in_group => FunctionAssignment::from_name("foo", Block::default())
.with_attribute(
AttributeGroup::new(
AttributeGroupElement::new("native").with_arguments(AttributeTupleArguments::default())
Expand Down
Loading
Loading