From df6b5ef34b8c468f174ceacf3fd1e30375c3f536 Mon Sep 17 00:00:00 2001 From: sofia Date: Sun, 13 Jul 2025 17:46:34 +0300 Subject: [PATCH] Add array indexing --- reid/examples/reid/array.reid | 2 +- reid/src/ast/mod.rs | 1 + reid/src/ast/parse.rs | 16 +++++++++++++++- reid/src/ast/process.rs | 1 + 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/reid/examples/reid/array.reid b/reid/examples/reid/array.reid index 67ca7cc..54b5a07 100644 --- a/reid/examples/reid/array.reid +++ b/reid/examples/reid/array.reid @@ -9,5 +9,5 @@ fn main() -> u16 { let list = array(); - return heehoo; + return list[0]; } diff --git a/reid/src/ast/mod.rs b/reid/src/ast/mod.rs index 5a9f37a..1cb6e56 100644 --- a/reid/src/ast/mod.rs +++ b/reid/src/ast/mod.rs @@ -39,6 +39,7 @@ pub enum ExpressionKind { VariableName(String), Literal(Literal), Array(Vec), + Index(Box, u64), Binop(BinaryOperator, Box, Box), FunctionCall(Box), BlockExpr(Box), diff --git a/reid/src/ast/parse.rs b/reid/src/ast/parse.rs index 1c63141..1f8c3a6 100644 --- a/reid/src/ast/parse.rs +++ b/reid/src/ast/parse.rs @@ -63,7 +63,7 @@ impl Parse for PrimaryExpression { fn parse(mut stream: TokenStream) -> Result { use ExpressionKind as Kind; - let expr = if let Ok(exp) = stream.parse() { + let mut expr = if let Ok(exp) = stream.parse() { Expression( Kind::FunctionCall(Box::new(exp)), stream.get_range().unwrap(), @@ -114,6 +114,20 @@ impl Parse for PrimaryExpression { } else { Err(stream.expected_err("expression")?)? }; + + while let Some(Token::BracketOpen) = stream.peek() { + stream.next(); // Consume BracketOpen + if let Some(Token::DecimalValue(idx)) = stream.next() { + stream.expect(Token::BracketClose)?; + expr = Expression( + ExpressionKind::Index(Box::new(expr), idx), + stream.get_range().unwrap(), + ); + } else { + return Err(stream.expected_err("array index (number)")?); + } + } + Ok(PrimaryExpression(expr)) } } diff --git a/reid/src/ast/process.rs b/reid/src/ast/process.rs index 694f1b0..cecc090 100644 --- a/reid/src/ast/process.rs +++ b/reid/src/ast/process.rs @@ -150,6 +150,7 @@ impl ast::Expression { mir::ExprKind::If(mir::IfExpression(Box::new(cond), then_block, else_block)) } ast::ExpressionKind::Array(expressions) => todo!(), + ast::ExpressionKind::Index(expression, _) => todo!(), }; mir::Expression(kind, self.1.into())