From 01173d2f7d33a5f7490cad41bc89d2b4194845fc Mon Sep 17 00:00:00 2001 From: ElnuDev Date: Tue, 30 May 2023 14:49:06 -0700 Subject: [PATCH] Implement local variable assignment --- demo/demo.rpy | 7 ++++--- renrs/src/lib.rs | 1 + renrs/src/parser/block.rs | 23 ++++++++++++++++++++++- renrs/src/parser/command.rs | 5 +++++ 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/demo/demo.rpy b/demo/demo.rpy index d22c671..264b920 100644 --- a/demo/demo.rpy +++ b/demo/demo.rpy @@ -2,11 +2,12 @@ if True: let x = "3" "Bob will be here in [x] seconds." - let x = "2" + x = "2" "Bob will be here in [x] seconds." if True: - let x = "213" - let x = "1" + x = "1" + let x = "4" + "[x]" "Bob will be here in [x] seconds." "Bob will be here in [x] seconds." "Bob" "I will not say anything, [foo]" diff --git a/renrs/src/lib.rs b/renrs/src/lib.rs index 4824cf7..6c683f4 100644 --- a/renrs/src/lib.rs +++ b/renrs/src/lib.rs @@ -22,6 +22,7 @@ impl State { self.script.borrow_mut().next(&self.script) } } + impl Iterator for State { type Item = Event; fn next(&mut self) -> Option { diff --git a/renrs/src/parser/block.rs b/renrs/src/parser/block.rs index e355b25..863c822 100644 --- a/renrs/src/parser/block.rs +++ b/renrs/src/parser/block.rs @@ -1,4 +1,5 @@ use debug_cell::RefCell; +use core::panic; use std::{collections::HashMap, rc::Rc}; use super::{ @@ -71,7 +72,27 @@ impl CommandContext { if let Token::Keyword(_) = value { todo!("assignment variable interpolation isn't implemented"); } - todo!("local variable assignment isn't implemented") + let mut block_option = Some(self.context.clone()); + let mut modified = false; + while let Some(block) = block_option { + let block = block.borrow(); + block + .variables + .borrow_mut() + .entry(variable.clone()) + .and_modify(|e| { + *e = value.clone(); + modified = true; + }); + if modified { + break; + } + block_option = block.parent.clone(); + } + if !modified { + panic!("undefined variable `{variable}`"); + } + return None; } }, Eat { .. } => return None, diff --git a/renrs/src/parser/command.rs b/renrs/src/parser/command.rs index 0c3cba6..1831ba0 100644 --- a/renrs/src/parser/command.rs +++ b/renrs/src/parser/command.rs @@ -73,6 +73,11 @@ pub fn parse_command(pair: Pair) -> Command { variable: variable.clone(), value: value.clone(), }, + [Keyword(variable), Keyword(equals), value] if equals.eq("=") => Assign { + assign_type: AssignType::Assign, + variable: variable.clone(), + value: value.clone() + }, [Keyword(keyword), Str(food), tail @ ..] if keyword.eq("eat") => Eat { food: food.to_owned(), politely: match tail {