plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


eb9088b — Peter John 2026-11-09T21:27:56+05:30
Checker: scopes share the program's globals instead of copying them
compiler/checker/src/callsites.rs CHANGED
@@ -198,8 +198,13 @@ pub(crate) fn registerCalls(
198
198
  ctx: &CheckCtx,
199
199
  parent: Option<usize>,
200
200
  ) {
201
+ // The bindings recorded so far, read in place: they grow with the whole program.
202
+ let subst = |t: &PlumType| {
201
- let binds = withCheck(|s| { let r = &s.record_binds; r.borrow().clone() })
203
+ withCheck(|s| match s.record_binds.borrow().as_ref() {
202
- .unwrap_or_default();
204
+ Some(b) => substVars(t, b),
205
+ None => substVars(t, &Binds::new()),
206
+ })
207
+ };
203
208
  let parent_chain = parent.map(|p| st.chains[p].clone()).unwrap_or_default();
204
209
  let depth = parent_chain.matches("(called at").count();
205
210
  for cs in drainCalls() {
@@ -233,7 +238,7 @@ pub(crate) fn registerCalls(
233
238
  }
234
239
  let mut args = Vec::new();
235
240
  for g in &gens {
236
- match cs.args.get(g).map(|t| substVars(t, &binds)) {
241
+ match cs.args.get(g).map(subst) {
237
242
  Some(t) if !hasFreeVars(&t) => args.push(t),
238
243
  _ if owner_gens.contains(g) && !sig_free.contains(g) => {
239
244
  args.push(PlumType::TUnit)
compiler/checker/src/declchecks.rs CHANGED
@@ -308,10 +308,7 @@ pub(crate) fn checkConstDecls(source: &ast::Source) -> Vec<CheckError> {
308
308
  /// Does `t` name a type: one with consts, methods, statics or variants?
309
309
  pub(crate) fn isKnownType(t: &str, env: &TypeEnv, ctx: &CheckCtx) -> bool {
310
310
  let prefix = format!("{}{}", t, ast::MEMBER_SEP);
311
- let has_consts = env
312
- .range(prefix.clone()..)
313
- .next()
314
- .is_some_and(|(k, _)| k.starts_with(&prefix));
311
+ let has_consts = env.hasPrefix(&prefix);
315
312
  let first_of = |r: Option<(&(String, String), _)>| r.is_some_and(|((owner, _), _)| owner == t);
316
313
  has_consts
317
314
  || first_of(ctx.methods.range((t.to_string(), String::new())..).next())
compiler/checker/src/env.rs ADDED
@@ -0,0 +1,169 @@
1
+ //! `TypeEnv`: the names in scope and their types. A sorted map, like the `BTreeMap` it
2
+ //! replaces, made of a shared frozen base (the program's globals, `freeze`) and the names
3
+ //! bound or removed since. Every fn body, match arm, closure and branch the checker enters
4
+ //! clones its scope's env; with the base shared, a clone copies only the locals instead of
5
+ //! every global of the program.
6
+
7
+ use crate::types::TypeScheme;
8
+ use std::collections::btree_map;
9
+ use std::collections::BTreeMap;
10
+ use std::iter::Peekable;
11
+ use std::rc::Rc;
12
+
13
+ #[derive(Debug, Clone, Default)]
14
+ pub struct TypeEnv {
15
+ base: Rc<BTreeMap<String, TypeScheme>>,
16
+ /// Names bound since the base was frozen; `None` hides a base name (`remove`).
17
+ own: BTreeMap<String, Option<TypeScheme>>,
18
+ }
19
+
20
+ impl TypeEnv {
21
+ pub fn new() -> Self {
22
+ TypeEnv::default()
23
+ }
24
+
25
+ /// Moves every binding into the shared base, so clones of this env share them.
26
+ pub fn freeze(&mut self) {
27
+ if self.own.is_empty() {
28
+ return;
29
+ }
30
+ let base = Rc::make_mut(&mut self.base);
31
+ for (k, v) in std::mem::take(&mut self.own) {
32
+ match v {
33
+ Some(v) => {
34
+ base.insert(k, v);
35
+ }
36
+ None => {
37
+ base.remove(&k);
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ pub fn get(&self, k: &str) -> Option<&TypeScheme> {
44
+ match self.own.get(k) {
45
+ Some(v) => v.as_ref(),
46
+ None => self.base.get(k),
47
+ }
48
+ }
49
+
50
+ pub fn contains_key(&self, k: &str) -> bool {
51
+ self.get(k).is_some()
52
+ }
53
+
54
+ pub fn insert(&mut self, k: String, v: TypeScheme) -> Option<TypeScheme> {
55
+ let shadowed = if self.own.contains_key(&k) { None } else { self.base.get(&k).cloned() };
56
+ match self.own.insert(k, Some(v)) {
57
+ Some(p) => p,
58
+ None => shadowed,
59
+ }
60
+ }
61
+
62
+ pub fn remove(&mut self, k: &str) -> Option<TypeScheme> {
63
+ let inBase = self.base.contains_key(k);
64
+ let prev = if inBase {
65
+ self.own.insert(k.to_string(), None)
66
+ } else {
67
+ self.own.remove(k)
68
+ };
69
+ match prev {
70
+ Some(p) => p,
71
+ None if inBase => self.base.get(k).cloned(),
72
+ None => None,
73
+ }
74
+ }
75
+
76
+ /// Whether some bound name starts with `prefix`.
77
+ pub fn hasPrefix(&self, prefix: &str) -> bool {
78
+ let live = |r: Option<(&String, bool)>| r.is_some_and(|(k, _)| k.starts_with(prefix));
79
+ let inOwn = self.own.range::<str, _>((std::ops::Bound::Included(prefix), std::ops::Bound::Unbounded)).find(|(_, v)| v.is_some()).map(|(k, _)| (k, true));
80
+ if live(inOwn) {
81
+ return true;
82
+ }
83
+ self.base
84
+ .range::<str, _>((std::ops::Bound::Included(prefix), std::ops::Bound::Unbounded))
85
+ .take_while(|(k, _)| k.starts_with(prefix))
86
+ .any(|(k, _)| !matches!(self.own.get(k), Some(None)))
87
+ }
88
+
89
+ pub fn iter(&self) -> Iter<'_> {
90
+ Iter { base: self.base.iter().peekable(), own: self.own.iter().peekable() }
91
+ }
92
+
93
+ pub fn keys(&self) -> impl Iterator<Item = &String> {
94
+ self.iter().map(|(k, _)| k)
95
+ }
96
+
97
+ pub fn values(&self) -> impl Iterator<Item = &TypeScheme> {
98
+ self.iter().map(|(_, v)| v)
99
+ }
100
+
101
+ pub fn len(&self) -> usize {
102
+ self.iter().count()
103
+ }
104
+
105
+ pub fn is_empty(&self) -> bool {
106
+ self.iter().next().is_none()
107
+ }
108
+ }
109
+
110
+ /// The bindings of a `TypeEnv` in key order: the base merged with the names bound since.
111
+ pub struct Iter<'a> {
112
+ base: Peekable<btree_map::Iter<'a, String, TypeScheme>>,
113
+ own: Peekable<btree_map::Iter<'a, String, Option<TypeScheme>>>,
114
+ }
115
+
116
+ impl<'a> Iterator for Iter<'a> {
117
+ type Item = (&'a String, &'a TypeScheme);
118
+ fn next(&mut self) -> Option<Self::Item> {
119
+ loop {
120
+ let pick_own = match (self.base.peek(), self.own.peek()) {
121
+ (None, None) => return None,
122
+ (Some(_), None) => false,
123
+ (None, Some(_)) => true,
124
+ (Some((bk, _)), Some((ok, _))) => ok <= bk,
125
+ };
126
+ if pick_own {
127
+ let (k, v) = self.own.next()?;
128
+ if self.base.peek().is_some_and(|(bk, _)| *bk == k) {
129
+ self.base.next();
130
+ }
131
+ if let Some(v) = v {
132
+ return Some((k, v));
133
+ }
134
+ } else {
135
+ return self.base.next();
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ impl<'a> IntoIterator for &'a TypeEnv {
142
+ type Item = (&'a String, &'a TypeScheme);
143
+ type IntoIter = Iter<'a>;
144
+ fn into_iter(self) -> Iter<'a> {
145
+ self.iter()
146
+ }
147
+ }
148
+
149
+ impl Extend<(String, TypeScheme)> for TypeEnv {
150
+ fn extend<I: IntoIterator<Item = (String, TypeScheme)>>(&mut self, it: I) {
151
+ for (k, v) in it {
152
+ self.insert(k, v);
153
+ }
154
+ }
155
+ }
156
+
157
+ impl FromIterator<(String, TypeScheme)> for TypeEnv {
158
+ fn from_iter<I: IntoIterator<Item = (String, TypeScheme)>>(it: I) -> Self {
159
+ let mut e = TypeEnv::new();
160
+ e.extend(it);
161
+ e
162
+ }
163
+ }
164
+
165
+ impl PartialEq for TypeEnv {
166
+ fn eq(&self, other: &Self) -> bool {
167
+ self.iter().eq(other.iter())
168
+ }
169
+ }
compiler/checker/src/lib.rs CHANGED
@@ -3,6 +3,7 @@
3
3
  #![allow(non_snake_case)]
4
4
 
5
5
  mod state;
6
+ mod env;
6
7
  mod callcheck;
7
8
  mod callsites;
8
9
  mod closurehints;
compiler/checker/src/program.rs CHANGED
@@ -261,6 +261,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
261
261
  }
262
262
  }
263
263
  withCheck(|s| *s.globals.borrow_mut() = global_env.keys().cloned().collect());
264
+ global_env.freeze();
264
265
  // The calls inside a const initializer (`List(1, 2)`) are instantiated like a
265
266
  // root fn's: codegen compiles each initializer once, outside any instantiation.
266
267
  let const_calls = drainCalls();
compiler/checker/src/tables.rs CHANGED
@@ -226,5 +226,7 @@ pub fn buildGlobalTables(source: &ast::Source) -> (TypeEnv, MethodEnv, EnumVaria
226
226
  }
227
227
 
228
228
  addTraitMethods(&buildTraits(source), &mut methods, None);
229
+ // Shared by every scope cloned from it (see `TypeEnv`).
230
+ global_env.freeze();
229
231
  (global_env, methods, enum_variants)
230
232
  }
compiler/checker/src/types.rs CHANGED
@@ -83,7 +83,7 @@ impl TypeScheme {
83
83
  }
84
84
  }
85
85
 
86
- pub type TypeEnv = BTreeMap<String, TypeScheme>;
86
+ pub use crate::env::TypeEnv;
87
87
 
88
88
  /// A checker error is a `Diagnostic`; the position is the enclosing declaration's (see
89
89
  /// `ast::Fn`/`ast::Enum`/`ast::Test`) unless a more specific one is known, `(0, 0)` when unknown.