bean_script/scope/
block_scope.rs1use std::{
2 any::Any, borrow::Borrow, cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc,
3};
4
5use crate::data::Data;
6
7use super::{function::Function, Scope, ScopeRef};
8
9#[derive(Debug, Clone, Copy)]
10pub enum IfState {
11 Started,
12 Captured,
13 Finished,
14}
15
16pub struct BlockScope {
17 local_functions: HashMap<String, Function>,
18 parent: Option<ScopeRef>,
19 did_break: bool,
20 pub return_value: Data,
21 pub if_state: IfState,
22}
23
24impl BlockScope {
25 pub fn new(parent: Option<ScopeRef>) -> Self {
26 Self {
27 local_functions: HashMap::new(),
28 parent,
29 return_value: Data::None,
30 did_break: false,
31 if_state: IfState::Finished,
32 }
33 }
34
35 pub fn break_self(&mut self) {
36 self.did_break = true;
37 }
38
39 pub fn did_break(&self) -> bool {
40 self.did_break
41 }
42}
43
44impl Debug for BlockScope {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 f.debug_struct("BlockScope")
47 .field("local_functions", &self.local_functions)
48 .field("parent", &self.parent)
49 .field("did_break", &self.did_break)
50 .field("return_value", &self.return_value)
51 .field("if_state", &self.if_state)
52 .finish()
53 }
54}
55
56impl Scope for BlockScope {
57 fn has_function(&self, name: &str) -> bool {
58 if self.local_functions.contains_key(name) {
59 true
60 } else if let Some(parent) = &self.parent {
61 let borrow: &RefCell<dyn Scope> = parent.borrow();
62 borrow.borrow().has_function(name)
63 } else {
64 false
65 }
66 }
67
68 fn get_function(&self, name: &str) -> Option<Function> {
69 let function = self.local_functions.get(name);
70 if function.is_some() {
71 function.map(|x| x.clone())
72 } else if let Some(parent) = &self.parent {
73 let borrow: &RefCell<dyn Scope> = parent.borrow();
74 borrow.borrow().get_function(name).map(|x| x.clone())
75 } else {
76 None
77 }
78 }
79
80 fn set_function(&mut self, name: &str, function: Function) {
81 if self.local_functions.contains_key(name) {
82 *self.local_functions.get_mut(name).unwrap() = function;
83 } else {
84 self.local_functions.insert(String::from(name), function);
85 }
86 }
87
88 fn delete_function(&mut self, name: &str) {
89 self.local_functions.remove(name);
90 }
91
92 fn parent(&self) -> Option<ScopeRef> {
93 self.parent.as_ref().map(|x| Rc::clone(x))
94 }
95
96 fn set_return_value(&mut self, value: Data) {
97 self.return_value = value;
98 }
99
100 fn get_function_list(&self) -> HashMap<String, Function> {
101 self.local_functions.clone()
102 }
103
104 fn get_if_state(&self) -> Option<IfState> {
105 Some(self.if_state)
106 }
107
108 fn as_any(&self) -> &dyn Any {
109 self
110 }
111 fn as_mut(&mut self) -> &mut dyn Any {
112 self
113 }
114
115 fn set_if_state(&mut self, state: IfState) {
116 self.if_state = state;
117 }
118}