Compare commits
10 Commits
0.4.6
...
8029fa82b0
| Author | SHA1 | Date | |
|---|---|---|---|
|
8029fa82b0
|
|||
|
6d8a22459c
|
|||
|
20f0f4b9a1
|
|||
|
5a88befac9
|
|||
|
e94fc0f5de
|
|||
|
b51800eb77
|
|||
|
87951ab12f
|
|||
|
00b0d4df26
|
|||
| 6ca53e8959 | |||
|
8dfdad3f34
|
@@ -1,5 +1,9 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
[0.4.7]
|
||||||
|
|
||||||
|
- Added support for Windows CRLF endings
|
||||||
|
|
||||||
[0.4.6]
|
[0.4.6]
|
||||||
|
|
||||||
- Fixed bug in compiler where you were unable to assign a `const` value to
|
- Fixed bug in compiler where you were unable to assign a `const` value to
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<ModMetadata xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
<ModMetadata xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||||
<Name>Slang</Name>
|
<Name>Slang</Name>
|
||||||
<Author>JoeDiertay</Author>
|
<Author>JoeDiertay</Author>
|
||||||
<Version>0.4.6</Version>
|
<Version>0.4.7</Version>
|
||||||
<Description>
|
<Description>
|
||||||
[h1]Slang: High-Level Programming for Stationeers[/h1]
|
[h1]Slang: High-Level Programming for Stationeers[/h1]
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ namespace Slang
|
|||||||
{
|
{
|
||||||
public const string PluginGuid = "com.biddydev.slang";
|
public const string PluginGuid = "com.biddydev.slang";
|
||||||
public const string PluginName = "Slang";
|
public const string PluginName = "Slang";
|
||||||
public const string PluginVersion = "0.4.6";
|
public const string PluginVersion = "0.4.7";
|
||||||
|
|
||||||
private static Harmony? _harmony;
|
private static Harmony? _harmony;
|
||||||
|
|
||||||
|
|||||||
2
rust_compiler/Cargo.lock
generated
2
rust_compiler/Cargo.lock
generated
@@ -930,7 +930,7 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "slang"
|
name = "slang"
|
||||||
version = "0.4.6"
|
version = "0.4.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "slang"
|
name = "slang"
|
||||||
version = "0.4.6"
|
version = "0.4.7"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
|
|||||||
@@ -47,3 +47,4 @@ mod logic_expression;
|
|||||||
mod loops;
|
mod loops;
|
||||||
mod math_syscall;
|
mod math_syscall;
|
||||||
mod syscall;
|
mod syscall;
|
||||||
|
mod tuple_literals;
|
||||||
|
|||||||
950
rust_compiler/libs/compiler/src/test/tuple_literals.rs
Normal file
950
rust_compiler/libs/compiler/src/test/tuple_literals.rs
Normal file
@@ -0,0 +1,950 @@
|
|||||||
|
#[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(expected_size, actual_count, _) => {
|
||||||
|
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::TupleSizeMismatch(_, _, _)
|
||||||
|
));
|
||||||
|
|
||||||
|
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);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
getValue:
|
||||||
|
pop r8
|
||||||
|
move r15 sp
|
||||||
|
push ra
|
||||||
|
beqz r8 __internal_L3
|
||||||
|
push 1
|
||||||
|
push 2
|
||||||
|
move r15 0
|
||||||
|
sub r0 sp 3
|
||||||
|
get ra db r0
|
||||||
|
j ra
|
||||||
|
sub sp sp 2
|
||||||
|
j __internal_L2
|
||||||
|
__internal_L3:
|
||||||
|
push 3
|
||||||
|
push 4
|
||||||
|
move r15 0
|
||||||
|
sub r0 sp 3
|
||||||
|
get ra db r0
|
||||||
|
j ra
|
||||||
|
sub sp sp 2
|
||||||
|
__internal_L2:
|
||||||
|
main:
|
||||||
|
push 1
|
||||||
|
jal getValue
|
||||||
|
pop r9
|
||||||
|
pop r8
|
||||||
|
move sp 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);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
add:
|
||||||
|
pop r8
|
||||||
|
pop r9
|
||||||
|
move r15 sp
|
||||||
|
push ra
|
||||||
|
push r9
|
||||||
|
push r8
|
||||||
|
move r15 1
|
||||||
|
sub r0 sp 3
|
||||||
|
get ra db r0
|
||||||
|
j ra
|
||||||
|
main:
|
||||||
|
push 5
|
||||||
|
push 10
|
||||||
|
jal add
|
||||||
|
pop r9
|
||||||
|
pop r8
|
||||||
|
move sp r15
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
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();
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
inner:
|
||||||
|
move r15 sp
|
||||||
|
push ra
|
||||||
|
push 1
|
||||||
|
push 2
|
||||||
|
move r15 1
|
||||||
|
sub r0 sp 3
|
||||||
|
get ra db r0
|
||||||
|
j ra
|
||||||
|
outer:
|
||||||
|
move r15 sp
|
||||||
|
push ra
|
||||||
|
jal inner
|
||||||
|
pop r9
|
||||||
|
pop r8
|
||||||
|
move sp r15
|
||||||
|
push r9
|
||||||
|
push r8
|
||||||
|
move r15 1
|
||||||
|
sub r0 sp 3
|
||||||
|
get ra db r0
|
||||||
|
j ra
|
||||||
|
main:
|
||||||
|
jal outer
|
||||||
|
pop r9
|
||||||
|
pop r8
|
||||||
|
move sp r15
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_literal_with_constant_expressions() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
let (a, b) = (1 + 2, 3 * 4);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
main:
|
||||||
|
move r8 3
|
||||||
|
move r9 12
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_literal_with_variable_expressions() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
let x = 5;
|
||||||
|
let y = 10;
|
||||||
|
let (a, b) = (x + 1, y * 2);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
main:
|
||||||
|
move r8 5
|
||||||
|
move r9 10
|
||||||
|
add r1 r8 1
|
||||||
|
move r10 r1
|
||||||
|
mul r2 r9 2
|
||||||
|
move r11 r2
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_assignment_with_expressions() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
let a = 0;
|
||||||
|
let b = 0;
|
||||||
|
let x = 5;
|
||||||
|
(a, b) = (x + 1, x * 2);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
main:
|
||||||
|
move r8 0
|
||||||
|
move r9 0
|
||||||
|
move r10 5
|
||||||
|
add r1 r10 1
|
||||||
|
move r8 r1
|
||||||
|
mul r2 r10 2
|
||||||
|
move r9 r2
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_literal_with_function_calls() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
fn getValue() { return 42; };
|
||||||
|
fn getOther() { return 99; };
|
||||||
|
|
||||||
|
let (a, b) = (getValue(), getOther());
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
getValue:
|
||||||
|
push ra
|
||||||
|
move r15 42
|
||||||
|
j __internal_L1
|
||||||
|
__internal_L1:
|
||||||
|
pop ra
|
||||||
|
j ra
|
||||||
|
getOther:
|
||||||
|
push ra
|
||||||
|
move r15 99
|
||||||
|
j __internal_L2
|
||||||
|
__internal_L2:
|
||||||
|
pop ra
|
||||||
|
j ra
|
||||||
|
main:
|
||||||
|
push r8
|
||||||
|
jal getValue
|
||||||
|
pop r8
|
||||||
|
move r1 r15
|
||||||
|
move r8 r1
|
||||||
|
push r8
|
||||||
|
push r9
|
||||||
|
jal getOther
|
||||||
|
pop r9
|
||||||
|
pop r8
|
||||||
|
move r2 r15
|
||||||
|
move r9 r2
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_with_logical_expressions() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
let x = 1;
|
||||||
|
let y = 0;
|
||||||
|
let (a, b) = (x && y, x || y);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
main:
|
||||||
|
move r8 1
|
||||||
|
move r9 0
|
||||||
|
and r1 r8 r9
|
||||||
|
move r10 r1
|
||||||
|
or r2 r8 r9
|
||||||
|
move r11 r2
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_with_comparison_expressions() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
let x = 5;
|
||||||
|
let y = 10;
|
||||||
|
let (a, b) = (x > y, x < y);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
main:
|
||||||
|
move r8 5
|
||||||
|
move r9 10
|
||||||
|
sgt r1 r8 r9
|
||||||
|
move r10 r1
|
||||||
|
slt r2 r8 r9
|
||||||
|
move r11 r2
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_with_device_property_access() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
device sensor = "d0";
|
||||||
|
device display = "d1";
|
||||||
|
|
||||||
|
let (temp, pressure) = (sensor.Temperature, sensor.Pressure);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
main:
|
||||||
|
l r1 d0 Temperature
|
||||||
|
move r8 r1
|
||||||
|
l r2 d0 Pressure
|
||||||
|
move r9 r2
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_with_device_property_and_function_call() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
device self = "db";
|
||||||
|
|
||||||
|
fn getY() {
|
||||||
|
return 42;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (x, y) = (self.Setting, getY());
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
getY:
|
||||||
|
push ra
|
||||||
|
move r15 42
|
||||||
|
j __internal_L1
|
||||||
|
__internal_L1:
|
||||||
|
pop ra
|
||||||
|
j ra
|
||||||
|
main:
|
||||||
|
l r1 db Setting
|
||||||
|
move r8 r1
|
||||||
|
push r8
|
||||||
|
push r9
|
||||||
|
jal getY
|
||||||
|
pop r9
|
||||||
|
pop r8
|
||||||
|
move r2 r15
|
||||||
|
move r9 r2
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_with_function_call_expressions() -> anyhow::Result<()> {
|
||||||
|
let compiled = compile!(
|
||||||
|
debug
|
||||||
|
r#"
|
||||||
|
fn getValue() { return 10; }
|
||||||
|
fn getOther() { return 20; }
|
||||||
|
|
||||||
|
let (a, b) = (getValue() + 5, getOther() * 2);
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
compiled,
|
||||||
|
indoc! {
|
||||||
|
"
|
||||||
|
j main
|
||||||
|
getValue:
|
||||||
|
push ra
|
||||||
|
move r15 10
|
||||||
|
j __internal_L1
|
||||||
|
__internal_L1:
|
||||||
|
pop ra
|
||||||
|
j ra
|
||||||
|
getOther:
|
||||||
|
push ra
|
||||||
|
move r15 20
|
||||||
|
j __internal_L2
|
||||||
|
__internal_L2:
|
||||||
|
pop ra
|
||||||
|
j ra
|
||||||
|
main:
|
||||||
|
push r8
|
||||||
|
jal getValue
|
||||||
|
pop r8
|
||||||
|
move r1 r15
|
||||||
|
add r2 r1 5
|
||||||
|
move r8 r2
|
||||||
|
push r8
|
||||||
|
push r9
|
||||||
|
jal getOther
|
||||||
|
pop r9
|
||||||
|
pop r8
|
||||||
|
move r3 r15
|
||||||
|
mul r4 r3 2
|
||||||
|
move r9 r4
|
||||||
|
"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,8 @@ use parser::{
|
|||||||
AssignmentExpression, BinaryExpression, BlockExpression, ConstDeclarationExpression,
|
AssignmentExpression, BinaryExpression, BlockExpression, ConstDeclarationExpression,
|
||||||
DeviceDeclarationExpression, Expression, FunctionExpression, IfExpression,
|
DeviceDeclarationExpression, Expression, FunctionExpression, IfExpression,
|
||||||
InvocationExpression, Literal, LiteralOr, LiteralOrVariable, LogicalExpression,
|
InvocationExpression, Literal, LiteralOr, LiteralOrVariable, LogicalExpression,
|
||||||
LoopExpression, MemberAccessExpression, Spanned, TernaryExpression, WhileExpression,
|
LoopExpression, MemberAccessExpression, Spanned, TernaryExpression,
|
||||||
|
TupleAssignmentExpression, TupleDeclarationExpression, WhileExpression,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use rust_decimal::Decimal;
|
use rust_decimal::Decimal;
|
||||||
@@ -63,6 +64,9 @@ pub enum Error<'a> {
|
|||||||
#[error("Attempted to re-assign a value to a device const `{0}`")]
|
#[error("Attempted to re-assign a value to a device const `{0}`")]
|
||||||
DeviceAssignment(Cow<'a, str>, Span),
|
DeviceAssignment(Cow<'a, str>, Span),
|
||||||
|
|
||||||
|
#[error("Expected a {0}-tuple, but you're trying to destructure into {1} variables")]
|
||||||
|
TupleSizeMismatch(usize, usize, Span),
|
||||||
|
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
Unknown(String, Option<Span>),
|
Unknown(String, Option<Span>),
|
||||||
}
|
}
|
||||||
@@ -84,7 +88,8 @@ impl<'a> From<Error<'a>> for lsp_types::Diagnostic {
|
|||||||
| InvalidDevice(_, span)
|
| InvalidDevice(_, span)
|
||||||
| ConstAssignment(_, span)
|
| ConstAssignment(_, span)
|
||||||
| DeviceAssignment(_, span)
|
| DeviceAssignment(_, span)
|
||||||
| AgrumentMismatch(_, span) => Diagnostic {
|
| AgrumentMismatch(_, span)
|
||||||
|
| TupleSizeMismatch(_, _, span) => Diagnostic {
|
||||||
range: span.into(),
|
range: span.into(),
|
||||||
message: value.to_string(),
|
message: value.to_string(),
|
||||||
severity: Some(DiagnosticSeverity::ERROR),
|
severity: Some(DiagnosticSeverity::ERROR),
|
||||||
@@ -142,6 +147,8 @@ pub struct Compiler<'a> {
|
|||||||
pub parser: ASTParser<'a>,
|
pub parser: ASTParser<'a>,
|
||||||
function_locations: HashMap<Cow<'a, str>, usize>,
|
function_locations: HashMap<Cow<'a, str>, usize>,
|
||||||
function_metadata: HashMap<Cow<'a, str>, Vec<Cow<'a, str>>>,
|
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>>,
|
devices: HashMap<Cow<'a, str>, Cow<'a, str>>,
|
||||||
|
|
||||||
// This holds the IL code which will be used in the
|
// This holds the IL code which will be used in the
|
||||||
@@ -155,6 +162,8 @@ pub struct Compiler<'a> {
|
|||||||
label_counter: usize,
|
label_counter: usize,
|
||||||
loop_stack: Vec<(Cow<'a, str>, Cow<'a, str>)>, // Stores (start_label, end_label)
|
loop_stack: Vec<(Cow<'a, str>, Cow<'a, str>)>, // Stores (start_label, end_label)
|
||||||
current_return_label: Option<Cow<'a, str>>,
|
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>`)
|
/// stores (IC10 `line_num`, `Vec<Span>`)
|
||||||
pub source_map: HashMap<usize, Vec<Span>>,
|
pub source_map: HashMap<usize, Vec<Span>>,
|
||||||
/// Accumulative errors from the compilation process
|
/// Accumulative errors from the compilation process
|
||||||
@@ -176,6 +185,10 @@ impl<'a> Compiler<'a> {
|
|||||||
label_counter: 0,
|
label_counter: 0,
|
||||||
loop_stack: Vec::new(),
|
loop_stack: Vec::new(),
|
||||||
current_return_label: None,
|
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(),
|
source_map: HashMap::new(),
|
||||||
errors: Vec::new(),
|
errors: Vec::new(),
|
||||||
}
|
}
|
||||||
@@ -465,6 +478,14 @@ impl<'a> Compiler<'a> {
|
|||||||
temp_name: Some(result_name),
|
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(
|
_ => Err(Error::Unknown(
|
||||||
format!(
|
format!(
|
||||||
"Expression type not yet supported in general expression context: {:?}",
|
"Expression type not yet supported in general expression context: {:?}",
|
||||||
@@ -932,6 +953,504 @@ impl<'a> Compiler<'a> {
|
|||||||
Ok(())
|
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(
|
||||||
|
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::TupleSizeMismatch(
|
||||||
|
names.len(),
|
||||||
|
tuple_elements.len(),
|
||||||
|
value.span,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compile each element and assign to corresponding variable
|
||||||
|
for (name_spanned, element) in names.into_iter().zip(tuple_elements.into_iter()) {
|
||||||
|
// 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 - use compile_operand to handle all expression types
|
||||||
|
let (value_operand, cleanup) = self.compile_operand(element, scope)?;
|
||||||
|
self.emit_variable_assignment(&var_location, value_operand)?;
|
||||||
|
|
||||||
|
// Clean up any temporary registers used for complex expressions
|
||||||
|
if let Some(temp_name) = cleanup {
|
||||||
|
scope.free_temp(temp_name, None)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
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(
|
||||||
|
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::TupleSizeMismatch(
|
||||||
|
tuple_elements.len(),
|
||||||
|
names.len(),
|
||||||
|
value.span,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compile each element and assign to corresponding variable
|
||||||
|
for (name_spanned, element) in names.into_iter().zip(tuple_elements.into_iter()) {
|
||||||
|
// 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 - use compile_operand to handle all expression types
|
||||||
|
let (value_operand, cleanup) = self.compile_operand(element, scope)?;
|
||||||
|
|
||||||
|
// Assign the compiled value to the target variable location
|
||||||
|
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,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up any temporary registers used for complex expressions
|
||||||
|
if let Some(temp_name) = cleanup {
|
||||||
|
scope.free_temp(temp_name, None)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
return Err(Error::Unknown(
|
||||||
|
"Tuple assignment only supports function invocations or tuple literals as RHS"
|
||||||
|
.into(),
|
||||||
|
Some(value.span),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn expression_function_invocation(
|
fn expression_function_invocation(
|
||||||
&mut self,
|
&mut self,
|
||||||
invoke_expr: Spanned<InvocationExpression<'a>>,
|
invoke_expr: Spanned<InvocationExpression<'a>>,
|
||||||
@@ -1946,6 +2465,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(
|
return Err(Error::Unknown(
|
||||||
format!("Unsupported `return` statement: {:?}", expr),
|
format!("Unsupported `return` statement: {:?}", expr),
|
||||||
@@ -2574,6 +3256,78 @@ 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Expression::If(if_expr) => {
|
||||||
|
// Check the then block
|
||||||
|
if Self::has_tuple_return(&if_expr.node.body.node) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Check the else branch if it exists
|
||||||
|
if let Some(else_branch) = &if_expr.node.else_branch {
|
||||||
|
match &else_branch.node {
|
||||||
|
Expression::Block(block) => {
|
||||||
|
if Self::has_tuple_return(block) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Expression::If(_) => {
|
||||||
|
// Handle else-if chains
|
||||||
|
if Self::has_tuple_return_in_expr(else_branch) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Expression::While(while_expr) => {
|
||||||
|
if Self::has_tuple_return(&while_expr.node.body) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Expression::Loop(loop_expr) => {
|
||||||
|
if Self::has_tuple_return(&loop_expr.node.body.node) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Expression::Block(block) => {
|
||||||
|
if Self::has_tuple_return(block) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper to check for tuple returns in any expression
|
||||||
|
fn has_tuple_return_in_expr(expr: &Spanned<Expression>) -> bool {
|
||||||
|
match &expr.node {
|
||||||
|
Expression::Block(block) => Self::has_tuple_return(block),
|
||||||
|
Expression::If(if_expr) => {
|
||||||
|
if Self::has_tuple_return(&if_expr.node.body.node) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if let Some(else_branch) = &if_expr.node.else_branch {
|
||||||
|
return Self::has_tuple_return_in_expr(else_branch);
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Expression::While(while_expr) => Self::has_tuple_return(&while_expr.node.body),
|
||||||
|
Expression::Loop(loop_expr) => Self::has_tuple_return(&loop_expr.node.body.node),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Compile a function declaration.
|
/// Compile a function declaration.
|
||||||
/// Calees are responsible for backing up any registers they wish to use.
|
/// Calees are responsible for backing up any registers they wish to use.
|
||||||
fn expression_function(
|
fn expression_function(
|
||||||
@@ -2601,6 +3355,9 @@ impl<'a> Compiler<'a> {
|
|||||||
arguments.iter().map(|a| a.node.clone()).collect(),
|
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
|
// Declare the function as a line identifier
|
||||||
self.write_instruction(Instruction::LabelDef(name.node.clone()), Some(span))?;
|
self.write_instruction(Instruction::LabelDef(name.node.clone()), Some(span))?;
|
||||||
|
|
||||||
@@ -2662,6 +3419,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))?;
|
self.write_instruction(Instruction::Push(Operand::ReturnAddress), Some(span))?;
|
||||||
|
|
||||||
let return_label = self.next_label_name();
|
let return_label = self.next_label_name();
|
||||||
@@ -2715,6 +3484,9 @@ impl<'a> Compiler<'a> {
|
|||||||
|
|
||||||
self.current_return_label = prev_return_label;
|
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))?;
|
self.write_instruction(Instruction::LabelDef(return_label.clone()), Some(span))?;
|
||||||
|
|
||||||
if ra_stack_offset == 1 {
|
if ra_stack_offset == 1 {
|
||||||
@@ -2763,6 +3535,12 @@ impl<'a> Compiler<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.write_instruction(Instruction::Jump(Operand::ReturnAddress), Some(span))?;
|
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(())
|
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) => {
|
TokenType::Keyword(Keyword::Device) => {
|
||||||
let spanned_dev = self.spanned(|p| p.device())?;
|
let spanned_dev = self.spanned(|p| p.device())?;
|
||||||
@@ -561,9 +567,7 @@ impl<'a> Parser<'a> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
TokenType::Symbol(Symbol::LParen) => {
|
TokenType::Symbol(Symbol::LParen) => self.parenthesized_or_tuple()?,
|
||||||
self.spanned(|p| p.priority())?.node.map(|node| *node)
|
|
||||||
}
|
|
||||||
|
|
||||||
TokenType::Symbol(Symbol::Minus) => {
|
TokenType::Symbol(Symbol::Minus) => {
|
||||||
let start_span = self.current_span();
|
let start_span = self.current_span();
|
||||||
@@ -642,8 +646,8 @@ impl<'a> Parser<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
TokenType::Symbol(Symbol::LParen) => *self
|
TokenType::Symbol(Symbol::LParen) => *self
|
||||||
.spanned(|p| p.priority())?
|
.parenthesized_or_tuple()?
|
||||||
.node
|
.map(Box::new)
|
||||||
.ok_or(Error::UnexpectedEOF)?,
|
.ok_or(Error::UnexpectedEOF)?,
|
||||||
|
|
||||||
TokenType::Identifier(ref id) if SysCall::is_syscall(id) => {
|
TokenType::Identifier(ref id) if SysCall::is_syscall(id) => {
|
||||||
@@ -774,7 +778,8 @@ impl<'a> Parser<'a> {
|
|||||||
| Expression::Ternary(_)
|
| Expression::Ternary(_)
|
||||||
| Expression::Negation(_)
|
| Expression::Negation(_)
|
||||||
| Expression::MemberAccess(_)
|
| Expression::MemberAccess(_)
|
||||||
| Expression::MethodCall(_) => {}
|
| Expression::MethodCall(_)
|
||||||
|
| Expression::Tuple(_) => {}
|
||||||
_ => {
|
_ => {
|
||||||
return Err(Error::InvalidSyntax(
|
return Err(Error::InvalidSyntax(
|
||||||
self.current_span(),
|
self.current_span(),
|
||||||
@@ -1081,19 +1086,39 @@ impl<'a> Parser<'a> {
|
|||||||
end_col: right.span.end_col,
|
end_col: right.span.end_col,
|
||||||
};
|
};
|
||||||
|
|
||||||
expressions.insert(
|
// Check if the left side is a tuple, and if so, create a TupleAssignment
|
||||||
i,
|
let node = if let Expression::Tuple(tuple_expr) = &left.node {
|
||||||
Spanned {
|
// 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,
|
span,
|
||||||
node: Expression::Assignment(Spanned {
|
node: TupleAssignmentExpression {
|
||||||
|
names,
|
||||||
|
value: boxed!(right),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Expression::Assignment(Spanned {
|
||||||
span,
|
span,
|
||||||
node: AssignmentExpression {
|
node: AssignmentExpression {
|
||||||
assignee: boxed!(left),
|
assignee: boxed!(left),
|
||||||
expression: boxed!(right),
|
expression: boxed!(right),
|
||||||
},
|
},
|
||||||
}),
|
})
|
||||||
},
|
};
|
||||||
);
|
|
||||||
|
expressions.insert(i, Spanned { span, node });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
operators.retain(|symbol| !matches!(symbol, Symbol::Assign));
|
operators.retain(|symbol| !matches!(symbol, Symbol::Assign));
|
||||||
@@ -1117,8 +1142,12 @@ impl<'a> Parser<'a> {
|
|||||||
expressions.pop().ok_or(Error::UnexpectedEOF)
|
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)?;
|
let current_token = self.current_token.as_ref().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
if !token_matches!(current_token, TokenType::Symbol(Symbol::LParen)) {
|
if !token_matches!(current_token, TokenType::Symbol(Symbol::LParen)) {
|
||||||
return Err(Error::UnexpectedToken(
|
return Err(Error::UnexpectedToken(
|
||||||
self.current_span(),
|
self.current_span(),
|
||||||
@@ -1127,17 +1156,112 @@ impl<'a> Parser<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.assign_next()?;
|
self.assign_next()?;
|
||||||
let expression = self.expression()?.ok_or(Error::UnexpectedEOF)?;
|
|
||||||
|
|
||||||
let current_token = self.get_next()?.ok_or(Error::UnexpectedEOF)?;
|
// Handle empty tuple '()'
|
||||||
if !token_matches!(current_token, TokenType::Symbol(Symbol::RParen)) {
|
if self_matches_peek!(self, TokenType::Symbol(Symbol::RParen)) {
|
||||||
return Err(Error::UnexpectedToken(
|
self.assign_next()?;
|
||||||
Self::token_to_span(¤t_token),
|
let end_span = self.current_span();
|
||||||
current_token,
|
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()?;
|
||||||
|
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>> {
|
fn invocation(&mut self) -> Result<InvocationExpression<'a>, Error<'a>> {
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ fn test_function_invocation() -> Result<()> {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_priority_expression() -> Result<()> {
|
fn test_priority_expression() -> Result<()> {
|
||||||
let input = r#"
|
let input = r#"
|
||||||
let x = (4);
|
let x = (4 + 3);
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
let tokenizer = Tokenizer::from(input);
|
let tokenizer = Tokenizer::from(input);
|
||||||
@@ -120,7 +120,7 @@ fn test_priority_expression() -> Result<()> {
|
|||||||
|
|
||||||
let expression = parser.parse()?.unwrap();
|
let expression = parser.parse()?.unwrap();
|
||||||
|
|
||||||
assert_eq!("(let x = 4)", expression.to_string());
|
assert_eq!("(let x = ((4 + 3)))", expression.to_string());
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -137,7 +137,7 @@ fn test_binary_expression() -> Result<()> {
|
|||||||
assert_eq!("(((45 * 2) - (15 / 5)) + (5 ** 2))", expr.to_string());
|
assert_eq!("(((45 * 2) - (15 / 5)) + (5 ** 2))", expr.to_string());
|
||||||
|
|
||||||
let expr = parser!("(5 - 2) * 10;").parse()?.unwrap();
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -170,7 +170,7 @@ fn test_ternary_expression() -> Result<()> {
|
|||||||
fn test_complex_binary_with_ternary() -> Result<()> {
|
fn test_complex_binary_with_ternary() -> Result<()> {
|
||||||
let expr = parser!("let i = (x ? 1 : 3) * 2;").parse()?.unwrap();
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -191,3 +191,99 @@ fn test_nested_ternary_right_associativity() -> Result<()> {
|
|||||||
assert_eq!("(let i = (a ? b : (c ? d : e)))", expr.to_string());
|
assert_eq!("(let i = (a ? b : (c ? d : e)))", expr.to_string());
|
||||||
Ok(())
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_declaration_with_complex_expressions() -> Result<()> {
|
||||||
|
let expr = parser!("let (x, y) = (1 + 1, doSomething());")
|
||||||
|
.parse()?
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!("(let (x, y) = ((1 + 1), doSomething()))", expr.to_string());
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_assignment_with_complex_expressions() -> Result<()> {
|
||||||
|
let expr = parser!("(x, y) = (doSomething(), 123 / someValue.Setting);")
|
||||||
|
.parse()?
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
"((x, y) = (doSomething(), (123 / someValue.Setting)))",
|
||||||
|
expr.to_string()
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_tuple_declaration_all_complex_expressions() -> Result<()> {
|
||||||
|
let expr = parser!("let (x, y) = (a + b, c * d);").parse()?.unwrap();
|
||||||
|
|
||||||
|
assert_eq!("(let (x, y) = ((a + b), (c * d)))", 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)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
pub struct IfExpression<'a> {
|
pub struct IfExpression<'a> {
|
||||||
pub condition: Box<Spanned<Expression<'a>>>,
|
pub condition: Box<Spanned<Expression<'a>>>,
|
||||||
@@ -348,6 +384,9 @@ pub enum Expression<'a> {
|
|||||||
Return(Option<Box<Spanned<Expression<'a>>>>),
|
Return(Option<Box<Spanned<Expression<'a>>>>),
|
||||||
Syscall(Spanned<SysCall<'a>>),
|
Syscall(Spanned<SysCall<'a>>),
|
||||||
Ternary(Spanned<TernaryExpression<'a>>),
|
Ternary(Spanned<TernaryExpression<'a>>),
|
||||||
|
Tuple(Spanned<Vec<Spanned<Expression<'a>>>>),
|
||||||
|
TupleAssignment(Spanned<TupleAssignmentExpression<'a>>),
|
||||||
|
TupleDeclaration(Spanned<TupleDeclarationExpression<'a>>),
|
||||||
Variable(Spanned<Cow<'a, str>>),
|
Variable(Spanned<Cow<'a, str>>),
|
||||||
While(Spanned<WhileExpression<'a>>),
|
While(Spanned<WhileExpression<'a>>),
|
||||||
}
|
}
|
||||||
@@ -384,8 +423,20 @@ impl<'a> std::fmt::Display for Expression<'a> {
|
|||||||
),
|
),
|
||||||
Expression::Syscall(e) => write!(f, "{}", e),
|
Expression::Syscall(e) => write!(f, "{}", e),
|
||||||
Expression::Ternary(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::Variable(id) => write!(f, "{}", id),
|
||||||
Expression::While(e) => write!(f, "{}", e),
|
Expression::While(e) => write!(f, "{}", e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ macro_rules! keyword {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Hash, Eq, Clone, Logos)]
|
#[derive(Debug, PartialEq, Hash, Eq, Clone, Logos)]
|
||||||
#[logos(skip r"[ \t\f]+")]
|
#[logos(skip r"[ \r\t\f]+")]
|
||||||
#[logos(extras = Extras)]
|
#[logos(extras = Extras)]
|
||||||
#[logos(error(LexError, LexError::from_lexer))]
|
#[logos(error(LexError, LexError::from_lexer))]
|
||||||
pub enum TokenType<'a> {
|
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