Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/scope.rs

1.8 KiB, 1 run

created by r1870400018:63510, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// U2 owns this file. The evaluator keeps its block frames as plain maps above a base `Scope`; a `Scope`
2// chain is what a closure captures and what a module exports.
3
4use crate::eval::value::Value;
5use crate::syntax::Span;
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10#[derive(Clone, Debug)]
11pub struct Binding {
12 pub value: Value,
13 pub span: Span, // where it was bound, detached for the standard library
14}
15
16/// A chain of frames, innermost first. The root of every chain is the standard library.
17#[derive(Clone, Debug, Default)]
18pub struct Scope {
19 pub map: HashMap<String, Binding>,
20 pub parent: Option<Arc<Scope>>,
21}
22
23impl Scope {
24 pub fn new() -> Self { Self::default() }
25
26 /// A fresh frame whose lookups fall through to `parent`.
27 pub fn child(parent: Arc<Scope>) -> Self { Self { map: HashMap::new(), parent: Some(parent) } }
28
29 pub fn define<S: Into<String>>(&mut self, name: S, value: Value) {
30 self.map.insert(name.into(), Binding { value, span: Span::detached() });
31 }
32
33 pub fn define_at<S: Into<String>>(&mut self, name: S, value: Value, span: Span) {
34 self.map.insert(name.into(), Binding { value, span });
35 }
36
37 /// The innermost binding of a name.
38 pub fn get(&self, name: &str) -> Option<&Value> {
39 match self.map.get(name) {
40 Some(b) => Some(&b.value),
41 None => self.parent.as_ref().and_then(|p| p.get(name)),
42 }
43 }
44
45 /// The binding of a name in this frame only, with where it was bound.
46 pub fn binding(&self, name: &str) -> Option<&Binding> { self.map.get(name) }
47
48 /// This frame's bindings, in no particular order.
49 pub fn iter(&self) -> impl Iterator<Item = (&String, &Binding)> { self.map.iter() }
50
51 /// A binding in this frame only, for assignment (`x = 1` may not reach through a closure's capture).
52 pub fn get_mut(&mut self, name: &str) -> Option<&mut Value> {
53 self.map.get_mut(name).map(|b| &mut b.value)
54 }
55}