Compare commits
10 Commits
0.4.5
...
20f0f4b9a1
| Author | SHA1 | Date | |
|---|---|---|---|
|
20f0f4b9a1
|
|||
|
5a88befac9
|
|||
|
e94fc0f5de
|
|||
|
b51800eb77
|
|||
|
87951ab12f
|
|||
|
00b0d4df26
|
|||
| 6ca53e8959 | |||
|
8dfdad3f34
|
|||
| e272737ea2 | |||
|
f679601818
|
@@ -1,5 +1,14 @@
|
||||
# Changelog
|
||||
|
||||
[0.4.7]
|
||||
|
||||
- Added support for Windows CRLF endings
|
||||
|
||||
[0.4.6]
|
||||
|
||||
- Fixed bug in compiler where you were unable to assign a `const` value to
|
||||
a `let` variable
|
||||
|
||||
[0.4.5]
|
||||
|
||||
- Fixed issue where after clicking "Cancel" on the IC10 Editor, the side-by-side
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<ModMetadata xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<Name>Slang</Name>
|
||||
<Author>JoeDiertay</Author>
|
||||
<Version>0.4.5</Version>
|
||||
<Version>0.4.7</Version>
|
||||
<Description>
|
||||
[h1]Slang: High-Level Programming for Stationeers[/h1]
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ namespace Slang
|
||||
{
|
||||
public const string PluginGuid = "com.biddydev.slang";
|
||||
public const string PluginName = "Slang";
|
||||
public const string PluginVersion = "0.4.5";
|
||||
public const string PluginVersion = "0.4.7";
|
||||
|
||||
private static Harmony? _harmony;
|
||||
|
||||
|
||||
2
rust_compiler/Cargo.lock
generated
2
rust_compiler/Cargo.lock
generated
@@ -930,7 +930,7 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
||||
|
||||
[[package]]
|
||||
name = "slang"
|
||||
version = "0.4.5"
|
||||
version = "0.4.7"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "slang"
|
||||
version = "0.4.5"
|
||||
version = "0.4.7"
|
||||
edition = "2021"
|
||||
|
||||
[workspace]
|
||||
|
||||
@@ -168,3 +168,28 @@ fn test_const_hash_expr() -> anyhow::Result<()> {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_declaration_is_const() -> anyhow::Result<()> {
|
||||
let compiled = compile! {
|
||||
debug
|
||||
r#"
|
||||
const MAX = 100;
|
||||
|
||||
let max = MAX;
|
||||
"#
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
main:
|
||||
move r8 100
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -47,3 +47,4 @@ mod logic_expression;
|
||||
mod loops;
|
||||
mod math_syscall;
|
||||
mod syscall;
|
||||
mod tuple_literals;
|
||||
|
||||
539
rust_compiler/libs/compiler/src/test/tuple_literals.rs
Normal file
539
rust_compiler/libs/compiler/src/test/tuple_literals.rs
Normal file
@@ -0,0 +1,539 @@
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use indoc::indoc;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn test_tuple_literal_declaration() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
let (x, y) = (1, 2);
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
main:
|
||||
move r8 1
|
||||
move r9 2
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_literal_declaration_with_underscore() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
let (x, _) = (1, 2);
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
main:
|
||||
move r8 1
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_literal_assignment() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
(x, y) = (5, 10);
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
main:
|
||||
move r8 0
|
||||
move r9 0
|
||||
move r8 5
|
||||
move r9 10
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_literal_with_variables() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
let a = 42;
|
||||
let b = 99;
|
||||
let (x, y) = (a, b);
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
main:
|
||||
move r8 42
|
||||
move r9 99
|
||||
move r10 r8
|
||||
move r11 r9
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_literal_three_elements() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
let (x, y, z) = (1, 2, 3);
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
main:
|
||||
move r8 1
|
||||
move r9 2
|
||||
move r10 3
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_literal_assignment_with_underscore() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
let i = 0;
|
||||
let x = 123;
|
||||
(i, _) = (456, 789);
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
main:
|
||||
move r8 0
|
||||
move r9 123
|
||||
move r8 456
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_return_simple() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn getPair() {
|
||||
return (10, 20);
|
||||
};
|
||||
let (x, y) = getPair();
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
getPair:
|
||||
move r15 sp
|
||||
push ra
|
||||
push 10
|
||||
push 20
|
||||
move r15 1
|
||||
sub r0 sp 3
|
||||
get ra db r0
|
||||
j ra
|
||||
main:
|
||||
jal getPair
|
||||
pop r9
|
||||
pop r8
|
||||
move sp r15
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_return_with_underscore() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn getPair() {
|
||||
return (5, 15);
|
||||
};
|
||||
let (x, _) = getPair();
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
getPair:
|
||||
move r15 sp
|
||||
push ra
|
||||
push 5
|
||||
push 15
|
||||
move r15 1
|
||||
sub r0 sp 3
|
||||
get ra db r0
|
||||
j ra
|
||||
main:
|
||||
jal getPair
|
||||
pop r0
|
||||
pop r8
|
||||
move sp r15
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_return_three_elements() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn getTriple() {
|
||||
return (1, 2, 3);
|
||||
};
|
||||
let (a, b, c) = getTriple();
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
getTriple:
|
||||
move r15 sp
|
||||
push ra
|
||||
push 1
|
||||
push 2
|
||||
push 3
|
||||
move r15 1
|
||||
sub r0 sp 4
|
||||
get ra db r0
|
||||
j ra
|
||||
main:
|
||||
jal getTriple
|
||||
pop r10
|
||||
pop r9
|
||||
pop r8
|
||||
move sp r15
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_return_assignment() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn getPair() {
|
||||
return (42, 84);
|
||||
};
|
||||
let i = 1;
|
||||
let j = 2;
|
||||
(i, j) = getPair();
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
getPair:
|
||||
move r15 sp
|
||||
push ra
|
||||
push 42
|
||||
push 84
|
||||
move r15 1
|
||||
sub r0 sp 3
|
||||
get ra db r0
|
||||
j ra
|
||||
main:
|
||||
move r8 1
|
||||
move r9 2
|
||||
jal getPair
|
||||
pop r9
|
||||
pop r8
|
||||
move sp r15
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_return_mismatch() -> anyhow::Result<()> {
|
||||
let errors = compile!(
|
||||
result
|
||||
r#"
|
||||
fn doSomething() {
|
||||
return (1, 2, 3);
|
||||
};
|
||||
let (x, y) = doSomething();
|
||||
"#
|
||||
);
|
||||
|
||||
// Should have exactly one error about tuple size mismatch
|
||||
assert_eq!(errors.len(), 1);
|
||||
|
||||
// Check for the specific TupleSizeMismatch error
|
||||
match &errors[0] {
|
||||
crate::Error::TupleSizeMismatch(func_name, expected_size, actual_count, _) => {
|
||||
assert_eq!(func_name.as_ref(), "doSomething");
|
||||
assert_eq!(*expected_size, 3);
|
||||
assert_eq!(*actual_count, 2);
|
||||
}
|
||||
e => panic!("Expected TupleSizeMismatch error, got: {:?}", e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_return_called_by_non_tuple_return() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn doSomething() {
|
||||
return (1, 2);
|
||||
};
|
||||
|
||||
fn doSomethingElse() {
|
||||
let (x, y) = doSomething();
|
||||
return y;
|
||||
};
|
||||
|
||||
let returnedValue = doSomethingElse();
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
doSomething:
|
||||
move r15 sp
|
||||
push ra
|
||||
push 1
|
||||
push 2
|
||||
move r15 1
|
||||
sub r0 sp 3
|
||||
get ra db r0
|
||||
j ra
|
||||
doSomethingElse:
|
||||
push ra
|
||||
jal doSomething
|
||||
pop r9
|
||||
pop r8
|
||||
move sp r15
|
||||
move r15 r9
|
||||
j __internal_L2
|
||||
__internal_L2:
|
||||
pop ra
|
||||
j ra
|
||||
main:
|
||||
jal doSomethingElse
|
||||
move r8 r15
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_tuple_return_called_by_tuple_return() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn getValue() {
|
||||
return 42;
|
||||
};
|
||||
|
||||
fn getTuple() {
|
||||
let x = getValue();
|
||||
return (x, x);
|
||||
};
|
||||
|
||||
let (a, b) = getTuple();
|
||||
"#
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
compiled,
|
||||
indoc! {
|
||||
"
|
||||
j main
|
||||
getValue:
|
||||
push ra
|
||||
move r15 42
|
||||
j __internal_L1
|
||||
__internal_L1:
|
||||
pop ra
|
||||
j ra
|
||||
getTuple:
|
||||
move r15 sp
|
||||
push ra
|
||||
jal getValue
|
||||
move r8 r15
|
||||
push r8
|
||||
push r8
|
||||
move r15 1
|
||||
sub r0 sp 3
|
||||
get ra db r0
|
||||
j ra
|
||||
main:
|
||||
jal getTuple
|
||||
pop r9
|
||||
pop r8
|
||||
move sp r15
|
||||
"
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_literal_size_mismatch() -> anyhow::Result<()> {
|
||||
let errors = compile!(
|
||||
result
|
||||
r#"
|
||||
let (x, y) = (1, 2, 3);
|
||||
"#
|
||||
);
|
||||
|
||||
// Should have exactly one error about tuple size mismatch
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert!(matches!(errors[0], crate::Error::Unknown(_, _)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_tuple_returns_in_function() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn getValue(x) {
|
||||
if (x) {
|
||||
return (1, 2);
|
||||
} else {
|
||||
return (3, 4);
|
||||
}
|
||||
};
|
||||
|
||||
let (a, b) = getValue(1);
|
||||
"#
|
||||
);
|
||||
|
||||
println!("Generated code:\n{}", compiled);
|
||||
|
||||
// Both returns are 2-tuples, should compile successfully
|
||||
assert!(compiled.contains("getValue:"));
|
||||
assert!(compiled.contains("move r15 "));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_return_with_expression() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn add(x, y) {
|
||||
return (x, y);
|
||||
};
|
||||
|
||||
let (a, b) = add(5, 10);
|
||||
"#
|
||||
);
|
||||
|
||||
// Should compile - we're just passing the parameter variables through
|
||||
assert!(compiled.contains("add:"));
|
||||
assert!(compiled.contains("jal "));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_function_tuple_calls() -> anyhow::Result<()> {
|
||||
let compiled = compile!(
|
||||
debug
|
||||
r#"
|
||||
fn inner() {
|
||||
return (1, 2);
|
||||
};
|
||||
|
||||
fn outer() {
|
||||
let (x, y) = inner();
|
||||
return (y, x);
|
||||
};
|
||||
|
||||
let (a, b) = outer();
|
||||
"#
|
||||
);
|
||||
|
||||
// Both functions return tuples
|
||||
assert!(compiled.contains("inner:"));
|
||||
assert!(compiled.contains("outer:"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ use parser::{
|
||||
AssignmentExpression, BinaryExpression, BlockExpression, ConstDeclarationExpression,
|
||||
DeviceDeclarationExpression, Expression, FunctionExpression, IfExpression,
|
||||
InvocationExpression, Literal, LiteralOr, LiteralOrVariable, LogicalExpression,
|
||||
LoopExpression, MemberAccessExpression, Spanned, TernaryExpression, WhileExpression,
|
||||
LoopExpression, MemberAccessExpression, Spanned, TernaryExpression,
|
||||
TupleAssignmentExpression, TupleDeclarationExpression, WhileExpression,
|
||||
},
|
||||
};
|
||||
use rust_decimal::Decimal;
|
||||
@@ -63,6 +64,11 @@ pub enum Error<'a> {
|
||||
#[error("Attempted to re-assign a value to a device const `{0}`")]
|
||||
DeviceAssignment(Cow<'a, str>, Span),
|
||||
|
||||
#[error(
|
||||
"Function '{0}' returns a {1}-tuple, but you're trying to destructure into {2} variables"
|
||||
)]
|
||||
TupleSizeMismatch(Cow<'a, str>, usize, usize, Span),
|
||||
|
||||
#[error("{0}")]
|
||||
Unknown(String, Option<Span>),
|
||||
}
|
||||
@@ -84,7 +90,8 @@ impl<'a> From<Error<'a>> for lsp_types::Diagnostic {
|
||||
| InvalidDevice(_, span)
|
||||
| ConstAssignment(_, span)
|
||||
| DeviceAssignment(_, span)
|
||||
| AgrumentMismatch(_, span) => Diagnostic {
|
||||
| AgrumentMismatch(_, span)
|
||||
| TupleSizeMismatch(_, _, _, span) => Diagnostic {
|
||||
range: span.into(),
|
||||
message: value.to_string(),
|
||||
severity: Some(DiagnosticSeverity::ERROR),
|
||||
@@ -142,6 +149,8 @@ pub struct Compiler<'a> {
|
||||
pub parser: ASTParser<'a>,
|
||||
function_locations: HashMap<Cow<'a, str>, usize>,
|
||||
function_metadata: HashMap<Cow<'a, str>, Vec<Cow<'a, str>>>,
|
||||
function_tuple_return_sizes: HashMap<Cow<'a, str>, usize>, // Track tuple return sizes
|
||||
current_function_name: Option<Cow<'a, str>>, // Track the function currently being compiled
|
||||
devices: HashMap<Cow<'a, str>, Cow<'a, str>>,
|
||||
|
||||
// This holds the IL code which will be used in the
|
||||
@@ -155,6 +164,8 @@ pub struct Compiler<'a> {
|
||||
label_counter: usize,
|
||||
loop_stack: Vec<(Cow<'a, str>, Cow<'a, str>)>, // Stores (start_label, end_label)
|
||||
current_return_label: Option<Cow<'a, str>>,
|
||||
current_return_is_tuple: bool, // Track if the current function returns a tuple
|
||||
current_function_sp_saved: bool, // Track if we've emitted the SP save for the current function
|
||||
/// stores (IC10 `line_num`, `Vec<Span>`)
|
||||
pub source_map: HashMap<usize, Vec<Span>>,
|
||||
/// Accumulative errors from the compilation process
|
||||
@@ -176,6 +187,10 @@ impl<'a> Compiler<'a> {
|
||||
label_counter: 0,
|
||||
loop_stack: Vec::new(),
|
||||
current_return_label: None,
|
||||
current_return_is_tuple: false,
|
||||
current_function_sp_saved: false,
|
||||
current_function_name: None,
|
||||
function_tuple_return_sizes: HashMap::new(),
|
||||
source_map: HashMap::new(),
|
||||
errors: Vec::new(),
|
||||
}
|
||||
@@ -465,6 +480,14 @@ impl<'a> Compiler<'a> {
|
||||
temp_name: Some(result_name),
|
||||
}))
|
||||
}
|
||||
Expression::TupleDeclaration(tuple_decl) => {
|
||||
self.expression_tuple_declaration(tuple_decl.node, scope)?;
|
||||
Ok(None)
|
||||
}
|
||||
Expression::TupleAssignment(tuple_assign) => {
|
||||
self.expression_tuple_assignment(tuple_assign.node, scope)?;
|
||||
Ok(None)
|
||||
}
|
||||
_ => Err(Error::Unknown(
|
||||
format!(
|
||||
"Expression type not yet supported in general expression context: {:?}",
|
||||
@@ -714,7 +737,12 @@ impl<'a> Compiler<'a> {
|
||||
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER)
|
||||
}
|
||||
VariableLocation::Constant(_) | VariableLocation::Device(_) => unreachable!(),
|
||||
VariableLocation::Constant(Literal::Number(num)) => Operand::Number(num.into()),
|
||||
VariableLocation::Constant(Literal::Boolean(b)) => {
|
||||
Operand::Number(Number::from(b).into())
|
||||
}
|
||||
VariableLocation::Device(_)
|
||||
| VariableLocation::Constant(Literal::String(_)) => unreachable!(),
|
||||
};
|
||||
self.emit_variable_assignment(&var_loc, src)?;
|
||||
(var_loc, None)
|
||||
@@ -927,6 +955,658 @@ impl<'a> Compiler<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expression_function_invocation_with_invocation(
|
||||
&mut self,
|
||||
invoke_expr: &InvocationExpression<'a>,
|
||||
parent_scope: &mut VariableScope<'a, '_>,
|
||||
backup_registers: bool,
|
||||
) -> Result<(), Error<'a>> {
|
||||
let InvocationExpression { name, arguments } = invoke_expr;
|
||||
|
||||
if !self.function_locations.contains_key(name.node.as_ref()) {
|
||||
self.errors
|
||||
.push(Error::UnknownIdentifier(name.node.clone(), name.span));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(args) = self.function_metadata.get(name.node.as_ref()) else {
|
||||
return Err(Error::UnknownIdentifier(name.node.clone(), name.span));
|
||||
};
|
||||
|
||||
if args.len() != arguments.len() {
|
||||
self.errors
|
||||
.push(Error::AgrumentMismatch(name.node.clone(), name.span));
|
||||
return Ok(());
|
||||
}
|
||||
let mut stack = VariableScope::scoped(parent_scope);
|
||||
|
||||
// Get the list of active registers (may or may not backup)
|
||||
let active_registers = stack.registers();
|
||||
|
||||
// backup all used registers to the stack (unless this is for tuple return handling)
|
||||
if backup_registers {
|
||||
for register in &active_registers {
|
||||
stack.add_variable(
|
||||
Cow::from(format!("temp_{register}")),
|
||||
LocationRequest::Stack,
|
||||
None,
|
||||
)?;
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Register(*register)),
|
||||
Some(name.span),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
for arg in arguments {
|
||||
match &arg.node {
|
||||
Expression::Literal(spanned_lit) => match &spanned_lit.node {
|
||||
Literal::Number(num) => {
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Number((*num).into())),
|
||||
Some(spanned_lit.span),
|
||||
)?;
|
||||
}
|
||||
Literal::Boolean(b) => {
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Number(Number::from(*b).into())),
|
||||
Some(spanned_lit.span),
|
||||
)?;
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Expression::Variable(var_name) => {
|
||||
let loc = match stack.get_location_of(&var_name.node, Some(var_name.span)) {
|
||||
Ok(l) => l,
|
||||
Err(_) => {
|
||||
self.errors.push(Error::UnknownIdentifier(
|
||||
var_name.node.clone(),
|
||||
var_name.span,
|
||||
));
|
||||
VariableLocation::Temporary(0)
|
||||
}
|
||||
};
|
||||
|
||||
match loc {
|
||||
VariableLocation::Persistant(reg) | VariableLocation::Temporary(reg) => {
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Register(reg)),
|
||||
Some(var_name.span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Constant(lit) => {
|
||||
self.write_instruction(
|
||||
Instruction::Push(extract_literal(lit, false)?),
|
||||
Some(var_name.span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Stack(stack_offset) => {
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::StackPointer,
|
||||
Operand::Number(stack_offset.into()),
|
||||
),
|
||||
Some(var_name.span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Get(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
),
|
||||
Some(var_name.span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Register(
|
||||
VariableScope::TEMP_STACK_REGISTER,
|
||||
)),
|
||||
Some(var_name.span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Device(_) => {
|
||||
self.errors.push(Error::Unknown(
|
||||
"Device references not supported in function arguments".into(),
|
||||
Some(var_name.span),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(Error::Unknown(
|
||||
"Only literals and variables supported in function arguments".into(),
|
||||
Some(arg.span),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(_location) = self.function_locations.get(&name.node) else {
|
||||
self.errors
|
||||
.push(Error::UnknownIdentifier(name.node.clone(), name.span));
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::JumpAndLink(Operand::Label(name.node.clone())),
|
||||
Some(name.span),
|
||||
)?;
|
||||
|
||||
// pop all registers back (if they were backed up)
|
||||
if backup_registers {
|
||||
for register in active_registers.iter().rev() {
|
||||
self.write_instruction(
|
||||
Instruction::Pop(Operand::Register(*register)),
|
||||
Some(name.span),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expression_tuple_declaration(
|
||||
&mut self,
|
||||
tuple_decl: TupleDeclarationExpression<'a>,
|
||||
scope: &mut VariableScope<'a, '_>,
|
||||
) -> Result<(), Error<'a>> {
|
||||
let TupleDeclarationExpression { names, value } = tuple_decl;
|
||||
|
||||
// Compile the right-hand side expression
|
||||
// For function calls returning tuples:
|
||||
// r15 = pointer to beginning of tuple on stack
|
||||
// r14, r13, ... contain the tuple elements, or they're on the stack
|
||||
match &value.node {
|
||||
Expression::Invocation(invoke_expr) => {
|
||||
// Execute the function call
|
||||
// Tuple values are on the stack, sp points after the last pushed value
|
||||
// Pop them in reverse order (from end to beginning)
|
||||
// We don't need to backup registers for tuple returns
|
||||
self.expression_function_invocation_with_invocation(invoke_expr, scope, false)?;
|
||||
|
||||
// Validate tuple return size matches the declaration
|
||||
let func_name = &invoke_expr.node.name.node;
|
||||
if let Some(&expected_size) = self.function_tuple_return_sizes.get(func_name) {
|
||||
if names.len() != expected_size {
|
||||
self.errors.push(Error::TupleSizeMismatch(
|
||||
func_name.clone(),
|
||||
expected_size,
|
||||
names.len(),
|
||||
value.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// First pass: allocate variables in order
|
||||
let mut var_locations = Vec::new();
|
||||
for name_spanned in names.iter() {
|
||||
// Skip underscores
|
||||
if name_spanned.node.as_ref() == "_" {
|
||||
var_locations.push(None);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add variable to scope
|
||||
let var_location = scope.add_variable(
|
||||
name_spanned.node.clone(),
|
||||
LocationRequest::Persist,
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
var_locations.push(Some(var_location));
|
||||
}
|
||||
|
||||
// Second pass: pop in reverse order through the list (since stack is LIFO)
|
||||
// var_locations[0] is the first element (bottom of stack)
|
||||
// var_locations[n-1] is the last element (top of stack)
|
||||
// We pop from the top, so we iterate in reverse through var_locations
|
||||
for (idx, var_loc_opt) in var_locations.iter().enumerate().rev() {
|
||||
match var_loc_opt {
|
||||
Some(var_location) => {
|
||||
let var_reg = self.resolve_register(&var_location)?;
|
||||
|
||||
// Pop from stack into the variable's register
|
||||
self.write_instruction(
|
||||
Instruction::Pop(Operand::Register(var_reg)),
|
||||
Some(names[idx].span),
|
||||
)?;
|
||||
}
|
||||
None => {
|
||||
// Underscore: pop into temp register to discard
|
||||
self.write_instruction(
|
||||
Instruction::Pop(Operand::Register(
|
||||
VariableScope::TEMP_STACK_REGISTER,
|
||||
)),
|
||||
Some(names[idx].span),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore stack pointer to value saved at function entry
|
||||
self.write_instruction(
|
||||
Instruction::Move(
|
||||
Operand::StackPointer,
|
||||
Operand::Register(VariableScope::RETURN_REGISTER),
|
||||
),
|
||||
Some(value.span),
|
||||
)?;
|
||||
}
|
||||
Expression::Tuple(tuple_expr) => {
|
||||
// Direct tuple literal: (value1, value2, ...)
|
||||
let tuple_elements = &tuple_expr.node;
|
||||
|
||||
// Validate tuple size matches names
|
||||
if tuple_elements.len() != names.len() {
|
||||
return Err(Error::Unknown(
|
||||
format!(
|
||||
"Tuple size mismatch: expected {} elements, got {}",
|
||||
names.len(),
|
||||
tuple_elements.len()
|
||||
),
|
||||
Some(value.span),
|
||||
));
|
||||
}
|
||||
|
||||
// Compile each element and assign to corresponding variable
|
||||
for (_index, (name_spanned, element)) in
|
||||
names.iter().zip(tuple_elements.iter()).enumerate()
|
||||
{
|
||||
// Skip underscores
|
||||
if name_spanned.node.as_ref() == "_" {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add variable to scope
|
||||
let var_location = scope.add_variable(
|
||||
name_spanned.node.clone(),
|
||||
LocationRequest::Persist,
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
|
||||
// Compile the element expression - handle common cases directly
|
||||
match &element.node {
|
||||
Expression::Literal(lit) => {
|
||||
let value_operand = extract_literal(lit.node.clone(), false)?;
|
||||
self.emit_variable_assignment(&var_location, value_operand)?;
|
||||
}
|
||||
Expression::Variable(var) => {
|
||||
let var_loc = match scope.get_location_of(&var.node, Some(var.span)) {
|
||||
Ok(l) => l,
|
||||
Err(_) => {
|
||||
self.errors
|
||||
.push(Error::UnknownIdentifier(var.node.clone(), var.span));
|
||||
VariableLocation::Temporary(0)
|
||||
}
|
||||
};
|
||||
|
||||
let value_operand = match &var_loc {
|
||||
VariableLocation::Temporary(reg)
|
||||
| VariableLocation::Persistant(reg) => Operand::Register(*reg),
|
||||
VariableLocation::Constant(lit) => {
|
||||
extract_literal(lit.clone(), false)?
|
||||
}
|
||||
VariableLocation::Stack(offset) => {
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::StackPointer,
|
||||
Operand::Number((*offset).into()),
|
||||
),
|
||||
Some(var.span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Get(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
),
|
||||
Some(var.span),
|
||||
)?;
|
||||
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER)
|
||||
}
|
||||
VariableLocation::Device(_) => {
|
||||
return Err(Error::Unknown(
|
||||
"Device values not supported in tuple literals".into(),
|
||||
Some(var.span),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
self.emit_variable_assignment(&var_location, value_operand)?;
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::Unknown(
|
||||
"Complex expressions in tuple literals not yet supported".into(),
|
||||
Some(element.span),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::Unknown(
|
||||
"Tuple declaration only supports function invocations or tuple literals as RHS"
|
||||
.into(),
|
||||
Some(value.span),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expression_tuple_assignment(
|
||||
&mut self,
|
||||
tuple_assign: TupleAssignmentExpression<'a>,
|
||||
scope: &mut VariableScope<'a, '_>,
|
||||
) -> Result<(), Error<'a>> {
|
||||
let TupleAssignmentExpression { names, value } = tuple_assign;
|
||||
|
||||
// Similar to tuple declaration, but variables must already exist
|
||||
match &value.node {
|
||||
Expression::Invocation(invoke_expr) => {
|
||||
// Execute the function call
|
||||
// Tuple values are on the stack, sp points after the last pushed value
|
||||
// Pop them in reverse order (from end to beginning)
|
||||
// We don't need to backup registers for tuple returns
|
||||
self.expression_function_invocation_with_invocation(invoke_expr, scope, false)?;
|
||||
|
||||
// Validate tuple return size matches the assignment
|
||||
let func_name = &invoke_expr.node.name.node;
|
||||
if let Some(&expected_size) = self.function_tuple_return_sizes.get(func_name) {
|
||||
if names.len() != expected_size {
|
||||
self.errors.push(Error::TupleSizeMismatch(
|
||||
func_name.clone(),
|
||||
expected_size,
|
||||
names.len(),
|
||||
value.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// First pass: look up variable locations
|
||||
let mut var_locs = Vec::new();
|
||||
for name_spanned in names.iter() {
|
||||
// Skip underscores
|
||||
if name_spanned.node.as_ref() == "_" {
|
||||
var_locs.push(None);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the existing variable location
|
||||
let var_location =
|
||||
match scope.get_location_of(&name_spanned.node, Some(name_spanned.span)) {
|
||||
Ok(l) => l,
|
||||
Err(_) => {
|
||||
self.errors.push(Error::UnknownIdentifier(
|
||||
name_spanned.node.clone(),
|
||||
name_spanned.span,
|
||||
));
|
||||
VariableLocation::Temporary(0)
|
||||
}
|
||||
};
|
||||
var_locs.push(Some(var_location));
|
||||
}
|
||||
|
||||
// Second pass: pop in reverse order and assign
|
||||
for (idx, var_loc_opt) in var_locs.iter().enumerate().rev() {
|
||||
if let Some(var_location) = var_loc_opt {
|
||||
// Pop from stack and assign to variable
|
||||
match var_location {
|
||||
VariableLocation::Temporary(reg)
|
||||
| VariableLocation::Persistant(reg) => {
|
||||
// Pop directly into the variable's register
|
||||
self.write_instruction(
|
||||
Instruction::Pop(Operand::Register(*reg)),
|
||||
Some(names[idx].span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Stack(offset) => {
|
||||
// Pop into temp register, then write to variable stack
|
||||
self.write_instruction(
|
||||
Instruction::Pop(Operand::Register(
|
||||
VariableScope::TEMP_STACK_REGISTER,
|
||||
)),
|
||||
Some(names[idx].span),
|
||||
)?;
|
||||
|
||||
// Write to variable stack location
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(0),
|
||||
Operand::StackPointer,
|
||||
Operand::Number((*offset).into()),
|
||||
),
|
||||
Some(names[idx].span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Put(
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(0),
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
),
|
||||
Some(names[idx].span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Constant(_) => {
|
||||
return Err(Error::ConstAssignment(
|
||||
names[idx].node.clone(),
|
||||
names[idx].span,
|
||||
));
|
||||
}
|
||||
VariableLocation::Device(_) => {
|
||||
return Err(Error::DeviceAssignment(
|
||||
names[idx].node.clone(),
|
||||
names[idx].span,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore stack pointer to value saved at function entry
|
||||
self.write_instruction(
|
||||
Instruction::Move(
|
||||
Operand::StackPointer,
|
||||
Operand::Register(VariableScope::RETURN_REGISTER),
|
||||
),
|
||||
Some(value.span),
|
||||
)?;
|
||||
}
|
||||
Expression::Tuple(tuple_expr) => {
|
||||
// Direct tuple literal: (value1, value2, ...)
|
||||
let tuple_elements = &tuple_expr.node;
|
||||
|
||||
// Validate tuple size matches names
|
||||
if tuple_elements.len() != names.len() {
|
||||
return Err(Error::Unknown(
|
||||
format!(
|
||||
"Tuple size mismatch: expected {} elements, got {}",
|
||||
names.len(),
|
||||
tuple_elements.len()
|
||||
),
|
||||
Some(value.span),
|
||||
));
|
||||
}
|
||||
|
||||
// Compile each element and assign to corresponding variable
|
||||
for (_index, (name_spanned, element)) in
|
||||
names.iter().zip(tuple_elements.iter()).enumerate()
|
||||
{
|
||||
// Skip underscores
|
||||
if name_spanned.node.as_ref() == "_" {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the existing variable location
|
||||
let var_location =
|
||||
match scope.get_location_of(&name_spanned.node, Some(name_spanned.span)) {
|
||||
Ok(l) => l,
|
||||
Err(_) => {
|
||||
self.errors.push(Error::UnknownIdentifier(
|
||||
name_spanned.node.clone(),
|
||||
name_spanned.span,
|
||||
));
|
||||
VariableLocation::Temporary(0)
|
||||
}
|
||||
};
|
||||
|
||||
// Compile the element expression - handle common cases directly
|
||||
match &element.node {
|
||||
Expression::Literal(lit) => {
|
||||
let value_operand = extract_literal(lit.node.clone(), false)?;
|
||||
match &var_location {
|
||||
VariableLocation::Temporary(reg)
|
||||
| VariableLocation::Persistant(reg) => {
|
||||
self.write_instruction(
|
||||
Instruction::Move(Operand::Register(*reg), value_operand),
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Stack(offset) => {
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::StackPointer,
|
||||
Operand::Number((*offset).into()),
|
||||
),
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Put(
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
value_operand,
|
||||
),
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Constant(_) => {
|
||||
return Err(Error::ConstAssignment(
|
||||
name_spanned.node.clone(),
|
||||
name_spanned.span,
|
||||
));
|
||||
}
|
||||
VariableLocation::Device(_) => {
|
||||
return Err(Error::DeviceAssignment(
|
||||
name_spanned.node.clone(),
|
||||
name_spanned.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::Variable(var) => {
|
||||
let var_loc = match scope.get_location_of(&var.node, Some(var.span)) {
|
||||
Ok(l) => l,
|
||||
Err(_) => {
|
||||
self.errors
|
||||
.push(Error::UnknownIdentifier(var.node.clone(), var.span));
|
||||
VariableLocation::Temporary(0)
|
||||
}
|
||||
};
|
||||
|
||||
let value_operand = match &var_loc {
|
||||
VariableLocation::Temporary(reg)
|
||||
| VariableLocation::Persistant(reg) => Operand::Register(*reg),
|
||||
VariableLocation::Constant(lit) => {
|
||||
extract_literal(lit.clone(), false)?
|
||||
}
|
||||
VariableLocation::Stack(offset) => {
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::StackPointer,
|
||||
Operand::Number((*offset).into()),
|
||||
),
|
||||
Some(var.span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Get(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
),
|
||||
Some(var.span),
|
||||
)?;
|
||||
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER)
|
||||
}
|
||||
VariableLocation::Device(_) => {
|
||||
return Err(Error::Unknown(
|
||||
"Device values not supported in tuple literals".into(),
|
||||
Some(var.span),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
match &var_location {
|
||||
VariableLocation::Temporary(reg)
|
||||
| VariableLocation::Persistant(reg) => {
|
||||
self.write_instruction(
|
||||
Instruction::Move(Operand::Register(*reg), value_operand),
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Stack(offset) => {
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::StackPointer,
|
||||
Operand::Number((*offset).into()),
|
||||
),
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Put(
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
value_operand,
|
||||
),
|
||||
Some(name_spanned.span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Constant(_) => {
|
||||
return Err(Error::ConstAssignment(
|
||||
name_spanned.node.clone(),
|
||||
name_spanned.span,
|
||||
));
|
||||
}
|
||||
VariableLocation::Device(_) => {
|
||||
return Err(Error::DeviceAssignment(
|
||||
name_spanned.node.clone(),
|
||||
name_spanned.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::Unknown(
|
||||
"Complex expressions in tuple literals not yet supported".into(),
|
||||
Some(element.span),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::Unknown(
|
||||
"Tuple assignment only supports function invocations or tuple literals as RHS"
|
||||
.into(),
|
||||
Some(value.span),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expression_function_invocation(
|
||||
&mut self,
|
||||
invoke_expr: Spanned<InvocationExpression<'a>>,
|
||||
@@ -1941,6 +2621,169 @@ impl<'a> Compiler<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Expression::Tuple(tuple_expr) => {
|
||||
let span = expr.span;
|
||||
let tuple_elements = &tuple_expr.node;
|
||||
|
||||
// Record the stack offset where the tuple will start
|
||||
let tuple_start_offset = scope.stack_offset();
|
||||
|
||||
// First pass: Add temporary variables to scope for each tuple element
|
||||
// This updates the scope's stack_offset so we can calculate ra position later
|
||||
let mut temp_names = Vec::new();
|
||||
for (i, _element) in tuple_elements.iter().enumerate() {
|
||||
let temp_name = format!("__tuple_ret_{}", i);
|
||||
scope.add_variable(
|
||||
temp_name.clone().into(),
|
||||
LocationRequest::Stack,
|
||||
Some(span),
|
||||
)?;
|
||||
temp_names.push(temp_name);
|
||||
}
|
||||
|
||||
// Second pass: Push the actual values onto the stack
|
||||
for element in tuple_elements.iter() {
|
||||
match &element.node {
|
||||
Expression::Literal(lit) => {
|
||||
let value_operand = extract_literal(lit.node.clone(), false)?;
|
||||
self.write_instruction(
|
||||
Instruction::Push(value_operand),
|
||||
Some(span),
|
||||
)?;
|
||||
}
|
||||
Expression::Variable(var) => {
|
||||
let var_loc = match scope.get_location_of(&var.node, Some(var.span))
|
||||
{
|
||||
Ok(l) => l,
|
||||
Err(_) => {
|
||||
self.errors.push(Error::UnknownIdentifier(
|
||||
var.node.clone(),
|
||||
var.span,
|
||||
));
|
||||
VariableLocation::Temporary(0)
|
||||
}
|
||||
};
|
||||
|
||||
match &var_loc {
|
||||
VariableLocation::Temporary(reg)
|
||||
| VariableLocation::Persistant(reg) => {
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Register(*reg)),
|
||||
Some(span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Constant(lit) => {
|
||||
let value_operand = extract_literal(lit.clone(), false)?;
|
||||
self.write_instruction(
|
||||
Instruction::Push(value_operand),
|
||||
Some(span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Stack(offset) => {
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(
|
||||
VariableScope::TEMP_STACK_REGISTER,
|
||||
),
|
||||
Operand::StackPointer,
|
||||
Operand::Number((*offset).into()),
|
||||
),
|
||||
Some(span),
|
||||
)?;
|
||||
self.write_instruction(
|
||||
Instruction::Get(
|
||||
Operand::Register(
|
||||
VariableScope::TEMP_STACK_REGISTER,
|
||||
),
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(
|
||||
VariableScope::TEMP_STACK_REGISTER,
|
||||
),
|
||||
),
|
||||
Some(span),
|
||||
)?;
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Register(
|
||||
VariableScope::TEMP_STACK_REGISTER,
|
||||
)),
|
||||
Some(span),
|
||||
)?;
|
||||
}
|
||||
VariableLocation::Device(_) => {
|
||||
return Err(Error::Unknown(
|
||||
"You can not return a device from a function.".into(),
|
||||
Some(var.span),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// For complex expressions, just push 0 for now
|
||||
self.write_instruction(
|
||||
Instruction::Push(Operand::Number(
|
||||
Number::Integer(0, Unit::None).into(),
|
||||
)),
|
||||
Some(span),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Store the pointer to the tuple (stack offset) in r15
|
||||
self.write_instruction(
|
||||
Instruction::Move(
|
||||
Operand::Register(VariableScope::RETURN_REGISTER),
|
||||
Operand::Number(tuple_start_offset.into()),
|
||||
),
|
||||
Some(span),
|
||||
)?;
|
||||
|
||||
// For tuple returns, ra is buried under the tuple values on the stack.
|
||||
// Stack layout: [ra, val0, val1, val2, ...]
|
||||
// Instead of popping and pushing, use Get to read ra from its stack position
|
||||
// while leaving the tuple values in place.
|
||||
|
||||
// Calculate offset to ra from current stack position
|
||||
// ra is at tuple_start_offset - 1, so offset = (current - tuple_start) + 1
|
||||
let current_offset = scope.stack_offset();
|
||||
let ra_offset_from_current = (current_offset - tuple_start_offset + 1) as i32;
|
||||
|
||||
// Use a temp register to read ra from the stack
|
||||
if ra_offset_from_current > 0 {
|
||||
self.write_instruction(
|
||||
Instruction::Sub(
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
Operand::StackPointer,
|
||||
Operand::Number(ra_offset_from_current.into()),
|
||||
),
|
||||
Some(span),
|
||||
)?;
|
||||
|
||||
self.write_instruction(
|
||||
Instruction::Get(
|
||||
Operand::ReturnAddress,
|
||||
Operand::Device(Cow::from("db")),
|
||||
Operand::Register(VariableScope::TEMP_STACK_REGISTER),
|
||||
),
|
||||
Some(span),
|
||||
)?;
|
||||
}
|
||||
|
||||
// Jump back to caller
|
||||
self.write_instruction(Instruction::Jump(Operand::ReturnAddress), Some(span))?;
|
||||
|
||||
// Mark that we had a tuple return so the function declaration can skip return label cleanup
|
||||
self.current_return_is_tuple = true;
|
||||
|
||||
// Record the tuple return size for validation at call sites
|
||||
if let Some(func_name) = &self.current_function_name {
|
||||
self.function_tuple_return_sizes
|
||||
.insert(func_name.clone(), tuple_elements.len());
|
||||
}
|
||||
|
||||
// Early return to skip the normal return label processing
|
||||
return Ok(VariableLocation::Persistant(VariableScope::RETURN_REGISTER));
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::Unknown(
|
||||
format!("Unsupported `return` statement: {:?}", expr),
|
||||
@@ -2569,6 +3412,23 @@ impl<'a> Compiler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a function body contains any tuple returns
|
||||
fn has_tuple_return(body: &BlockExpression) -> bool {
|
||||
for expr in &body.0 {
|
||||
match &expr.node {
|
||||
Expression::Return(Some(ret_expr)) => {
|
||||
if let Expression::Tuple(_) = &ret_expr.node {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Could recursively check nested blocks, but for now just check direct returns
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Compile a function declaration.
|
||||
/// Calees are responsible for backing up any registers they wish to use.
|
||||
fn expression_function(
|
||||
@@ -2596,6 +3456,9 @@ impl<'a> Compiler<'a> {
|
||||
arguments.iter().map(|a| a.node.clone()).collect(),
|
||||
);
|
||||
|
||||
// Set the current function being compiled
|
||||
self.current_function_name = Some(name.node.clone());
|
||||
|
||||
// Declare the function as a line identifier
|
||||
self.write_instruction(Instruction::LabelDef(name.node.clone()), Some(span))?;
|
||||
|
||||
@@ -2657,6 +3520,18 @@ impl<'a> Compiler<'a> {
|
||||
)?;
|
||||
}
|
||||
|
||||
// If this function has tuple returns, save the SP to r15 before pushing ra
|
||||
if Self::has_tuple_return(&body) {
|
||||
self.write_instruction(
|
||||
Instruction::Move(
|
||||
Operand::Register(VariableScope::RETURN_REGISTER),
|
||||
Operand::StackPointer,
|
||||
),
|
||||
Some(span),
|
||||
)?;
|
||||
self.current_function_sp_saved = true;
|
||||
}
|
||||
|
||||
self.write_instruction(Instruction::Push(Operand::ReturnAddress), Some(span))?;
|
||||
|
||||
let return_label = self.next_label_name();
|
||||
@@ -2710,6 +3585,9 @@ impl<'a> Compiler<'a> {
|
||||
|
||||
self.current_return_label = prev_return_label;
|
||||
|
||||
// Only write the return label if this function doesn't have a tuple return
|
||||
// (tuple returns handle their own pop ra and return)
|
||||
if !self.current_return_is_tuple {
|
||||
self.write_instruction(Instruction::LabelDef(return_label.clone()), Some(span))?;
|
||||
|
||||
if ra_stack_offset == 1 {
|
||||
@@ -2758,6 +3636,12 @@ impl<'a> Compiler<'a> {
|
||||
}
|
||||
|
||||
self.write_instruction(Instruction::Jump(Operand::ReturnAddress), Some(span))?;
|
||||
}
|
||||
|
||||
// Reset the flag for the next function
|
||||
self.current_return_is_tuple = false;
|
||||
self.current_function_sp_saved = false;
|
||||
self.current_function_name = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -441,7 +441,13 @@ impl<'a> Parser<'a> {
|
||||
));
|
||||
}
|
||||
|
||||
TokenType::Keyword(Keyword::Let) => Some(self.spanned(|p| p.declaration())?),
|
||||
TokenType::Keyword(Keyword::Let) => {
|
||||
if self_matches_peek!(self, TokenType::Symbol(Symbol::LParen)) {
|
||||
Some(self.spanned(|p| p.tuple_declaration())?)
|
||||
} else {
|
||||
Some(self.spanned(|p| p.declaration())?)
|
||||
}
|
||||
}
|
||||
|
||||
TokenType::Keyword(Keyword::Device) => {
|
||||
let spanned_dev = self.spanned(|p| p.device())?;
|
||||
@@ -561,9 +567,7 @@ impl<'a> Parser<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
TokenType::Symbol(Symbol::LParen) => {
|
||||
self.spanned(|p| p.priority())?.node.map(|node| *node)
|
||||
}
|
||||
TokenType::Symbol(Symbol::LParen) => self.parenthesized_or_tuple()?,
|
||||
|
||||
TokenType::Symbol(Symbol::Minus) => {
|
||||
let start_span = self.current_span();
|
||||
@@ -642,8 +646,8 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
TokenType::Symbol(Symbol::LParen) => *self
|
||||
.spanned(|p| p.priority())?
|
||||
.node
|
||||
.parenthesized_or_tuple()?
|
||||
.map(Box::new)
|
||||
.ok_or(Error::UnexpectedEOF)?,
|
||||
|
||||
TokenType::Identifier(ref id) if SysCall::is_syscall(id) => {
|
||||
@@ -774,7 +778,8 @@ impl<'a> Parser<'a> {
|
||||
| Expression::Ternary(_)
|
||||
| Expression::Negation(_)
|
||||
| Expression::MemberAccess(_)
|
||||
| Expression::MethodCall(_) => {}
|
||||
| Expression::MethodCall(_)
|
||||
| Expression::Tuple(_) => {}
|
||||
_ => {
|
||||
return Err(Error::InvalidSyntax(
|
||||
self.current_span(),
|
||||
@@ -1081,17 +1086,43 @@ impl<'a> Parser<'a> {
|
||||
end_col: right.span.end_col,
|
||||
};
|
||||
|
||||
expressions.insert(
|
||||
i,
|
||||
Spanned {
|
||||
// Check if the left side is a tuple, and if so, create a TupleAssignment
|
||||
let node = if let Expression::Tuple(tuple_expr) = &left.node {
|
||||
// Extract variable names from the tuple, handling underscores
|
||||
let mut names = Vec::new();
|
||||
for item in &tuple_expr.node {
|
||||
if let Expression::Variable(var) = &item.node {
|
||||
names.push(var.clone());
|
||||
} else {
|
||||
return Err(Error::InvalidSyntax(
|
||||
item.span,
|
||||
String::from("Tuple assignment can only contain variable names"),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Expression::TupleAssignment(Spanned {
|
||||
span,
|
||||
node: Expression::Assignment(Spanned {
|
||||
node: TupleAssignmentExpression {
|
||||
names,
|
||||
value: boxed!(right),
|
||||
},
|
||||
})
|
||||
} else {
|
||||
Expression::Assignment(Spanned {
|
||||
span,
|
||||
node: AssignmentExpression {
|
||||
assignee: boxed!(left),
|
||||
expression: boxed!(right),
|
||||
},
|
||||
}),
|
||||
})
|
||||
};
|
||||
|
||||
expressions.insert(
|
||||
i,
|
||||
Spanned {
|
||||
span,
|
||||
node,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1117,8 +1148,12 @@ impl<'a> Parser<'a> {
|
||||
expressions.pop().ok_or(Error::UnexpectedEOF)
|
||||
}
|
||||
|
||||
fn priority(&mut self) -> Result<Option<Box<Spanned<Expression<'a>>>>, Error<'a>> {
|
||||
fn parenthesized_or_tuple(
|
||||
&mut self,
|
||||
) -> Result<Option<Spanned<tree_node::Expression<'a>>>, Error<'a>> {
|
||||
let start_span = self.current_span();
|
||||
let current_token = self.current_token.as_ref().ok_or(Error::UnexpectedEOF)?;
|
||||
|
||||
if !token_matches!(current_token, TokenType::Symbol(Symbol::LParen)) {
|
||||
return Err(Error::UnexpectedToken(
|
||||
self.current_span(),
|
||||
@@ -1127,17 +1162,113 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
|
||||
self.assign_next()?;
|
||||
let expression = self.expression()?.ok_or(Error::UnexpectedEOF)?;
|
||||
|
||||
let current_token = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
||||
if !token_matches!(current_token, TokenType::Symbol(Symbol::RParen)) {
|
||||
return Err(Error::UnexpectedToken(
|
||||
Self::token_to_span(¤t_token),
|
||||
current_token,
|
||||
));
|
||||
// Handle empty tuple '()'
|
||||
if self_matches_peek!(self, TokenType::Symbol(Symbol::RParen)) {
|
||||
self.assign_next()?;
|
||||
let end_span = self.current_span();
|
||||
let span = Span {
|
||||
start_line: start_span.start_line,
|
||||
start_col: start_span.start_col,
|
||||
end_line: end_span.end_line,
|
||||
end_col: end_span.end_col,
|
||||
};
|
||||
return Ok(Some(Spanned {
|
||||
span,
|
||||
node: Expression::Tuple(Spanned { span, node: vec![] }),
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(Some(boxed!(expression)))
|
||||
let first_expression = self.expression()?.ok_or(Error::UnexpectedEOF)?;
|
||||
|
||||
if self_matches_peek!(self, TokenType::Symbol(Symbol::Comma)) {
|
||||
// It is a tuple
|
||||
let mut items = vec![first_expression];
|
||||
while self_matches_peek!(self, TokenType::Symbol(Symbol::Comma)) {
|
||||
// Next toekn is a comma, we need to consume it and advance 1 more time.
|
||||
self.assign_next()?;
|
||||
self.assign_next()?;
|
||||
println!("{:?}", self.current_token);
|
||||
items.push(self.expression()?.ok_or(Error::UnexpectedEOF)?);
|
||||
}
|
||||
|
||||
let next = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
||||
if !token_matches!(next, TokenType::Symbol(Symbol::RParen)) {
|
||||
return Err(Error::UnexpectedToken(Self::token_to_span(&next), next));
|
||||
}
|
||||
|
||||
let end_span = Self::token_to_span(&next);
|
||||
let span = Span {
|
||||
start_line: start_span.start_line,
|
||||
start_col: start_span.start_col,
|
||||
end_line: end_span.end_line,
|
||||
end_col: end_span.end_col,
|
||||
};
|
||||
|
||||
Ok(Some(Spanned {
|
||||
span,
|
||||
node: Expression::Tuple(Spanned { span, node: items }),
|
||||
}))
|
||||
} else {
|
||||
// It is just priority
|
||||
let next = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
||||
if !token_matches!(next, TokenType::Symbol(Symbol::RParen)) {
|
||||
return Err(Error::UnexpectedToken(Self::token_to_span(&next), next));
|
||||
}
|
||||
|
||||
Ok(Some(Spanned {
|
||||
span: first_expression.span,
|
||||
node: Expression::Priority(boxed!(first_expression)),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn tuple_declaration(&mut self) -> Result<Expression<'a>, Error<'a>> {
|
||||
// 'let' is consumed before this call
|
||||
// expect '('
|
||||
let next = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
||||
if !token_matches!(next, TokenType::Symbol(Symbol::LParen)) {
|
||||
return Err(Error::UnexpectedToken(Self::token_to_span(&next), next));
|
||||
}
|
||||
|
||||
let mut names = Vec::new();
|
||||
while !self_matches_peek!(self, TokenType::Symbol(Symbol::RParen)) {
|
||||
let token = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
||||
let span = Self::token_to_span(&token);
|
||||
if let TokenType::Identifier(id) = token.token_type {
|
||||
names.push(Spanned { span, node: id });
|
||||
} else {
|
||||
return Err(Error::UnexpectedToken(span, token));
|
||||
}
|
||||
|
||||
if self_matches_peek!(self, TokenType::Symbol(Symbol::Comma)) {
|
||||
self.assign_next()?;
|
||||
}
|
||||
}
|
||||
self.assign_next()?; // consume ')'
|
||||
|
||||
let assign = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
||||
|
||||
if !token_matches!(assign, TokenType::Symbol(Symbol::Assign)) {
|
||||
return Err(Error::UnexpectedToken(Self::token_to_span(&assign), assign));
|
||||
}
|
||||
|
||||
self.assign_next()?; // Consume the `=`
|
||||
|
||||
let value = self.expression()?.ok_or(Error::UnexpectedEOF)?;
|
||||
|
||||
let semi = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
||||
if !token_matches!(semi, TokenType::Symbol(Symbol::Semicolon)) {
|
||||
return Err(Error::UnexpectedToken(Self::token_to_span(&semi), semi));
|
||||
}
|
||||
|
||||
Ok(Expression::TupleDeclaration(Spanned {
|
||||
span: names.first().map(|n| n.span).unwrap_or(value.span),
|
||||
node: TupleDeclarationExpression {
|
||||
names,
|
||||
value: boxed!(value),
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
fn invocation(&mut self) -> Result<InvocationExpression<'a>, Error<'a>> {
|
||||
|
||||
@@ -112,7 +112,7 @@ fn test_function_invocation() -> Result<()> {
|
||||
#[test]
|
||||
fn test_priority_expression() -> Result<()> {
|
||||
let input = r#"
|
||||
let x = (4);
|
||||
let x = (4 + 3);
|
||||
"#;
|
||||
|
||||
let tokenizer = Tokenizer::from(input);
|
||||
@@ -120,7 +120,7 @@ fn test_priority_expression() -> Result<()> {
|
||||
|
||||
let expression = parser.parse()?.unwrap();
|
||||
|
||||
assert_eq!("(let x = 4)", expression.to_string());
|
||||
assert_eq!("(let x = ((4 + 3)))", expression.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -137,7 +137,7 @@ fn test_binary_expression() -> Result<()> {
|
||||
assert_eq!("(((45 * 2) - (15 / 5)) + (5 ** 2))", expr.to_string());
|
||||
|
||||
let expr = parser!("(5 - 2) * 10;").parse()?.unwrap();
|
||||
assert_eq!("((5 - 2) * 10)", expr.to_string());
|
||||
assert_eq!("(((5 - 2)) * 10)", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fn test_ternary_expression() -> Result<()> {
|
||||
fn test_complex_binary_with_ternary() -> Result<()> {
|
||||
let expr = parser!("let i = (x ? 1 : 3) * 2;").parse()?.unwrap();
|
||||
|
||||
assert_eq!("(let i = ((x ? 1 : 3) * 2))", expr.to_string());
|
||||
assert_eq!("(let i = (((x ? 1 : 3)) * 2))", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -191,3 +191,65 @@ fn test_nested_ternary_right_associativity() -> Result<()> {
|
||||
assert_eq!("(let i = (a ? b : (c ? d : e)))", expr.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_declaration() -> Result<()> {
|
||||
let expr = parser!("let (x, _) = (1, 2);").parse()?.unwrap();
|
||||
|
||||
assert_eq!("(let (x, _) = (1, 2))", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
#[test]
|
||||
fn test_tuple_assignment() -> Result<()> {
|
||||
let expr = parser!("(x, y) = (1, 2);").parse()?.unwrap();
|
||||
|
||||
assert_eq!("((x, y) = (1, 2))", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_assignment_with_underscore() -> Result<()> {
|
||||
let expr = parser!("(x, _) = (1, 2);").parse()?.unwrap();
|
||||
|
||||
assert_eq!("((x, _) = (1, 2))", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_declaration_with_function_call() -> Result<()> {
|
||||
let expr = parser!("let (x, y) = doSomething();").parse()?.unwrap();
|
||||
|
||||
assert_eq!("(let (x, y) = doSomething())", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_declaration_with_function_call_with_underscore() -> Result<()> {
|
||||
let expr = parser!("let (x, _) = doSomething();").parse()?.unwrap();
|
||||
|
||||
assert_eq!("(let (x, _) = doSomething())", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_assignment_with_function_call() -> Result<()> {
|
||||
let expr = parser!("(x, y) = doSomething();").parse()?.unwrap();
|
||||
|
||||
assert_eq!("((x, y) = doSomething())", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tuple_assignment_with_function_call_with_underscore() -> Result<()> {
|
||||
let expr = parser!("(x, _) = doSomething();").parse()?.unwrap();
|
||||
|
||||
assert_eq!("((x, _) = doSomething())", expr.to_string());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -245,6 +245,42 @@ impl<'a> std::fmt::Display for DeviceDeclarationExpression<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct TupleDeclarationExpression<'a> {
|
||||
pub names: Vec<Spanned<Cow<'a, str>>>,
|
||||
pub value: Box<Spanned<Expression<'a>>>,
|
||||
}
|
||||
|
||||
impl<'a> std::fmt::Display for TupleDeclarationExpression<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let names = self
|
||||
.names
|
||||
.iter()
|
||||
.map(|n| n.node.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
write!(f, "(let ({}) = {})", names, self.value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct TupleAssignmentExpression<'a> {
|
||||
pub names: Vec<Spanned<Cow<'a, str>>>,
|
||||
pub value: Box<Spanned<Expression<'a>>>,
|
||||
}
|
||||
|
||||
impl<'a> std::fmt::Display for TupleAssignmentExpression<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let names = self
|
||||
.names
|
||||
.iter()
|
||||
.map(|n| n.node.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
write!(f, "(({}) = {})", names, self.value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct IfExpression<'a> {
|
||||
pub condition: Box<Spanned<Expression<'a>>>,
|
||||
@@ -348,6 +384,9 @@ pub enum Expression<'a> {
|
||||
Return(Option<Box<Spanned<Expression<'a>>>>),
|
||||
Syscall(Spanned<SysCall<'a>>),
|
||||
Ternary(Spanned<TernaryExpression<'a>>),
|
||||
Tuple(Spanned<Vec<Spanned<Expression<'a>>>>),
|
||||
TupleAssignment(Spanned<TupleAssignmentExpression<'a>>),
|
||||
TupleDeclaration(Spanned<TupleDeclarationExpression<'a>>),
|
||||
Variable(Spanned<Cow<'a, str>>),
|
||||
While(Spanned<WhileExpression<'a>>),
|
||||
}
|
||||
@@ -384,8 +423,20 @@ impl<'a> std::fmt::Display for Expression<'a> {
|
||||
),
|
||||
Expression::Syscall(e) => write!(f, "{}", e),
|
||||
Expression::Ternary(e) => write!(f, "{}", e),
|
||||
Expression::Tuple(e) => {
|
||||
let items = e
|
||||
.node
|
||||
.iter()
|
||||
.map(|x| x.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
write!(f, "({})", items)
|
||||
}
|
||||
Expression::TupleAssignment(e) => write!(f, "{}", e),
|
||||
Expression::TupleDeclaration(e) => write!(f, "{}", e),
|
||||
Expression::Variable(id) => write!(f, "{}", id),
|
||||
Expression::While(e) => write!(f, "{}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -115,7 +115,7 @@ macro_rules! keyword {
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Hash, Eq, Clone, Logos)]
|
||||
#[logos(skip r"[ \t\f]+")]
|
||||
#[logos(skip r"[ \r\t\f]+")]
|
||||
#[logos(extras = Extras)]
|
||||
#[logos(error(LexError, LexError::from_lexer))]
|
||||
pub enum TokenType<'a> {
|
||||
@@ -843,3 +843,20 @@ documented! {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::TokenType;
|
||||
use logos::Logos;
|
||||
|
||||
#[test]
|
||||
fn test_windows_crlf_endings() -> anyhow::Result<()> {
|
||||
let src = "let i = 0;\r\n";
|
||||
|
||||
let lexer = TokenType::lexer(src);
|
||||
|
||||
let tokens = lexer.collect::<Vec<_>>();
|
||||
|
||||
assert!(!tokens.iter().any(|res| res.is_err()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user