Merge pull request #19 from dbidwell94/pre-release
Pre release.. finish Math syscalls, various bug fixes, cleanup logging
This commit is contained in:
70
ModData/About/About.xml
Normal file
70
ModData/About/About.xml
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ModMetadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
|
||||||
|
<Name>StationeersSlang</Name>
|
||||||
|
<Author>JoeDiertay</Author>
|
||||||
|
<Version>0.1.0</Version>
|
||||||
|
<Description>
|
||||||
|
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.
|
||||||
|
</Description>
|
||||||
|
<Tags>
|
||||||
|
<Tag>Logic</Tag>
|
||||||
|
<Tag>Scripting</Tag>
|
||||||
|
<Tag>Code</Tag>
|
||||||
|
<Tag>BepInEx</Tag>
|
||||||
|
<Tag>StationeersLaunchPad</Tag>
|
||||||
|
<Tag>Quality of Life</Tag>
|
||||||
|
</Tags>
|
||||||
|
<InGameDescription><![CDATA[
|
||||||
|
<size=30><color=#ffff00>Slang - High Level Language Compiler</color></size>
|
||||||
|
A modern programming experience for Stationeers. Write C-style code that compiles to MIPS assembly instantly.
|
||||||
|
|
||||||
|
<color=#ffa500><b>Features</b></color>
|
||||||
|
- <b>In-Game Compilation:</b> Write high-level logic directly in the chip editor.
|
||||||
|
- <b>Automatic Registers:</b> Stop juggling <color=#add8e6>r0-r15</color>. Just use <color=#569cd6>let</color> variables.
|
||||||
|
- <b>Control Flow:</b> Full support for <color=#c586c0>if</color>, <color=#c586c0>else</color>, <color=#c586c0>while</color>, and <color=#c586c0>loop</color>.
|
||||||
|
- <b>Smart Editor:</b> Integrated syntax highlighting and real-time error checking.
|
||||||
|
- <b>Persistent Code:</b> Your Slang source code is saved with the chip, so you never lose your work.
|
||||||
|
- <b>Optimization:</b> The compiler automatically optimizes constant math (e.g., <color=#b5cea8>1 + 2</color> becomes <color=#b5cea8>3</color>).
|
||||||
|
|
||||||
|
<color=#ffa500><b>Example Code</b></color>
|
||||||
|
<color=#569cd6>device</color> sensor = <color=#ce9178>"d0"</color>;
|
||||||
|
<color=#569cd6>const</color> MAX_TEMP = <color=#b5cea8>300k</color>;
|
||||||
|
|
||||||
|
<color=#c586c0>loop</color> {
|
||||||
|
<color=#569cd6>let</color> temp = sensor.Temperature;
|
||||||
|
<color=#c586c0>if</color> (temp > MAX_TEMP) {
|
||||||
|
<color=#6a9955>// Do logic here</color>
|
||||||
|
}
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
|
||||||
|
<b><color=#ffff00>Installation</color></b>
|
||||||
|
This is a <color=#ffa500>StationeersLaunchPad</color> Plugin Mod. It requires BepInEx to be installed.
|
||||||
|
See: https://github.com/StationeersLaunchPad/StationeersLaunchPad
|
||||||
|
|
||||||
|
Source Code: https://github.com/dbidwell94/stationeers_lang
|
||||||
|
]]>
|
||||||
|
</InGameDescription>
|
||||||
|
<Dependencies>
|
||||||
|
<Dependency>IC10Editor</Dependency>
|
||||||
|
</Dependencies>
|
||||||
|
<LoadAfter>IC10Editor</LoadAfter>
|
||||||
|
</ModMetadata>
|
||||||
BIN
ModData/About/Preview.png
Normal file
BIN
ModData/About/Preview.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 481 KiB |
BIN
ModData/About/thumb.png
Normal file
BIN
ModData/About/thumb.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 481 KiB |
0
ModData/Bepinex
Normal file
0
ModData/Bepinex
Normal file
14
build.sh
14
build.sh
@@ -5,6 +5,7 @@ set -e
|
|||||||
RUST_DIR="rust_compiler"
|
RUST_DIR="rust_compiler"
|
||||||
CSHARP_DIR="csharp_mod"
|
CSHARP_DIR="csharp_mod"
|
||||||
RELEASE_DIR="release"
|
RELEASE_DIR="release"
|
||||||
|
METADATA_DIR="ModData"
|
||||||
|
|
||||||
export RUSTFLAGS="--remap-path-prefix=${PWD}=. --remap-path-prefix=${HOME}/.cargo=~/.cargo"
|
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_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_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"
|
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
|
if [[ ! -d "$RELEASE_DIR" ]]; then
|
||||||
mkdir "$RELEASE_DIR"
|
mkdir "$RELEASE_DIR"
|
||||||
fi
|
fi
|
||||||
@@ -51,6 +56,9 @@ cp "$RUST_WIN_EXE" "$RELEASE_DIR/slang.exe"
|
|||||||
# This is the linux executable
|
# This is the linux executable
|
||||||
cp "$RUST_LINUX_BIN" "$RELEASE_DIR/slang"
|
cp "$RUST_LINUX_BIN" "$RELEASE_DIR/slang"
|
||||||
# This is the DLL mod itself
|
# 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
|
# This is the rust-only compiler for use in injecting into the mod
|
||||||
cp "$RUST_WIN_DLL" "$RELEASE_DIR/rust_slang.dll"
|
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"
|
||||||
|
|||||||
@@ -72,8 +72,6 @@ public class SlangFormatter : ICodeFormatter
|
|||||||
|
|
||||||
public override StyledLine ParseLine(string line)
|
public override StyledLine ParseLine(string line)
|
||||||
{
|
{
|
||||||
L.Debug($"Parsing line for syntax highlighting: {line}");
|
|
||||||
|
|
||||||
// We create the line first
|
// We create the line first
|
||||||
var styledLine = new StyledLine(line);
|
var styledLine = new StyledLine(line);
|
||||||
|
|
||||||
@@ -83,7 +81,6 @@ public class SlangFormatter : ICodeFormatter
|
|||||||
// We call update to create the basic tokens
|
// We call update to create the basic tokens
|
||||||
styledLine.Update(tokens);
|
styledLine.Update(tokens);
|
||||||
|
|
||||||
// CRITICAL FIX: We must manually re-attach metadata because StyledLine.Update() drops it.
|
|
||||||
ReattachMetadata(styledLine, tokens);
|
ReattachMetadata(styledLine, tokens);
|
||||||
|
|
||||||
return styledLine;
|
return styledLine;
|
||||||
@@ -170,34 +167,35 @@ public class SlangFormatter : ICodeFormatter
|
|||||||
if (line is null)
|
if (line is null)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
// 1. Get base syntax tokens
|
// 1. Get base syntax tokens, converting to a dictionary for ease in deduping error tokens
|
||||||
var allTokens = Marshal.TokenizeLine(line.Text);
|
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))
|
if (dict.ContainsKey(lineIndex))
|
||||||
{
|
{
|
||||||
foreach (var lineDiagnostic in dict[lineIndex])
|
foreach (var lineDiagnostic in dict[lineIndex])
|
||||||
{
|
{
|
||||||
allTokens.Add(
|
var column = Math.Abs((int)lineDiagnostic.Range.StartCol);
|
||||||
new SemanticToken(
|
|
||||||
line: (int)lineIndex,
|
allTokensDict[column] = new SemanticToken(
|
||||||
column: Math.Abs((int)lineDiagnostic.Range.StartCol),
|
line: (int)lineIndex,
|
||||||
length: Math.Abs(
|
column,
|
||||||
(int)(lineDiagnostic.Range.EndCol - lineDiagnostic.Range.StartCol)
|
length: Math.Abs(
|
||||||
),
|
(int)(lineDiagnostic.Range.EndCol - lineDiagnostic.Range.StartCol)
|
||||||
type: 0,
|
),
|
||||||
style: ICodeFormatter.ColorError,
|
type: 0,
|
||||||
data: lineDiagnostic.Message,
|
style: ICodeFormatter.ColorError,
|
||||||
isError: true
|
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)
|
// 3. Update the line (this clears existing tokens and uses the list we just built)
|
||||||
line.Update(allTokens);
|
line.Update(allTokens);
|
||||||
|
|
||||||
// 4. CRITICAL FIX: Re-attach metadata that Update() dropped
|
|
||||||
ReattachMetadata(line, allTokens);
|
ReattachMetadata(line, allTokens);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -147,7 +147,6 @@ public static class Marshal
|
|||||||
};
|
};
|
||||||
|
|
||||||
var tokens = Ffi.tokenize_line(strRef);
|
var tokens = Ffi.tokenize_line(strRef);
|
||||||
L.Debug($"Tokenized line '{inputString}' into {tokens.len} tokens.");
|
|
||||||
return tokens.ToTokenList();
|
return tokens.ToTokenList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
388
rust_compiler/libs/compiler/src/test/math_syscall.rs
Normal file
388
rust_compiler/libs/compiler/src/test/math_syscall.rs
Normal file
@@ -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(())
|
||||||
|
}
|
||||||
@@ -47,4 +47,5 @@ mod declaration_literal;
|
|||||||
mod function_declaration;
|
mod function_declaration;
|
||||||
mod logic_expression;
|
mod logic_expression;
|
||||||
mod loops;
|
mod loops;
|
||||||
|
mod math_syscall;
|
||||||
mod syscall;
|
mod syscall;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use crate::variable_manager::{self, LocationRequest, VariableLocation, VariableS
|
|||||||
use helpers::prelude::*;
|
use helpers::prelude::*;
|
||||||
use parser::{
|
use parser::{
|
||||||
Parser as ASTParser,
|
Parser as ASTParser,
|
||||||
sys_call::{SysCall, System},
|
sys_call::{Math, SysCall, System},
|
||||||
tree_node::{
|
tree_node::{
|
||||||
AssignmentExpression, BinaryExpression, BlockExpression, ConstDeclarationExpression,
|
AssignmentExpression, BinaryExpression, BlockExpression, ConstDeclarationExpression,
|
||||||
DeviceDeclarationExpression, Expression, FunctionExpression, IfExpression,
|
DeviceDeclarationExpression, Expression, FunctionExpression, IfExpression,
|
||||||
@@ -97,12 +97,7 @@ impl From<Error> for lsp_types::Diagnostic {
|
|||||||
severity: Some(DiagnosticSeverity::ERROR),
|
severity: Some(DiagnosticSeverity::ERROR),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
ScopeError(e) => Diagnostic {
|
ScopeError(e) => e.into(),
|
||||||
message: e.to_string(),
|
|
||||||
range: Range::default(),
|
|
||||||
severity: Some(DiagnosticSeverity::ERROR),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
DuplicateIdentifier(_, span)
|
DuplicateIdentifier(_, span)
|
||||||
| UnknownIdentifier(_, span)
|
| UnknownIdentifier(_, span)
|
||||||
| InvalidDevice(_, span)
|
| InvalidDevice(_, span)
|
||||||
@@ -271,6 +266,10 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
node: SysCall::System(system),
|
node: SysCall::System(system),
|
||||||
span,
|
span,
|
||||||
}) => self.expression_syscall_system(system, span, scope),
|
}) => self.expression_syscall_system(system, span, scope),
|
||||||
|
Expression::Syscall(Spanned {
|
||||||
|
node: SysCall::Math(math),
|
||||||
|
..
|
||||||
|
}) => self.expression_syscall_math(math, scope),
|
||||||
Expression::While(expr_while) => {
|
Expression::While(expr_while) => {
|
||||||
self.expression_while(expr_while.node, scope)?;
|
self.expression_while(expr_while.node, scope)?;
|
||||||
Ok(None)
|
Ok(None)
|
||||||
@@ -284,7 +283,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
Expression::DeviceDeclaration(expr_dev) => {
|
Expression::DeviceDeclaration(expr_dev) => {
|
||||||
self.expression_device(expr_dev.node, expr_dev.span)?;
|
self.expression_device(expr_dev.node)?;
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
Expression::Declaration(var_name, decl_expr) => {
|
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).
|
// Invocation returns result in r15 (RETURN_REGISTER).
|
||||||
// If used as an expression, we must move it to a temp to avoid overwrite.
|
// If used as an expression, we must move it to a temp to avoid overwrite.
|
||||||
let temp_name = self.next_temp_name();
|
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(
|
self.emit_variable_assignment(
|
||||||
&temp_name,
|
&temp_name,
|
||||||
&temp_loc,
|
&temp_loc,
|
||||||
@@ -326,7 +325,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
Expression::Literal(spanned_lit) => match spanned_lit.node {
|
Expression::Literal(spanned_lit) => match spanned_lit.node {
|
||||||
Literal::Number(num) => {
|
Literal::Number(num) => {
|
||||||
let temp_name = self.next_temp_name();
|
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())?;
|
self.emit_variable_assignment(&temp_name, &loc, num.to_string())?;
|
||||||
Ok(Some(CompilationResult {
|
Ok(Some(CompilationResult {
|
||||||
location: loc,
|
location: loc,
|
||||||
@@ -336,7 +335,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
Literal::Boolean(b) => {
|
Literal::Boolean(b) => {
|
||||||
let val = if b { "1" } else { "0" };
|
let val = if b { "1" } else { "0" };
|
||||||
let temp_name = self.next_temp_name();
|
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)?;
|
self.emit_variable_assignment(&temp_name, &loc, val)?;
|
||||||
Ok(Some(CompilationResult {
|
Ok(Some(CompilationResult {
|
||||||
location: loc,
|
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
|
_ => Ok(None), // String literals don't return values in this context typically
|
||||||
},
|
},
|
||||||
Expression::Variable(name) => {
|
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 {
|
Ok(loc) => Ok(Some(CompilationResult {
|
||||||
location: loc,
|
location: loc,
|
||||||
temp_name: None, // User variable, do not free
|
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
|
// 2. Allocate a temp register for the result
|
||||||
let result_name = self.next_temp_name();
|
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)?;
|
let reg = self.resolve_register(&loc)?;
|
||||||
|
|
||||||
// 3. Emit load instruction: l rX device member
|
// 3. Emit load instruction: l rX device member
|
||||||
@@ -386,7 +385,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
|
|
||||||
// 4. Cleanup
|
// 4. Cleanup
|
||||||
if let Some(c) = cleanup {
|
if let Some(c) = cleanup {
|
||||||
scope.free_temp(c)?;
|
scope.free_temp(c, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Some(CompilationResult {
|
Ok(Some(CompilationResult {
|
||||||
@@ -410,13 +409,13 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
// Compile negation as 0 - inner
|
// Compile negation as 0 - inner
|
||||||
let (inner_str, cleanup) = self.compile_operand(*inner_expr, scope)?;
|
let (inner_str, cleanup) = self.compile_operand(*inner_expr, scope)?;
|
||||||
let result_name = self.next_temp_name();
|
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)?;
|
let result_reg = self.resolve_register(&result_loc)?;
|
||||||
|
|
||||||
self.write_output(format!("sub {result_reg} 0 {inner_str}"))?;
|
self.write_output(format!("sub {result_reg} 0 {inner_str}"))?;
|
||||||
|
|
||||||
if let Some(name) = cleanup {
|
if let Some(name) = cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Some(CompilationResult {
|
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 Expression::Literal(spanned_lit) = &box_expr.node
|
||||||
&& let Literal::Number(neg_num) = &spanned_lit.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}"))?;
|
self.emit_variable_assignment(&name_str, &loc, format!("-{neg_num}"))?;
|
||||||
return Ok(Some(CompilationResult {
|
return Ok(Some(CompilationResult {
|
||||||
location: loc,
|
location: loc,
|
||||||
@@ -517,16 +516,22 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
let (loc, temp_name) = match expr.node {
|
let (loc, temp_name) = match expr.node {
|
||||||
Expression::Literal(spanned_lit) => match spanned_lit.node {
|
Expression::Literal(spanned_lit) => match spanned_lit.node {
|
||||||
Literal::Number(num) => {
|
Literal::Number(num) => {
|
||||||
let var_location =
|
let var_location = scope.add_variable(
|
||||||
scope.add_variable(name_str.clone(), LocationRequest::Persist)?;
|
name_str.clone(),
|
||||||
|
LocationRequest::Persist,
|
||||||
|
Some(name_span),
|
||||||
|
)?;
|
||||||
|
|
||||||
self.emit_variable_assignment(&name_str, &var_location, num)?;
|
self.emit_variable_assignment(&name_str, &var_location, num)?;
|
||||||
(var_location, None)
|
(var_location, None)
|
||||||
}
|
}
|
||||||
Literal::Boolean(b) => {
|
Literal::Boolean(b) => {
|
||||||
let val = if b { "1" } else { "0" };
|
let val = if b { "1" } else { "0" };
|
||||||
let var_location =
|
let var_location = scope.add_variable(
|
||||||
scope.add_variable(name_str.clone(), LocationRequest::Persist)?;
|
name_str.clone(),
|
||||||
|
LocationRequest::Persist,
|
||||||
|
Some(name_span),
|
||||||
|
)?;
|
||||||
|
|
||||||
self.emit_variable_assignment(&name_str, &var_location, val)?;
|
self.emit_variable_assignment(&name_str, &var_location, val)?;
|
||||||
(var_location, None)
|
(var_location, None)
|
||||||
@@ -536,7 +541,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
Expression::Invocation(invoke_expr) => {
|
Expression::Invocation(invoke_expr) => {
|
||||||
self.expression_function_invocation(invoke_expr, scope)?;
|
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(
|
self.emit_variable_assignment(
|
||||||
&name_str,
|
&name_str,
|
||||||
&loc,
|
&loc,
|
||||||
@@ -546,26 +552,22 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
}
|
}
|
||||||
Expression::Syscall(spanned_call) => {
|
Expression::Syscall(spanned_call) => {
|
||||||
let sys_call = spanned_call.node;
|
let sys_call = spanned_call.node;
|
||||||
let SysCall::System(call) = sys_call else {
|
let res = match sys_call {
|
||||||
// Math syscalls might be handled differently or here
|
SysCall::System(s) => {
|
||||||
// For now assuming System returns value
|
self.expression_syscall_system(s, spanned_call.span, scope)?
|
||||||
return Err(Error::Unknown(
|
}
|
||||||
"Math syscall not yet supported in declaration".into(),
|
SysCall::Math(m) => self.expression_syscall_math(m, scope)?,
|
||||||
Some(spanned_call.span),
|
|
||||||
));
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if self
|
if res.is_none() {
|
||||||
.expression_syscall_system(call, spanned_call.span, scope)?
|
|
||||||
.is_none()
|
|
||||||
{
|
|
||||||
return Err(Error::Unknown(
|
return Err(Error::Unknown(
|
||||||
"SysCall did not return a value".into(),
|
"SysCall did not return a value".into(),
|
||||||
Some(spanned_call.span),
|
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(
|
self.emit_variable_assignment(
|
||||||
&name_str,
|
&name_str,
|
||||||
&loc,
|
&loc,
|
||||||
@@ -577,7 +579,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
// Support assigning binary expressions to variables directly
|
// Support assigning binary expressions to variables directly
|
||||||
Expression::Binary(bin_expr) => {
|
Expression::Binary(bin_expr) => {
|
||||||
let result = self.expression_binary(bin_expr, scope)?;
|
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 {
|
if let CompilationResult {
|
||||||
location: VariableLocation::Constant(Literal::Number(num)),
|
location: VariableLocation::Constant(Literal::Number(num)),
|
||||||
@@ -593,14 +596,15 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
|
|
||||||
// Free the temp result
|
// Free the temp result
|
||||||
if let Some(name) = result.temp_name {
|
if let Some(name) = result.temp_name {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
(var_loc, None)
|
(var_loc, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Expression::Logical(log_expr) => {
|
Expression::Logical(log_expr) => {
|
||||||
let result = self.expression_logical(log_expr, scope)?;
|
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
|
// Move result from temp to new persistent variable
|
||||||
let result_reg = self.resolve_register(&result.location)?;
|
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
|
// Free the temp result
|
||||||
if let Some(name) = result.temp_name {
|
if let Some(name) = result.temp_name {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
(var_loc, None)
|
(var_loc, None)
|
||||||
}
|
}
|
||||||
Expression::Variable(name) => {
|
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 {
|
let src_loc = match src_loc_res {
|
||||||
Ok(l) => l,
|
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
|
// Handle loading from stack if necessary
|
||||||
let src_str = match src_loc {
|
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)?;
|
let result_reg = self.resolve_register(&comp_res.location)?;
|
||||||
|
|
||||||
self.emit_variable_assignment(&name_str, &var_loc, result_reg)?;
|
self.emit_variable_assignment(&name_str, &var_loc, result_reg)?;
|
||||||
|
|
||||||
if let Some(temp) = comp_res.temp_name {
|
if let Some(temp) = comp_res.temp_name {
|
||||||
scope.free_temp(temp)?;
|
scope.free_temp(temp, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
(var_loc, None)
|
(var_loc, None)
|
||||||
@@ -730,7 +736,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
Ok(CompilationResult {
|
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,
|
temp_name: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -747,7 +753,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
|
|
||||||
match assignee.node {
|
match assignee.node {
|
||||||
Expression::Variable(identifier) => {
|
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,
|
Ok(l) => l,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
self.errors.push(Error::UnknownIdentifier(
|
self.errors.push(Error::UnknownIdentifier(
|
||||||
@@ -791,7 +798,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(name) = cleanup {
|
if let Some(name) = cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Expression::MemberAccess(access) => {
|
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))?;
|
self.write_output(format!("s {} {} {}", device_str, member.node, val_str))?;
|
||||||
|
|
||||||
if let Some(c) = dev_cleanup {
|
if let Some(c) = dev_cleanup {
|
||||||
scope.free_temp(c)?;
|
scope.free_temp(c, None)?;
|
||||||
}
|
}
|
||||||
if let Some(c) = val_cleanup {
|
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
|
// backup all used registers to the stack
|
||||||
let active_registers = stack.registers().cloned().collect::<Vec<_>>();
|
let active_registers = stack.registers().cloned().collect::<Vec<_>>();
|
||||||
for register in &active_registers {
|
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}"))?;
|
self.write_output(format!("push r{register}"))?;
|
||||||
}
|
}
|
||||||
for arg in arguments {
|
for arg in arguments {
|
||||||
@@ -872,14 +879,15 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
_ => {}
|
_ => {}
|
||||||
},
|
},
|
||||||
Expression::Variable(var_name) => {
|
Expression::Variable(var_name) => {
|
||||||
let loc = match stack.get_location_of(var_name.node.clone()) {
|
let loc =
|
||||||
Ok(l) => l,
|
match stack.get_location_of(var_name.node.clone(), Some(var_name.span)) {
|
||||||
Err(_) => {
|
Ok(l) => l,
|
||||||
self.errors
|
Err(_) => {
|
||||||
.push(Error::UnknownIdentifier(var_name.node, var_name.span));
|
self.errors
|
||||||
VariableLocation::Temporary(0)
|
.push(Error::UnknownIdentifier(var_name.node, var_name.span));
|
||||||
}
|
VariableLocation::Temporary(0)
|
||||||
};
|
}
|
||||||
|
};
|
||||||
|
|
||||||
match loc {
|
match loc {
|
||||||
VariableLocation::Persistant(reg) | VariableLocation::Temporary(reg) => {
|
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)?;
|
let reg_str = self.resolve_register(&result.location)?;
|
||||||
self.write_output(format!("push {reg_str}"))?;
|
self.write_output(format!("push {reg_str}"))?;
|
||||||
if let Some(name) = result.temp_name {
|
if let Some(name) = result.temp_name {
|
||||||
stack.free_temp(name)?;
|
stack.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Expression::Logical(log_expr) => {
|
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)?;
|
let reg_str = self.resolve_register(&result.location)?;
|
||||||
self.write_output(format!("push {reg_str}"))?;
|
self.write_output(format!("push {reg_str}"))?;
|
||||||
if let Some(name) = result.temp_name {
|
if let Some(name) = result.temp_name {
|
||||||
stack.free_temp(name)?;
|
stack.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Expression::MemberAccess(access) => {
|
Expression::MemberAccess(access) => {
|
||||||
@@ -947,7 +955,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
let reg_str = self.resolve_register(&result.location)?;
|
let reg_str = self.resolve_register(&result.location)?;
|
||||||
self.write_output(format!("push {reg_str}"))?;
|
self.write_output(format!("push {reg_str}"))?;
|
||||||
if let Some(name) = result.temp_name {
|
if let Some(name) = result.temp_name {
|
||||||
stack.free_temp(name)?;
|
stack.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
self.write_output("push 0")?; // Should fail ideally
|
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 {
|
for register in active_registers {
|
||||||
let VariableLocation::Stack(stack_offset) = stack
|
let VariableLocation::Stack(stack_offset) = stack
|
||||||
.get_location_of(format!("temp_{register}"))
|
.get_location_of(format!("temp_{register}"), None)
|
||||||
.map_err(Error::ScopeError)?
|
.map_err(Error::ScopeError)?
|
||||||
else {
|
else {
|
||||||
// This shouldn't happen if we just added it
|
// This shouldn't happen if we just added it
|
||||||
@@ -996,14 +1004,12 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn expression_device(
|
fn expression_device(&mut self, expr: DeviceDeclarationExpression) -> Result<(), Error> {
|
||||||
&mut self,
|
|
||||||
expr: DeviceDeclarationExpression,
|
|
||||||
span: Span,
|
|
||||||
) -> Result<(), Error> {
|
|
||||||
if self.devices.contains_key(&expr.name.node) {
|
if self.devices.contains_key(&expr.name.node) {
|
||||||
self.errors
|
self.errors.push(Error::DuplicateIdentifier(
|
||||||
.push(Error::DuplicateIdentifier(expr.name.node.clone(), span));
|
expr.name.node.clone(),
|
||||||
|
expr.name.span,
|
||||||
|
));
|
||||||
// We can overwrite or ignore. Let's ignore new declaration to avoid cascading errors?
|
// 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?
|
// Actually, for recovery, maybe we want to allow it so subsequent uses work?
|
||||||
// But we already have it.
|
// 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}"))?;
|
self.write_output(format!("beq {cond_str} 0 {else_label}"))?;
|
||||||
|
|
||||||
if let Some(name) = cleanup {
|
if let Some(name) = cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compile Body
|
// 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}"))?;
|
self.write_output(format!("beq {cond_str} 0 {end_label}"))?;
|
||||||
|
|
||||||
if let Some(name) = cleanup {
|
if let Some(name) = cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compile Body
|
// Compile Body
|
||||||
@@ -1221,7 +1227,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
VariableLocation::Stack(offset) => {
|
VariableLocation::Stack(offset) => {
|
||||||
// If it's on the stack, we must load it into a temp to use it as an operand
|
// 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_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)?;
|
let temp_reg = self.resolve_register(&temp_loc)?;
|
||||||
|
|
||||||
self.write_output(format!(
|
self.write_output(format!(
|
||||||
@@ -1343,7 +1349,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
|
|
||||||
// Allocate result register
|
// Allocate result register
|
||||||
let result_name = self.next_temp_name();
|
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)?;
|
let result_reg = self.resolve_register(&result_loc)?;
|
||||||
|
|
||||||
// Emit instruction: op result lhs rhs
|
// Emit instruction: op result lhs rhs
|
||||||
@@ -1351,10 +1357,10 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
|
|
||||||
// Clean up operand temps
|
// Clean up operand temps
|
||||||
if let Some(name) = lhs_cleanup {
|
if let Some(name) = lhs_cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
if let Some(name) = rhs_cleanup {
|
if let Some(name) = rhs_cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(CompilationResult {
|
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 (inner_str, cleanup) = self.compile_operand(*inner, scope)?;
|
||||||
|
|
||||||
let result_name = self.next_temp_name();
|
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)?;
|
let result_reg = self.resolve_register(&result_loc)?;
|
||||||
|
|
||||||
// seq rX rY 0 => if rY == 0 set rX = 1 else rX = 0
|
// seq rX rY 0 => if rY == 0 set rX = 1 else rX = 0
|
||||||
self.write_output(format!("seq {result_reg} {inner_str} 0"))?;
|
self.write_output(format!("seq {result_reg} {inner_str} 0"))?;
|
||||||
|
|
||||||
if let Some(name) = cleanup {
|
if let Some(name) = cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(CompilationResult {
|
Ok(CompilationResult {
|
||||||
@@ -1408,7 +1414,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
|
|
||||||
// Allocate result register
|
// Allocate result register
|
||||||
let result_name = self.next_temp_name();
|
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)?;
|
let result_reg = self.resolve_register(&result_loc)?;
|
||||||
|
|
||||||
// Emit instruction: op result lhs rhs
|
// Emit instruction: op result lhs rhs
|
||||||
@@ -1416,10 +1422,10 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
|
|
||||||
// Clean up operand temps
|
// Clean up operand temps
|
||||||
if let Some(name) = lhs_cleanup {
|
if let Some(name) = lhs_cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
if let Some(name) = rhs_cleanup {
|
if let Some(name) = rhs_cleanup {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(CompilationResult {
|
Ok(CompilationResult {
|
||||||
@@ -1478,7 +1484,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
if let Some(comp_res) = result
|
if let Some(comp_res) = result
|
||||||
&& let Some(name) = comp_res.temp_name
|
&& let Some(name) = comp_res.temp_name
|
||||||
{
|
{
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}) {
|
}) {
|
||||||
@@ -1511,49 +1517,51 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
match expr.node {
|
match expr.node {
|
||||||
Expression::Variable(var_name) => match scope.get_location_of(&var_name.node) {
|
Expression::Variable(var_name) => {
|
||||||
Ok(loc) => match loc {
|
match scope.get_location_of(&var_name.node, Some(var_name.span)) {
|
||||||
VariableLocation::Temporary(reg) | VariableLocation::Persistant(reg) => {
|
Ok(loc) => match loc {
|
||||||
self.write_output(format!(
|
VariableLocation::Temporary(reg) | VariableLocation::Persistant(reg) => {
|
||||||
"move r{} r{reg} {}",
|
self.write_output(format!(
|
||||||
VariableScope::RETURN_REGISTER,
|
"move r{} r{reg} {}",
|
||||||
debug!(self, "#returnValue")
|
VariableScope::RETURN_REGISTER,
|
||||||
))?;
|
debug!(self, "#returnValue")
|
||||||
}
|
))?;
|
||||||
VariableLocation::Constant(lit) => {
|
}
|
||||||
let str = extract_literal(lit, false)?;
|
VariableLocation::Constant(lit) => {
|
||||||
self.write_output(format!(
|
let str = extract_literal(lit, false)?;
|
||||||
"move r{} {str} {}",
|
self.write_output(format!(
|
||||||
VariableScope::RETURN_REGISTER,
|
"move r{} {str} {}",
|
||||||
debug!(self, "#returnValue")
|
VariableScope::RETURN_REGISTER,
|
||||||
))?
|
debug!(self, "#returnValue")
|
||||||
}
|
))?
|
||||||
VariableLocation::Stack(offset) => {
|
}
|
||||||
self.write_output(format!(
|
VariableLocation::Stack(offset) => {
|
||||||
"sub r{} sp {offset}",
|
self.write_output(format!(
|
||||||
VariableScope::TEMP_STACK_REGISTER
|
"sub r{} sp {offset}",
|
||||||
))?;
|
VariableScope::TEMP_STACK_REGISTER
|
||||||
self.write_output(format!(
|
))?;
|
||||||
"get r{} db r{}",
|
self.write_output(format!(
|
||||||
VariableScope::RETURN_REGISTER,
|
"get r{} db r{}",
|
||||||
VariableScope::TEMP_STACK_REGISTER
|
VariableScope::RETURN_REGISTER,
|
||||||
))?;
|
VariableScope::TEMP_STACK_REGISTER
|
||||||
}
|
))?;
|
||||||
VariableLocation::Device(_) => {
|
}
|
||||||
return Err(Error::Unknown(
|
VariableLocation::Device(_) => {
|
||||||
"You can not return a device from a function.".into(),
|
return Err(Error::Unknown(
|
||||||
Some(var_name.span),
|
"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 {
|
Expression::Literal(spanned_lit) => match spanned_lit.node {
|
||||||
Literal::Number(num) => {
|
Literal::Number(num) => {
|
||||||
self.emit_variable_assignment(
|
self.emit_variable_assignment(
|
||||||
@@ -1581,7 +1589,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
result_reg
|
result_reg
|
||||||
))?;
|
))?;
|
||||||
if let Some(name) = result.temp_name {
|
if let Some(name) = result.temp_name {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Expression::Logical(log_expr) => {
|
Expression::Logical(log_expr) => {
|
||||||
@@ -1593,7 +1601,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
result_reg
|
result_reg
|
||||||
))?;
|
))?;
|
||||||
if let Some(name) = result.temp_name {
|
if let Some(name) = result.temp_name {
|
||||||
scope.free_temp(name)?;
|
scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Expression::MemberAccess(access) => {
|
Expression::MemberAccess(access) => {
|
||||||
@@ -1609,7 +1617,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
let reg = self.resolve_register(&res.location)?;
|
let reg = self.resolve_register(&res.location)?;
|
||||||
self.write_output(format!("move r{} {}", VariableScope::RETURN_REGISTER, reg))?;
|
self.write_output(format!("move r{} {}", VariableScope::RETURN_REGISTER, reg))?;
|
||||||
if let Some(temp) = res.temp_name {
|
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),*) => {
|
($($to_clean:expr),*) => {
|
||||||
$(
|
$(
|
||||||
if let Some(to_clean) = $to_clean {
|
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<Option<CompilationResult>, Error> {
|
||||||
|
macro_rules! cleanup {
|
||||||
|
($($to_clean:expr),*) => {
|
||||||
|
$(
|
||||||
|
if let Some(to_clean) = $to_clean {
|
||||||
|
scope.free_temp(to_clean, None)?;
|
||||||
|
}
|
||||||
|
)*
|
||||||
|
};
|
||||||
|
}
|
||||||
|
match expr {
|
||||||
|
Math::Acos(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("acos r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Asin(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("asin r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Atan(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("atan r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Atan2(expr1, expr2) => {
|
||||||
|
let (var1, var1_cleanup) = self.compile_operand(*expr1, scope)?;
|
||||||
|
let (var2, var2_cleanup) = self.compile_operand(*expr2, scope)?;
|
||||||
|
|
||||||
|
self.write_output(format!(
|
||||||
|
"atan2 r{} {} {}",
|
||||||
|
VariableScope::RETURN_REGISTER,
|
||||||
|
var1,
|
||||||
|
var2
|
||||||
|
))?;
|
||||||
|
cleanup!(var1_cleanup, var2_cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Abs(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("abs r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Ceil(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("ceil r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Cos(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("cos r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Floor(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("floor r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Log(expr) => {
|
||||||
|
let (var, cleanup) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("log r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(cleanup);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Max(expr1, expr2) => {
|
||||||
|
let (var1, clean1) = self.compile_operand(*expr1, scope)?;
|
||||||
|
let (var2, clean2) = self.compile_operand(*expr2, scope)?;
|
||||||
|
self.write_output(format!(
|
||||||
|
"max r{} {} {}",
|
||||||
|
VariableScope::RETURN_REGISTER,
|
||||||
|
var1,
|
||||||
|
var2
|
||||||
|
))?;
|
||||||
|
|
||||||
|
cleanup!(clean1, clean2);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Min(expr1, expr2) => {
|
||||||
|
let (var1, clean1) = self.compile_operand(*expr1, scope)?;
|
||||||
|
let (var2, clean2) = self.compile_operand(*expr2, scope)?;
|
||||||
|
self.write_output(format!(
|
||||||
|
"min r{} {} {}",
|
||||||
|
VariableScope::RETURN_REGISTER,
|
||||||
|
var1,
|
||||||
|
var2
|
||||||
|
))?;
|
||||||
|
|
||||||
|
cleanup!(clean1, clean2);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Rand => {
|
||||||
|
self.write_output(format!("rand r{}", VariableScope::RETURN_REGISTER))?;
|
||||||
|
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Sin(expr) => {
|
||||||
|
let (var, clean) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("sin r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(clean);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Sqrt(expr) => {
|
||||||
|
let (var, clean) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("sqrt r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(clean);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Tan(expr) => {
|
||||||
|
let (var, clean) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("tan r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(clean);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Math::Trunc(expr) => {
|
||||||
|
let (var, clean) = self.compile_operand(*expr, scope)?;
|
||||||
|
self.write_output(format!("trunc r{} {}", VariableScope::RETURN_REGISTER, var))?;
|
||||||
|
|
||||||
|
cleanup!(clean);
|
||||||
|
Ok(Some(CompilationResult {
|
||||||
|
location: VariableLocation::Persistant(VariableScope::RETURN_REGISTER),
|
||||||
|
temp_name: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 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<'v>(
|
fn expression_function<'v>(
|
||||||
@@ -1926,7 +2128,11 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
.rev()
|
.rev()
|
||||||
.take(VariableScope::PERSIST_REGISTER_COUNT as usize)
|
.take(VariableScope::PERSIST_REGISTER_COUNT as usize)
|
||||||
{
|
{
|
||||||
let loc = block_scope.add_variable(var_name.node.clone(), LocationRequest::Persist)?;
|
let loc = block_scope.add_variable(
|
||||||
|
var_name.node.clone(),
|
||||||
|
LocationRequest::Persist,
|
||||||
|
Some(var_name.span),
|
||||||
|
)?;
|
||||||
// we don't need to imcrement the stack offset as it's already on the stack from the
|
// we don't need to imcrement the stack offset as it's already on the stack from the
|
||||||
// previous scope
|
// previous scope
|
||||||
|
|
||||||
@@ -1959,11 +2165,19 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
// anything as they already exist on the stack, but we DO need to let our block_scope be
|
// anything as they already exist on the stack, but we DO need to let our block_scope be
|
||||||
// aware that the variables exist on the stack (left to right)
|
// aware that the variables exist on the stack (left to right)
|
||||||
for var_name in arguments.iter().take(arguments.len() - saved_variables) {
|
for var_name in arguments.iter().take(arguments.len() - saved_variables) {
|
||||||
block_scope.add_variable(var_name.node.clone(), LocationRequest::Stack)?;
|
block_scope.add_variable(
|
||||||
|
var_name.node.clone(),
|
||||||
|
LocationRequest::Stack,
|
||||||
|
Some(var_name.span),
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.write_output("push ra")?;
|
self.write_output("push ra")?;
|
||||||
block_scope.add_variable(format!("{}_ra", name.node), LocationRequest::Stack)?;
|
block_scope.add_variable(
|
||||||
|
format!("{}_ra", name.node),
|
||||||
|
LocationRequest::Stack,
|
||||||
|
Some(name.span),
|
||||||
|
)?;
|
||||||
|
|
||||||
for expr in body.0 {
|
for expr in body.0 {
|
||||||
match expr.node {
|
match expr.node {
|
||||||
@@ -1976,7 +2190,7 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
if let Some(comp_res) = result
|
if let Some(comp_res) = result
|
||||||
&& let Some(name) = comp_res.temp_name
|
&& let Some(name) = comp_res.temp_name
|
||||||
{
|
{
|
||||||
block_scope.free_temp(name)?;
|
block_scope.free_temp(name, None)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}) {
|
}) {
|
||||||
@@ -1987,7 +2201,8 @@ impl<'a, W: std::io::Write> Compiler<'a, W> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get the saved return address and save it back into `ra`
|
// Get the saved return address and save it back into `ra`
|
||||||
let ra_res = block_scope.get_location_of(format!("{}_ra", name.node));
|
let ra_res = block_scope.get_location_of(format!("{}_ra", name.node), Some(name.span));
|
||||||
|
|
||||||
let ra_stack_offset = match ra_res {
|
let ra_stack_offset = match ra_res {
|
||||||
Ok(VariableLocation::Stack(offset)) => offset,
|
Ok(VariableLocation::Stack(offset)) => offset,
|
||||||
_ => {
|
_ => {
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
// r1 - r7 : Temporary Variables
|
// r1 - r7 : Temporary Variables
|
||||||
// r8 - r14 : Persistant Variables
|
// r8 - r14 : Persistant Variables
|
||||||
|
|
||||||
use parser::tree_node::Literal;
|
use lsp_types::{Diagnostic, DiagnosticSeverity};
|
||||||
|
use parser::tree_node::{Literal, Span};
|
||||||
use quick_error::quick_error;
|
use quick_error::quick_error;
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
|
||||||
@@ -13,18 +14,33 @@ const PERSIST: [u8; 7] = [8, 9, 10, 11, 12, 13, 14];
|
|||||||
quick_error! {
|
quick_error! {
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
DuplicateVariable(var: String) {
|
DuplicateVariable(var: String, span: Option<Span>) {
|
||||||
display("{var} already exists.")
|
display("{var} already exists.")
|
||||||
}
|
}
|
||||||
UnknownVariable(var: String) {
|
UnknownVariable(var: String, span: Option<Span>) {
|
||||||
display("{var} does not exist.")
|
display("{var} does not exist.")
|
||||||
}
|
}
|
||||||
Unknown(reason: String) {
|
Unknown(reason: String, span: Option<Span>) {
|
||||||
display("{reason}")
|
display("{reason}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<Error> for lsp_types::Diagnostic {
|
||||||
|
fn from(value: Error) -> Self {
|
||||||
|
match value {
|
||||||
|
Error::DuplicateVariable(_, span)
|
||||||
|
| Error::UnknownVariable(_, span)
|
||||||
|
| Error::Unknown(_, span) => Diagnostic {
|
||||||
|
range: span.map(lsp_types::Range::from).unwrap_or_default(),
|
||||||
|
severity: Some(DiagnosticSeverity::ERROR),
|
||||||
|
message: value.to_string(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A request to store a variable at a specific register type
|
/// A request to store a variable at a specific register type
|
||||||
pub enum LocationRequest {
|
pub enum LocationRequest {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@@ -112,10 +128,11 @@ impl<'a> VariableScope<'a> {
|
|||||||
&mut self,
|
&mut self,
|
||||||
var_name: impl Into<String>,
|
var_name: impl Into<String>,
|
||||||
location: LocationRequest,
|
location: LocationRequest,
|
||||||
|
span: Option<Span>,
|
||||||
) -> Result<VariableLocation, Error> {
|
) -> Result<VariableLocation, Error> {
|
||||||
let var_name = var_name.into();
|
let var_name = var_name.into();
|
||||||
if self.var_lookup_table.contains_key(var_name.as_str()) {
|
if self.var_lookup_table.contains_key(var_name.as_str()) {
|
||||||
return Err(Error::DuplicateVariable(var_name));
|
return Err(Error::DuplicateVariable(var_name, span));
|
||||||
}
|
}
|
||||||
let var_location = match location {
|
let var_location = match location {
|
||||||
LocationRequest::Temp => {
|
LocationRequest::Temp => {
|
||||||
@@ -151,10 +168,11 @@ impl<'a> VariableScope<'a> {
|
|||||||
&mut self,
|
&mut self,
|
||||||
var_name: impl Into<String>,
|
var_name: impl Into<String>,
|
||||||
value: Literal,
|
value: Literal,
|
||||||
|
span: Option<Span>,
|
||||||
) -> Result<VariableLocation, Error> {
|
) -> Result<VariableLocation, Error> {
|
||||||
let var_name = var_name.into();
|
let var_name = var_name.into();
|
||||||
if self.var_lookup_table.contains_key(&var_name) {
|
if self.var_lookup_table.contains_key(&var_name) {
|
||||||
return Err(Error::DuplicateVariable(var_name));
|
return Err(Error::DuplicateVariable(var_name, span));
|
||||||
}
|
}
|
||||||
|
|
||||||
let new_value = VariableLocation::Constant(value);
|
let new_value = VariableLocation::Constant(value);
|
||||||
@@ -163,7 +181,11 @@ impl<'a> VariableScope<'a> {
|
|||||||
Ok(new_value)
|
Ok(new_value)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_location_of(&self, var_name: impl Into<String>) -> Result<VariableLocation, Error> {
|
pub fn get_location_of(
|
||||||
|
&self,
|
||||||
|
var_name: impl Into<String>,
|
||||||
|
span: Option<Span>,
|
||||||
|
) -> Result<VariableLocation, Error> {
|
||||||
let var_name = var_name.into();
|
let var_name = var_name.into();
|
||||||
|
|
||||||
// 1. Check this scope
|
// 1. Check this scope
|
||||||
@@ -180,7 +202,7 @@ impl<'a> VariableScope<'a> {
|
|||||||
|
|
||||||
// 2. Recursively check parent
|
// 2. Recursively check parent
|
||||||
if let Some(parent) = self.parent {
|
if let Some(parent) = self.parent {
|
||||||
let loc = parent.get_location_of(var_name)?;
|
let loc = parent.get_location_of(var_name, span)?;
|
||||||
|
|
||||||
if let VariableLocation::Stack(parent_offset) = loc {
|
if let VariableLocation::Stack(parent_offset) = loc {
|
||||||
return Ok(VariableLocation::Stack(parent_offset + self.stack_offset));
|
return Ok(VariableLocation::Stack(parent_offset + self.stack_offset));
|
||||||
@@ -188,7 +210,7 @@ impl<'a> VariableScope<'a> {
|
|||||||
return Ok(loc);
|
return Ok(loc);
|
||||||
}
|
}
|
||||||
|
|
||||||
Err(Error::UnknownVariable(var_name))
|
Err(Error::UnknownVariable(var_name, span))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_parent(&self) -> bool {
|
pub fn has_parent(&self) -> bool {
|
||||||
@@ -196,10 +218,14 @@ impl<'a> VariableScope<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn free_temp(&mut self, var_name: impl Into<String>) -> Result<(), Error> {
|
pub fn free_temp(
|
||||||
|
&mut self,
|
||||||
|
var_name: impl Into<String>,
|
||||||
|
span: Option<Span>,
|
||||||
|
) -> Result<(), Error> {
|
||||||
let var_name = var_name.into();
|
let var_name = var_name.into();
|
||||||
let Some(location) = self.var_lookup_table.remove(var_name.as_str()) else {
|
let Some(location) = self.var_lookup_table.remove(var_name.as_str()) else {
|
||||||
return Err(Error::UnknownVariable(var_name));
|
return Err(Error::UnknownVariable(var_name, span));
|
||||||
};
|
};
|
||||||
|
|
||||||
match location {
|
match location {
|
||||||
@@ -207,9 +233,10 @@ impl<'a> VariableScope<'a> {
|
|||||||
self.temporary_vars.push_back(t);
|
self.temporary_vars.push_back(t);
|
||||||
}
|
}
|
||||||
VariableLocation::Persistant(_) => {
|
VariableLocation::Persistant(_) => {
|
||||||
return Err(Error::UnknownVariable(String::from(
|
return Err(Error::UnknownVariable(
|
||||||
"Attempted to free a `let` variable.",
|
String::from("Attempted to free a `let` variable."),
|
||||||
)));
|
span,
|
||||||
|
));
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ mod test;
|
|||||||
pub mod sys_call;
|
pub mod sys_call;
|
||||||
pub mod tree_node;
|
pub mod tree_node;
|
||||||
|
|
||||||
use crate::sys_call::System;
|
use crate::sys_call::{Math, System};
|
||||||
use quick_error::quick_error;
|
use quick_error::quick_error;
|
||||||
use std::io::SeekFrom;
|
use std::io::SeekFrom;
|
||||||
use sys_call::SysCall;
|
use sys_call::SysCall;
|
||||||
@@ -1349,11 +1349,24 @@ impl<'a> Parser<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn literal(&mut self) -> Result<Literal, Error> {
|
fn literal(&mut self) -> Result<Literal, Error> {
|
||||||
let current_token = self.current_token.as_ref().ok_or(Error::UnexpectedEOF)?;
|
let current_token = self.current_token.clone().ok_or(Error::UnexpectedEOF)?;
|
||||||
let literal = match current_token.token_type {
|
let literal = match current_token.token_type {
|
||||||
TokenType::Number(num) => Literal::Number(num),
|
TokenType::Number(num) => Literal::Number(num),
|
||||||
TokenType::String(ref string) => Literal::String(string.clone()),
|
TokenType::String(ref string) => Literal::String(string.clone()),
|
||||||
TokenType::Boolean(boolean) => Literal::Boolean(boolean),
|
TokenType::Boolean(boolean) => Literal::Boolean(boolean),
|
||||||
|
TokenType::Symbol(Symbol::Minus) => match self.get_next()? {
|
||||||
|
Some(Token {
|
||||||
|
token_type: TokenType::Number(num),
|
||||||
|
..
|
||||||
|
}) => Literal::Number(-*num),
|
||||||
|
Some(wrong_token) => {
|
||||||
|
return Err(Error::UnexpectedToken(
|
||||||
|
Self::token_to_span(wrong_token),
|
||||||
|
wrong_token.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
None => return Err(Error::UnexpectedEOF),
|
||||||
|
},
|
||||||
_ => {
|
_ => {
|
||||||
return Err(Error::UnexpectedToken(
|
return Err(Error::UnexpectedToken(
|
||||||
self.current_span(),
|
self.current_span(),
|
||||||
@@ -1636,6 +1649,7 @@ impl<'a> Parser<'a> {
|
|||||||
let invocation = self.invocation()?;
|
let invocation = self.invocation()?;
|
||||||
|
|
||||||
match invocation.name.node.as_str() {
|
match invocation.name.node.as_str() {
|
||||||
|
// System SysCalls
|
||||||
"yield" => {
|
"yield" => {
|
||||||
check_length(self, &invocation.arguments, 0)?;
|
check_length(self, &invocation.arguments, 0)?;
|
||||||
Ok(SysCall::System(sys_call::System::Yield))
|
Ok(SysCall::System(sys_call::System::Yield))
|
||||||
@@ -1809,6 +1823,119 @@ impl<'a> Parser<'a> {
|
|||||||
expr,
|
expr,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
// Math SysCalls
|
||||||
|
"acos" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let tmp = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Acos(boxed!(tmp))))
|
||||||
|
}
|
||||||
|
"asin" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let tmp = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Asin(boxed!(tmp))))
|
||||||
|
}
|
||||||
|
"atan" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let expr = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Atan(boxed!(expr))))
|
||||||
|
}
|
||||||
|
"atan2" => {
|
||||||
|
check_length(self, &invocation.arguments, 2)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg1 = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
let arg2 = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Atan2(boxed!(arg1), boxed!(arg2))))
|
||||||
|
}
|
||||||
|
"abs" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let expr = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Abs(boxed!(expr))))
|
||||||
|
}
|
||||||
|
"ceil" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Ceil(boxed!(arg))))
|
||||||
|
}
|
||||||
|
"cos" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Cos(boxed!(arg))))
|
||||||
|
}
|
||||||
|
"floor" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Floor(boxed!(arg))))
|
||||||
|
}
|
||||||
|
"log" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Log(boxed!(arg))))
|
||||||
|
}
|
||||||
|
"max" => {
|
||||||
|
check_length(self, &invocation.arguments, 2)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg1 = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
let arg2 = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Max(boxed!(arg1), boxed!(arg2))))
|
||||||
|
}
|
||||||
|
"min" => {
|
||||||
|
check_length(self, &invocation.arguments, 2)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg1 = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
let arg2 = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Min(boxed!(arg1), boxed!(arg2))))
|
||||||
|
}
|
||||||
|
"rand" => {
|
||||||
|
check_length(self, &invocation.arguments, 0)?;
|
||||||
|
Ok(SysCall::Math(Math::Rand))
|
||||||
|
}
|
||||||
|
"sin" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Sin(boxed!(arg))))
|
||||||
|
}
|
||||||
|
"sqrt" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Sqrt(boxed!(arg))))
|
||||||
|
}
|
||||||
|
"tan" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Tan(boxed!(arg))))
|
||||||
|
}
|
||||||
|
"trunc" => {
|
||||||
|
check_length(self, &invocation.arguments, 1)?;
|
||||||
|
let mut args = invocation.arguments.into_iter();
|
||||||
|
let arg = args.next().ok_or(Error::UnexpectedEOF)?;
|
||||||
|
|
||||||
|
Ok(SysCall::Math(Math::Trunc(boxed!(arg))))
|
||||||
|
}
|
||||||
_ => Err(Error::UnsupportedKeyword(
|
_ => Err(Error::UnsupportedKeyword(
|
||||||
self.current_span(),
|
self.current_span(),
|
||||||
self.current_token.clone().ok_or(Error::UnexpectedEOF)?,
|
self.current_token.clone().ok_or(Error::UnexpectedEOF)?,
|
||||||
|
|||||||
@@ -10,67 +10,67 @@ documented! {
|
|||||||
/// `acos r? a(r?|num)`
|
/// `acos r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).acos();`
|
/// `(number|var).acos();`
|
||||||
Acos(LiteralOrVariable),
|
Acos(Box<Spanned<Expression>>),
|
||||||
/// Returns the angle in radians whose sine is the specified number.
|
/// Returns the angle in radians whose sine is the specified number.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `asin r? a(r?|num)`
|
/// `asin r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).asin();`
|
/// `(number|var).asin();`
|
||||||
Asin(LiteralOrVariable),
|
Asin(Box<Spanned<Expression>>),
|
||||||
/// Returns the angle in radians whose tangent is the specified number.
|
/// Returns the angle in radians whose tangent is the specified number.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `atan r? a(r?|num)`
|
/// `atan r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).atan();`
|
/// `(number|var).atan();`
|
||||||
Atan(LiteralOrVariable),
|
Atan(Box<Spanned<Expression>>),
|
||||||
/// Returns the angle in radians whose tangent is the quotient of the specified numbers.
|
/// Returns the angle in radians whose tangent is the quotient of the specified numbers.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `atan2 r? a(r?|num) b(r?|num)`
|
/// `atan2 r? a(r?|num) b(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).atan2((number|var));`
|
/// `(number|var).atan2((number|var));`
|
||||||
Atan2(LiteralOrVariable, LiteralOrVariable),
|
Atan2(Box<Spanned<Expression>>, Box<Spanned<Expression>>),
|
||||||
/// Gets the absolute value of a number.
|
/// Gets the absolute value of a number.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `abs r? a(r?|num)`
|
/// `abs r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).abs();`
|
/// `(number|var).abs();`
|
||||||
Abs(LiteralOrVariable),
|
Abs(Box<Spanned<Expression>>),
|
||||||
/// Rounds a number up to the nearest whole number.
|
/// Rounds a number up to the nearest whole number.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `ceil r? a(r?|num)`
|
/// `ceil r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).ceil();`
|
/// `(number|var).ceil();`
|
||||||
Ceil(LiteralOrVariable),
|
Ceil(Box<Spanned<Expression>>),
|
||||||
/// Returns the cosine of the specified angle in radians.
|
/// Returns the cosine of the specified angle in radians.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `cos r? a(r?|num)`
|
/// `cos r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).cos();`
|
/// `(number|var).cos();`
|
||||||
Cos(LiteralOrVariable),
|
Cos(Box<Spanned<Expression>>),
|
||||||
/// Rounds a number down to the nearest whole number.
|
/// Rounds a number down to the nearest whole number.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `floor r? a(r?|num)`
|
/// `floor r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).floor();`
|
/// `(number|var).floor();`
|
||||||
Floor(LiteralOrVariable),
|
Floor(Box<Spanned<Expression>>),
|
||||||
/// Computes the natural logarithm of a number.
|
/// Computes the natural logarithm of a number.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `log r? a(r?|num)`
|
/// `log r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).log();`
|
/// `(number|var).log();`
|
||||||
Log(LiteralOrVariable),
|
Log(Box<Spanned<Expression>>),
|
||||||
/// Computes the maximum of two numbers.
|
/// Computes the maximum of two numbers.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `max r? a(r?|num) b(r?|num)`
|
/// `max r? a(r?|num) b(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).max((number|var));`
|
/// `(number|var).max((number|var));`
|
||||||
Max(LiteralOrVariable, LiteralOrVariable),
|
Max(Box<Spanned<Expression>>, Box<Spanned<Expression>>),
|
||||||
/// Computes the minimum of two numbers.
|
/// Computes the minimum of two numbers.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `min r? a(r?|num) b(r?|num)`
|
/// `min r? a(r?|num) b(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).min((number|var));`
|
/// `(number|var).min((number|var));`
|
||||||
Min(LiteralOrVariable, LiteralOrVariable),
|
Min(Box<Spanned<Expression>>, Box<Spanned<Expression>>),
|
||||||
/// Gets a random number between 0 and 1.
|
/// Gets a random number between 0 and 1.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `rand r?`
|
/// `rand r?`
|
||||||
@@ -82,25 +82,25 @@ documented! {
|
|||||||
/// `sin r? a(r?|num)`
|
/// `sin r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).sin();`
|
/// `(number|var).sin();`
|
||||||
Sin(LiteralOrVariable),
|
Sin(Box<Spanned<Expression>>),
|
||||||
/// Computes the square root of a number.
|
/// Computes the square root of a number.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `sqrt r? a(r?|num)`
|
/// `sqrt r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).sqrt();`
|
/// `(number|var).sqrt();`
|
||||||
Sqrt(LiteralOrVariable),
|
Sqrt(Box<Spanned<Expression>>),
|
||||||
/// Returns the tangent of the specified angle in radians.
|
/// Returns the tangent of the specified angle in radians.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `tan r? a(r?|num)`
|
/// `tan r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).tan();`
|
/// `(number|var).tan();`
|
||||||
Tan(LiteralOrVariable),
|
Tan(Box<Spanned<Expression>>),
|
||||||
/// Truncates a number by removing the decimal portion.
|
/// Truncates a number by removing the decimal portion.
|
||||||
/// ## IC10
|
/// ## IC10
|
||||||
/// `trunc r? a(r?|num)`
|
/// `trunc r? a(r?|num)`
|
||||||
/// ## Slang
|
/// ## Slang
|
||||||
/// `(number|var).trunc();`
|
/// `(number|var).trunc();`
|
||||||
Trunc(LiteralOrVariable),
|
Trunc(Box<Spanned<Expression>>),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,6 +231,7 @@ impl std::fmt::Display for System {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
/// This represents built in functions that cannot be overwritten, but can be invoked by the user as functions.
|
/// This represents built in functions that cannot be overwritten, but can be invoked by the user as functions.
|
||||||
pub enum SysCall {
|
pub enum SysCall {
|
||||||
|
|||||||
@@ -151,3 +151,12 @@ fn test_const_hash_expression() -> Result<()> {
|
|||||||
assert_eq!("(const i = hash(\"item\"))", expr.to_string());
|
assert_eq!("(const i = hash(\"item\"))", expr.to_string());
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_negative_literal_const() -> Result<()> {
|
||||||
|
let expr = parser!(r#"const i = -123"#).parse()?.unwrap();
|
||||||
|
|
||||||
|
assert_eq!("(const i = -123)", expr.to_string());
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user