From 1e1aeb4dad97f013d7e3dd53fce7652ec3da5074 Mon Sep 17 00:00:00 2001 From: nic-gaffney Date: Sat, 19 Aug 2023 18:55:31 -0500 Subject: [PATCH] stuff --- build.sh | 3 ++- sloth/src/parser/ast.rs | 5 +++++ sloth/src/parser/stmt.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/build.sh b/build.sh index cbcd805..01cb027 100755 --- a/build.sh +++ b/build.sh @@ -1,11 +1,12 @@ # Build Sloth -cargo build +#cargo build FILENAME="$1" # Compile standard library ./target/debug/sloth std/extern.sloth std/stdmath.sloth std/stdio.sloth $FILENAME # Generate binary clang --verbose -lm output.o std/stdio.c std/stdlib.c std/stdmath.c -o "${FILENAME%.sloth}" +rm output.o # Move file mv "${FILENAME%.sloth}" . diff --git a/sloth/src/parser/ast.rs b/sloth/src/parser/ast.rs index 74500ef..bf6f342 100644 --- a/sloth/src/parser/ast.rs +++ b/sloth/src/parser/ast.rs @@ -237,6 +237,11 @@ pub enum StmtKind { identifier: String, value: Expr, }, + DefineValue { + identifier: String, + value: Expr, + typ: Option, + }, /// A function definition. Output is None when the function returns nothing /// meaning void, otherwise it is the name of the type the function /// returns. diff --git a/sloth/src/parser/stmt.rs b/sloth/src/parser/stmt.rs index 75ef1b2..a617f87 100644 --- a/sloth/src/parser/stmt.rs +++ b/sloth/src/parser/stmt.rs @@ -16,6 +16,7 @@ impl<'a> AstParser<'a> { TokenType::While => self.while_stmt(), TokenType::For => self.for_stmt(), TokenType::Var => self.define_variable(), + TokenType::Val => self.define_value(), TokenType::Fn => self.define_function(false), TokenType::Return => self.return_stmt(), @@ -116,6 +117,37 @@ impl<'a> AstParser<'a> { )) } + fn define_value(&mut self) -> Result { + // Consume the var token + self.consume(TokenType::Val, "Expected val")?; + + // Get the identifier and type + let identifier = self.consume_identifier()?; + let typ = if self.consume(TokenType::Colon, "Expected ':'").is_ok() { + self.consume_type().ok() + } else { + None + }; + + // Get the default value + self.consume(TokenType::Eq, "Expected '='")?; + let value = self.expression()?; + + self.consume(TokenType::SemiColon, "Expected ';' at end of statement")?; + + let kind = StmtKind::DefineVariable { + identifier, + value, + typ, + }; + + Ok(Stmt::new( + self.reserve_id(), + self.line, + kind, + self.top.clone(), + )) + } // TODO: Make variable types optional fn define_variable(&mut self) -> Result { // Consume the var token