From c3adcf57f5300d746bd61dcd227c3bd1c65e092d Mon Sep 17 00:00:00 2001 From: Devin Bidwell Date: Sat, 22 Nov 2025 23:02:49 -0700 Subject: [PATCH] More support for negative numbers --- .../test/declaration_function_invocation.rs | 36 ++++++++++++++++++- libs/compiler/src/v2.rs | 17 ++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/libs/compiler/src/test/declaration_function_invocation.rs b/libs/compiler/src/test/declaration_function_invocation.rs index 8be25cb..788bb5f 100644 --- a/libs/compiler/src/test/declaration_function_invocation.rs +++ b/libs/compiler/src/test/declaration_function_invocation.rs @@ -192,7 +192,7 @@ fn with_return_statement() -> anyhow::Result<()> { doSomething: pop r8 #arg1 push ra - move r15 456 + move r15 456 #returnValue sub r0 sp 1 get ra db r0 sub sp sp 1 @@ -207,3 +207,37 @@ fn with_return_statement() -> anyhow::Result<()> { Ok(()) } + +#[test] +fn with_negative_return_literal() -> anyhow::Result<()> { + let compiled = compile! { + debug + " + fn doSomething() { + return -1; + }; + let i = doSomething(); + " + }; + + assert_eq!( + compiled, + indoc! { + " + j main + doSomething: + push ra + move r15 -1 #returnValue + sub r0 sp 1 + get ra db r0 + sub sp sp 1 + j ra + main: + jal doSomething + move r8 r15 #i + " + } + ); + + Ok(()) +} diff --git a/libs/compiler/src/v2.rs b/libs/compiler/src/v2.rs index 979319f..c19c203 100644 --- a/libs/compiler/src/v2.rs +++ b/libs/compiler/src/v2.rs @@ -327,6 +327,17 @@ impl<'a, W: std::io::Write> Compiler<'a, W> { expr: Expression, scope: &mut VariableScope<'v>, ) -> Result<(), Error> { + if let Expression::Negation(neg_expr) = &expr + && let Expression::Literal(Literal::Number(neg_num)) = &**neg_expr + { + self.emit_variable_assignment( + "returnValue", + VariableLocation::Persistant(VariableScope::RETURN_REGISTER), + format!("-{neg_num}"), + )?; + return Ok(()); + }; + match expr { Expression::Variable(var_name) => match scope.get_location_of(var_name)? { VariableLocation::Temporary(reg) | VariableLocation::Persistant(reg) => { @@ -349,7 +360,11 @@ impl<'a, W: std::io::Write> Compiler<'a, W> { } }, Expression::Literal(Literal::Number(num)) => { - self.write_output(format!("move r{} {}", VariableScope::RETURN_REGISTER, num))?; + self.emit_variable_assignment( + "returnValue", + VariableLocation::Persistant(VariableScope::RETURN_REGISTER), + num, + )?; } _ => return Err(Error::Unknown("Unsupported `return` statement.".into())), }