plum

#treesitter#compiler#wasm

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

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


00217f5 — Peter John 2026-11-11T01:04:47+05:30
loader: read and parse the imported files on several threads
compiler/cli/tests/cli/determinism_test.rs CHANGED
@@ -97,3 +97,82 @@ fn webBuildsAndModulesHoldNoPathOrTime() {
97
97
  assert!(relative == absolute, "a relative and an absolute entry path give other bytes");
98
98
  assert!(relative == moved && moved == moved0, "std in another folder gives other bytes");
99
99
  }
100
+
101
+ /// The thread counts the tests below compare: one (nothing runs on another thread), a few,
102
+ /// more than the files a wave can have, and the default (one per core).
103
+ const THREADS: [Option<&str>; 4] = [Some("1"), Some("2"), Some("64"), None];
104
+
105
+ fn withThreads<'a>(cmd: &'a mut Command, t: Option<&str>) -> &'a mut Command {
106
+ match t {
107
+ Some(n) => cmd.env("PLUM_THREADS", n),
108
+ None => cmd.env_remove("PLUM_THREADS"),
109
+ }
110
+ }
111
+
112
+ /// Work a compile spreads over threads (reading and parsing the imported files) gives the
113
+ /// same module with one thread as with many.
114
+ #[test]
115
+ fn threadCountDoesNotChangeTheBytes() {
116
+ let dir = Scratch::new("det_threads");
117
+ for game in ["examples/games/orb_run.plum", "examples/games/kids/balloon_pop.plum", "examples/functional.plum"] {
118
+ let outs: Vec<Vec<u8>> = THREADS
119
+ .iter()
120
+ .enumerate()
121
+ .map(|(i, t)| {
122
+ let out = dir.join(format!("t{i}.wasm"));
123
+ let st = withThreads(Command::new(plumBin()).arg("compile").arg(root().join(game)).arg("-o").arg(&out), *t).output().unwrap();
124
+ assert!(st.status.success(), "{game} with PLUM_THREADS={t:?}: {}", String::from_utf8_lossy(&st.stderr));
125
+ std::fs::read(&out).unwrap()
126
+ })
127
+ .collect();
128
+ assert!(outs.iter().all(|o| *o == outs[0]), "{game}: another thread count gave other bytes");
129
+ }
130
+ for file in ["std/collections/KdTree.plum", "std/collections/Map.plum"] {
131
+ let outs: Vec<Vec<u8>> = THREADS
132
+ .iter()
133
+ .enumerate()
134
+ .map(|(i, t)| {
135
+ let out = dir.join(format!("s{i}.wasm"));
136
+ let st = withThreads(Command::new(plumBin()).arg("test").arg(root().join(file)).env("PLUM_DUMP_WASM", &out), *t).output().unwrap();
137
+ std::fs::read(&out).unwrap_or_else(|_| panic!("{file}: no module dumped: {}", String::from_utf8_lossy(&st.stderr)))
138
+ })
139
+ .collect();
140
+ assert!(outs.iter().all(|o| *o == outs[0]), "{file}: another thread count gave other bytes");
141
+ }
142
+ }
143
+
144
+ /// Imported files are parsed ahead on other threads, but the error a broken import gives is
145
+ /// the one a file-by-file walk meets first, whatever the thread count: here a parse error in
146
+ /// the second import, then (with that import gone) a missing third one, each behind a
147
+ /// working import of its own import.
148
+ #[test]
149
+ fn threadCountDoesNotChangeTheFirstLoadError() {
150
+ let dir = Scratch::new("det_thread_errors");
151
+ #[cfg(unix)]
152
+ std::os::unix::fs::symlink(root().join("std"), dir.join("std")).unwrap();
153
+ #[cfg(not(unix))]
154
+ return;
155
+ let write = |name: &str, text: &str| std::fs::write(dir.join(name), text).unwrap();
156
+ write("good.plum", "import std/Int\nimport deep\n\nfun one() -> Int = 1\n");
157
+ write("deep.plum", "import std/Int\n\nfun three() -> Int = 3\n");
158
+ write("bad.plum", "fun two( -> Int = 2\n");
159
+ write("main.plum", "import std/Int\nimport good\nimport bad\nimport missing\n\nfun main() -> Int = 0\n");
160
+ write("main2.plum", "import std/Int\nimport good\nimport missing\nimport bad\n\nfun main() -> Int = 0\n");
161
+ for (entry, expect) in [("main.plum", "bad.plum:1:"), ("main2.plum", "import 'missing'")] {
162
+ let errs: Vec<String> = THREADS
163
+ .iter()
164
+ .map(|t| {
165
+ let st = withThreads(
166
+ Command::new(plumBin()).current_dir(dir.path()).arg("compile").arg(entry).arg("--lib-path").arg(".").arg("-o").arg(dir.join("x.wasm")),
167
+ *t,
168
+ )
169
+ .output()
170
+ .unwrap();
171
+ assert!(!st.status.success(), "{entry} compiled");
172
+ String::from_utf8_lossy(&st.stderr).into_owned()
173
+ })
174
+ .collect();
175
+ assert!(errs[0].contains(expect), "{entry}: {}", errs[0]);
176
+ assert!(errs.iter().all(|e| *e == errs[0]), "{entry}: another thread count gave another error: {errs:?}");
177
+ }
178
+ }
compiler/core/src/loader.rs CHANGED
@@ -57,9 +57,10 @@ pub fn loadAndMergeWithOverridesDiag(
57
57
  MERGED_LIT_ERRORS.with(|e| e.borrow_mut().clear());
58
58
  visited.insert(entry_canon.clone());
59
59
  let imports = entry_source.imports.clone();
60
+ let mut parsed = prefetch(&entry_canon, &imports, lib_path, overrides);
60
61
  let mut files = vec![Loaded { path: entry_canon, text: entry_text, source: entry_source }];
61
62
  for import in &imports {
62
- collectImport(import, lib_path, overrides, &mut visited, &mut files)?;
63
+ collectImport(import, lib_path, overrides, &mut parsed, &mut visited, &mut files)?;
63
64
  }
64
65
  shadowStdTypes(&mut files, lib_path)?;
65
66
  nativeOnlyInStd(&files, lib_path)?;
@@ -154,6 +155,7 @@ fn collectImport(
154
155
  import: &Import,
155
156
  lib_path: &Path,
156
157
  overrides: &HashMap<PathBuf, String>,
158
+ parsed: &mut Parsed,
157
159
  visited: &mut HashSet<PathBuf>,
158
160
  files: &mut Vec<Loaded>,
159
161
  ) -> Loaded_<()> {
@@ -162,17 +164,111 @@ fn collectImport(
162
164
  // Already loaded — a diamond import or a cycle.
163
165
  return Ok(());
164
166
  }
167
+ let (text, source) = match parsed.remove(&target_canon) {
168
+ Some(done) => done,
165
- let text = readText(&target_canon, overrides)?;
169
+ None => readAndParse(&target_canon, overrides),
170
+ };
171
+ let text = text?;
166
- let source = parseText(&target_canon, &text)?;
172
+ let source = source?;
167
173
  checkBuiltinImports(&target_canon, &source, lib_path)?;
168
174
  let nested = source.imports.clone();
169
175
  files.push(Loaded { path: target_canon, text, source });
170
176
  for n in &nested {
171
- collectImport(n, lib_path, overrides, visited, files)?;
177
+ collectImport(n, lib_path, overrides, parsed, visited, files)?;
172
178
  }
173
179
  Ok(())
174
180
  }
175
181
 
182
+ /// A file read and parsed: its text (or why it could not be read) and its parse (or the
183
+ /// parse error; the read error again when there is no text).
184
+ type ReadParse = (Loaded_<String>, Loaded_<Source>);
185
+ type Parsed = HashMap<PathBuf, ReadParse>;
186
+
187
+ fn readAndParse(path: &Path, overrides: &HashMap<PathBuf, String>) -> ReadParse {
188
+ let text = readText(path, overrides);
189
+ let source = match &text {
190
+ Ok(t) => parseText(path, t),
191
+ Err(e) => Err(e.clone()),
192
+ };
193
+ (text, source)
194
+ }
195
+
196
+ /// How many threads a compile may use: `PLUM_THREADS`, else one per core. With 1 nothing
197
+ /// runs on another thread. Whatever the count, the output is the same: work done in
198
+ /// parallel is pure, and its results are used in the order the sequential code uses them.
199
+ pub fn threads() -> usize {
200
+ static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
201
+ *N.get_or_init(|| match std::env::var("PLUM_THREADS").ok().and_then(|v| v.trim().parse::<usize>().ok()) {
202
+ Some(n) => n.max(1),
203
+ None => std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1),
204
+ })
205
+ }
206
+
207
+ /// Every file `imports` reach (transitively), read and parsed on `threads()` threads: a file's
208
+ /// imports are queued as soon as it is parsed. `collectImport` then walks the imports in its
209
+ /// own order as before and takes each file's result from here: reading and parsing a file
210
+ /// depends on nothing but the file, so the program and the first error are what a
211
+ /// sequential walk gives. A file that an earlier failing import would hide is parsed for nothing.
212
+ fn prefetch(entry: &Path, imports: &[Import], lib_path: &Path, overrides: &HashMap<PathBuf, String>) -> Parsed {
213
+ use std::sync::{Condvar, Mutex};
214
+ struct Work {
215
+ queue: Vec<PathBuf>,
216
+ seen: HashSet<PathBuf>,
217
+ /// Files taken off the queue and not parsed yet.
218
+ busy: usize,
219
+ done: Parsed,
220
+ }
221
+ let n = threads();
222
+ if n <= 1 {
223
+ return HashMap::new();
224
+ }
225
+ let resolved = |imports: &[Import]| -> Vec<PathBuf> { imports.iter().filter_map(|i| resolveImport(i, lib_path).ok()).collect() };
226
+ let mut work = Work { queue: Vec::new(), seen: HashSet::from([entry.to_path_buf()]), busy: 0, done: HashMap::new() };
227
+ for p in resolved(imports) {
228
+ if work.seen.insert(p.clone()) {
229
+ work.queue.push(p);
230
+ }
231
+ }
232
+ let work = Mutex::new(work);
233
+ let wake = Condvar::new();
234
+ std::thread::scope(|sc| {
235
+ for _ in 0..n {
236
+ sc.spawn(|| {
237
+ let mut w = work.lock().unwrap_or_else(|e| e.into_inner());
238
+ loop {
239
+ if let Some(path) = w.queue.pop() {
240
+ w.busy += 1;
241
+ drop(w);
242
+ // A parser panic leaves the file to `collectImport`, which meets it
243
+ // where a sequential walk would; this thread must not die busy.
244
+ let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| readAndParse(&path, overrides))).ok();
245
+ let more = match &r {
246
+ Some((_, Ok(src))) => resolved(&src.imports),
247
+ _ => Vec::new(),
248
+ };
249
+ w = work.lock().unwrap_or_else(|e| e.into_inner());
250
+ w.busy -= 1;
251
+ for p in more {
252
+ if w.seen.insert(p.clone()) {
253
+ w.queue.push(p);
254
+ }
255
+ }
256
+ if let Some(r) = r {
257
+ w.done.insert(path, r);
258
+ }
259
+ wake.notify_all();
260
+ } else if w.busy == 0 {
261
+ break;
262
+ } else {
263
+ w = wake.wait(w).unwrap_or_else(|e| e.into_inner());
264
+ }
265
+ }
266
+ });
267
+ }
268
+ });
269
+ work.into_inner().unwrap_or_else(|e| e.into_inner()).done
270
+ }
271
+
176
272
  /// `@native` is std's: a function outside std with that body is an error at the function.
177
273
  fn nativeOnlyInStd(files: &[Loaded], lib_path: &Path) -> Loaded_<()> {
178
274
  for f in files.iter().filter(|f| !isStdFile(&f.path, lib_path)) {