1use super::*;
2
3#[derive(Debug)]
4pub struct Scope<'src: 'run, 'run> {
5 parent: Option<&'run Self>,
6 bindings: Table<'src, Binding<'src, String>>,
7}
8
9impl<'src, 'run> Scope<'src, 'run> {
10 pub fn child(&'run self) -> Self {
11 Self {
12 parent: Some(self),
13 bindings: Table::new(),
14 }
15 }
16
17 pub fn root() -> Self {
18 let mut root = Self {
19 parent: None,
20 bindings: Table::new(),
21 };
22
23 for (key, value) in constants() {
24 root.bind(Binding {
25 constant: true,
26 export: false,
27 file_depth: 0,
28 name: Name {
29 token: Token {
30 column: 0,
31 kind: TokenKind::Identifier,
32 length: key.len(),
33 line: 0,
34 offset: 0,
35 path: Path::new("PRELUDE"),
36 src: key,
37 },
38 },
39 private: false,
40 value: (*value).into(),
41 });
42 }
43
44 root
45 }
46
47 pub fn bind(&mut self, binding: Binding<'src>) {
48 self.bindings.insert(binding);
49 }
50
51 pub fn bound(&self, name: &str) -> bool {
52 self.bindings.contains_key(name)
53 }
54
55 pub fn value(&self, name: &str) -> Option<&str> {
56 if let Some(binding) = self.bindings.get(name) {
57 Some(binding.value.as_ref())
58 } else {
59 self.parent?.value(name)
60 }
61 }
62
63 pub fn bindings(&self) -> impl Iterator<Item = &Binding<String>> {
64 self.bindings.values()
65 }
66
67 pub fn names(&self) -> impl Iterator<Item = &str> {
68 self.bindings.keys().copied()
69 }
70
71 pub fn parent(&self) -> Option<&'run Self> {
72 self.parent
73 }
74}