plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
c086b70
— Peter John
2026-11-16T14:15:19+05:30
the parse cache (user: Roc-style per-file caching of the front end): each file a program imports is parsed once and reused, in memory by every program of one run and on disk across runs (`plum_core::parse_cache`, hooked into the loader's `parseCached`); profile first (debug, `PLUM_TIMINGS`, new loader phases parse/collect/shadow std types/resolve modules/merge/front end): a `plum check` file is load ~90 ms (parse 30-40 ms of it) and a whole-program check ~130 ms, a `plum test` file adds 5 re-checks of ~48 ms and the passes, so the front end is ~15% of it; only the parse is truly per file: the loader merges every file into one program before anything else, `resolveModules` renames fns several files define, `shadowStdTypes` rewrites and re-parses std's text by what the importer declares, generic bodies are checked per instantiation from call sites anywhere (the importer's types), trait-object calls reach the importer's implementers, and type info is keyed by node ids numbered over the merged program, so resolution, checking and everything after stay per program (the backlog says what a modular checker needs); an entry is the exact text, its `Source` and the compiler that wrote it (the executable's path, size and mtime, the package version): a hit needs both the very same, hashes only name files, so a collision, another compiler's entry, an edited file or a partial/corrupt entry (bad magic, truncated, undecodable) is a miss; only successful parses are cached; a hit is renumbered (`ast::renumberIds`, the walk `numberIds` does, so the same numbering a fresh parse gets) and stamped with the current display path; memory keeps one entry per canonical path (the LSP's edited buffers replace theirs), disk one per text in `plum-cache/<exe>-<compiler hash>/` beside the executable (`target/debug/plum-cache/`) or `PLUM_CACHE_DIR`, the folders of the executable's earlier builds removed when a new one is made, writes to a temporary file renamed into place; the AST derives serde (postcard); `--no-cache` (a global flag, any command; a sweep passes it to its children) and `PLUM_NO_CACHE` turn both off; the language server keeps memory only; `plum check` checks its files side by side (`loader::threads()` workers with 256 MB stacks, each parsing on its own thread, `loader::parseOnThisThread`), errors printed in file order as before; timings (debug, a loaded machine, against 56bbbeb8): `plum check std tests` 33.1 s before, 4.5 s cold, 4.2 s warm (7.8 s `--no-cache`, so ~3.3 s of it is the cache and the rest the workers), `plum test std examples tests` 25.2 s / 241 s CPU before, 21.6 s / 200 s CPU cold and warm (a sweep's children share the disk entries at once), one `plum test tests/std/collections/Map.plum` 1.47 s before, 1.45 s warm, `plum check` of it 0.16 s and 0.13 s, compiling Orbit Runner 1.22 s and 1.17 s; test-all 146 s; tests: core parse_cache_test (every std file reads back as its parse, an entry only for its own compiler and text, a hash collision a miss, cut and garbage entries misses, writers side by side leave whole entries and no temporaries, older builds pruned, a load sees edited direct and transitive imports and a syntax error, no duplicate ids), cli parse_cache_test (four programs and two test modules the same bytes with `--no-cache`, a cold and a warm cache; `plum run` sees each edit of a direct and a transitive import, a syntax error, a corrupt cache; four `plum check` runs side by side on one cold cache); docs: tools.md (`--no-cache`, the parse cache, `PLUM_NO_CACHE`, `PLUM_CACHE_DIR`), backlog (only the parse is cached per file, and why)
Generated files not shown: Cargo.lock
- compiler/cli/src/main.rs +50 -10
- compiler/cli/tests/cli/main.rs +1 -0
- compiler/cli/tests/cli/parse_cache_test.rs +121 -0
- compiler/core/Cargo.toml +2 -0
- compiler/core/src/ast.rs +72 -62
- compiler/core/src/lib.rs +1 -0
- compiler/core/src/loader.rs +35 -13
- compiler/core/src/parse_cache.rs +213 -0
- compiler/core/tests/core/main.rs +1 -0
- compiler/core/tests/core/parse_cache_test.rs +191 -0
- compiler/lsp/src/main.rs +3 -0
- docs/backlog.md +1 -0
- docs/tools.md +5 -0
compiler/cli/src/main.rs
CHANGED
|
@@ -23,6 +23,10 @@ use editor::EditorType;
|
|
|
23
23
|
struct Cli {
|
|
24
24
|
#[command(subcommand)]
|
|
25
25
|
command: Command,
|
|
26
|
+
/// Parse every file again: neither read nor write the parse cache (memory and `plum-cache/` beside
|
|
27
|
+
/// the executable; `PLUM_NO_CACHE` does the same)
|
|
28
|
+
#[arg(long, global = true)]
|
|
29
|
+
no_cache: bool,
|
|
26
30
|
}
|
|
27
31
|
|
|
28
32
|
#[derive(Subcommand)]
|
|
@@ -206,6 +210,9 @@ fn renderAll(ds: &[Diagnostic], entry: &std::path::Path) -> String {
|
|
|
206
210
|
|
|
207
211
|
fn run() -> Result<()> {
|
|
208
212
|
let cli = Cli::parse();
|
|
213
|
+
if cli.no_cache {
|
|
214
|
+
plum_core::parse_cache::disable();
|
|
215
|
+
}
|
|
209
216
|
match cli.command {
|
|
210
217
|
Command::Format { file, check, stdin } => cmdFormat(file, check, stdin),
|
|
211
218
|
Command::Compile { file, output, lib_path, explain_fusion, no_fusion, no_fbip } => {
|
|
@@ -317,7 +324,7 @@ fn compileToTestWasm(
|
|
|
317
324
|
lib_path: &std::path::Path,
|
|
318
325
|
fusion: plum_driver::PassOptions,
|
|
319
326
|
) -> Result<(Vec<u8>, Vec<String>)> {
|
|
320
|
-
let ast = plum_core::loadAndMergeDiag(file, lib_path).map_err(|e| anyhow::anyhow!("{}", renderAll(&e, file)))?;
|
|
327
|
+
let ast = plum_core::timing::time("load", || plum_core::loadAndMergeDiag(file, lib_path)).map_err(|e| anyhow::anyhow!("{}", renderAll(&e, file)))?;
|
|
321
328
|
|
|
322
329
|
// Returns an error (rather than exiting the process directly, as
|
|
323
330
|
// `compileToWasm`'s equivalent check does for the single-file
|
|
@@ -326,7 +333,7 @@ fn compileToTestWasm(
|
|
|
326
333
|
// continue to the rest of the directory instead of the whole run
|
|
327
334
|
// dying on the first file with a type error. Checked once, on the
|
|
328
335
|
// test-desugared source codegen then compiles.
|
|
329
|
-
let out = plum_wasm_codegen::compile(&ast, &plum_wasm_codegen::CompileOptions { tests: true, passes: fusion, ..Default::default() }).map_err(|ds| anyhow::anyhow!("{}", renderAll(&ds, file)))?;
|
|
336
|
+
let out = plum_core::timing::time("compile", || plum_wasm_codegen::compile(&ast, &plum_wasm_codegen::CompileOptions { tests: true, passes: fusion, ..Default::default() })).map_err(|ds| anyhow::anyhow!("{}", renderAll(&ds, file)))?;
|
|
330
337
|
let compiled = (out.wasm, out.test_names);
|
|
331
338
|
// Debug aid: `PLUM_DUMP_WASM=out.wasm plum test file.plum` keeps the module.
|
|
332
339
|
if let Some(path) = std::env::var_os("PLUM_DUMP_WASM") {
|
|
@@ -352,22 +359,52 @@ fn cmdCompile(
|
|
|
352
359
|
}
|
|
353
360
|
|
|
354
361
|
/// `plum check`: loads and type-checks every file, printing each error; no wasm is made.
|
|
362
|
+
/// The files are checked side by side (`plum_core::loader::threads()` at a time), sharing the
|
|
363
|
+
/// parse cache, and their errors are printed in file order.
|
|
355
364
|
fn cmdCheck(paths: Vec<std::path::PathBuf>, lib_path: std::path::PathBuf) -> Result<()> {
|
|
365
|
+
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
356
366
|
let mut files = Vec::new();
|
|
357
367
|
for path in &paths {
|
|
358
368
|
files.extend(collectPlumFiles(path)?);
|
|
359
369
|
}
|
|
370
|
+
let checkOne = |file: &std::path::Path| -> Option<String> {
|
|
360
|
-
|
|
371
|
+
let opts = plum_driver::PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
|
|
361
|
-
let mut bad = 0usize;
|
|
362
|
-
for file in &files {
|
|
363
|
-
let errors = match plum_core::loadAndMergeDiag(file, &lib_path) {
|
|
372
|
+
let errors = match plum_core::timing::time("load", || plum_core::loadAndMergeDiag(file, &lib_path)) {
|
|
364
|
-
Ok(ast) => plum_driver::check(&ast, &opts).err(),
|
|
373
|
+
Ok(ast) => plum_core::timing::time("check", || plum_driver::check(&ast, &opts)).err(),
|
|
365
374
|
Err(ds) => Some(ds),
|
|
366
375
|
};
|
|
367
|
-
if let Some(ds) = errors {
|
|
368
|
-
|
|
376
|
+
errors.map(|ds| renderAll(&ds, file))
|
|
377
|
+
};
|
|
378
|
+
let jobs = plum_core::loader::threads().min(files.len()).max(1);
|
|
379
|
+
let mut results: Vec<Option<String>> = vec![None; files.len()];
|
|
369
|
-
|
|
380
|
+
if jobs == 1 {
|
|
381
|
+
for (i, file) in files.iter().enumerate() {
|
|
382
|
+
results[i] = checkOne(file);
|
|
370
383
|
}
|
|
384
|
+
} else {
|
|
385
|
+
let next = AtomicUsize::new(0);
|
|
386
|
+
let done = std::sync::Mutex::new(&mut results);
|
|
387
|
+
std::thread::scope(|sc| {
|
|
388
|
+
for _ in 0..jobs {
|
|
389
|
+
let (next, done, files, checkOne) = (&next, &done, &files, &checkOne);
|
|
390
|
+
// The checker recurses as deep as the program nests: the main thread's stack.
|
|
391
|
+
std::thread::Builder::new()
|
|
392
|
+
.stack_size(256 << 20)
|
|
393
|
+
.spawn_scoped(sc, move || loop {
|
|
394
|
+
plum_core::loader::parseOnThisThread();
|
|
395
|
+
let i = next.fetch_add(1, Ordering::Relaxed);
|
|
396
|
+
let Some(file) = files.get(i) else { break };
|
|
397
|
+
let r = checkOne(file);
|
|
398
|
+
done.lock().unwrap_or_else(|e| e.into_inner())[i] = r;
|
|
399
|
+
})
|
|
400
|
+
.expect("cannot start a check thread");
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
let mut bad = 0usize;
|
|
405
|
+
for text in results.into_iter().flatten() {
|
|
406
|
+
eprintln!("{text}");
|
|
407
|
+
bad += 1;
|
|
371
408
|
}
|
|
372
409
|
if files.len() > 1 || bad > 0 {
|
|
373
410
|
println!("{}/{} files checked without errors", files.len() - bad, files.len());
|
|
@@ -694,6 +731,9 @@ fn runSweepParallel(
|
|
|
694
731
|
let started = std::time::Instant::now();
|
|
695
732
|
let mut cmd = process::Command::new(exe);
|
|
696
733
|
cmd.arg("test").arg("--lib-path").arg(lib_path);
|
|
734
|
+
if !plum_core::parse_cache::enabled() {
|
|
735
|
+
cmd.arg("--no-cache");
|
|
736
|
+
}
|
|
697
737
|
if !fusion.fusion {
|
|
698
738
|
cmd.arg("--no-fusion");
|
|
699
739
|
}
|
compiler/cli/tests/cli/main.rs
CHANGED
|
@@ -17,6 +17,7 @@ mod inputs_test;
|
|
|
17
17
|
mod main_result_test;
|
|
18
18
|
mod no_fbip_test;
|
|
19
19
|
mod old_forms_test;
|
|
20
|
+
mod parse_cache_test;
|
|
20
21
|
mod replay_test;
|
|
21
22
|
mod run_folder_test;
|
|
22
23
|
mod std_bounds_test;
|
compiler/cli/tests/cli/parse_cache_test.rs
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
//! The parse cache changes nothing a compile makes: the same bytes with `--no-cache`, with a
|
|
2
|
+
//! cold cache (written) and a warm one (read back, from another process), and a run sees
|
|
3
|
+
//! every edit of a file it imports, directly or not.
|
|
4
|
+
use crate::common::{plumBin, root, Scratch};
|
|
5
|
+
use std::path::Path;
|
|
6
|
+
use std::process::Command;
|
|
7
|
+
|
|
8
|
+
fn plum(cache: &Path) -> Command {
|
|
9
|
+
let mut c = Command::new(plumBin());
|
|
10
|
+
c.current_dir(root()).env("PLUM_CACHE_DIR", cache).env_remove("PLUM_NO_CACHE");
|
|
11
|
+
c
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
fn entries(cache: &Path) -> usize {
|
|
15
|
+
std::fs::read_dir(cache).map_or(0, |d| d.flatten().map(|e| std::fs::read_dir(e.path()).map_or(0, |f| f.count())).sum())
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
#[test]
|
|
19
|
+
fn modulesAreTheSameBytesWithAndWithoutTheCache() {
|
|
20
|
+
let dir = Scratch::new("parse_cache_bytes");
|
|
21
|
+
let cache = dir.join("cache");
|
|
22
|
+
let programs = ["examples/functional.plum", "examples/traits.plum", "examples/games/orbitrunner/OrbitRunner.plum", "examples/games/balloonpop/BalloonPop.plum"];
|
|
23
|
+
let tests = ["tests/std/collections/Map.plum", "tests/std/Str.plum"];
|
|
24
|
+
for (k, file) in programs.iter().chain(&tests).enumerate() {
|
|
25
|
+
let isTest = k >= programs.len();
|
|
26
|
+
let outs: Vec<Vec<u8>> = ["--no-cache", "cold", "warm"]
|
|
27
|
+
.iter()
|
|
28
|
+
.map(|how| {
|
|
29
|
+
let out = dir.join(format!("p{k}-{how}.wasm"));
|
|
30
|
+
let mut c = plum(&cache);
|
|
31
|
+
if *how == "--no-cache" {
|
|
32
|
+
c.arg("--no-cache");
|
|
33
|
+
}
|
|
34
|
+
if isTest {
|
|
35
|
+
c.arg("test").arg(file).env("PLUM_DUMP_WASM", &out);
|
|
36
|
+
} else {
|
|
37
|
+
c.arg("compile").arg(file).arg("-o").arg(&out);
|
|
38
|
+
}
|
|
39
|
+
let st = c.output().unwrap();
|
|
40
|
+
assert!(st.status.success(), "{file} {how}: {}", String::from_utf8_lossy(&st.stderr));
|
|
41
|
+
if *how == "--no-cache" && k == 0 {
|
|
42
|
+
assert_eq!(entries(&cache), 0, "--no-cache wrote the cache");
|
|
43
|
+
}
|
|
44
|
+
std::fs::read(&out).unwrap_or_else(|_| panic!("{file} {how}: no module"))
|
|
45
|
+
})
|
|
46
|
+
.collect();
|
|
47
|
+
assert!(outs[0] == outs[1] && outs[1] == outs[2], "{file}: other bytes with the cache");
|
|
48
|
+
}
|
|
49
|
+
assert!(entries(&cache) > 20, "the cache holds {} entries", entries(&cache));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
fn write(dir: &Path, name: &str, text: &str) {
|
|
53
|
+
std::fs::write(dir.join(format!("{name}.plum")), text).unwrap();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
fn runs(cache: &Path, app: &Path) -> String {
|
|
57
|
+
let out = plum(cache).arg("run").arg(app).output().unwrap();
|
|
58
|
+
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
|
59
|
+
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
fn b(v: u8) -> String {
|
|
63
|
+
format!("import std/Int\n\nprimitive Lower =\n fun v() -> Int =\n {v}\n")
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
fn a(add: u8) -> String {
|
|
67
|
+
format!("import std/Int\nimport second\n\nprimitive Upper =\n fun v() -> Int =\n Lower.v() + {add}\n")
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
#[test]
|
|
71
|
+
fn aRunSeesEveryEditOfItsImports() {
|
|
72
|
+
let dir = Scratch::new("parse_cache_edits");
|
|
73
|
+
let cache = dir.join("cache");
|
|
74
|
+
let src = dir.join("src");
|
|
75
|
+
std::fs::create_dir_all(&src).unwrap();
|
|
76
|
+
write(&src, "app", "import std/Result\nimport std/Int\nimport std/Io\nimport std/App\nimport first\n\nenum AppError =\n | Bad\n\nprimitive Main[App] =\n fun main(io: Io) -> Result<Int, AppError> =\n Ok(value: Upper.v())\n");
|
|
77
|
+
write(&src, "first", &a(10));
|
|
78
|
+
write(&src, "second", &b(1));
|
|
79
|
+
let app = src.join("app.plum");
|
|
80
|
+
assert_eq!(runs(&cache, &app), "11");
|
|
81
|
+
assert_eq!(runs(&cache, &app), "11");
|
|
82
|
+
// A transitive import, then a direct one, each the same length as before.
|
|
83
|
+
write(&src, "second", &b(2));
|
|
84
|
+
assert_eq!(runs(&cache, &app), "12");
|
|
85
|
+
write(&src, "first", &a(20));
|
|
86
|
+
assert_eq!(runs(&cache, &app), "22");
|
|
87
|
+
// Back to texts the cache has seen: their entries are right again.
|
|
88
|
+
write(&src, "first", &a(10));
|
|
89
|
+
write(&src, "second", &b(1));
|
|
90
|
+
assert_eq!(runs(&cache, &app), "11");
|
|
91
|
+
// A syntax error is reported, cached parse or not.
|
|
92
|
+
write(&src, "second", "import std/Int\n\nprimitive Lower =\n fun v() -> Int =\n 1 +\n");
|
|
93
|
+
let out = plum(&cache).arg("run").arg(&app).output().unwrap();
|
|
94
|
+
assert!(!out.status.success());
|
|
95
|
+
// A corrupt cache is read as missing.
|
|
96
|
+
for d in std::fs::read_dir(&cache).unwrap().flatten() {
|
|
97
|
+
for f in std::fs::read_dir(d.path()).unwrap().flatten() {
|
|
98
|
+
std::fs::write(f.path(), b"PLUMAST\x01garbage").unwrap();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
write(&src, "second", &b(3));
|
|
102
|
+
assert_eq!(runs(&cache, &app), "13");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/// Checks side by side on one cold cache, then warm: all succeed with the same output.
|
|
106
|
+
#[test]
|
|
107
|
+
fn runsSideBySideShareTheCache() {
|
|
108
|
+
let dir = Scratch::new("parse_cache_side");
|
|
109
|
+
let cache = dir.join("cache");
|
|
110
|
+
let check = || {
|
|
111
|
+
let st = plum(&cache).args(["check", "tests/std/collections", "examples/traits.plum"]).output().unwrap();
|
|
112
|
+
assert!(st.status.success(), "{}", String::from_utf8_lossy(&st.stderr));
|
|
113
|
+
String::from_utf8_lossy(&st.stdout).to_string()
|
|
114
|
+
};
|
|
115
|
+
let outs: Vec<String> = std::thread::scope(|sc| {
|
|
116
|
+
let hs: Vec<_> = (0..4).map(|_| sc.spawn(check)).collect();
|
|
117
|
+
hs.into_iter().map(|h| h.join().unwrap()).collect()
|
|
118
|
+
});
|
|
119
|
+
assert!(outs.iter().all(|o| o == &outs[0]), "{outs:?}");
|
|
120
|
+
assert_eq!(check(), outs[0]);
|
|
121
|
+
}
|
compiler/core/Cargo.toml
CHANGED
|
@@ -8,6 +8,8 @@ tree-sitter = "0.26"
|
|
|
8
8
|
tree-sitter-plum = { path = "../tooling/tree-sitter-plum" }
|
|
9
9
|
topiary-core = "0.7.3"
|
|
10
10
|
topiary-tree-sitter-facade = "0.7.3"
|
|
11
|
+
serde = { version = "1", features = ["derive"] }
|
|
12
|
+
postcard = { version = "1.1", features = ["use-std"] }
|
|
11
13
|
|
|
12
14
|
[dev-dependencies]
|
|
13
15
|
plum-test-support = { path = "../test-support" }
|
compiler/core/src/ast.rs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/// Stable identity of an `Expr`/`Stmt`; `NodeId(0)` means not yet numbered.
|
|
2
|
-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
|
|
2
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
|
|
3
3
|
pub struct NodeId(pub u32);
|
|
4
4
|
|
|
5
5
|
/// Source range of a node, 1-based line/column (the `Diagnostic` convention; the
|
|
6
6
|
/// LSP wants 0-based). `end` is exclusive. All zero when unknown (synthetic nodes).
|
|
7
|
-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
7
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
8
8
|
pub struct Span {
|
|
9
9
|
pub startLine: usize,
|
|
10
10
|
pub startColumn: usize,
|
|
@@ -149,27 +149,37 @@ fn patternIds(ps: &[CasePattern], bad: &mut dyn FnMut(NodeId) -> bool) -> Option
|
|
|
149
149
|
/// Gives every unnumbered `Expr`/`Stmt` of `src` a fresh, process-unique id.
|
|
150
150
|
/// Already numbered nodes keep theirs (clones keep ids).
|
|
151
151
|
pub fn numberIds(src: &mut Source) {
|
|
152
|
+
numberSource(src, false);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/// Gives every `Expr`/`Stmt` that `numberIds` numbers a fresh id, numbered or not: a
|
|
156
|
+
/// program's file read back from the parse cache (`parse_cache`) is numbered as if just parsed.
|
|
157
|
+
pub fn renumberIds(src: &mut Source) {
|
|
158
|
+
numberSource(src, true);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
fn numberSource(src: &mut Source, all: bool) {
|
|
152
162
|
for item in &mut src.items {
|
|
153
163
|
match item {
|
|
154
164
|
Item::Fn(f) => {
|
|
155
165
|
for p in &mut f.params {
|
|
156
166
|
if let Some(d) = &mut p.default {
|
|
157
|
-
numberExpr(d,
|
|
167
|
+
numberExpr(d, all);
|
|
158
168
|
}
|
|
159
169
|
}
|
|
160
170
|
match &mut f.body {
|
|
161
|
-
FnBody::Expr(e) => numberExpr(e,
|
|
171
|
+
FnBody::Expr(e) => numberExpr(e, all),
|
|
162
|
-
FnBody::Block(b) => numberBlock(b,
|
|
172
|
+
FnBody::Block(b) => numberBlock(b, all),
|
|
163
173
|
FnBody::Extern => {}
|
|
164
174
|
}
|
|
165
175
|
}
|
|
166
|
-
Item::Const(c) => numberExpr(&mut c.value,
|
|
176
|
+
Item::Const(c) => numberExpr(&mut c.value, all),
|
|
167
177
|
// A trait method's parameter defaults: compiled at a call on a trait object.
|
|
168
178
|
Item::Trait(t) => {
|
|
169
179
|
for m in &mut t.methods {
|
|
170
180
|
for p in &mut m.sig.params {
|
|
171
181
|
if let Some(d) = &mut p.default {
|
|
172
|
-
numberExpr(d,
|
|
182
|
+
numberExpr(d, all);
|
|
173
183
|
}
|
|
174
184
|
}
|
|
175
185
|
}
|
|
@@ -296,7 +306,7 @@ pub fn hasUnnumbered(src: &Source) -> bool {
|
|
|
296
306
|
firstNode(src, &mut |id| id == NodeId(0)).is_some()
|
|
297
307
|
}
|
|
298
308
|
|
|
299
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
309
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
300
310
|
pub struct Source {
|
|
301
311
|
/// Path of the file this source was parsed from (empty for in-memory sources).
|
|
302
312
|
pub file: String,
|
|
@@ -318,7 +328,7 @@ pub struct Source {
|
|
|
318
328
|
}
|
|
319
329
|
|
|
320
330
|
/// A `primitive Name =` block.
|
|
321
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
331
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
322
332
|
pub struct PrimitiveDecl {
|
|
323
333
|
pub name: String,
|
|
324
334
|
pub line: usize,
|
|
@@ -369,7 +379,7 @@ pub fn takesIoFirst(f: &Fn) -> bool {
|
|
|
369
379
|
/// Separator of an associated item's mangled global name: `Float.Pi`.
|
|
370
380
|
pub const MEMBER_SEP: &str = ".";
|
|
371
381
|
|
|
372
|
-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
382
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
|
|
373
383
|
pub enum TopLevelKind {
|
|
374
384
|
Import,
|
|
375
385
|
Other,
|
|
@@ -419,17 +429,17 @@ impl Source {
|
|
|
419
429
|
}
|
|
420
430
|
}
|
|
421
431
|
|
|
422
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
432
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
423
433
|
pub struct Module {
|
|
424
434
|
pub name: String,
|
|
425
435
|
}
|
|
426
436
|
|
|
427
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
437
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
428
438
|
pub struct Import {
|
|
429
439
|
pub path: String,
|
|
430
440
|
}
|
|
431
441
|
|
|
432
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
442
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
433
443
|
pub enum Item {
|
|
434
444
|
Enum(Enum),
|
|
435
445
|
/// `trait Name<..> =` + method signatures. Its default bodies are also ordinary
|
|
@@ -442,7 +452,7 @@ pub enum Item {
|
|
|
442
452
|
|
|
443
453
|
// ---------- Type definitions ----------
|
|
444
454
|
|
|
445
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
455
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
446
456
|
pub struct GenericParam {
|
|
447
457
|
pub name: String,
|
|
448
458
|
/// `[T: Show + Eq]`: the traits `T` must implement (empty = unbounded).
|
|
@@ -453,7 +463,7 @@ pub struct GenericParam {
|
|
|
453
463
|
pub const SELF_TYPE: &str = "Self";
|
|
454
464
|
|
|
455
465
|
/// `trait Actor =` / `trait Reducer<M> =`: a list of method signatures.
|
|
456
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
466
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
457
467
|
pub struct Trait {
|
|
458
468
|
pub name: String,
|
|
459
469
|
/// Declaring file (stamped by the loader).
|
|
@@ -470,7 +480,7 @@ pub struct Trait {
|
|
|
470
480
|
|
|
471
481
|
/// One method of a trait: its signature as written (with `Self`; the body is
|
|
472
482
|
/// always `FnBody::Extern`), and whether it has a default body.
|
|
473
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
483
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
474
484
|
pub struct TraitMethod {
|
|
475
485
|
pub sig: Fn,
|
|
476
486
|
pub hasDefault: bool,
|
|
@@ -533,7 +543,7 @@ impl Fn {
|
|
|
533
543
|
}
|
|
534
544
|
}
|
|
535
545
|
|
|
536
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
546
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
537
547
|
pub struct Enum {
|
|
538
548
|
pub name: String,
|
|
539
549
|
/// Declaring file (stamped by the loader; empty for an in-memory source).
|
|
@@ -557,13 +567,13 @@ pub struct Enum {
|
|
|
557
567
|
|
|
558
568
|
/// Whether a declaration is a plain `enum` or a `struct`. Struct-only data lives
|
|
559
569
|
/// in `StructInfo`, so it is readable only for a struct.
|
|
560
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
570
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
561
571
|
pub enum TypeKind {
|
|
562
572
|
Enum,
|
|
563
573
|
Struct(StructInfo),
|
|
564
574
|
}
|
|
565
575
|
|
|
566
|
-
#[derive(Debug, Clone, PartialEq, Default)]
|
|
576
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Default)]
|
|
567
577
|
pub struct StructInfo {
|
|
568
578
|
/// Always `Boxed` — generated from an inline variant or a `fun init(self)`
|
|
569
579
|
/// method. Otherwise the layout is decided only by `layout::structLayout`.
|
|
@@ -588,7 +598,7 @@ impl Enum {
|
|
|
588
598
|
}
|
|
589
599
|
}
|
|
590
600
|
|
|
591
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
601
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
592
602
|
pub struct EnumParam {
|
|
593
603
|
pub name: String,
|
|
594
604
|
pub ty: Type,
|
|
@@ -596,7 +606,7 @@ pub struct EnumParam {
|
|
|
596
606
|
pub isMut: bool,
|
|
597
607
|
}
|
|
598
608
|
|
|
599
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
609
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
600
610
|
pub struct EnumVariant {
|
|
601
611
|
pub name: String,
|
|
602
612
|
pub fields: Vec<Type>,
|
|
@@ -622,7 +632,7 @@ pub struct EnumVariant {
|
|
|
622
632
|
|
|
623
633
|
// ---------- Functions ----------
|
|
624
634
|
|
|
625
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
635
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
626
636
|
pub struct Fn {
|
|
627
637
|
pub name: String,
|
|
628
638
|
/// Path of the file the fn was declared in (empty for in-memory sources);
|
|
@@ -664,7 +674,7 @@ pub struct Fn {
|
|
|
664
674
|
pub body: FnBody,
|
|
665
675
|
}
|
|
666
676
|
|
|
667
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
677
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
668
678
|
pub struct Const {
|
|
669
679
|
pub name: String,
|
|
670
680
|
pub value: Expr,
|
|
@@ -672,14 +682,14 @@ pub struct Const {
|
|
|
672
682
|
pub line: usize,
|
|
673
683
|
}
|
|
674
684
|
|
|
675
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
685
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
676
686
|
pub struct Param {
|
|
677
687
|
pub name: String,
|
|
678
688
|
pub ty: ParamType,
|
|
679
689
|
pub default: Option<Expr>,
|
|
680
690
|
}
|
|
681
691
|
|
|
682
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
692
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
683
693
|
pub enum ParamType {
|
|
684
694
|
Type(Type),
|
|
685
695
|
/// `fn(Int, Str) -> Bool` — a function-value type annotation. Positional types
|
|
@@ -687,7 +697,7 @@ pub enum ParamType {
|
|
|
687
697
|
Fn(Vec<Type>, Option<Box<Type>>),
|
|
688
698
|
}
|
|
689
699
|
|
|
690
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
700
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
691
701
|
pub struct Type {
|
|
692
702
|
pub name: String,
|
|
693
703
|
pub generics: Vec<Type>,
|
|
@@ -727,7 +737,7 @@ impl Type {
|
|
|
727
737
|
}
|
|
728
738
|
}
|
|
729
739
|
|
|
730
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
740
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
731
741
|
pub enum FnBody {
|
|
732
742
|
Expr(Expr),
|
|
733
743
|
Block(Block),
|
|
@@ -738,12 +748,12 @@ pub enum FnBody {
|
|
|
738
748
|
|
|
739
749
|
// ---------- Statements ----------
|
|
740
750
|
|
|
741
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
751
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
742
752
|
pub struct Block {
|
|
743
753
|
pub stmts: Vec<Stmt>,
|
|
744
754
|
}
|
|
745
755
|
|
|
746
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
756
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
747
757
|
pub struct Closure {
|
|
748
758
|
pub params: Vec<String>,
|
|
749
759
|
/// One per param: the declared type (`|b: Box|`), `None` when untyped.
|
|
@@ -752,14 +762,14 @@ pub struct Closure {
|
|
|
752
762
|
}
|
|
753
763
|
|
|
754
764
|
/// A statement with its node id and source span.
|
|
755
|
-
#[derive(Debug, Clone)]
|
|
765
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
|
756
766
|
pub struct Stmt {
|
|
757
767
|
pub id: NodeId,
|
|
758
768
|
pub span: Span,
|
|
759
769
|
pub kind: StmtKind,
|
|
760
770
|
}
|
|
761
771
|
|
|
762
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
772
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
763
773
|
pub enum StmtKind {
|
|
764
774
|
Assign(Assign),
|
|
765
775
|
/// Outside a test, traps (hard failure) if `cond` is false. Inside
|
|
@@ -792,7 +802,7 @@ pub enum StmtKind {
|
|
|
792
802
|
/// time, before desugaring can rewrite `cond` into something
|
|
793
803
|
/// unrecognizable (a rewritten variable, a lowered call, ...). `line`/`column`
|
|
794
804
|
/// are 1-based (editor convention).
|
|
795
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
805
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
796
806
|
pub struct Check {
|
|
797
807
|
pub cond: Expr,
|
|
798
808
|
pub line: usize,
|
|
@@ -800,7 +810,7 @@ pub struct Check {
|
|
|
800
810
|
pub text: String,
|
|
801
811
|
}
|
|
802
812
|
|
|
803
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
813
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
804
814
|
pub enum AssignTarget {
|
|
805
815
|
Var(String),
|
|
806
816
|
/// `object.field = value` — `object`'s evaluated type must be a class; `field`
|
|
@@ -808,7 +818,7 @@ pub enum AssignTarget {
|
|
|
808
818
|
Field(Box<Expr>, String),
|
|
809
819
|
}
|
|
810
820
|
|
|
811
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
821
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
812
822
|
pub struct Assign {
|
|
813
823
|
pub targets: Vec<AssignTarget>,
|
|
814
824
|
pub values: Vec<Expr>,
|
|
@@ -835,13 +845,13 @@ pub const FOR_ITER_PREFIX: &str = "__for_it";
|
|
|
835
845
|
/// `for` is a call that the checker lifts to a function (`forms.rs`). It stays because TRMC's
|
|
836
846
|
/// loop keeps its state in compiler-made locals, which a function's arguments can't hold while
|
|
837
847
|
/// holes are filled in place.
|
|
838
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
848
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
839
849
|
pub struct While {
|
|
840
850
|
pub condition: Expr,
|
|
841
851
|
pub body: Block,
|
|
842
852
|
}
|
|
843
853
|
|
|
844
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
854
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
845
855
|
pub struct If {
|
|
846
856
|
pub condition: Expr,
|
|
847
857
|
pub body: Block,
|
|
@@ -849,19 +859,19 @@ pub struct If {
|
|
|
849
859
|
pub else_: Option<Block>,
|
|
850
860
|
}
|
|
851
861
|
|
|
852
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
862
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
853
863
|
pub struct ElseIf {
|
|
854
864
|
pub condition: Expr,
|
|
855
865
|
pub body: Block,
|
|
856
866
|
}
|
|
857
867
|
|
|
858
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
868
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
859
869
|
pub struct Match {
|
|
860
870
|
pub subjects: Vec<Expr>,
|
|
861
871
|
pub cases: Vec<Case>,
|
|
862
872
|
}
|
|
863
873
|
|
|
864
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
874
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
865
875
|
pub struct Case {
|
|
866
876
|
pub patterns: Vec<CasePattern>,
|
|
867
877
|
/// Optional `when <expr>` guard: even once every pattern matches
|
|
@@ -871,7 +881,7 @@ pub struct Case {
|
|
|
871
881
|
pub body: Block,
|
|
872
882
|
}
|
|
873
883
|
|
|
874
|
-
#[derive(Debug, Clone)]
|
|
884
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
|
875
885
|
pub enum CasePattern {
|
|
876
886
|
Class {
|
|
877
887
|
name: String,
|
|
@@ -922,14 +932,14 @@ impl CasePattern {
|
|
|
922
932
|
/// Expressions are the core of the language. Operator precedence is already
|
|
923
933
|
/// resolved by the tree-sitter parser (via the PREC table in grammar.js), so
|
|
924
934
|
/// the tree structure here directly reflects evaluation order.
|
|
925
|
-
#[derive(Debug, Clone)]
|
|
935
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
|
|
926
936
|
pub struct Expr {
|
|
927
937
|
pub id: NodeId,
|
|
928
938
|
pub span: Span,
|
|
929
939
|
pub kind: ExprKind,
|
|
930
940
|
}
|
|
931
941
|
|
|
932
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
942
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
933
943
|
pub enum ExprKind {
|
|
934
944
|
/// Arithmetic / bitwise / range: `a + b`, `a .. b`, etc.
|
|
935
945
|
Binary(Box<BinaryExpr>),
|
|
@@ -975,14 +985,14 @@ pub enum ExprKind {
|
|
|
975
985
|
Block(Box<Block>),
|
|
976
986
|
}
|
|
977
987
|
|
|
978
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
988
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
979
989
|
pub struct BinaryExpr {
|
|
980
990
|
pub op: BinOp,
|
|
981
991
|
pub left: Expr,
|
|
982
992
|
pub right: Expr,
|
|
983
993
|
}
|
|
984
994
|
|
|
985
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
995
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
986
996
|
pub enum BinOp {
|
|
987
997
|
Add,
|
|
988
998
|
Sub,
|
|
@@ -996,39 +1006,39 @@ pub enum BinOp {
|
|
|
996
1006
|
Shr,
|
|
997
1007
|
}
|
|
998
1008
|
|
|
999
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1009
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1000
1010
|
pub struct UnaryExpr {
|
|
1001
1011
|
pub op: UnOp,
|
|
1002
1012
|
pub operand: Expr,
|
|
1003
1013
|
}
|
|
1004
1014
|
|
|
1005
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1015
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1006
1016
|
pub enum UnOp {
|
|
1007
1017
|
Pos,
|
|
1008
1018
|
Neg,
|
|
1009
1019
|
}
|
|
1010
1020
|
|
|
1011
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1021
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1012
1022
|
pub struct BoolExpr {
|
|
1013
1023
|
pub op: BoolOp,
|
|
1014
1024
|
pub left: Expr,
|
|
1015
1025
|
pub right: Expr,
|
|
1016
1026
|
}
|
|
1017
1027
|
|
|
1018
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1028
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1019
1029
|
pub enum BoolOp {
|
|
1020
1030
|
And,
|
|
1021
1031
|
Or,
|
|
1022
1032
|
}
|
|
1023
1033
|
|
|
1024
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1034
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1025
1035
|
pub struct CompareExpr {
|
|
1026
1036
|
pub op: CmpOp,
|
|
1027
1037
|
pub left: Expr,
|
|
1028
1038
|
pub right: Expr,
|
|
1029
1039
|
}
|
|
1030
1040
|
|
|
1031
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1041
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1032
1042
|
pub enum CmpOp {
|
|
1033
1043
|
Lt,
|
|
1034
1044
|
Lte,
|
|
@@ -1039,7 +1049,7 @@ pub enum CmpOp {
|
|
|
1039
1049
|
NotEq2,
|
|
1040
1050
|
}
|
|
1041
1051
|
|
|
1042
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1052
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1043
1053
|
pub struct InlineIf {
|
|
1044
1054
|
pub condition: Expr,
|
|
1045
1055
|
pub then: Expr,
|
|
@@ -1047,7 +1057,7 @@ pub struct InlineIf {
|
|
|
1047
1057
|
}
|
|
1048
1058
|
|
|
1049
1059
|
/// `value!`; `line`/`column` (1-based) locate the `!` operand for the crash message.
|
|
1050
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1060
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1051
1061
|
pub struct BangExpr {
|
|
1052
1062
|
pub value: Expr,
|
|
1053
1063
|
pub line: usize,
|
|
@@ -1059,7 +1069,7 @@ pub struct BangExpr {
|
|
|
1059
1069
|
/// pattern, `guard` the trailing `, cond`s joined by `&&` (they see the
|
|
1060
1070
|
/// bindings), `body` the constant `true` codegen evaluates once both hold. It
|
|
1061
1071
|
/// is a real `Case` so the match-arm pattern compiler can be reused in place.
|
|
1062
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1072
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1063
1073
|
pub struct BindExpr {
|
|
1064
1074
|
pub case: Case,
|
|
1065
1075
|
pub value: Expr,
|
|
@@ -1071,7 +1081,7 @@ impl BindExpr {
|
|
|
1071
1081
|
}
|
|
1072
1082
|
}
|
|
1073
1083
|
|
|
1074
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1084
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1075
1085
|
pub struct FnCall {
|
|
1076
1086
|
pub name: String,
|
|
1077
1087
|
pub args: Vec<Arg>,
|
|
@@ -1101,7 +1111,7 @@ pub fn fnKey(f: &Fn) -> String {
|
|
|
1101
1111
|
}
|
|
1102
1112
|
|
|
1103
1113
|
/// How a call in tail position is made (see `tail.rs`). `NotTail` is the default.
|
|
1104
|
-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
1114
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
1105
1115
|
pub enum TailKind {
|
|
1106
1116
|
#[default]
|
|
1107
1117
|
NotTail,
|
|
@@ -1113,7 +1123,7 @@ pub enum TailKind {
|
|
|
1113
1123
|
Closure,
|
|
1114
1124
|
}
|
|
1115
1125
|
|
|
1116
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1126
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1117
1127
|
pub enum Arg {
|
|
1118
1128
|
Positional(Expr),
|
|
1119
1129
|
Keyword { name: String, value: Expr },
|
|
@@ -1129,7 +1139,7 @@ pub fn isEmptyListLiteral(e: &Expr) -> bool {
|
|
|
1129
1139
|
&& e.span.endColumn == e.span.startColumn + 2
|
|
1130
1140
|
}
|
|
1131
1141
|
|
|
1132
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1142
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1133
1143
|
pub struct ClassCall {
|
|
1134
1144
|
pub type_name: String,
|
|
1135
1145
|
pub fields: Vec<FieldArg>,
|
|
@@ -1154,30 +1164,30 @@ pub struct ClassCall {
|
|
|
1154
1164
|
pub reboxed: Vec<String>,
|
|
1155
1165
|
}
|
|
1156
1166
|
|
|
1157
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1167
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1158
1168
|
pub struct FieldArg {
|
|
1159
1169
|
pub name: String,
|
|
1160
1170
|
pub value: Expr,
|
|
1161
1171
|
}
|
|
1162
1172
|
|
|
1163
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1173
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1164
1174
|
pub struct AttributeExpr {
|
|
1165
1175
|
pub object: Expr,
|
|
1166
1176
|
pub attr: AttrKind,
|
|
1167
1177
|
}
|
|
1168
1178
|
|
|
1169
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1179
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1170
1180
|
pub enum AttrKind {
|
|
1171
1181
|
Field(String),
|
|
1172
1182
|
Method(FnCall),
|
|
1173
1183
|
}
|
|
1174
1184
|
|
|
1175
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1185
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1176
1186
|
pub struct StringExpr {
|
|
1177
1187
|
pub parts: Vec<StringPart>,
|
|
1178
1188
|
}
|
|
1179
1189
|
|
|
1180
|
-
#[derive(Debug, Clone, PartialEq)]
|
|
1190
|
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
|
|
1181
1191
|
pub enum StringPart {
|
|
1182
1192
|
Text(String),
|
|
1183
1193
|
Interp(Expr),
|
compiler/core/src/lib.rs
CHANGED
|
@@ -27,6 +27,7 @@ pub mod lower;
|
|
|
27
27
|
pub mod main_result;
|
|
28
28
|
pub mod modules;
|
|
29
29
|
pub mod native;
|
|
30
|
+
pub mod parse_cache;
|
|
30
31
|
pub mod parser;
|
|
31
32
|
pub mod prune;
|
|
32
33
|
pub mod purity;
|
compiler/core/src/loader.rs
CHANGED
|
@@ -46,7 +46,7 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
46
46
|
// full path to exist.
|
|
47
47
|
let entry_canon = canonicalizeMaybeMissing(entry)?;
|
|
48
48
|
let entry_text = readText(&entry_canon, overrides)?;
|
|
49
|
-
let entry_source =
|
|
49
|
+
let entry_source = parseCached(&entry_canon, &entry_text)?;
|
|
50
50
|
checkBuiltinImports(&entry_canon, &entry_source, lib_path)?;
|
|
51
51
|
|
|
52
52
|
let mut visited: HashSet<PathBuf> = HashSet::new();
|
|
@@ -57,25 +57,31 @@ 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
|
+
let mut parsed = crate::timing::time("parse", || prefetch(&entry_canon, &imports, lib_path, overrides));
|
|
61
61
|
let mut files = vec![Loaded { path: entry_canon.clone(), text: entry_text, source: entry_source }];
|
|
62
|
+
crate::timing::time("collect", || -> Loaded_<()> {
|
|
62
|
-
|
|
63
|
+
for import in &imports {
|
|
63
|
-
|
|
64
|
+
collectImport(import, &entry_canon, lib_path, overrides, &mut parsed, &mut visited, &mut files)?;
|
|
64
|
-
|
|
65
|
+
}
|
|
66
|
+
Ok(())
|
|
67
|
+
})?;
|
|
65
68
|
// `App`, the marker of a program's entry, is std/App's: a file that lists it imports it,
|
|
66
69
|
// like any module. A library folder without it (a test's own) has nothing to import, and
|
|
67
70
|
// the marker needs no declaration there (see `primitiveTraits`).
|
|
68
71
|
let hasApp = resolveImport(&Import { path: "std/App".to_string() }, &entry_canon, lib_path).is_ok();
|
|
69
|
-
shadowStdTypes(&mut files, lib_path)?;
|
|
72
|
+
crate::timing::time("shadow std types", || shadowStdTypes(&mut files, lib_path))?;
|
|
70
73
|
nativeOnlyInStd(&files, lib_path)?;
|
|
71
74
|
testsOnlyInTests(&files, lib_path)?;
|
|
72
75
|
noGlobals(&files)?;
|
|
73
76
|
oneApp(&files)?;
|
|
74
77
|
importedMainsAreStatics(&mut files);
|
|
75
|
-
resolveFileModules(&mut files, lib_path)?;
|
|
78
|
+
crate::timing::time("resolve modules", || resolveFileModules(&mut files, lib_path))?;
|
|
79
|
+
crate::timing::time("merge", || -> Loaded_<()> {
|
|
76
|
-
|
|
80
|
+
for f in &files {
|
|
77
|
-
|
|
81
|
+
mergeItems(&f.path, &f.source, &mut items, &mut names, &mut prims)?;
|
|
78
|
-
|
|
82
|
+
}
|
|
83
|
+
Ok(())
|
|
84
|
+
})?;
|
|
79
85
|
primitiveTraits(&files, &items, hasApp)?;
|
|
80
86
|
let entry_source = files.swap_remove(0).source;
|
|
81
87
|
|
|
@@ -91,7 +97,7 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
91
97
|
formLoops: false,
|
|
92
98
|
primitives: prims,
|
|
93
99
|
};
|
|
94
|
-
crate::lower::frontEndDiag(&mut merged)?;
|
|
100
|
+
crate::timing::time("front end", || crate::lower::frontEndDiag(&mut merged))?;
|
|
95
101
|
Ok(merged)
|
|
96
102
|
}
|
|
97
103
|
|
|
@@ -236,7 +242,7 @@ type Parsed = HashMap<PathBuf, ReadParse>;
|
|
|
236
242
|
fn readAndParse(path: &Path, overrides: &HashMap<PathBuf, String>) -> ReadParse {
|
|
237
243
|
let text = readText(path, overrides);
|
|
238
244
|
let source = match &text {
|
|
239
|
-
Ok(t) =>
|
|
245
|
+
Ok(t) => parseCached(path, t),
|
|
240
246
|
Err(e) => Err(e.clone()),
|
|
241
247
|
};
|
|
242
248
|
(text, source)
|
|
@@ -253,6 +259,16 @@ pub fn threads() -> usize {
|
|
|
253
259
|
})
|
|
254
260
|
}
|
|
255
261
|
|
|
262
|
+
thread_local! {
|
|
263
|
+
static SERIAL_PARSE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/// This thread's loads parse their files on this thread alone: for a thread that is one of
|
|
267
|
+
/// several each loading a program (`plum check`'s), which are parallel enough.
|
|
268
|
+
pub fn parseOnThisThread() {
|
|
269
|
+
SERIAL_PARSE.with(|s| s.set(true));
|
|
270
|
+
}
|
|
271
|
+
|
|
256
272
|
/// Every file `imports` reach (transitively), read and parsed on `threads()` threads: a file's
|
|
257
273
|
/// imports are queued as soon as it is parsed. `collectImport` then walks the imports in its
|
|
258
274
|
/// own order as before and takes each file's result from here: reading and parsing a file
|
|
@@ -268,7 +284,7 @@ fn prefetch(entry: &Path, imports: &[Import], lib_path: &Path, overrides: &HashM
|
|
|
268
284
|
done: Parsed,
|
|
269
285
|
}
|
|
270
286
|
let n = threads();
|
|
271
|
-
if n <= 1 {
|
|
287
|
+
if n <= 1 || SERIAL_PARSE.with(|s| s.get()) {
|
|
272
288
|
return HashMap::new();
|
|
273
289
|
}
|
|
274
290
|
let resolved = |from: &Path, imports: &[Import]| -> Vec<PathBuf> { imports.iter().filter_map(|i| resolveImport(i, from, lib_path).ok()).collect() };
|
|
@@ -686,6 +702,12 @@ fn treeOfIn(text: &str, path: &Path) -> Loaded_<tree_sitter::Tree> {
|
|
|
686
702
|
treeOf(text).map_err(|e| vec![Diagnostic::bare(DiagKind::Parse, format!("{} for '{}'", e, path.display()))])
|
|
687
703
|
}
|
|
688
704
|
|
|
705
|
+
/// `parseText` through the parse cache (`parse_cache`): `path` is canonical.
|
|
706
|
+
fn parseCached(path: &Path, text: &str) -> Loaded_<Source> {
|
|
707
|
+
let disk = if crate::parse_cache::diskOn() { crate::parse_cache::DiskCache::global() } else { None };
|
|
708
|
+
crate::parse_cache::parse(path, text, &displayPath(path), disk, || parseText(path, text))
|
|
709
|
+
}
|
|
710
|
+
|
|
689
711
|
fn parseText(path: &Path, text: &str) -> Loaded_<Source> {
|
|
690
712
|
let tree = treeOfIn(text, path)?;
|
|
691
713
|
let root = tree.root_node();
|
compiler/core/src/parse_cache.rs
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
//! The per-file cache of the loader's parse: a file's text parsed into its `Source` once, and
|
|
2
|
+
//! reused by every program that imports it, in this process (memory) and across runs (disk).
|
|
3
|
+
//!
|
|
4
|
+
//! A parse depends on the file's text alone (its path only names it in diagnostics and is
|
|
5
|
+
//! stamped again on every hit), so an entry is its text and its `Source`, and a hit needs the
|
|
6
|
+
//! very same text: memory keeps one entry per canonical path, the disk one per text, and a
|
|
7
|
+
//! disk entry also names the compiler that wrote it (the executable's path, size and mtime),
|
|
8
|
+
//! so a rebuilt compiler never reads another's. Hashes only name the files: an entry whose
|
|
9
|
+
//! compiler or text is not the current one exactly, or that fails to decode (a partial or
|
|
10
|
+
//! corrupt file), is a miss. Only parses that succeed are cached; a file with a syntax error
|
|
11
|
+
//! is parsed again each time, so its diagnostics are the parser's own.
|
|
12
|
+
//!
|
|
13
|
+
//! On a hit the `Source` is a copy with fresh node ids (ids must be unique within a program
|
|
14
|
+
//! and ahead of nothing the process numbers later, which ids read back from disk may not be),
|
|
15
|
+
//! the same numbering a fresh parse gets.
|
|
16
|
+
//!
|
|
17
|
+
//! What a program does with its files after parsing is not cached: the loader merges every
|
|
18
|
+
//! file into one program, and the name resolution, the front end and the checker run over
|
|
19
|
+
//! the merged program (see `docs/backlog.md`).
|
|
20
|
+
//!
|
|
21
|
+
//! Disk entries live in `PLUM_CACHE_DIR`, else `plum-cache/` beside the executable (so
|
|
22
|
+
//! `target/debug/plum-cache/` for `target/debug/plum`), in a folder per compiler build; the
|
|
23
|
+
//! folders of the executable's earlier builds are removed when its new one is made. Writes go
|
|
24
|
+
//! to a temporary file renamed into place, so runs side by side never read a partial entry.
|
|
25
|
+
//! `--no-cache` (or `PLUM_NO_CACHE`) turns both off; the language server keeps memory only.
|
|
26
|
+
|
|
27
|
+
use std::collections::HashMap;
|
|
28
|
+
use std::hash::{Hash, Hasher};
|
|
29
|
+
use std::path::{Path, PathBuf};
|
|
30
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
31
|
+
use std::sync::{Mutex, OnceLock};
|
|
32
|
+
|
|
33
|
+
use crate::ast::Source;
|
|
34
|
+
|
|
35
|
+
/// The leading bytes of a disk entry: the entry format, bumped when it changes.
|
|
36
|
+
const MAGIC: &[u8] = b"PLUMAST\x01";
|
|
37
|
+
|
|
38
|
+
static MEMORY_OFF: AtomicBool = AtomicBool::new(false);
|
|
39
|
+
static DISK_OFF: AtomicBool = AtomicBool::new(false);
|
|
40
|
+
|
|
41
|
+
fn envOff() -> bool {
|
|
42
|
+
static OFF: OnceLock<bool> = OnceLock::new();
|
|
43
|
+
*OFF.get_or_init(|| std::env::var_os("PLUM_NO_CACHE").is_some_and(|v| !v.is_empty() && v != "0"))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/// `--no-cache`: neither cache is read or written for the rest of the process.
|
|
47
|
+
pub fn disable() {
|
|
48
|
+
MEMORY_OFF.store(true, Ordering::Relaxed);
|
|
49
|
+
DISK_OFF.store(true, Ordering::Relaxed);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/// Memory only (the language server: its files change under it, and a run is one long session).
|
|
53
|
+
pub fn memoryOnly() {
|
|
54
|
+
DISK_OFF.store(true, Ordering::Relaxed);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// Whether the cache is on (no `--no-cache`, no `PLUM_NO_CACHE`), for a run's child processes.
|
|
58
|
+
pub fn enabled() -> bool {
|
|
59
|
+
memoryOn()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
fn memoryOn() -> bool {
|
|
63
|
+
!MEMORY_OFF.load(Ordering::Relaxed) && !envOff()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Whether the disk cache is read and written (on, unless `--no-cache`, `PLUM_NO_CACHE` or the language server).
|
|
67
|
+
pub fn diskOn() -> bool {
|
|
68
|
+
!DISK_OFF.load(Ordering::Relaxed) && !envOff()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// Canonical path -> (text, its parse).
|
|
72
|
+
fn memory() -> &'static Mutex<HashMap<PathBuf, (String, Source)>> {
|
|
73
|
+
static M: OnceLock<Mutex<HashMap<PathBuf, (String, Source)>>> = OnceLock::new();
|
|
74
|
+
M.get_or_init(|| Mutex::new(HashMap::new()))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/// Drops every memory entry (tests).
|
|
78
|
+
pub fn clearMemory() {
|
|
79
|
+
memory().lock().unwrap_or_else(|e| e.into_inner()).clear();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// A folder of disk entries written by one compiler.
|
|
83
|
+
#[derive(Clone, Debug)]
|
|
84
|
+
pub struct DiskCache {
|
|
85
|
+
pub dir: PathBuf,
|
|
86
|
+
/// Who wrote the entries: an entry by any other compiler is a miss.
|
|
87
|
+
pub compiler: String,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#[derive(serde::Serialize, serde::Deserialize)]
|
|
91
|
+
struct Entry {
|
|
92
|
+
compiler: String,
|
|
93
|
+
text: String,
|
|
94
|
+
source: Source,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
fn hex(h: u64) -> String {
|
|
98
|
+
format!("{h:016x}")
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
fn hashOf(t: impl Hash) -> u64 {
|
|
102
|
+
let mut h = std::collections::hash_map::DefaultHasher::new();
|
|
103
|
+
t.hash(&mut h);
|
|
104
|
+
h.finish()
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
impl DiskCache {
|
|
108
|
+
/// The cache of this executable, or `None` when it cannot be located.
|
|
109
|
+
pub fn global() -> Option<&'static DiskCache> {
|
|
110
|
+
static D: OnceLock<Option<DiskCache>> = OnceLock::new();
|
|
111
|
+
D.get_or_init(|| {
|
|
112
|
+
let exe = std::env::current_exe().ok()?;
|
|
113
|
+
let meta = std::fs::metadata(&exe).ok()?;
|
|
114
|
+
let mtime = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?.as_nanos();
|
|
115
|
+
let compiler = format!("{}:{}:{}:{}", exe.display(), meta.len(), mtime, env!("CARGO_PKG_VERSION"));
|
|
116
|
+
let root = match std::env::var_os("PLUM_CACHE_DIR").filter(|v| !v.is_empty()) {
|
|
117
|
+
Some(d) => PathBuf::from(d),
|
|
118
|
+
None => exe.parent()?.join("plum-cache"),
|
|
119
|
+
};
|
|
120
|
+
let stem = exe.file_stem()?.to_string_lossy().to_string();
|
|
121
|
+
let dir = root.join(format!("{stem}-{}", hex(hashOf(&compiler))));
|
|
122
|
+
if !dir.is_dir() {
|
|
123
|
+
pruneOlder(&root, &stem, &dir);
|
|
124
|
+
}
|
|
125
|
+
Some(DiskCache { dir, compiler })
|
|
126
|
+
})
|
|
127
|
+
.as_ref()
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
fn entryPath(&self, text: &str) -> PathBuf {
|
|
131
|
+
self.dir.join(format!("{}-{}.ast", hex(hashOf(text)), text.len()))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// The parse of `text` this cache holds, if any.
|
|
135
|
+
pub fn read(&self, text: &str) -> Option<Source> {
|
|
136
|
+
let bytes = std::fs::read(self.entryPath(text)).ok()?;
|
|
137
|
+
let body = bytes.strip_prefix(MAGIC)?;
|
|
138
|
+
let entry: Entry = postcard::from_bytes(body).ok()?;
|
|
139
|
+
(entry.compiler == self.compiler && entry.text == text).then_some(entry.source)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/// Keeps `source` as the parse of `text`. Failures are ignored: the cache is only a cache.
|
|
143
|
+
pub fn write(&self, text: &str, source: &Source) {
|
|
144
|
+
#[derive(serde::Serialize)]
|
|
145
|
+
struct EntryRef<'a> {
|
|
146
|
+
compiler: &'a str,
|
|
147
|
+
text: &'a str,
|
|
148
|
+
source: &'a Source,
|
|
149
|
+
}
|
|
150
|
+
let Ok(body) = postcard::to_stdvec(&EntryRef { compiler: &self.compiler, text, source }) else { return };
|
|
151
|
+
if std::fs::create_dir_all(&self.dir).is_err() {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
let path = self.entryPath(text);
|
|
155
|
+
static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
|
156
|
+
let tmp = path.with_extension(format!("{}.{}.tmp", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
|
|
157
|
+
let mut bytes = Vec::with_capacity(MAGIC.len() + body.len());
|
|
158
|
+
bytes.extend_from_slice(MAGIC);
|
|
159
|
+
bytes.extend_from_slice(&body);
|
|
160
|
+
if std::fs::write(&tmp, &bytes).is_err() || std::fs::rename(&tmp, &path).is_err() {
|
|
161
|
+
let _ = std::fs::remove_file(&tmp);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/// Removes the folders of `stem`'s earlier builds under `root` (all but `keep`).
|
|
167
|
+
pub fn pruneOlder(root: &Path, stem: &str, keep: &Path) {
|
|
168
|
+
let Ok(entries) = std::fs::read_dir(root) else { return };
|
|
169
|
+
let prefix = format!("{stem}-");
|
|
170
|
+
for e in entries.flatten() {
|
|
171
|
+
let p = e.path();
|
|
172
|
+
let name = e.file_name().to_string_lossy().to_string();
|
|
173
|
+
let rest = name.strip_prefix(&prefix);
|
|
174
|
+
// `<stem>-<16 hex digits>`: another executable whose name starts with `stem-` is not ours.
|
|
175
|
+
if p != keep && rest.is_some_and(|r| r.len() == 16 && r.bytes().all(|b| b.is_ascii_hexdigit())) && p.is_dir() {
|
|
176
|
+
let _ = std::fs::remove_dir_all(&p);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/// The parse of `text` (the file at canonical `path`): from memory, else from `disk`, else
|
|
182
|
+
/// `parse()`, whose success is kept in both. A cached `Source` comes back renumbered and
|
|
183
|
+
/// stamped with `display` (what a fresh parse stamps).
|
|
184
|
+
pub fn parse<E>(path: &Path, text: &str, display: &str, disk: Option<&DiskCache>, parse: impl FnOnce() -> Result<Source, E>) -> Result<Source, E> {
|
|
185
|
+
let useMemory = memoryOn();
|
|
186
|
+
let disk = disk.filter(|_| diskOn());
|
|
187
|
+
if useMemory {
|
|
188
|
+
let m = memory().lock().unwrap_or_else(|e| e.into_inner());
|
|
189
|
+
if let Some((t, src)) = m.get(path) {
|
|
190
|
+
if t == text {
|
|
191
|
+
return Ok(fresh(src.clone(), display));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
let found = disk.and_then(|d| d.read(text));
|
|
196
|
+
let (src, fromDisk) = match found {
|
|
197
|
+
Some(src) => (src, true),
|
|
198
|
+
None => (parse()?, false),
|
|
199
|
+
};
|
|
200
|
+
if let (Some(d), false) = (disk, fromDisk) {
|
|
201
|
+
d.write(text, &src);
|
|
202
|
+
}
|
|
203
|
+
if useMemory {
|
|
204
|
+
memory().lock().unwrap_or_else(|e| e.into_inner()).insert(path.to_path_buf(), (text.to_string(), src.clone()));
|
|
205
|
+
}
|
|
206
|
+
Ok(if fromDisk { fresh(src, display) } else { src })
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
fn fresh(mut src: Source, display: &str) -> Source {
|
|
210
|
+
crate::ast::renumberIds(&mut src);
|
|
211
|
+
src.stampFile(display);
|
|
212
|
+
src
|
|
213
|
+
}
|
compiler/core/tests/core/main.rs
CHANGED
|
@@ -14,6 +14,7 @@ mod loader_test;
|
|
|
14
14
|
mod lower_test;
|
|
15
15
|
mod match_body_parse_test;
|
|
16
16
|
mod native_test;
|
|
17
|
+
mod parse_cache_test;
|
|
17
18
|
mod parser_test;
|
|
18
19
|
mod purity_test;
|
|
19
20
|
mod question_parse_test;
|
compiler/core/tests/core/parse_cache_test.rs
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
#![allow(non_snake_case)]
|
|
2
|
+
//! The parse cache (`plum_core::parse_cache`): an entry is used only for the very text and
|
|
3
|
+
//! compiler it was written for, a partial or corrupt entry is a miss, and a program loaded
|
|
4
|
+
//! again after an import changed sees the change.
|
|
5
|
+
use plum_core::ast::Source;
|
|
6
|
+
use plum_core::parse_cache::DiskCache;
|
|
7
|
+
use plum_core::{loadAndMergeDiag, AstParser};
|
|
8
|
+
use tempfile::TempDir;
|
|
9
|
+
|
|
10
|
+
fn parsed(text: &str) -> Source {
|
|
11
|
+
let mut p = tree_sitter::Parser::new();
|
|
12
|
+
p.set_language(&tree_sitter_plum::LANGUAGE.into()).unwrap();
|
|
13
|
+
let tree = p.parse(text, None).unwrap();
|
|
14
|
+
AstParser::new(text).parseSourceRaw(tree.root_node())
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/// `src` printed with every node id left out (ids are the one thing a cached parse renumbers).
|
|
18
|
+
fn shape(src: &Source) -> String {
|
|
19
|
+
let text = format!("{src:?}");
|
|
20
|
+
let mut out = String::with_capacity(text.len());
|
|
21
|
+
let mut rest = text.as_str();
|
|
22
|
+
while let Some(at) = rest.find("NodeId(") {
|
|
23
|
+
out.push_str(&rest[..at]);
|
|
24
|
+
let after = &rest[at + "NodeId(".len()..];
|
|
25
|
+
rest = &after[after.find(')').map_or(0, |k| k + 1)..];
|
|
26
|
+
}
|
|
27
|
+
out.push_str(rest);
|
|
28
|
+
out
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fn cache(dir: &TempDir, compiler: &str) -> DiskCache {
|
|
32
|
+
DiskCache { dir: dir.path().join("c"), compiler: compiler.to_string() }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
fn repoRoot() -> std::path::PathBuf {
|
|
36
|
+
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap().to_path_buf()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Every std file read back from the disk is the parse it was written as.
|
|
40
|
+
#[test]
|
|
41
|
+
fn everyStdFileReadsBackAsItsParse() {
|
|
42
|
+
let dir = TempDir::new().unwrap();
|
|
43
|
+
let c = cache(&dir, "test");
|
|
44
|
+
let mut files = Vec::new();
|
|
45
|
+
let mut stack = vec![repoRoot().join("std")];
|
|
46
|
+
while let Some(d) = stack.pop() {
|
|
47
|
+
for e in std::fs::read_dir(d).unwrap().flatten() {
|
|
48
|
+
let p = e.path();
|
|
49
|
+
if p.is_dir() {
|
|
50
|
+
stack.push(p);
|
|
51
|
+
} else if p.extension().is_some_and(|x| x == "plum") {
|
|
52
|
+
files.push(p);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
assert!(files.len() > 20, "{} std files", files.len());
|
|
57
|
+
for f in files {
|
|
58
|
+
let text = std::fs::read_to_string(&f).unwrap();
|
|
59
|
+
let src = parsed(&text);
|
|
60
|
+
c.write(&text, &src);
|
|
61
|
+
let back = c.read(&text).unwrap_or_else(|| panic!("{}: no entry", f.display()));
|
|
62
|
+
assert_eq!(shape(&back), shape(&src), "{}", f.display());
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
#[test]
|
|
67
|
+
fn anEntryIsOnlyForItsOwnCompilerAndText() {
|
|
68
|
+
let dir = TempDir::new().unwrap();
|
|
69
|
+
let text = "module m\n\nprimitive M =\n fun f(u: Unit) -> Unit =\n u\n";
|
|
70
|
+
cache(&dir, "one").write(text, &parsed(text));
|
|
71
|
+
assert!(cache(&dir, "one").read(text).is_some());
|
|
72
|
+
assert!(cache(&dir, "two").read(text).is_none(), "another compiler's entry was read");
|
|
73
|
+
let other = text.replace("u\n", "{ u }\n");
|
|
74
|
+
assert!(cache(&dir, "one").read(&other).is_none());
|
|
75
|
+
// Another text under this text's file name (a hash collision): a miss, not its parse.
|
|
76
|
+
let files: Vec<_> = std::fs::read_dir(dir.path().join("c")).unwrap().flatten().map(|e| e.path()).collect();
|
|
77
|
+
assert_eq!(files.len(), 1);
|
|
78
|
+
let same_len = text.replace("fun f", "fun g");
|
|
79
|
+
let c = cache(&dir, "one");
|
|
80
|
+
c.write(&same_len, &parsed(&same_len));
|
|
81
|
+
let theirs: Vec<_> = std::fs::read_dir(dir.path().join("c")).unwrap().flatten().map(|e| e.path()).filter(|p| p != &files[0]).collect();
|
|
82
|
+
std::fs::copy(&theirs[0], &files[0]).unwrap();
|
|
83
|
+
assert!(c.read(text).is_none(), "an entry for another text was read");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
#[test]
|
|
87
|
+
fn aPartialOrCorruptEntryIsAMiss() {
|
|
88
|
+
let dir = TempDir::new().unwrap();
|
|
89
|
+
let c = cache(&dir, "test");
|
|
90
|
+
let text = "module m\n\nprimitive M =\n fun f(u: Unit) -> Unit =\n u\n";
|
|
91
|
+
c.write(text, &parsed(text));
|
|
92
|
+
let file = std::fs::read_dir(dir.path().join("c")).unwrap().flatten().next().unwrap().path();
|
|
93
|
+
let whole = std::fs::read(&file).unwrap();
|
|
94
|
+
for cut in [0, 3, 8, 20, whole.len() / 2, whole.len() - 1] {
|
|
95
|
+
std::fs::write(&file, &whole[..cut]).unwrap();
|
|
96
|
+
assert!(c.read(text).is_none(), "cut at {cut}");
|
|
97
|
+
}
|
|
98
|
+
let mut flipped = whole.clone();
|
|
99
|
+
flipped[0] ^= 0xff;
|
|
100
|
+
std::fs::write(&file, &flipped).unwrap();
|
|
101
|
+
assert!(c.read(text).is_none(), "another magic");
|
|
102
|
+
let garbage: Vec<u8> = (0..whole.len()).map(|i| (i * 7919 % 251) as u8).collect();
|
|
103
|
+
let mut bad = b"PLUMAST\x01".to_vec();
|
|
104
|
+
bad.extend_from_slice(&garbage);
|
|
105
|
+
std::fs::write(&file, &bad).unwrap();
|
|
106
|
+
assert!(c.read(text).is_none(), "garbage after the magic");
|
|
107
|
+
std::fs::write(&file, &whole).unwrap();
|
|
108
|
+
assert!(c.read(text).is_some());
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/// Writers and readers side by side: a read is a miss or the whole parse, never a part.
|
|
112
|
+
#[test]
|
|
113
|
+
fn entriesWrittenSideBySideAreWholeOrMissing() {
|
|
114
|
+
let dir = TempDir::new().unwrap();
|
|
115
|
+
let text = std::fs::read_to_string(repoRoot().join("std/collections/Map.plum")).unwrap();
|
|
116
|
+
let src = parsed(&text);
|
|
117
|
+
let want = shape(&src);
|
|
118
|
+
std::thread::scope(|sc| {
|
|
119
|
+
for _ in 0..8 {
|
|
120
|
+
sc.spawn(|| {
|
|
121
|
+
let c = cache(&dir, "test");
|
|
122
|
+
for _ in 0..10 {
|
|
123
|
+
c.write(&text, &src);
|
|
124
|
+
if let Some(back) = c.read(&text) {
|
|
125
|
+
assert_eq!(shape(&back), want);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
assert!(cache(&dir, "test").read(&text).is_some());
|
|
132
|
+
let left: Vec<_> = std::fs::read_dir(dir.path().join("c")).unwrap().flatten().map(|e| e.file_name()).collect();
|
|
133
|
+
assert_eq!(left.len(), 1, "temporary files left: {left:?}");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
#[test]
|
|
137
|
+
fn olderBuildsOfTheSameProgramArePruned() {
|
|
138
|
+
let dir = TempDir::new().unwrap();
|
|
139
|
+
for name in ["plum-0123456789abcdef", "plum-fedcba9876543210", "plum-lsp-0123456789abcdef", "other-0123456789abcdef", "plum-notahash"] {
|
|
140
|
+
std::fs::create_dir_all(dir.path().join(name)).unwrap();
|
|
141
|
+
}
|
|
142
|
+
let keep = dir.path().join("plum-fedcba9876543210");
|
|
143
|
+
plum_core::parse_cache::pruneOlder(dir.path(), "plum", &keep);
|
|
144
|
+
let mut left: Vec<String> = std::fs::read_dir(dir.path()).unwrap().flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect();
|
|
145
|
+
left.sort();
|
|
146
|
+
assert_eq!(left, ["other-0123456789abcdef", "plum-fedcba9876543210", "plum-lsp-0123456789abcdef", "plum-notahash"]);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
fn write(dir: &std::path::Path, name: &str, text: &str) -> std::path::PathBuf {
|
|
150
|
+
let p = dir.join(format!("{name}.plum"));
|
|
151
|
+
std::fs::write(&p, text).unwrap();
|
|
152
|
+
p
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
fn names(src: &Source) -> Vec<String> {
|
|
156
|
+
let mut v: Vec<String> = src.items.iter().filter_map(|i| match i {
|
|
157
|
+
plum_core::ast::Item::Fn(f) => Some(format!("{}.{}", f.type_param.clone().unwrap_or_default(), f.name)),
|
|
158
|
+
_ => None,
|
|
159
|
+
}).collect();
|
|
160
|
+
v.sort();
|
|
161
|
+
v
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/// A program loaded again after the file it imports, or one that file imports, changed sees
|
|
165
|
+
/// the change (the caches are on: the loads before warmed them).
|
|
166
|
+
#[test]
|
|
167
|
+
fn aLoadSeesItsEditedImportsDirectAndTransitive() {
|
|
168
|
+
let dir = TempDir::new().unwrap();
|
|
169
|
+
let lib = dir.path().join("libs");
|
|
170
|
+
std::fs::create_dir_all(&lib).unwrap();
|
|
171
|
+
write(&lib, "c", "module fixtures\n\nprimitive C =\n fun one(u: Unit) -> Unit =\n u\n");
|
|
172
|
+
write(&lib, "b", "module fixtures\n\nimport c\n\nprimitive B =\n fun bFn(u: Unit) -> Unit =\n C.one(u)\n");
|
|
173
|
+
let entry = write(&lib, "a", "module fixtures\n\nimport b\n\nprimitive Main[App] =\n fun main(u: Unit) -> Unit =\n B.bFn(u)\n");
|
|
174
|
+
let first = loadAndMergeDiag(&entry, &lib).expect("load");
|
|
175
|
+
assert!(names(&first).contains(&"C.one".to_string()));
|
|
176
|
+
let again = loadAndMergeDiag(&entry, &lib).expect("load again");
|
|
177
|
+
assert_eq!(names(&again), names(&first));
|
|
178
|
+
// The transitive import changes (the same length, so only its bytes tell).
|
|
179
|
+
write(&lib, "c", "module fixtures\n\nprimitive C =\n fun two(u: Unit) -> Unit =\n u\n");
|
|
180
|
+
write(&lib, "b", "module fixtures\n\nimport c\n\nprimitive B =\n fun bFn(u: Unit) -> Unit =\n C.two(u)\n");
|
|
181
|
+
let edited = loadAndMergeDiag(&entry, &lib).expect("load after the edit");
|
|
182
|
+
assert!(names(&edited).contains(&"C.two".to_string()) && !names(&edited).contains(&"C.one".to_string()), "{:?}", names(&edited));
|
|
183
|
+
// A syntax error in an import is reported, not hidden by its cached parse.
|
|
184
|
+
write(&lib, "c", "module fixtures\n\nprimitive C =\n fun two(u: Unit) -> Unit =\n u +\n");
|
|
185
|
+
assert!(loadAndMergeDiag(&entry, &lib).is_err());
|
|
186
|
+
write(&lib, "c", "module fixtures\n\nprimitive C =\n fun two(u: Unit) -> Unit =\n u\n");
|
|
187
|
+
assert!(loadAndMergeDiag(&entry, &lib).is_ok());
|
|
188
|
+
// Two loads of one program have no node id in common past the parse: each is renumbered.
|
|
189
|
+
let x = loadAndMergeDiag(&entry, &lib).unwrap();
|
|
190
|
+
assert!(plum_core::ast::duplicateId(&x).is_none());
|
|
191
|
+
}
|
compiler/lsp/src/main.rs
CHANGED
|
@@ -522,6 +522,9 @@ fn recordHover(text: &str, line0: usize, col: usize) -> Option<String> {
|
|
|
522
522
|
|
|
523
523
|
#[tokio::main]
|
|
524
524
|
async fn main() {
|
|
525
|
+
// The parse cache in memory only: every check of an open file reuses the parses of the
|
|
526
|
+
// files it imports, and an edited buffer's text is a different entry.
|
|
527
|
+
plum_core::parse_cache::memoryOnly();
|
|
525
528
|
// `--lib-path` mirrors `plum-cli`'s own required flag (see
|
|
526
529
|
// plum-cli/src/main.rs's `Command::Run`/`Compile`) — the checker has no
|
|
527
530
|
// built-in default location for the std lib. It's the directory
|
docs/backlog.md
CHANGED
|
@@ -24,6 +24,7 @@ The retained scene tree was replaced by master's screen view in functional form:
|
|
|
24
24
|
## Performance
|
|
25
25
|
|
|
26
26
|
- **Compile time is worse than on 2026-11-10 morning**: 1.32x CPU for Orb Run (538 to 708 ms), 1.40x Balloon Pop, 2.0x for a small program, even after a 30% speed-up of the passes. Causes measured or likely: programs reach more std (+17% items for Orb Run), the in-place pass is now its own pass with its own re-check, the loader's threads add CPU. The program is still checked about 7 times per compile. Re-checking only changed functions was tried and dropped: type info is keyed by node id and instantiation numbering depends on whole-program order, so the output would change. Needs stable ids first. Pruning std before the first check fails because loop and `?` lowering add calls the raw program does not name.
|
|
27
|
+
- **Only the parse is cached per file** (`parse_cache`, 2026-11-16). Checking a module once and reusing it in every program that imports it, as Roc does, needs a checker that works module by module. Today's is whole-program. The loader merges every file into one program before anything after the parse. `resolveModules` renames functions that several files of the program define. `shadowStdTypes` rewrites and re-parses std's text when the importer declares a std type's name. Generic bodies are checked once per instantiation, starting from call sites anywhere in the program (with the importer's types). Trait-object calls reach the importer's implementers. Type info is keyed by node ids numbered over the merged program. Measured with a debug build on Map's tests: load 90 ms (parse 30 to 40 of it), first check 130 ms, then 5 re-checks of about 48 ms each and the passes. The front end is about 15% of a `plum test` file; a `plum check` file is about half parse and half check.
|
|
27
28
|
- **`Map` reuse stops as soon as any map in the program is shared.** A uniquely owned map is now updated in its own cells (the `map` workload went from 479 to 281 ms; the old hash table took about 200), and `Int`, `Byte` and `Float.compare` are native and inlined. But field uniqueness is decided per type over the whole program, so one kept old version of a `Map` anywhere turns deep reuse off for every `Map`: Orb Run gets none. Reuse alongside sharing needs a per-value deep-uniqueness analysis. Also open: `Map.get` allocates an `Option` on a hit (fusion treats `Map.get` as an impure producer).
|
|
28
29
|
- **Closure calls are untyped.** A closure is held as `anyref`: each call does two casts and an indirect call, and building one allocates two objects. A typed closure struct per signature with `call_ref` would fix it. Indirect evidence: `cons_rec` (1.94 s) and `cons` without fusion (1.0 s) did not move.
|
|
29
30
|
- **A value struct inside an enum payload is boxed twice** (`Some(Pos)` allocates two objects). No measurement yet.
|
docs/tools.md
CHANGED
|
@@ -51,6 +51,9 @@ Folders are tested one file per process, as many at once as there are cores (`PL
|
|
|
51
51
|
| `--no-fusion` | Turn off the optimisations described in [Performance](performance.md) |
|
|
52
52
|
| `--no-fbip` | Turn off in-place updates: every spread copies and no cell is reused |
|
|
53
53
|
| `--explain-fusion` | Print each optimisation decision and how each struct is stored |
|
|
54
|
+
| `--no-cache` | Parse every file again: don't read or write the parse cache (any command) |
|
|
55
|
+
|
|
56
|
+
**The parse cache.** Each file a program imports is parsed once and reused: in memory by every program of one run (`plum check` checks its files side by side, sharing it) and on disk across runs, in `plum-cache/` beside the `plum` executable (`target/debug/plum-cache/` for a build from source). An entry is the file's exact text, its parse and the build of `plum` that wrote it, so an edited file, or a rebuilt `plum`, never reads an old one; a partial or damaged entry is ignored, and a new build of `plum` removes the folder of its earlier one. Only the parse is cached: resolving names and type checking run over the whole program each time, as do the optimisations and code generation, so the output is the same with the cache or without it. The language server keeps the cache in memory only.
|
|
54
57
|
|
|
55
58
|
**Environment variables:**
|
|
56
59
|
|
|
@@ -60,6 +63,8 @@ Folders are tested one file per process, as many at once as there are cores (`PL
|
|
|
60
63
|
| `PLUM_TEST_TIMEOUT=SECONDS` | The default of `plum test --timeout` |
|
|
61
64
|
| `PLUM_DUMP_WASM=out.wasm` | `plum test`: also write the compiled test module to `out.wasm` |
|
|
62
65
|
| `PLUM_TIMINGS=1` | Print how long each compiler pass takes |
|
|
66
|
+
| `PLUM_NO_CACHE=1` | The same as `--no-cache` |
|
|
67
|
+
| `PLUM_CACHE_DIR=dir` | Keep the parse cache in `dir` instead of beside the executable |
|
|
63
68
|
| `PLUM_NO_WASM_OPT=1` | Skip the passes over the finished wasm (dropping redundant casts, inlining small functions, removing unreachable ones), to compare a program with and without them. Set to any value, it turns them off |
|
|
64
69
|
|
|
65
70
|
A program that crashes prints one line, such as `crash: division by zero in div (called from main)`, or the message and place of a `crash`.
|