diff --git a/ModData/About/About.xml b/ModData/About/About.xml
new file mode 100644
index 0000000..464e823
--- /dev/null
+++ b/ModData/About/About.xml
@@ -0,0 +1,70 @@
+
+
+ StationeersSlang
+ JoeDiertay
+ 0.1.0
+
+ Slang (Stationeers Language) is a high-level programming language that compiles directly into IC10 within the game.
+
+ Features:
+ - In-Game Compilation: Write C-style code directly in the IC editor.
+ - Automatic Register Management: Define variables with 'let' (e.g., let x = 10) without managing r0-r15.
+ - Standard Control Flow: Use if/else, while, loop, break, and continue.
+ - Functions: Define and call functions with arguments.
+ - Smart Editor: Real-time syntax highlighting and error checking (red text for errors).
+ - Persistent Source: Your high-level source code is saved inside the chip data, so you can edit it later.
+ - Constant Folding: Mathematical operations on constants are calculated at compile time to save instructions.
+ - Device Aliasing: Easy device mapping (e.g., device sensor = "d0").
+
+ Installation:
+ This is a StationeersLaunchPad Plugin Mod. It requires BepInEx to be installed.
+
+ Usage:
+ 1. Open any IC10 housing or editor.
+ 2. Write Slang code.
+ 3. Press Confirm to compile and run.
+
+
+ Logic
+ Scripting
+ Code
+ BepInEx
+ StationeersLaunchPad
+ Quality of Life
+
+ Slang - High Level Language Compiler
+ A modern programming experience for Stationeers. Write C-style code that compiles to MIPS assembly instantly.
+
+ Features
+ - In-Game Compilation: Write high-level logic directly in the chip editor.
+ - Automatic Registers: Stop juggling r0-r15. Just use let variables.
+ - Control Flow: Full support for if, else, while, and loop.
+ - Smart Editor: Integrated syntax highlighting and real-time error checking.
+ - Persistent Code: Your Slang source code is saved with the chip, so you never lose your work.
+ - Optimization: The compiler automatically optimizes constant math (e.g., 1 + 2 becomes 3).
+
+ Example Code
+ device sensor = "d0";
+ const MAX_TEMP = 300k;
+
+ loop {
+ let temp = sensor.Temperature;
+ if (temp > MAX_TEMP) {
+ // Do logic here
+ }
+ yield();
+ }
+
+ Installation
+ This is a StationeersLaunchPad Plugin Mod. It requires BepInEx to be installed.
+ See: https://github.com/StationeersLaunchPad/StationeersLaunchPad
+
+ Source Code: https://github.com/dbidwell94/stationeers_lang
+ ]]>
+
+
+ IC10Editor
+
+ IC10Editor
+
diff --git a/ModData/About/Preview.png b/ModData/About/Preview.png
new file mode 100644
index 0000000..252edb7
Binary files /dev/null and b/ModData/About/Preview.png differ
diff --git a/ModData/About/thumb.png b/ModData/About/thumb.png
new file mode 100644
index 0000000..252edb7
Binary files /dev/null and b/ModData/About/thumb.png differ
diff --git a/ModData/Bepinex b/ModData/Bepinex
new file mode 100644
index 0000000..e69de29
diff --git a/build.sh b/build.sh
index f0e2866..3f0e9a7 100755
--- a/build.sh
+++ b/build.sh
@@ -5,6 +5,7 @@ set -e
RUST_DIR="rust_compiler"
CSHARP_DIR="csharp_mod"
RELEASE_DIR="release"
+METADATA_DIR="ModData"
export RUSTFLAGS="--remap-path-prefix=${PWD}=. --remap-path-prefix=${HOME}/.cargo=~/.cargo"
@@ -39,9 +40,13 @@ echo "--------------------"
RUST_WIN_EXE="$RUST_DIR/target/x86_64-pc-windows-gnu/release/slang.exe"
RUST_WIN_DLL="$RUST_DIR/target/x86_64-pc-windows-gnu/release/slang.dll"
RUST_LINUX_BIN="$RUST_DIR/target/x86_64-unknown-linux-gnu/release/slang"
-CHARP_DLL="$CSHARP_DIR/bin/Release/net48/StationeersSlang.dll"
+CSHARP_DLL="$CSHARP_DIR/bin/Release/net48/StationeersSlang.dll"
+
+# Remove the release directory if it exists so we have a fresh build dir
+if [[ -d "$RELEASE_DIR" ]]; then
+ rm -rd "$RELEASE_DIR"
+fi
-# Check if the release dir exists, if not: create it.
if [[ ! -d "$RELEASE_DIR" ]]; then
mkdir "$RELEASE_DIR"
fi
@@ -51,6 +56,9 @@ cp "$RUST_WIN_EXE" "$RELEASE_DIR/slang.exe"
# This is the linux executable
cp "$RUST_LINUX_BIN" "$RELEASE_DIR/slang"
# This is the DLL mod itself
-cp "$CHARP_DLL" "$RELEASE_DIR/StationeersSlang.dll"
+cp "$CSHARP_DLL" "$RELEASE_DIR/StationeersSlang.dll"
# This is the rust-only compiler for use in injecting into the mod
cp "$RUST_WIN_DLL" "$RELEASE_DIR/rust_slang.dll"
+# This is the whole bundled workshop release version of the mod
+cp -r "$METADATA_DIR" "$RELEASE_DIR/workshop"
+cp "$CSHARP_DLL" "$RELEASE_DIR/workshop/StationeersSlang.dll"
diff --git a/csharp_mod/Formatter.cs b/csharp_mod/Formatter.cs
index 18ece90..24d0152 100644
--- a/csharp_mod/Formatter.cs
+++ b/csharp_mod/Formatter.cs
@@ -72,8 +72,6 @@ public class SlangFormatter : ICodeFormatter
public override StyledLine ParseLine(string line)
{
- L.Debug($"Parsing line for syntax highlighting: {line}");
-
// We create the line first
var styledLine = new StyledLine(line);
@@ -83,7 +81,6 @@ public class SlangFormatter : ICodeFormatter
// We call update to create the basic tokens
styledLine.Update(tokens);
- // CRITICAL FIX: We must manually re-attach metadata because StyledLine.Update() drops it.
ReattachMetadata(styledLine, tokens);
return styledLine;
@@ -170,34 +167,35 @@ public class SlangFormatter : ICodeFormatter
if (line is null)
continue;
- // 1. Get base syntax tokens
- var allTokens = Marshal.TokenizeLine(line.Text);
+ // 1. Get base syntax tokens, converting to a dictionary for ease in deduping error tokens
+ var allTokensDict = Marshal.TokenizeLine(line.Text).ToDictionary((k) => k.Column);
- // 2. Overlay error tokens if diagnostics exist for this line
+ // 2. Replace valid tokens with error tokens if present
if (dict.ContainsKey(lineIndex))
{
foreach (var lineDiagnostic in dict[lineIndex])
{
- allTokens.Add(
- new SemanticToken(
- line: (int)lineIndex,
- column: Math.Abs((int)lineDiagnostic.Range.StartCol),
- length: Math.Abs(
- (int)(lineDiagnostic.Range.EndCol - lineDiagnostic.Range.StartCol)
- ),
- type: 0,
- style: ICodeFormatter.ColorError,
- data: lineDiagnostic.Message,
- isError: true
- )
+ var column = Math.Abs((int)lineDiagnostic.Range.StartCol);
+
+ allTokensDict[column] = new SemanticToken(
+ line: (int)lineIndex,
+ column,
+ length: Math.Abs(
+ (int)(lineDiagnostic.Range.EndCol - lineDiagnostic.Range.StartCol)
+ ),
+ type: 0,
+ style: ICodeFormatter.ColorError,
+ data: lineDiagnostic.Message,
+ isError: true
);
}
}
+ var allTokens = allTokensDict.Values.ToList();
+
// 3. Update the line (this clears existing tokens and uses the list we just built)
line.Update(allTokens);
- // 4. CRITICAL FIX: Re-attach metadata that Update() dropped
ReattachMetadata(line, allTokens);
}
diff --git a/csharp_mod/Marshal.cs b/csharp_mod/Marshal.cs
index b03696f..1163b74 100644
--- a/csharp_mod/Marshal.cs
+++ b/csharp_mod/Marshal.cs
@@ -147,7 +147,6 @@ public static class Marshal
};
var tokens = Ffi.tokenize_line(strRef);
- L.Debug($"Tokenized line '{inputString}' into {tokens.len} tokens.");
return tokens.ToTokenList();
}
}
diff --git a/rust_compiler/libs/compiler/src/test/math_syscall.rs b/rust_compiler/libs/compiler/src/test/math_syscall.rs
new file mode 100644
index 0000000..966a1e3
--- /dev/null
+++ b/rust_compiler/libs/compiler/src/test/math_syscall.rs
@@ -0,0 +1,388 @@
+use crate::compile;
+use anyhow::Result;
+use indoc::indoc;
+use pretty_assertions::assert_eq;
+
+#[test]
+fn test_acos() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = acos(123);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ acos r15 123
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_asin() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = asin(123);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ asin r15 123
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_atan() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = atan(123);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ atan r15 123
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_atan2() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = atan2(123, 456);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ atan2 r15 123 456
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_abs() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = abs(-123);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ abs r15 -123
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_ceil() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = ceil(123.90);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ ceil r15 123.90
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_cos() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = cos(123);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ cos r15 123
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_floor() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = floor(123);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ floor r15 123
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_log() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = log(123);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ log r15 123
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_max() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = max(123, 456);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ max r15 123 456
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_min() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = min(123, 456);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ min r15 123 456
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_rand() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = rand();
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ rand r15
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_sin() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = sin(3);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ sin r15 3
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_sqrt() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = sqrt(3);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ sqrt r15 3
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_tan() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = tan(3);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ tan r15 3
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
+
+#[test]
+fn test_trunc() -> Result<()> {
+ let compiled = compile! {
+ debug
+ "
+ let i = trunc(3.234);
+ "
+ };
+
+ assert_eq!(
+ compiled,
+ indoc! {
+ "
+ j main
+ main:
+ trunc r15 3.234
+ move r8 r15 #i
+ "
+ }
+ );
+
+ Ok(())
+}
diff --git a/rust_compiler/libs/compiler/src/test/mod.rs b/rust_compiler/libs/compiler/src/test/mod.rs
index 0c8aac1..b3e51c2 100644
--- a/rust_compiler/libs/compiler/src/test/mod.rs
+++ b/rust_compiler/libs/compiler/src/test/mod.rs
@@ -47,4 +47,5 @@ mod declaration_literal;
mod function_declaration;
mod logic_expression;
mod loops;
+mod math_syscall;
mod syscall;
diff --git a/rust_compiler/libs/compiler/src/v1.rs b/rust_compiler/libs/compiler/src/v1.rs
index 7b4dffa..005b95f 100644
--- a/rust_compiler/libs/compiler/src/v1.rs
+++ b/rust_compiler/libs/compiler/src/v1.rs
@@ -3,7 +3,7 @@ use crate::variable_manager::{self, LocationRequest, VariableLocation, VariableS
use helpers::prelude::*;
use parser::{
Parser as ASTParser,
- sys_call::{SysCall, System},
+ sys_call::{Math, SysCall, System},
tree_node::{
AssignmentExpression, BinaryExpression, BlockExpression, ConstDeclarationExpression,
DeviceDeclarationExpression, Expression, FunctionExpression, IfExpression,
@@ -97,12 +97,7 @@ impl From for lsp_types::Diagnostic {
severity: Some(DiagnosticSeverity::ERROR),
..Default::default()
},
- ScopeError(e) => Diagnostic {
- message: e.to_string(),
- range: Range::default(),
- severity: Some(DiagnosticSeverity::ERROR),
- ..Default::default()
- },
+ ScopeError(e) => e.into(),
DuplicateIdentifier(_, span)
| UnknownIdentifier(_, span)
| InvalidDevice(_, span)
@@ -271,6 +266,10 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
node: SysCall::System(system),
span,
}) => self.expression_syscall_system(system, span, scope),
+ Expression::Syscall(Spanned {
+ node: SysCall::Math(math),
+ ..
+ }) => self.expression_syscall_math(math, scope),
Expression::While(expr_while) => {
self.expression_while(expr_while.node, scope)?;
Ok(None)
@@ -284,7 +283,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
Ok(None)
}
Expression::DeviceDeclaration(expr_dev) => {
- self.expression_device(expr_dev.node, expr_dev.span)?;
+ self.expression_device(expr_dev.node)?;
Ok(None)
}
Expression::Declaration(var_name, decl_expr) => {
@@ -304,7 +303,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Invocation returns result in r15 (RETURN_REGISTER).
// If used as an expression, we must move it to a temp to avoid overwrite.
let temp_name = self.next_temp_name();
- let temp_loc = scope.add_variable(&temp_name, LocationRequest::Temp)?;
+ let temp_loc = scope.add_variable(&temp_name, LocationRequest::Temp, None)?;
self.emit_variable_assignment(
&temp_name,
&temp_loc,
@@ -326,7 +325,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
Expression::Literal(spanned_lit) => match spanned_lit.node {
Literal::Number(num) => {
let temp_name = self.next_temp_name();
- let loc = scope.add_variable(&temp_name, LocationRequest::Temp)?;
+ let loc = scope.add_variable(&temp_name, LocationRequest::Temp, None)?;
self.emit_variable_assignment(&temp_name, &loc, num.to_string())?;
Ok(Some(CompilationResult {
location: loc,
@@ -336,7 +335,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
Literal::Boolean(b) => {
let val = if b { "1" } else { "0" };
let temp_name = self.next_temp_name();
- let loc = scope.add_variable(&temp_name, LocationRequest::Temp)?;
+ let loc = scope.add_variable(&temp_name, LocationRequest::Temp, None)?;
self.emit_variable_assignment(&temp_name, &loc, val)?;
Ok(Some(CompilationResult {
location: loc,
@@ -346,7 +345,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
_ => Ok(None), // String literals don't return values in this context typically
},
Expression::Variable(name) => {
- match scope.get_location_of(&name.node) {
+ match scope.get_location_of(&name.node, Some(name.span)) {
Ok(loc) => Ok(Some(CompilationResult {
location: loc,
temp_name: None, // User variable, do not free
@@ -378,7 +377,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// 2. Allocate a temp register for the result
let result_name = self.next_temp_name();
- let loc = scope.add_variable(&result_name, LocationRequest::Temp)?;
+ let loc = scope.add_variable(&result_name, LocationRequest::Temp, None)?;
let reg = self.resolve_register(&loc)?;
// 3. Emit load instruction: l rX device member
@@ -386,7 +385,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// 4. Cleanup
if let Some(c) = cleanup {
- scope.free_temp(c)?;
+ scope.free_temp(c, None)?;
}
Ok(Some(CompilationResult {
@@ -410,13 +409,13 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Compile negation as 0 - inner
let (inner_str, cleanup) = self.compile_operand(*inner_expr, scope)?;
let result_name = self.next_temp_name();
- let result_loc = scope.add_variable(&result_name, LocationRequest::Temp)?;
+ let result_loc = scope.add_variable(&result_name, LocationRequest::Temp, None)?;
let result_reg = self.resolve_register(&result_loc)?;
self.write_output(format!("sub {result_reg} 0 {inner_str}"))?;
if let Some(name) = cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
Ok(Some(CompilationResult {
@@ -506,7 +505,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
&& let Expression::Literal(spanned_lit) = &box_expr.node
&& let Literal::Number(neg_num) = &spanned_lit.node
{
- let loc = scope.add_variable(&name_str, LocationRequest::Persist)?;
+ let loc = scope.add_variable(&name_str, LocationRequest::Persist, Some(name_span))?;
self.emit_variable_assignment(&name_str, &loc, format!("-{neg_num}"))?;
return Ok(Some(CompilationResult {
location: loc,
@@ -517,16 +516,22 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
let (loc, temp_name) = match expr.node {
Expression::Literal(spanned_lit) => match spanned_lit.node {
Literal::Number(num) => {
- let var_location =
- scope.add_variable(name_str.clone(), LocationRequest::Persist)?;
+ let var_location = scope.add_variable(
+ name_str.clone(),
+ LocationRequest::Persist,
+ Some(name_span),
+ )?;
self.emit_variable_assignment(&name_str, &var_location, num)?;
(var_location, None)
}
Literal::Boolean(b) => {
let val = if b { "1" } else { "0" };
- let var_location =
- scope.add_variable(name_str.clone(), LocationRequest::Persist)?;
+ let var_location = scope.add_variable(
+ name_str.clone(),
+ LocationRequest::Persist,
+ Some(name_span),
+ )?;
self.emit_variable_assignment(&name_str, &var_location, val)?;
(var_location, None)
@@ -536,7 +541,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
Expression::Invocation(invoke_expr) => {
self.expression_function_invocation(invoke_expr, scope)?;
- let loc = scope.add_variable(&name_str, LocationRequest::Persist)?;
+ let loc =
+ scope.add_variable(&name_str, LocationRequest::Persist, Some(name_span))?;
self.emit_variable_assignment(
&name_str,
&loc,
@@ -546,26 +552,22 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
}
Expression::Syscall(spanned_call) => {
let sys_call = spanned_call.node;
- let SysCall::System(call) = sys_call else {
- // Math syscalls might be handled differently or here
- // For now assuming System returns value
- return Err(Error::Unknown(
- "Math syscall not yet supported in declaration".into(),
- Some(spanned_call.span),
- ));
+ let res = match sys_call {
+ SysCall::System(s) => {
+ self.expression_syscall_system(s, spanned_call.span, scope)?
+ }
+ SysCall::Math(m) => self.expression_syscall_math(m, scope)?,
};
- if self
- .expression_syscall_system(call, spanned_call.span, scope)?
- .is_none()
- {
+ if res.is_none() {
return Err(Error::Unknown(
"SysCall did not return a value".into(),
Some(spanned_call.span),
));
};
- let loc = scope.add_variable(&name_str, LocationRequest::Persist)?;
+ let loc =
+ scope.add_variable(&name_str, LocationRequest::Persist, Some(name_span))?;
self.emit_variable_assignment(
&name_str,
&loc,
@@ -577,7 +579,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Support assigning binary expressions to variables directly
Expression::Binary(bin_expr) => {
let result = self.expression_binary(bin_expr, scope)?;
- let var_loc = scope.add_variable(&name_str, LocationRequest::Persist)?;
+ let var_loc =
+ scope.add_variable(&name_str, LocationRequest::Persist, Some(name_span))?;
if let CompilationResult {
location: VariableLocation::Constant(Literal::Number(num)),
@@ -593,14 +596,15 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Free the temp result
if let Some(name) = result.temp_name {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
(var_loc, None)
}
}
Expression::Logical(log_expr) => {
let result = self.expression_logical(log_expr, scope)?;
- let var_loc = scope.add_variable(&name_str, LocationRequest::Persist)?;
+ let var_loc =
+ scope.add_variable(&name_str, LocationRequest::Persist, Some(name_span))?;
// Move result from temp to new persistent variable
let result_reg = self.resolve_register(&result.location)?;
@@ -608,12 +612,12 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Free the temp result
if let Some(name) = result.temp_name {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
(var_loc, None)
}
Expression::Variable(name) => {
- let src_loc_res = scope.get_location_of(&name.node);
+ let src_loc_res = scope.get_location_of(&name.node, Some(name.span));
let src_loc = match src_loc_res {
Ok(l) => l,
@@ -624,7 +628,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
}
};
- let var_loc = scope.add_variable(&name_str, LocationRequest::Persist)?;
+ let var_loc =
+ scope.add_variable(&name_str, LocationRequest::Persist, Some(name_span))?;
// Handle loading from stack if necessary
let src_str = match src_loc {
@@ -675,13 +680,14 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
));
};
- let var_loc = scope.add_variable(&name_str, LocationRequest::Persist)?;
+ let var_loc =
+ scope.add_variable(&name_str, LocationRequest::Persist, Some(name_span))?;
let result_reg = self.resolve_register(&comp_res.location)?;
self.emit_variable_assignment(&name_str, &var_loc, result_reg)?;
if let Some(temp) = comp_res.temp_name {
- scope.free_temp(temp)?;
+ scope.free_temp(temp, None)?;
}
(var_loc, None)
@@ -730,7 +736,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
};
Ok(CompilationResult {
- location: scope.define_const(const_name.node, value)?,
+ location: scope.define_const(const_name.node, value, Some(const_name.span))?,
temp_name: None,
})
}
@@ -747,7 +753,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
match assignee.node {
Expression::Variable(identifier) => {
- let location = match scope.get_location_of(&identifier.node) {
+ let location = match scope.get_location_of(&identifier.node, Some(identifier.span))
+ {
Ok(l) => l,
Err(_) => {
self.errors.push(Error::UnknownIdentifier(
@@ -791,7 +798,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
}
if let Some(name) = cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
}
Expression::MemberAccess(access) => {
@@ -804,10 +811,10 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
self.write_output(format!("s {} {} {}", device_str, member.node, val_str))?;
if let Some(c) = dev_cleanup {
- scope.free_temp(c)?;
+ scope.free_temp(c, None)?;
}
if let Some(c) = val_cleanup {
- scope.free_temp(c)?;
+ scope.free_temp(c, None)?;
}
}
_ => {
@@ -855,7 +862,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// backup all used registers to the stack
let active_registers = stack.registers().cloned().collect::>();
for register in &active_registers {
- stack.add_variable(format!("temp_{register}"), LocationRequest::Stack)?;
+ stack.add_variable(format!("temp_{register}"), LocationRequest::Stack, None)?;
self.write_output(format!("push r{register}"))?;
}
for arg in arguments {
@@ -872,14 +879,15 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
_ => {}
},
Expression::Variable(var_name) => {
- let loc = match stack.get_location_of(var_name.node.clone()) {
- Ok(l) => l,
- Err(_) => {
- self.errors
- .push(Error::UnknownIdentifier(var_name.node, var_name.span));
- VariableLocation::Temporary(0)
- }
- };
+ let loc =
+ match stack.get_location_of(var_name.node.clone(), Some(var_name.span)) {
+ Ok(l) => l,
+ Err(_) => {
+ self.errors
+ .push(Error::UnknownIdentifier(var_name.node, var_name.span));
+ VariableLocation::Temporary(0)
+ }
+ };
match loc {
VariableLocation::Persistant(reg) | VariableLocation::Temporary(reg) => {
@@ -916,7 +924,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
let reg_str = self.resolve_register(&result.location)?;
self.write_output(format!("push {reg_str}"))?;
if let Some(name) = result.temp_name {
- stack.free_temp(name)?;
+ stack.free_temp(name, None)?;
}
}
Expression::Logical(log_expr) => {
@@ -925,7 +933,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
let reg_str = self.resolve_register(&result.location)?;
self.write_output(format!("push {reg_str}"))?;
if let Some(name) = result.temp_name {
- stack.free_temp(name)?;
+ stack.free_temp(name, None)?;
}
}
Expression::MemberAccess(access) => {
@@ -947,7 +955,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
let reg_str = self.resolve_register(&result.location)?;
self.write_output(format!("push {reg_str}"))?;
if let Some(name) = result.temp_name {
- stack.free_temp(name)?;
+ stack.free_temp(name, None)?;
}
} else {
self.write_output("push 0")?; // Should fail ideally
@@ -970,7 +978,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
for register in active_registers {
let VariableLocation::Stack(stack_offset) = stack
- .get_location_of(format!("temp_{register}"))
+ .get_location_of(format!("temp_{register}"), None)
.map_err(Error::ScopeError)?
else {
// This shouldn't happen if we just added it
@@ -996,14 +1004,12 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
Ok(())
}
- fn expression_device(
- &mut self,
- expr: DeviceDeclarationExpression,
- span: Span,
- ) -> Result<(), Error> {
+ fn expression_device(&mut self, expr: DeviceDeclarationExpression) -> Result<(), Error> {
if self.devices.contains_key(&expr.name.node) {
- self.errors
- .push(Error::DuplicateIdentifier(expr.name.node.clone(), span));
+ self.errors.push(Error::DuplicateIdentifier(
+ expr.name.node.clone(),
+ expr.name.span,
+ ));
// We can overwrite or ignore. Let's ignore new declaration to avoid cascading errors?
// Actually, for recovery, maybe we want to allow it so subsequent uses work?
// But we already have it.
@@ -1033,7 +1039,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
self.write_output(format!("beq {cond_str} 0 {else_label}"))?;
if let Some(name) = cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
// Compile Body
@@ -1108,7 +1114,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
self.write_output(format!("beq {cond_str} 0 {end_label}"))?;
if let Some(name) = cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
// Compile Body
@@ -1221,7 +1227,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
VariableLocation::Stack(offset) => {
// If it's on the stack, we must load it into a temp to use it as an operand
let temp_name = self.next_temp_name();
- let temp_loc = scope.add_variable(&temp_name, LocationRequest::Temp)?;
+ let temp_loc = scope.add_variable(&temp_name, LocationRequest::Temp, None)?;
let temp_reg = self.resolve_register(&temp_loc)?;
self.write_output(format!(
@@ -1343,7 +1349,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Allocate result register
let result_name = self.next_temp_name();
- let result_loc = scope.add_variable(&result_name, LocationRequest::Temp)?;
+ let result_loc = scope.add_variable(&result_name, LocationRequest::Temp, None)?;
let result_reg = self.resolve_register(&result_loc)?;
// Emit instruction: op result lhs rhs
@@ -1351,10 +1357,10 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Clean up operand temps
if let Some(name) = lhs_cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
if let Some(name) = rhs_cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
Ok(CompilationResult {
@@ -1373,14 +1379,14 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
let (inner_str, cleanup) = self.compile_operand(*inner, scope)?;
let result_name = self.next_temp_name();
- let result_loc = scope.add_variable(&result_name, LocationRequest::Temp)?;
+ let result_loc = scope.add_variable(&result_name, LocationRequest::Temp, None)?;
let result_reg = self.resolve_register(&result_loc)?;
// seq rX rY 0 => if rY == 0 set rX = 1 else rX = 0
self.write_output(format!("seq {result_reg} {inner_str} 0"))?;
if let Some(name) = cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
Ok(CompilationResult {
@@ -1408,7 +1414,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Allocate result register
let result_name = self.next_temp_name();
- let result_loc = scope.add_variable(&result_name, LocationRequest::Temp)?;
+ let result_loc = scope.add_variable(&result_name, LocationRequest::Temp, None)?;
let result_reg = self.resolve_register(&result_loc)?;
// Emit instruction: op result lhs rhs
@@ -1416,10 +1422,10 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
// Clean up operand temps
if let Some(name) = lhs_cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
if let Some(name) = rhs_cleanup {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
Ok(CompilationResult {
@@ -1478,7 +1484,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
if let Some(comp_res) = result
&& let Some(name) = comp_res.temp_name
{
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
Ok(())
}) {
@@ -1511,49 +1517,51 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
};
match expr.node {
- Expression::Variable(var_name) => match scope.get_location_of(&var_name.node) {
- Ok(loc) => match loc {
- VariableLocation::Temporary(reg) | VariableLocation::Persistant(reg) => {
- self.write_output(format!(
- "move r{} r{reg} {}",
- VariableScope::RETURN_REGISTER,
- debug!(self, "#returnValue")
- ))?;
- }
- VariableLocation::Constant(lit) => {
- let str = extract_literal(lit, false)?;
- self.write_output(format!(
- "move r{} {str} {}",
- VariableScope::RETURN_REGISTER,
- debug!(self, "#returnValue")
- ))?
- }
- VariableLocation::Stack(offset) => {
- self.write_output(format!(
- "sub r{} sp {offset}",
- VariableScope::TEMP_STACK_REGISTER
- ))?;
- self.write_output(format!(
- "get r{} db r{}",
- VariableScope::RETURN_REGISTER,
- VariableScope::TEMP_STACK_REGISTER
- ))?;
- }
- VariableLocation::Device(_) => {
- return Err(Error::Unknown(
- "You can not return a device from a function.".into(),
- Some(var_name.span),
+ Expression::Variable(var_name) => {
+ match scope.get_location_of(&var_name.node, Some(var_name.span)) {
+ Ok(loc) => match loc {
+ VariableLocation::Temporary(reg) | VariableLocation::Persistant(reg) => {
+ self.write_output(format!(
+ "move r{} r{reg} {}",
+ VariableScope::RETURN_REGISTER,
+ debug!(self, "#returnValue")
+ ))?;
+ }
+ VariableLocation::Constant(lit) => {
+ let str = extract_literal(lit, false)?;
+ self.write_output(format!(
+ "move r{} {str} {}",
+ VariableScope::RETURN_REGISTER,
+ debug!(self, "#returnValue")
+ ))?
+ }
+ VariableLocation::Stack(offset) => {
+ self.write_output(format!(
+ "sub r{} sp {offset}",
+ VariableScope::TEMP_STACK_REGISTER
+ ))?;
+ self.write_output(format!(
+ "get r{} db r{}",
+ VariableScope::RETURN_REGISTER,
+ VariableScope::TEMP_STACK_REGISTER
+ ))?;
+ }
+ VariableLocation::Device(_) => {
+ return Err(Error::Unknown(
+ "You can not return a device from a function.".into(),
+ Some(var_name.span),
+ ));
+ }
+ },
+ Err(_) => {
+ self.errors.push(Error::UnknownIdentifier(
+ var_name.node.clone(),
+ var_name.span,
));
+ // Proceed with dummy
}
- },
- Err(_) => {
- self.errors.push(Error::UnknownIdentifier(
- var_name.node.clone(),
- var_name.span,
- ));
- // Proceed with dummy
}
- },
+ }
Expression::Literal(spanned_lit) => match spanned_lit.node {
Literal::Number(num) => {
self.emit_variable_assignment(
@@ -1581,7 +1589,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
result_reg
))?;
if let Some(name) = result.temp_name {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
}
Expression::Logical(log_expr) => {
@@ -1593,7 +1601,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
result_reg
))?;
if let Some(name) = result.temp_name {
- scope.free_temp(name)?;
+ scope.free_temp(name, None)?;
}
}
Expression::MemberAccess(access) => {
@@ -1609,7 +1617,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
let reg = self.resolve_register(&res.location)?;
self.write_output(format!("move r{} {}", VariableScope::RETURN_REGISTER, reg))?;
if let Some(temp) = res.temp_name {
- scope.free_temp(temp)?;
+ scope.free_temp(temp, None)?;
}
}
}
@@ -1636,7 +1644,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
($($to_clean:expr),*) => {
$(
if let Some(to_clean) = $to_clean {
- scope.free_temp(to_clean)?;
+ scope.free_temp(to_clean, None)?;
}
)*
};
@@ -1884,6 +1892,200 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
}
}
+ fn expression_syscall_math<'v>(
+ &mut self,
+ expr: Math,
+ scope: &mut VariableScope<'v>,
+ ) -> Result