Implement local variable assignment

main
Elnu 1 year ago
parent 149842c121
commit 01173d2f7d

@ -2,11 +2,12 @@
if True: if True:
let x = "3" let x = "3"
"Bob will be here in [x] seconds." "Bob will be here in [x] seconds."
let x = "2" x = "2"
"Bob will be here in [x] seconds." "Bob will be here in [x] seconds."
if True: if True:
let x = "213" x = "1"
let x = "1" let x = "4"
"[x]"
"Bob will be here in [x] seconds." "Bob will be here in [x] seconds."
"Bob will be here in [x] seconds." "Bob will be here in [x] seconds."
"Bob" "I will not say anything, [foo]" "Bob" "I will not say anything, [foo]"

@ -22,6 +22,7 @@ impl State {
self.script.borrow_mut().next(&self.script) self.script.borrow_mut().next(&self.script)
} }
} }
impl Iterator for State { impl Iterator for State {
type Item = Event; type Item = Event;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {

@ -1,4 +1,5 @@
use debug_cell::RefCell; use debug_cell::RefCell;
use core::panic;
use std::{collections::HashMap, rc::Rc}; use std::{collections::HashMap, rc::Rc};
use super::{ use super::{
@ -71,7 +72,27 @@ impl CommandContext {
if let Token::Keyword(_) = value { if let Token::Keyword(_) = value {
todo!("assignment variable interpolation isn't implemented"); 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, Eat { .. } => return None,

@ -73,6 +73,11 @@ pub fn parse_command(pair: Pair) -> Command {
variable: variable.clone(), variable: variable.clone(),
value: value.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 { [Keyword(keyword), Str(food), tail @ ..] if keyword.eq("eat") => Eat {
food: food.to_owned(), food: food.to_owned(),
politely: match tail { politely: match tail {

Loading…
Cancel
Save