From ef2496b87a75398004eb922237de0b2315161dfc Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 17 Mar 2026 20:31:01 +0530 Subject: [PATCH 1/2] feature rollout --- .gitignore | 3 +- compiler/.DS_Store | Bin 6148 -> 6148 bytes compiler/Cargo.lock | 7 - compiler/Cargo.toml | 10 - compiler/README.md | 32 -- compiler/simple.rey | 6 - compiler/src/ast/expr.rs | 30 -- compiler/src/ast/literal.rs | 7 - compiler/src/ast/mod.rs | 9 - compiler/src/ast/stmt.rs | 41 -- compiler/src/ast/ty.rs | 4 - compiler/src/interpreter/control_flow.rs | 33 -- compiler/src/interpreter/environment.rs | 59 --- compiler/src/interpreter/evaluator.rs | 86 ---- compiler/src/interpreter/executor.rs | 284 ------------- compiler/src/interpreter/function.rs | 25 -- compiler/src/interpreter/interpreter.rs | 31 -- compiler/src/interpreter/mod.rs | 17 - compiler/src/interpreter/std.rs | 44 -- compiler/src/interpreter/value.rs | 22 - compiler/src/lexer/cursor.rs | 32 -- compiler/src/lexer/error.rs | 16 - compiler/src/lexer/lexer.rs | 188 --------- compiler/src/lexer/mod.rs | 8 - compiler/src/lexer/span.rs | 14 - compiler/src/lexer/token.rs | 76 ---- compiler/src/main.rs | 65 --- compiler/src/parser/error.rs | 26 -- compiler/src/parser/mod.rs | 5 - compiler/src/parser/parser.rs | 509 ----------------------- compiler/src/tests/arrays.rey | 11 - compiler/src/tests/compute.rey | 14 - compiler/src/tests/datatypes.rey | 13 - compiler/src/tests/dictionaries.rey | 12 - compiler/src/tests/fub.rey | 0 compiler/src/tests/functions.rey | 14 - compiler/src/tests/io.rey | 7 - compiler/src/tests/math.rey | 16 - compiler/src/tests/stdlib.rey | 11 - compiler/src/tests/strings.rey | 7 - compiler/src/tests/variables.rey | 16 - 41 files changed, 2 insertions(+), 1808 deletions(-) delete mode 100644 compiler/Cargo.lock delete mode 100644 compiler/Cargo.toml delete mode 100644 compiler/README.md delete mode 100644 compiler/simple.rey delete mode 100644 compiler/src/ast/expr.rs delete mode 100644 compiler/src/ast/literal.rs delete mode 100644 compiler/src/ast/mod.rs delete mode 100644 compiler/src/ast/stmt.rs delete mode 100644 compiler/src/ast/ty.rs delete mode 100644 compiler/src/interpreter/control_flow.rs delete mode 100644 compiler/src/interpreter/environment.rs delete mode 100644 compiler/src/interpreter/evaluator.rs delete mode 100644 compiler/src/interpreter/executor.rs delete mode 100644 compiler/src/interpreter/function.rs delete mode 100644 compiler/src/interpreter/interpreter.rs delete mode 100644 compiler/src/interpreter/mod.rs delete mode 100644 compiler/src/interpreter/std.rs delete mode 100644 compiler/src/interpreter/value.rs delete mode 100644 compiler/src/lexer/cursor.rs delete mode 100644 compiler/src/lexer/error.rs delete mode 100644 compiler/src/lexer/lexer.rs delete mode 100644 compiler/src/lexer/mod.rs delete mode 100644 compiler/src/lexer/span.rs delete mode 100644 compiler/src/lexer/token.rs delete mode 100644 compiler/src/main.rs delete mode 100644 compiler/src/parser/error.rs delete mode 100644 compiler/src/parser/mod.rs delete mode 100644 compiler/src/parser/parser.rs delete mode 100644 compiler/src/tests/arrays.rey delete mode 100644 compiler/src/tests/compute.rey delete mode 100644 compiler/src/tests/datatypes.rey delete mode 100644 compiler/src/tests/dictionaries.rey delete mode 100644 compiler/src/tests/fub.rey delete mode 100644 compiler/src/tests/functions.rey delete mode 100644 compiler/src/tests/io.rey delete mode 100644 compiler/src/tests/math.rey delete mode 100644 compiler/src/tests/stdlib.rey delete mode 100644 compiler/src/tests/strings.rey delete mode 100644 compiler/src/tests/variables.rey diff --git a/.gitignore b/.gitignore index 8838ecf..bde15db 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,6 @@ target/ .DS_Store *.lock -test_all.rey + resumes.txt +test_all.rey diff --git a/compiler/.DS_Store b/compiler/.DS_Store index 3162d751a925f83edb9ebc2baed921f4dcc975e8..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 100644 GIT binary patch delta 70 zcmZoMXfc=|#>AjHF;Q%yo+1YW5HK<@2y7N)`o_9hfoT`xW_AvK4xj>{$am(+{342+ UKzW7)kiy9(Jj$D6L{=~Z01d_tO#lD@ delta 329 zcmZoMXfc=|#>B`mF;Q%yo+3X70|Nsi1A_pAVQ_MOZo$OFwe=t&W`<&hB8KFgbcire z1PGdb012o}ZoZ34QcivnP=w=sOhg51!*NGs*%Umo1sO=DG8q81F|aX|FeCzPOlL@~ zXDC6j_P)VcR0Rwr$d=z*WzQo3u^h<|kQ#&&aH&CY$nyyxhcGZ~O#jC^*+7J4GdBk} e2QZ*ECVpq0%rBzI$^?{Dm~1E_yxBu!4>JJo-%YXr diff --git a/compiler/Cargo.lock b/compiler/Cargo.lock deleted file mode 100644 index 114ae2a..0000000 --- a/compiler/Cargo.lock +++ /dev/null @@ -1,7 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "rey-v0" -version = "0.1.0" \ No newline at end of file diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml deleted file mode 100644 index 9e06cad..0000000 --- a/compiler/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "rey-v0" -version = "0.1.0" -edition = "2021" - -description = "Rey v0 reference interpreter" -license = "MIT" -authors = ["Misbah Khursheed "] - -[dependencies] diff --git a/compiler/README.md b/compiler/README.md deleted file mode 100644 index dee4af3..0000000 --- a/compiler/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# Rey Language Specification — Version 0 (v0) - -This document defines the **Version 0 (v0)** specification of the Rey programming language. - -Rey is an experimental programming language designed to be **dynamic by default**, with **optional, explicit type annotations** that are strictly enforced once declared. - -## Scope of v0 - -Rey v0 intentionally defines a **minimal core language**. Its purpose is to establish correct and consistent semantics, not feature completeness. - -Rey v0 includes: -- Variables and assignment -- Optional type annotations -- Functions -- Basic execution model -- Basic built-in types - -Rey v0 does **not** include: -- Objects or classes -- Contracts or invariants -- Concurrency or async execution -- Manual memory management -- Modules or imports - -These features are reserved for future versions. - -## Normative Language - -The key words **MUST**, **MUST NOT**, **SHOULD**, and **MAY** are to be interpreted as described in RFC 2119. - -This specification is **normative**. -Any implementation of Rey v0 **must conform** to the rules described here. diff --git a/compiler/simple.rey b/compiler/simple.rey deleted file mode 100644 index f616ef8..0000000 --- a/compiler/simple.rey +++ /dev/null @@ -1,6 +0,0 @@ -var x: int = 10; -var y = 20; -var result: int= x+y; -func main() { - println(result); -} diff --git a/compiler/src/ast/expr.rs b/compiler/src/ast/expr.rs deleted file mode 100644 index efa6635..0000000 --- a/compiler/src/ast/expr.rs +++ /dev/null @@ -1,30 +0,0 @@ -use super::Literal; -use crate::lexer::TokenKind; - -#[derive(Debug, Clone, PartialEq)] -pub enum Expr { - Literal(Literal), - Binary { - left: Box, - op: TokenKind, - right: Box, - }, - Variable(String), - Call { - callee: Box, - args: Vec, - }, - Unary { - op: TokenKind, - right: Box, - }, - - Assign { - name: String, - value: Box, - }, - Get { - object: Box, - name: String, - }, -} diff --git a/compiler/src/ast/literal.rs b/compiler/src/ast/literal.rs deleted file mode 100644 index 697fdb7..0000000 --- a/compiler/src/ast/literal.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[derive(Debug, Clone, PartialEq)] -pub enum Literal { - String(String), - Number(f64), - Bool(bool), - Null, -} diff --git a/compiler/src/ast/mod.rs b/compiler/src/ast/mod.rs deleted file mode 100644 index 8a87332..0000000 --- a/compiler/src/ast/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod expr; -pub mod literal; -pub mod stmt; -pub mod ty; - -pub use expr::Expr; -pub use literal::Literal; -pub use stmt::{Parameter, Stmt}; -pub use ty::Type; diff --git a/compiler/src/ast/stmt.rs b/compiler/src/ast/stmt.rs deleted file mode 100644 index 13ede5f..0000000 --- a/compiler/src/ast/stmt.rs +++ /dev/null @@ -1,41 +0,0 @@ -use super::{Expr, Type}; - -#[derive(Debug, Clone, PartialEq)] -pub struct Parameter { - pub name: String, - pub ty: Option, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum Stmt { - VarDecl { - name: String, - ty: Option, - initializer: Expr, - }, - FuncDecl { - name: String, - params: Vec, - return_ty: Option, - body: Vec, - }, - If { - condition: Expr, - then_branch: Vec, - else_branch: Option>, - }, - While { - condition: Expr, - body: Vec, - }, - For { - variable: String, - start: Expr, - end: Expr, - body: Vec, - }, - Break, - Continue, - Return(Expr), - ExprStmt(Expr), -} diff --git a/compiler/src/ast/ty.rs b/compiler/src/ast/ty.rs deleted file mode 100644 index bcae205..0000000 --- a/compiler/src/ast/ty.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[derive(Debug, Clone, PartialEq)] -pub struct Type { - pub name: String, -} diff --git a/compiler/src/interpreter/control_flow.rs b/compiler/src/interpreter/control_flow.rs deleted file mode 100644 index e55a98f..0000000 --- a/compiler/src/interpreter/control_flow.rs +++ /dev/null @@ -1,33 +0,0 @@ -use super::value::Value; - -#[derive(Debug, Clone)] -pub enum ControlFlow { - Normal(Value), - Return(Value), - Break, - Continue, -} - -impl ControlFlow { - pub fn normal(value: Value) -> Self { - ControlFlow::Normal(value) - } - - pub fn return_value(value: Value) -> Self { - ControlFlow::Return(value) - } - - pub fn unwrap_normal(self) -> Value { - match self { - ControlFlow::Normal(value) => value, - _ => panic!("Expected normal control flow"), - } - } - - pub fn unwrap_return(self) -> Value { - match self { - ControlFlow::Return(value) => value, - _ => panic!("Expected return control flow"), - } - } -} \ No newline at end of file diff --git a/compiler/src/interpreter/environment.rs b/compiler/src/interpreter/environment.rs deleted file mode 100644 index dcd36a6..0000000 --- a/compiler/src/interpreter/environment.rs +++ /dev/null @@ -1,59 +0,0 @@ -use std::collections::HashMap; -use std::rc::Rc; -use super::value::Value; - -pub struct Environment { - values: HashMap, - parent: Option>, -} - -impl Clone for Environment { - fn clone(&self) -> Self { - Self { - values: self.values.clone(), - parent: self.parent.clone(), - } - } -} - -impl Environment { - pub fn new() -> Self { - Self { - values: HashMap::new(), - parent: None, - } - } - pub fn with_parent(parent: Environment) -> Self { - Self { - values: HashMap::new(), - parent: Some(Rc::new(parent)), - } - } - - pub fn define(&mut self, name: String, value: Value) { - self.values.insert(name, value); - } - - pub fn get(&self, name: &str) -> Option<&Value> { - if let Some(v) = self.values.get(name) { - Some(v) - } else if let Some(parent) = &self.parent { - parent.get(name) - } else { - None - } - } - - - - pub fn assign(&mut self, name: &str, value: Value) -> Result<(), String> { - if self.values.contains_key(name) { - self.values.insert(name.to_string(), value); - Ok(()) - } else { - Err(format!("Undefined variable '{}'", name)) - } - } - - -} \ No newline at end of file diff --git a/compiler/src/interpreter/evaluator.rs b/compiler/src/interpreter/evaluator.rs deleted file mode 100644 index 4553cc0..0000000 --- a/compiler/src/interpreter/evaluator.rs +++ /dev/null @@ -1,86 +0,0 @@ -use crate::ast::Expr; -use crate::lexer::TokenKind; -use super::value::Value; -use super::environment::Environment; - -pub struct Evaluator; - -impl Evaluator { - pub fn new() -> Self { - Self - } - - pub fn evaluate(&self, expr: &Expr, env:&mut Environment) -> Result { - match expr { - Expr::Literal(lit) => Ok(Value::from(lit.clone())), - Expr::Variable(name) => env - .get(name) - .cloned() - .ok_or_else(|| format!("Undefined variable '{}'", name)), - Expr::Binary { left, op, right } => { - let left_val = self.evaluate(left, env)?; - let right_val = self.evaluate(right, env)?; - self.evaluate_binary(left_val, op, right_val) - } - Expr::Unary { op, right } => { - let right_val = self.evaluate(right, env)?; - self.evaluate_unary(op, right_val) - } - Expr::Assign { name, value } => { - let val = self.evaluate(value, env)?; - - Err("Assignment should be handled by executor".to_string()) - } - Expr::Call { callee, args } => { - Err("Function calls must be handled as statements".to_string()) - } - Expr::Get { .. } => { - Err("Property access not implemented yet".to_string()) - } - } - } - - fn evaluate_binary(&self, left: Value, op: &TokenKind, right: Value) -> Result { - use TokenKind::*; - - match (left, op, right) { - (Value::Number(l), Plus, Value::Number(r)) => Ok(Value::Number(l + r)), - (Value::Number(l), Minus, Value::Number(r)) => Ok(Value::Number(l - r)), - (Value::Number(l), Star, Value::Number(r)) => Ok(Value::Number(l * r)), - (Value::Number(l), Slash, Value::Number(r)) => { - if r == 0.0 { - Err("Division by zero".to_string()) - } else { - Ok(Value::Number(l / r)) - } - } - (Value::Number(l), EqualEqual, Value::Number(r)) => Ok(Value::Bool(l == r)), - (Value::Number(l), BangEqual, Value::Number(r)) => Ok(Value::Bool(l != r)), - (Value::Number(l), Less, Value::Number(r)) => Ok(Value::Bool(l < r)), - (Value::Number(l), LessEqual, Value::Number(r)) => Ok(Value::Bool(l <= r)), - (Value::Number(l), Greater, Value::Number(r)) => Ok(Value::Bool(l > r)), - (Value::Number(l), GreaterEqual, Value::Number(r)) => Ok(Value::Bool(l >= r)), - - (Value::String(l), Plus, Value::String(r)) => Ok(Value::String(l + &r)), - (Value::String(l), EqualEqual, Value::String(r)) => Ok(Value::Bool(l == r)), - (Value::String(l), BangEqual, Value::String(r)) => Ok(Value::Bool(l != r)), - - (Value::Bool(l), EqualEqual, Value::Bool(r)) => Ok(Value::Bool(l == r)), - (Value::Bool(l), BangEqual, Value::Bool(r)) => Ok(Value::Bool(l != r)), - (Value::Bool(l), And, Value::Bool(r)) => Ok(Value::Bool(l && r)), - (Value::Bool(l), Or, Value::Bool(r)) => Ok(Value::Bool(l || r)), - - _ => Err("Invalid binary operation".to_string()), - } - } - - fn evaluate_unary(&self, op: &TokenKind, right: Value) -> Result { - use TokenKind::*; - - match (op, right) { - (Minus, Value::Number(n)) => Ok(Value::Number(-n)), - (Bang, Value::Bool(b)) => Ok(Value::Bool(!b)), - _ => Err("Invalid unary operation".to_string()), - } - } -} \ No newline at end of file diff --git a/compiler/src/interpreter/executor.rs b/compiler/src/interpreter/executor.rs deleted file mode 100644 index 1f0a50b..0000000 --- a/compiler/src/interpreter/executor.rs +++ /dev/null @@ -1,284 +0,0 @@ -use crate::ast::{Expr, Stmt}; -use crate::lexer::span::Span; -use crate::lexer::TokenKind; -use super::control_flow::ControlFlow; -use super::environment::Environment; -use super::function::Function; -use super::value::Value; - -pub struct Executor; - -impl Executor { - pub fn new() -> Self { - Self - } - - pub fn execute(&self, stmt: &Stmt, env: &mut Environment) -> Result { - match stmt { - Stmt::VarDecl { name, initializer, .. } => { - let value = self.evaluate_expr(initializer, env)?; - env.define(name.clone(), value); - Ok(ControlFlow::normal(Value::Null)) - } - Stmt::ExprStmt(expr) => { - let value = self.evaluate_expr(expr, env)?; - Ok(ControlFlow::normal(value)) - } - Stmt::FuncDecl { name, params, body, .. } => { - let function = Function::new( - name.clone(), - params.clone(), - body.clone(), - Span { start: 0, end: 0 }, // TODO: Get actual span - ); - env.define(name.clone(), Value::Function(function)); - Ok(ControlFlow::normal(Value::Null)) - } - Stmt::If { condition, then_branch, else_branch } => { - let condition_value = self.evaluate_expr(condition, env)?; - if self.isTruthy(&condition_value) { - match self.execute_block_with_control_flow(then_branch, env)? { - ControlFlow::Normal(_) => {} - ControlFlow::Return(value) => return Ok(ControlFlow::Return(value)), - ControlFlow::Break | ControlFlow::Continue => { - return Err("Break/continue not allowed in if statement".to_string()); - } - } - } else if let Some(else_branch) = else_branch { - match self.execute_block_with_control_flow(else_branch, env)? { - ControlFlow::Normal(_) => {} - ControlFlow::Return(value) => return Ok(ControlFlow::Return(value)), - ControlFlow::Break | ControlFlow::Continue => { - return Err("Break/continue not allowed in if statement".to_string()); - } - } - } - Ok(ControlFlow::normal(Value::Null)) - } - Stmt::While { condition, body } => { - while self.isTruthy(&self.evaluate_expr(condition, env)?) { - match self.execute_block_with_control_flow(body, env)? { - ControlFlow::Break => break, - ControlFlow::Continue => continue, - ControlFlow::Return(value) => return Ok(ControlFlow::return_value(value)), - ControlFlow::Normal(_) => {} // Continue to next iteration - } - } - Ok(ControlFlow::normal(Value::Null)) - } - Stmt::For { variable, start, end, body } => { - // Evaluate start and end expressions - let start_val = self.evaluate_expr(start, env)?; - let end_val = self.evaluate_expr(end, env)?; - - // Extract numeric values - let start_num = match start_val { - Value::Number(n) => n as i64, - _ => return Err("Range start must be a number".to_string()), - }; - let end_num = match end_val { - Value::Number(n) => n as i64, - _ => return Err("Range end must be a number".to_string()), - }; - - // Loop from start to end-1 - for i in start_num..end_num { - // Set the loop variable - env.define(variable.clone(), Value::Number(i as f64)); - - // Execute body - match self.execute_block_with_control_flow(body, env)? { - ControlFlow::Break => break, - ControlFlow::Continue => continue, - ControlFlow::Return(value) => return Ok(ControlFlow::return_value(value)), - ControlFlow::Normal(_) => {} // Continue to next iteration - } - } - Ok(ControlFlow::normal(Value::Null)) - } - Stmt::Break => { - Ok(ControlFlow::Break) - } - Stmt::Continue => { - Ok(ControlFlow::Continue) - } - Stmt::Return(expr) => { - let value = self.evaluate_expr(expr, env)?; - Ok(ControlFlow::return_value(value)) - } - } - } - - pub fn evaluate_expr(&self, expr: &Expr, env: &mut Environment) -> Result { - match expr { - Expr::Literal(lit) => Ok(Value::from(lit.clone())), - Expr::Variable(name) => env - .get(name) - .cloned() - .ok_or_else(|| format!("Undefined variable '{}'", name)), - Expr::Binary { left, op, right } => { - let left_val = self.evaluate_expr(left, env)?; - let right_val = self.evaluate_expr(right, env)?; - self.evaluate_binary(left_val, op, right_val) - } - Expr::Unary { op, right } => { - let right_val = self.evaluate_expr(right, env)?; - self.evaluate_unary(op, right_val) - } - Expr::Assign { name, value } => { - let val = self.evaluate_expr(value, env)?; - env.assign(name, val.clone())?; - Ok(val) - } - Expr::Call { callee, args } => { - // Check if it's a built-in function first - if let Expr::Variable(name) = callee.as_ref() { - let mut evaluated_args = Vec::new(); - for arg in args { - evaluated_args.push(self.evaluate_expr(arg, env)?); - } - - if let Some(result) = super::std::StdLib::call_builtin_function(name, &evaluated_args) { - result - } else { - // Not a built-in, check if it's a user-defined function - let function = self.evaluate_expr(callee, env)?; - match function { - Value::Function(func) => { - if args.len() != func.arity() { - return Err(format!( - "Expected {} arguments but got {}", - func.arity(), - args.len() - )); - } - - // Create new environment with function parameters - // The function environment should have access to the global environment - let mut function_env = Environment::with_parent(env.clone()); - - // Bind parameters to arguments - for (param, arg_value) in func.params.iter().zip(evaluated_args) { - function_env.define(param.name.clone(), arg_value); - } - - // Execute function body - self.execute_block(&func.body, &mut function_env) - } - _ => Err(format!("Can only call functions, got {:?}", function)), - } - } - } else { - // Dynamic function call (function as expression) - let function = self.evaluate_expr(callee, env)?; - match function { - Value::Function(func) => { - if args.len() != func.arity() { - return Err(format!( - "Expected {} arguments but got {}", - func.arity(), - args.len() - )); - } - - // Evaluate arguments - let mut evaluated_args = Vec::new(); - for arg in args { - evaluated_args.push(self.evaluate_expr(arg, env)?); - } - - // Create new environment with function parameters - // The function environment should have access to the global environment - let mut function_env = Environment::with_parent(env.clone()); - - // Bind parameters to arguments - for (param, arg_value) in func.params.iter().zip(evaluated_args) { - function_env.define(param.name.clone(), arg_value); - } - - // Execute function body - self.execute_block(&func.body, &mut function_env) - } - _ => Err(format!("Can only call functions, got {:?}", function)), - } - } - } - Expr::Get { .. } => { - Err("Property access not implemented yet".to_string()) - } - } - } - - fn isTruthy(&self, value: &Value) -> bool { - match value { - Value::Bool(false) => false, - Value::Null => false, - Value::Number(n) => *n != 0.0, - _ => true, - } - } - - fn evaluate_binary(&self, left: Value, op: &TokenKind, right: Value) -> Result { - use TokenKind::*; - - match (left, op, right) { - (Value::Number(l), Plus, Value::Number(r)) => Ok(Value::Number(l + r)), - (Value::Number(l), Minus, Value::Number(r)) => Ok(Value::Number(l - r)), - (Value::Number(l), Star, Value::Number(r)) => Ok(Value::Number(l * r)), - (Value::Number(l), Slash, Value::Number(r)) => { - if r == 0.0 { - Err("Division by zero".to_string()) - } else { - Ok(Value::Number(l / r)) - } - } - (Value::Number(l), EqualEqual, Value::Number(r)) => Ok(Value::Bool(l == r)), - (Value::Number(l), BangEqual, Value::Number(r)) => Ok(Value::Bool(l != r)), - (Value::Number(l), Less, Value::Number(r)) => Ok(Value::Bool(l < r)), - (Value::Number(l), LessEqual, Value::Number(r)) => Ok(Value::Bool(l <= r)), - (Value::Number(l), Greater, Value::Number(r)) => Ok(Value::Bool(l > r)), - (Value::Number(l), GreaterEqual, Value::Number(r)) => Ok(Value::Bool(l >= r)), - - (Value::String(l), Plus, Value::String(r)) => Ok(Value::String(l + &r)), - (Value::String(l), EqualEqual, Value::String(r)) => Ok(Value::Bool(l == r)), - (Value::String(l), BangEqual, Value::String(r)) => Ok(Value::Bool(l != r)), - - (Value::Bool(l), EqualEqual, Value::Bool(r)) => Ok(Value::Bool(l == r)), - (Value::Bool(l), BangEqual, Value::Bool(r)) => Ok(Value::Bool(l != r)), - (Value::Bool(l), And, Value::Bool(r)) => Ok(Value::Bool(l && r)), - (Value::Bool(l), Or, Value::Bool(r)) => Ok(Value::Bool(l || r)), - - _ => Err("Invalid binary operation".to_string()), - } - } - - fn evaluate_unary(&self, op: &TokenKind, right: Value) -> Result { - use TokenKind::*; - - match (op, right) { - (Minus, Value::Number(n)) => Ok(Value::Number(-n)), - (Bang, Value::Bool(b)) => Ok(Value::Bool(!b)), - _ => Err("Invalid unary operation".to_string()), - } - } - - pub fn execute_block(&self, statements: &[Stmt], env: &mut Environment) -> Result { - match self.execute_block_with_control_flow(statements, env)? { - ControlFlow::Normal(value) | ControlFlow::Return(value) => Ok(value), - ControlFlow::Break | ControlFlow::Continue => Err("Break/continue outside of loop".to_string()), - } - } - - pub fn execute_block_with_control_flow(&self, statements: &[Stmt], env: &mut Environment) -> Result { - for stmt in statements { - let control_flow = self.execute(stmt, env)?; - match control_flow { - ControlFlow::Normal(_) => {} // Continue execution - ControlFlow::Break | ControlFlow::Continue | ControlFlow::Return(_) => { - return Ok(control_flow); - } - } - } - Ok(ControlFlow::normal(Value::Null)) - } -} \ No newline at end of file diff --git a/compiler/src/interpreter/function.rs b/compiler/src/interpreter/function.rs deleted file mode 100644 index 69ed699..0000000 --- a/compiler/src/interpreter/function.rs +++ /dev/null @@ -1,25 +0,0 @@ -use crate::ast::{Parameter, Stmt}; -use crate::lexer::span::Span; - -#[derive(Debug, Clone, PartialEq)] -pub struct Function { - pub name: String, - pub params: Vec, - pub body: Vec, - pub span: Span, -} - -impl Function { - pub fn new(name: String, params: Vec, body: Vec, span: Span) -> Self { - Self { - name, - params, - body, - span, - } - } - - pub fn arity(&self) -> usize { - self.params.len() - } -} \ No newline at end of file diff --git a/compiler/src/interpreter/interpreter.rs b/compiler/src/interpreter/interpreter.rs deleted file mode 100644 index 126f940..0000000 --- a/compiler/src/interpreter/interpreter.rs +++ /dev/null @@ -1,31 +0,0 @@ -use crate::ast::Stmt; -use super::environment::Environment; -use super::executor::Executor; -use super::std::StdLib; - -pub struct Interpreter { - environment: Environment, - executor: Executor, -} - -impl Interpreter { - pub fn new() -> Self { - let mut environment = Environment::new(); - - // Initialize global environment with std lib functions - let globals = StdLib::create_global_environment(); - for (name, value) in globals { - environment.define(name, value); - } - - Self { - environment, - executor: Executor::new(), - } - } - - pub fn interpret(&mut self, statements: &[Stmt]) -> Result<(), String> { - self.executor.execute_block(statements, &mut self.environment)?; - Ok(()) - } -} \ No newline at end of file diff --git a/compiler/src/interpreter/mod.rs b/compiler/src/interpreter/mod.rs deleted file mode 100644 index 2c65e0e..0000000 --- a/compiler/src/interpreter/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -pub mod control_flow; -pub mod environment; -pub mod evaluator; -pub mod executor; -pub mod function; -pub mod interpreter; -pub mod std; -pub mod value; - -pub use control_flow::ControlFlow; -pub use environment::Environment; -pub use evaluator::Evaluator; -pub use executor::Executor; -pub use function::Function; -pub use interpreter::Interpreter; -pub use std::StdLib; -pub use value::Value; \ No newline at end of file diff --git a/compiler/src/interpreter/std.rs b/compiler/src/interpreter/std.rs deleted file mode 100644 index 9f74738..0000000 --- a/compiler/src/interpreter/std.rs +++ /dev/null @@ -1,44 +0,0 @@ -use super::value::Value; -use super::function::Function; -use crate::lexer::span::Span; - -pub struct StdLib; - -impl StdLib { - pub fn create_global_environment() -> std::collections::HashMap { - let mut globals = std::collections::HashMap::new(); - - // Add println function - let println_func = Function::new( - "println".to_string(), - vec![], // No parameters - accepts any number of arguments - vec![], // Empty body - handled specially - Span { start: 0, end: 0 }, - ); - globals.insert("println".to_string(), Value::Function(println_func)); - - globals - } - - pub fn call_builtin_function(name: &str, args: &[Value]) -> Option> { - match name { - "println" => { - for (i, arg) in args.iter().enumerate() { - if i > 0 { - print!(" "); - } - match arg { - Value::String(s) => print!("{}", s), - Value::Number(n) => print!("{}", n), - Value::Bool(b) => print!("{}", b), - Value::Null => print!("null"), - Value::Function(_) => print!(""), - } - } - println!(); - Some(Ok(Value::Null)) - } - _ => None, // Not a built-in function - } - } -} \ No newline at end of file diff --git a/compiler/src/interpreter/value.rs b/compiler/src/interpreter/value.rs deleted file mode 100644 index c629e04..0000000 --- a/compiler/src/interpreter/value.rs +++ /dev/null @@ -1,22 +0,0 @@ -use crate::ast::Literal; - -use super::function::Function; - -#[derive(Debug, Clone, PartialEq)] -pub enum Value { - String(String), - Number(f64), - Bool(bool), - Function(Function), - Null, -} - -impl From for Value { - fn from(lit: Literal) -> Self { - match lit { - Literal::String(s) => Value::String(s), - Literal::Number(n) => Value::Number(n), - Literal::Bool(b) => Value::Bool(b), - Literal::Null => Value::Null, } - } -} \ No newline at end of file diff --git a/compiler/src/lexer/cursor.rs b/compiler/src/lexer/cursor.rs deleted file mode 100644 index 3ea4a2f..0000000 --- a/compiler/src/lexer/cursor.rs +++ /dev/null @@ -1,32 +0,0 @@ -//byte position in the source code -pub struct Cursor<'a> { - source: &'a str, - position: usize, -} - -impl<'a> Cursor<'a> { - pub fn new(source: &'a str) -> Self { - Self { - source, - position: 0, - } - } - - pub fn peek(&self) -> Option { - self.source[self.position..].chars().next() - } - - pub fn advance(&mut self) -> Option { - let ch = self.peek()?; - self.position += ch.len_utf8(); - Some(ch) - } - - pub fn position(&self) -> usize { - self.position - } - - pub fn peek_ahead(&self, n: usize) -> Option { - self.source[self.position..].chars().nth(n) - } -} diff --git a/compiler/src/lexer/error.rs b/compiler/src/lexer/error.rs deleted file mode 100644 index 4ec4232..0000000 --- a/compiler/src/lexer/error.rs +++ /dev/null @@ -1,16 +0,0 @@ -#![allow(non_snake_case)] - -use super::span::Span; - -#[derive(Debug, Clone)] -pub struct LexError { - pub message: String, - pub span: Span, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum LexerError { - UnexpectedCharacter { found: char, span: Span }, - - UnterminatedString { span: Span }, -} diff --git a/compiler/src/lexer/lexer.rs b/compiler/src/lexer/lexer.rs deleted file mode 100644 index b5d0fac..0000000 --- a/compiler/src/lexer/lexer.rs +++ /dev/null @@ -1,188 +0,0 @@ -use crate::lexer::token; - -use super::{ - cursor::Cursor, - error::LexerError, - span::Span, - token::{Token, TokenKind}, -}; - -pub struct Lexer<'a> { - cursor: Cursor<'a>, -} - -impl<'a> Lexer<'a> { - //new lexer - pub fn new(input: &'a str) -> Self { - Self { - cursor: Cursor::new(input), - } - } - - //next token - pub fn nextToken(&mut self) -> Result { - // 1.skip whitespace - while let Some(ch) = self.cursor.peek() { - if ch.is_whitespace() { - self.cursor.advance(); - } else { - break; - } - } - let start = self.cursor.position(); - - // 2.end of sc input - let ch = match self.cursor.advance() { - Some(c) => c, - None => { - return Ok(Token { - kind: TokenKind::Eof, - span: Span::new(start, start), - }); - } - }; - match ch { - '"' => self.lexString(start), - - c if c.is_alphabetic() || c == '_' => Ok(self.lexIdentifier(start, c)), - - '(' => Ok(self.simpleToken(TokenKind::LeftParen, start)), - ')' => Ok(self.simpleToken(TokenKind::RightParen, start)), - '{' => Ok(self.simpleToken(TokenKind::LeftBrace, start)), - '}' => Ok(self.simpleToken(TokenKind::RightBrace, start)), - ';' => Ok(self.simpleToken(TokenKind::Semicolon, start)), - '+' => Ok(self.simpleToken(TokenKind::Plus, start)), - '-' => Ok(self.simpleToken(TokenKind::Minus, start)), - '*' => Ok(self.simpleToken(TokenKind::Star, start)), - '/' => Ok(self.simpleToken(TokenKind::Slash, start)), - ':' => Ok(self.simpleToken(TokenKind::Colon, start)), - '.' => Ok(self.simpleToken(TokenKind::Dot, start)), - ',' => Ok(self.simpleToken(TokenKind::Comma, start)), - '%' => Ok(self.simpleToken(TokenKind::Percent, start)), - - '=' => { - let kind = if self.matchNext('=') { - TokenKind::EqualEqual - } else { - TokenKind::Equal - }; - Ok(self.simpleToken(kind, start)) - } - '<' => { - let kind = if self.matchNext('=') { - TokenKind::LessEqual - } else { - TokenKind::Less - }; - Ok(self.simpleToken(kind, start)) - } - '>' => { - let kind = if self.matchNext('=') { - TokenKind::GreaterEqual - } else { - TokenKind::Greater - }; - Ok(self.simpleToken(kind, start)) - } - '!' => { - let kind = if self.matchNext('=') { - TokenKind::NotEqual - } else { - TokenKind::Not - }; - Ok(self.simpleToken(kind, start)) - } - - int if int.is_digit(10) => { - let mut number = String::new(); - number.push(int); - - while let Some(ch) = self.cursor.peek() { - if ch.is_digit(10) || ch == '.' { - self.cursor.advance(); - number.push(ch); - } else { - break; - } - } - - let value: f64 = number.parse().unwrap(); - Ok(Token { - kind: TokenKind::NumberLiteral(value), - span: Span::new(start, self.cursor.position()), - }) - } - - _ => Err(LexerError::UnexpectedCharacter { - found: ch, - span: Span::new(start, self.cursor.position()), - }), - } - } - fn matchNext(&mut self, expected: char) -> bool { - match self.cursor.peek() { - Some(ch) if ch == expected => { - self.cursor.advance(); - true - } - _ => false, - } - } - fn lexString(&mut self, start: usize) -> Result { - let mut value = String::new(); - - while let Some(ch) = self.cursor.advance() { - if ch == '"' { - return Ok(Token { - kind: TokenKind::StringLiteral(value), - span: Span::new(start, self.cursor.position()), - }); - } - value.push(ch); - } - - Err(LexerError::UnterminatedString { - span: Span::new(start, self.cursor.position()), - }) - } - fn lexIdentifier(&mut self, start: usize, first: char) -> Token { - let mut ident = String::new(); - ident.push(first); - - while let Some(ch) = self.cursor.peek() { - if ch.is_alphanumeric() || ch == '_' { - self.cursor.advance(); - ident.push(ch); - } else { - break; - } - } - - let kind = match ident.as_str() { - "var" => TokenKind::Var, - "func" => TokenKind::Func, - "return" => TokenKind::Return, - "if" => TokenKind::If, - "else" => TokenKind::Else, - "while" => TokenKind::While, - "for" => TokenKind::For, - "in" => TokenKind::In, - "true" => TokenKind::True, - "false" => TokenKind::False, - "null" => TokenKind::Null, - _ => TokenKind::Identifier(ident), - }; - - Token { - kind, - span: Span::new(start, self.cursor.position()), - } - } - - fn simpleToken(&self, kind: TokenKind, start: usize) -> Token { - Token { - kind, - span: Span::new(start, start + 1), - } - } -} diff --git a/compiler/src/lexer/mod.rs b/compiler/src/lexer/mod.rs deleted file mode 100644 index be9982d..0000000 --- a/compiler/src/lexer/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -pub mod cursor; -pub mod error; -pub mod lexer; -pub mod span; -pub mod token; - -pub use lexer::Lexer; -pub use token::{Token, TokenKind}; diff --git a/compiler/src/lexer/span.rs b/compiler/src/lexer/span.rs deleted file mode 100644 index b59c102..0000000 --- a/compiler/src/lexer/span.rs +++ /dev/null @@ -1,14 +0,0 @@ -#![allow(non_snake_case)] - -//gonna use for error and diagnostics -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub struct Span { - pub start: usize, - pub end: usize, -} - -impl Span { - pub fn new(start: usize, end: usize) -> Self { - Self { start, end } - } -} diff --git a/compiler/src/lexer/token.rs b/compiler/src/lexer/token.rs deleted file mode 100644 index 78fdc7a..0000000 --- a/compiler/src/lexer/token.rs +++ /dev/null @@ -1,76 +0,0 @@ -use crate::lexer::span::Span; -#[derive(Debug, Clone, PartialEq)] -pub struct Token { - pub kind: TokenKind, - pub span: Span, -} - -//this enum will grow over time -// for v0, keeping it simple -//contains all tokens supported for v0 -#[derive(Debug, Clone, PartialEq)] -pub enum TokenKind { - //single char tokens - LeftParen, - RightParen, - LeftBrace, - RightBrace, - Comma, - Dot, - Minus, - Plus, - Semicolon, - Slash, - Star, - Percent, - Colon, - Not, - AndAnd, - OrOr, - BangEqual, - Bang, - Tilde, - PlusPlus, - MinusMinus, - PlusEqual, - MinusEqual, - StarEqual, - SlashEqual, - PercentEqual, - ColonEqual, - - //keywords - Var, - Func, - Return, - If, - Else, - While, - Break, - Continue, - For, - In, - True, - False, - Null, - - //literals - Identifier(String), - StringLiteral(String), - NumberLiteral(f64), - BooleanLiteral(bool), - - //operators - Equal, - EqualEqual, - Greater, - GreaterEqual, - NotEqual, - Less, - LessEqual, - And, - Or, - - //special - Eof, -} diff --git a/compiler/src/main.rs b/compiler/src/main.rs deleted file mode 100644 index 619add6..0000000 --- a/compiler/src/main.rs +++ /dev/null @@ -1,65 +0,0 @@ -#![allow(non_snake_case)] - -mod ast; -mod interpreter; -mod lexer; -mod parser; - -use interpreter::Interpreter; -use lexer::{Lexer, TokenKind}; -use parser::Parser; -use std::env; -use std::fs; - -fn main() { - let args: Vec = env::args().collect(); - let filename = if args.len() > 1 { - args[1].clone() - } else { - "".to_string() - }; - if filename.is_empty() { - println!("No filename provided"); - return; - } - - let source = fs::read_to_string(&filename) - .expect(&format!("Failed to read {} file", filename)); - - let mut lexer = Lexer::new(&source); - let mut tokens = Vec::new(); - - loop { - match lexer.nextToken() { - Ok(token) => { - println!("{:?}", token); - tokens.push(token.clone()); - if token.kind == TokenKind::Eof { - break; - } - } - Err(err) => { - println!("Lexer error: {:?}", err); - break; - } - } - } - println!("Parsing Started."); - let mut parser = Parser::new(tokens); - match parser.parse() { - Ok(ast) => { - let mut interpreter = Interpreter::new(); - match interpreter.interpret(&ast) { - Ok(()) => { - println!("Program executed successfully!"); - } - Err(err) => { - println!("Runtime error: {}", err); - } - } - } - Err(err) => { - println!("Parser error: {:?}", err); - } - } -} diff --git a/compiler/src/parser/error.rs b/compiler/src/parser/error.rs deleted file mode 100644 index 0033de2..0000000 --- a/compiler/src/parser/error.rs +++ /dev/null @@ -1,26 +0,0 @@ -use crate::lexer::span::Span; -use crate::lexer::TokenKind; - -#[derive(Debug, Clone, PartialEq)] -pub enum ParserError { - UnexpectedToken { - expected: Vec, - found: TokenKind, - span: Span, - }, - - UnexpectedEOF { - expected: Vec, - span: Span, - }, - - Custom { - message: String, - span: Span, - }, -} -impl ParserError { - pub fn new(message: String, span: Span) -> Self { - Self::Custom { message, span } - } -} \ No newline at end of file diff --git a/compiler/src/parser/mod.rs b/compiler/src/parser/mod.rs deleted file mode 100644 index ed1339b..0000000 --- a/compiler/src/parser/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub mod error; -pub mod parser; - -pub use parser::Parser; -pub use crate::ast::{Expr, Literal, Stmt, Type}; diff --git a/compiler/src/parser/parser.rs b/compiler/src/parser/parser.rs deleted file mode 100644 index 7ded7fa..0000000 --- a/compiler/src/parser/parser.rs +++ /dev/null @@ -1,509 +0,0 @@ -#![allow(non_snake_case)] - -use crate::ast::{Expr, Literal, Parameter, Stmt, Type}; -use crate::lexer::{Token, TokenKind}; -use crate::parser::error::ParserError; - -//impl for recursive descent parser -pub struct Parser { - tokens: Vec, - current: usize, -} -impl Parser { - pub fn new(tokens: Vec) -> Self { - Self { tokens, current: 0 } - } - pub fn parse(&mut self) -> Result, ParserError> { - let mut statements = Vec::new(); - while !self.isAtEnd() { - if let Some(stmt) = self.parseStatement()? { - statements.push(stmt); - } - } - Ok(statements) - } - - //parsing statements - fn parseStatement(&mut self) -> Result, ParserError> { - if self.isAtEnd() { - return Ok(None); - } - if self.matchToken(&TokenKind::Var) { - Ok(Some(self.parseVarDeclaration()?)) - } else if self.matchToken(&TokenKind::Func) { - Ok(Some(self.parseFuncDeclaration()?)) - } else if self.matchToken(&TokenKind::If) { - Ok(Some(self.parseIfStatement()?)) - } else if self.matchToken(&TokenKind::While) { - Ok(Some(self.parseWhileStatement()?)) - } else if self.matchToken(&TokenKind::For) { - Ok(Some(self.parseForStatement()?)) - } else if self.matchToken(&TokenKind::Break) { - Ok(Some(self.parseBreakStatement()?)) - } else if self.matchToken(&TokenKind::Continue) { - Ok(Some(self.parseContinueStatement()?)) - } else if self.matchToken(&TokenKind::Return) { - Ok(Some(self.parseReturnStatement()?)) - } else { - Ok(Some(self.parseExpressionStatement()?)) - } - } - fn parseVarDeclaration(&mut self) -> Result { - let name = match &self.peek().kind { - TokenKind::Identifier(name) => name.clone(), - _ => return Err(self.error("Expected variable name.")), - }; - self.advance(); - - let ty = self.parseTypeAnnotation()?; - - self.consume(&TokenKind::Equal, "Expected '=' after variable name.")?; - let initializer = self.parseExpression()?; - self.consume( - &TokenKind::Semicolon, - "Expected ';' after variable declaration.", - )?; - - Ok(Stmt::VarDecl { name, ty, initializer }) - } - - fn parseFuncDeclaration(&mut self) -> Result { - let name = match &self.peek().kind { - TokenKind::Identifier(name) => name.clone(), - _ => return Err(self.error("Expected function name.")), - }; - self.advance(); - - self.consume(&TokenKind::LeftParen, "Expected '(' after function name.")?; - - let mut params = Vec::new(); - if !self.check(&TokenKind::RightParen) { - loop { - let param_name = match &self.peek().kind { - TokenKind::Identifier(name) => name.clone(), - _ => return Err(self.error("Expected parameter name.")), - }; - self.advance(); - - let param_ty = self.parseTypeAnnotation()?; - - params.push(Parameter { - name: param_name, - ty: param_ty, - }); - - if !self.matchToken(&TokenKind::Comma) { - break; - } - } - } - self.consume(&TokenKind::RightParen, "Expected ')' after parameters.")?; - - let return_ty = self.parseTypeAnnotation()?; - - self.consume(&TokenKind::LeftBrace, "Expected '{' before function body.")?; - - let mut body = Vec::new(); - while !self.check(&TokenKind::RightBrace) && !self.isAtEnd() { - if let Some(stmt) = self.parseStatement()? { - body.push(stmt); - } - } - self.consume(&TokenKind::RightBrace, "Expected '}' after function body.")?; - - Ok(Stmt::FuncDecl { - name, - params, - return_ty, - body, - }) - } - - fn parseIfStatement(&mut self) -> Result { - self.consume(&TokenKind::LeftParen, "Expected '(' after 'if'.")?; - let condition = self.parseExpression()?; - self.consume(&TokenKind::RightParen, "Expected ')' after condition.")?; - - self.consume(&TokenKind::LeftBrace, "Expected '{' after condition.")?; - let then_branch = self.parseBlock()?; - self.consume(&TokenKind::RightBrace, "Expected '}' after then branch.")?; - - let else_branch = if self.matchToken(&TokenKind::Else) { - self.consume(&TokenKind::LeftBrace, "Expected '{' after 'else'.")?; - let block = self.parseBlock()?; - self.consume(&TokenKind::RightBrace, "Expected '}' after else branch.")?; - Some(block) - } else { - None - }; - - Ok(Stmt::If { - condition, - then_branch, - else_branch, - }) - } - - fn parseWhileStatement(&mut self) -> Result { - self.consume(&TokenKind::LeftParen, "Expected '(' after 'while'.")?; - let condition = self.parseExpression()?; - self.consume(&TokenKind::RightParen, "Expected ')' after condition.")?; - - self.consume(&TokenKind::LeftBrace, "Expected '{' after condition.")?; - let body = self.parseBlock()?; - self.consume(&TokenKind::RightBrace, "Expected '}' after while body.")?; - - Ok(Stmt::While { - condition, - body, - }) - } - - fn parseForStatement(&mut self) -> Result { - // Parse variable name - let variable = match self.peek().kind { - TokenKind::Identifier(ref name) => name.clone(), - _ => return Err(self.error("Expected variable name after 'for'.")), - }; - self.advance(); - - self.consume(&TokenKind::In, "Expected 'in' after variable name.")?; - match self.peek().kind { - TokenKind::Identifier(ref name) if name == "range" => { - self.advance(); - } - _ => return Err(self.error("Expected 'range' after 'in'.")), - } - self.consume(&TokenKind::LeftParen, "Expected '(' after 'range'.")?; - - let start = self.parseExpression()?; - self.consume(&TokenKind::Comma, "Expected ',' after start value.")?; - let end = self.parseExpression()?; - - self.consume(&TokenKind::RightParen, "Expected ')' after end value.")?; - self.consume(&TokenKind::LeftBrace, "Expected '{' after range.")?; - - let body = self.parseBlock()?; - - self.consume(&TokenKind::RightBrace, "Expected '}' after for body.")?; - - Ok(Stmt::For { - variable, - start, - end, - body, - }) - } - - fn parseBreakStatement(&mut self) -> Result { - self.consume(&TokenKind::Semicolon, "Expected ';' after 'break'.")?; - Ok(Stmt::Break) - } - - fn parseContinueStatement(&mut self) -> Result { - self.consume(&TokenKind::Semicolon, "Expected ';' after 'continue'.")?; - Ok(Stmt::Continue) - } - - fn parseBlock(&mut self) -> Result, ParserError> { - let mut statements = Vec::new(); - while !self.check(&TokenKind::RightBrace) && !self.isAtEnd() { - if let Some(stmt) = self.parseStatement()? { - statements.push(stmt); - } - } - Ok(statements) - } - - fn parseReturnStatement(&mut self) -> Result { - let expr = self.parseExpression()?; - self.consume(&TokenKind::Semicolon, "Expected ';' after return value.")?; - Ok(Stmt::Return(expr)) - } - - fn parseExpressionStatement(&mut self) -> Result { - let expr = self.parseExpression()?; - self.consume(&TokenKind::Semicolon, "Expected ';' after expression.")?; - Ok(Stmt::ExprStmt(expr)) - } - - fn parseTypeAnnotation(&mut self) -> Result, ParserError> { - if self.matchToken(&TokenKind::Colon) { - match &self.peek().kind { - TokenKind::Identifier(name) => { - let ty = Type { name: name.clone() }; - self.advance(); - Ok(Some(ty)) - } - _ => Err(self.error("Expected type name after ':'")), - } - } else { - Ok(None) - } - } - - fn parseUnary(&mut self) -> Result { - match &self.peek().kind { - TokenKind::Minus => { - self.advance(); - let expr = self.parseUnary()?; - Ok(Expr::Binary { - left: Box::new(Expr::Literal(Literal::Number(0.0))), - op: TokenKind::Minus, - right: Box::new(expr), - }) - } - _ => self.parsePrimary(), - } - } - - fn parsePrimary(&mut self) -> Result { - match self.peek().kind.clone() { - TokenKind::Identifier(name) => { - self.advance(); - if self.matchToken(&TokenKind::LeftParen) { - // Function call - let callee = Expr::Variable(name); - let mut args = Vec::new(); - - if !self.check(&TokenKind::RightParen) { - loop { - args.push(self.parseExpression()?); - if !self.matchToken(&TokenKind::Comma) { - break; - } - } - } - self.consume(&TokenKind::RightParen, "Expected ')' after function arguments.")?; - Ok(Expr::Call { - callee: Box::new(callee), - args, - }) - } else { - Ok(Expr::Variable(name)) - } - } - TokenKind::StringLiteral(value) => { - self.advance(); - Ok(Expr::Literal(Literal::String(value))) - } - TokenKind::NumberLiteral(value) => { - self.advance(); - Ok(Expr::Literal(Literal::Number(value))) - } - TokenKind::True => { - self.advance(); - Ok(Expr::Literal(Literal::Bool(true))) - } - TokenKind::False => { - self.advance(); - Ok(Expr::Literal(Literal::Bool(false))) - } - TokenKind::Null => { - self.advance(); - Ok(Expr::Literal(Literal::Null)) - } - _ => Err(self.error("Expected expression.")), - } - } - - fn parseAdditive(&mut self) -> Result { - let mut expr = self.parseUnary()?; - - while matches!(self.peek().kind, TokenKind::Plus | TokenKind::Minus) { - let op = self.peek().kind.clone(); - self.advance(); - let right = self.parseUnary()?; - - expr = Expr::Binary { - left: Box::new(expr), - op, - right: Box::new(right), - }; - } - Ok(expr) - } - - fn parseAssignment(&mut self) -> Result { - let expr = self.parseLogicOr()?; - - if self.matchToken(&TokenKind::Equal) { - let value = self.parseAssignment()?; - - if let Expr::Variable(name) = expr { - return Ok(Expr::Assign { - name, - value: Box::new(value), - }); - } - - return Err(self.error("Invalid assignment target.")); - } - - Ok(expr) - } - - fn parseLogicOr(&mut self) -> Result { - let mut expr = self.parseLogicAnd()?; - while self.matchToken(&TokenKind::OrOr) { - let op = self.previous().kind.clone(); - let right = self.parseLogicAnd()?; - expr = Expr::Binary { left: Box::new(expr), op, right: Box::new(right) }; - } - Ok(expr) -} - -fn parseLogicAnd(&mut self) -> Result { - let mut expr = self.parseEquality()?; - while self.matchToken(&TokenKind::AndAnd) { - let op = self.previous().kind.clone(); - let right = self.parseEquality()?; - expr = Expr::Binary { left: Box::new(expr), op, right: Box::new(right) }; - } - Ok(expr) -} -fn parseEquality(&mut self) -> Result { - let mut expr = self.parseComparison()?; - while matches!(self.peek().kind, TokenKind::EqualEqual | TokenKind::BangEqual) { - let op = self.peek().kind.clone(); - self.advance(); - let right = self.parseComparison()?; - expr = Expr::Binary { left: Box::new(expr), op, right: Box::new(right) }; - } - Ok(expr) -} - -fn parseComparison(&mut self) -> Result { - let mut expr = self.parseTerm()?; - while matches!(self.peek().kind, TokenKind::Greater | TokenKind::Less) { - let op = self.peek().kind.clone(); - self.advance(); - let right = self.parseTerm()?; - expr = Expr::Binary { left: Box::new(expr), op, right: Box::new(right) }; - } - Ok(expr) -} - - - //expressions - fn parseExpression(&mut self) -> Result { - self.parseAssignment() - } - - //token utils - fn matchToken(&mut self, kind: &TokenKind) -> bool { - if self.check(kind) { - self.advance(); - true - } else { - false - } - } - fn consume(&mut self, kind: &TokenKind, message: &str) -> Result<(), ParserError> { - if self.check(kind) { - self.advance(); - Ok(()) - } else { - Err(self.error(message)) - } - } - fn consumeIdentifier(&mut self, message: &str) -> Result<(), ParserError> { - match &self.peek().kind { - TokenKind::Identifier(_) => { - self.advance(); - Ok(()) - } - _ => Err(self.error(message)), - } - } - fn check(&self, kind: &TokenKind) -> bool { - if self.isAtEnd() { - return false; - } - std::mem::discriminant(&self.peek().kind) == std::mem::discriminant(kind) - } - fn advance(&mut self) -> &Token { - if !self.isAtEnd() { - self.current += 1; - } - self.previous() - } - fn isAtEnd(&self) -> bool { - matches!(self.peek().kind, TokenKind::Eof) - } - fn peek(&self) -> &Token { - &self.tokens[self.current] - } - fn previous(&self) -> &Token { - if self.current == 0 { - &self.tokens[0] - } else { - &self.tokens[self.current - 1] - } - } - -fn parseCall(&mut self) -> Result { - let mut expr = self.parsePrimary()?; - - loop { - if self.matchToken(&TokenKind::LeftParen) { - let mut args = Vec::new(); - if !self.check(&TokenKind::RightParen) { - loop { - args.push(self.parseExpression()?); - if !self.matchToken(&TokenKind::Comma) { - break; - } - } - } - self.consume(&TokenKind::RightParen, "Expected ')' after arguments.")?; - expr = Expr::Call { callee: Box::new(expr), args }; - } - else if self.matchToken(&TokenKind::Dot) { - let name = match &self.peek().kind { - TokenKind::Identifier(n) => n.clone(), - _ => return Err(self.error("Expected property name after '.'")), - }; - self.advance(); - expr = Expr::Get { object: Box::new(expr), name }; - } - else { - break; - } - } - - Ok(expr) - } - - fn parseTerm(&mut self) -> Result { - let mut expr = self.parseFactor()?; - while matches!(self.peek().kind, TokenKind::Plus | TokenKind::Minus) { - let op = self.peek().kind.clone(); - self.advance(); - let right = self.parseFactor()?; - expr = Expr::Binary { left: Box::new(expr), op, right: Box::new(right) }; - } - Ok(expr) - } - - fn parseFactor(&mut self) -> Result { - let mut expr = self.parseUnary()?; - while matches!(self.peek().kind, TokenKind::Star | TokenKind::Slash) { - let op = self.peek().kind.clone(); - self.advance(); - let right = self.parseUnary()?; - expr = Expr::Binary { left: Box::new(expr), op, right: Box::new(right) }; - } - Ok(expr) - } - - - //error - fn error(&self, message: &str) -> ParserError { - ParserError::Custom { - message: message.to_string(), - span: self.peek().span, - } - } - -} diff --git a/compiler/src/tests/arrays.rey b/compiler/src/tests/arrays.rey deleted file mode 100644 index b6dcdc3..0000000 --- a/compiler/src/tests/arrays.rey +++ /dev/null @@ -1,11 +0,0 @@ -// Array usage - -func main(): Void { - var arr: int = [1, 2, 3, 4, 5]; - - var i = 0; - while i < 5 { - println(arr[i]); - i = i + 1; - } -} diff --git a/compiler/src/tests/compute.rey b/compiler/src/tests/compute.rey deleted file mode 100644 index e7a9666..0000000 --- a/compiler/src/tests/compute.rey +++ /dev/null @@ -1,14 +0,0 @@ - -func compute(): Void { - var sum = 0; - var i = 0; - while i < 100 { - sum = sum + i; - i = i + 1; - } - println(sum); -} - -func main(): Void { - compute(); -} diff --git a/compiler/src/tests/datatypes.rey b/compiler/src/tests/datatypes.rey deleted file mode 100644 index 3528b84..0000000 --- a/compiler/src/tests/datatypes.rey +++ /dev/null @@ -1,13 +0,0 @@ -// Core data types - -func main(): Void { - var i: int = 5; - var f: float = 3.14; - var s: String = "text"; - var b: bool = false; - - println(i); - println(f); - println(s); - println(b); -} diff --git a/compiler/src/tests/dictionaries.rey b/compiler/src/tests/dictionaries.rey deleted file mode 100644 index a194d65..0000000 --- a/compiler/src/tests/dictionaries.rey +++ /dev/null @@ -1,12 +0,0 @@ -// Dictionary-like structures - -func main(): Void { - var user = { - "name": "Misbah", - "age": 18, - "active": true - }; - - println(user["name"]); - println(user["age"]); -} diff --git a/compiler/src/tests/fub.rey b/compiler/src/tests/fub.rey deleted file mode 100644 index e69de29..0000000 diff --git a/compiler/src/tests/functions.rey b/compiler/src/tests/functions.rey deleted file mode 100644 index b98e89b..0000000 --- a/compiler/src/tests/functions.rey +++ /dev/null @@ -1,14 +0,0 @@ -// Function basics - -func add(a: int, b: int): int { - return a + b; -} - -func sub(a: int, b: int): int { - return a - b; -} - -func main(): Void { - println(add(2, 3)); - println(sub(10, 4)); -} diff --git a/compiler/src/tests/io.rey b/compiler/src/tests/io.rey deleted file mode 100644 index 0ee1eb0..0000000 --- a/compiler/src/tests/io.rey +++ /dev/null @@ -1,7 +0,0 @@ -// Input / output simulation - -func main(): Void { - println("Enter name:"); - var name = input(); - println("Hello " + name); -} diff --git a/compiler/src/tests/math.rey b/compiler/src/tests/math.rey deleted file mode 100644 index 028d991..0000000 --- a/compiler/src/tests/math.rey +++ /dev/null @@ -1,16 +0,0 @@ - - -func fib(n: int): int { - if n <= 1 { - return n; - } - return fib(n - 1) + fib(n - 2); -} - -func main(): Void { - var i: int = 0; - while i < 10 { - println(fib(i)); - i = i + 1; - } -} diff --git a/compiler/src/tests/stdlib.rey b/compiler/src/tests/stdlib.rey deleted file mode 100644 index d588b97..0000000 --- a/compiler/src/tests/stdlib.rey +++ /dev/null @@ -1,11 +0,0 @@ -// Standard library mock - -func max(a: int, b: int): int { - if a > b { return a; } - return b; -} - -func min(a: int, b: int): int { - if a < b { return a; } - return b; -} diff --git a/compiler/src/tests/strings.rey b/compiler/src/tests/strings.rey deleted file mode 100644 index 86763f3..0000000 --- a/compiler/src/tests/strings.rey +++ /dev/null @@ -1,7 +0,0 @@ -// String operations - -func main(): Void { - var s: String = "Rey Language"; - println(s); - println(s.length()); -} diff --git a/compiler/src/tests/variables.rey b/compiler/src/tests/variables.rey deleted file mode 100644 index 9a26d53..0000000 --- a/compiler/src/tests/variables.rey +++ /dev/null @@ -1,16 +0,0 @@ -// Variable behavior - -func main(): Void { - var x = 10; - x = 20; - x = 30; - - var name = "Rey"; - println(name); - - var typed: int = 42; - typed = 100; - - var flag = true; - println(flag); -}x From ca39c19cfef583554a1300258367cbb0b660f0be Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 17 Mar 2026 21:19:43 +0530 Subject: [PATCH 2/2] s --- .gitmodules | 3 +++ rey-vscode | 1 + 2 files changed, 4 insertions(+) create mode 100644 .gitmodules create mode 160000 rey-vscode diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..2171bfc --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "rey-vscode"] + path = rey-vscode + url = https://github.com/rey-language/rey-vscode.git diff --git a/rey-vscode b/rey-vscode new file mode 160000 index 0000000..450be87 --- /dev/null +++ b/rey-vscode @@ -0,0 +1 @@ +Subproject commit 450be875e9346f433e3c32e1960041f462c9929f