plum

#treesitter#compiler#wasm

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

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


9167b5f — Peter John 2026-11-09T21:30:17+05:30
Driver: prune unreachable imported code before the passes; reuse the check's pre-union program; PLUM_TIMINGS
compiler/checker/src/lib.rs CHANGED
@@ -120,6 +120,14 @@ pub fn checkProgram(source: &ast::Source) -> (CheckResult<()>, TypedInfo) {
120
120
  checkSourceFull(source)
121
121
  }
122
122
 
123
+ /// `checkProgram`, and the program it checked before union lowering (own generics applied,
124
+ /// trait defaults expanded, `for` loops lowered): what the driver's passes rewrite.
125
+ pub fn checkProgramPre(source: &ast::Source) -> (CheckResult<()>, TypedInfo, Option<ast::Source>) {
126
+ let mut pre = None;
127
+ let (r, info) = checkSourceFullPre(source, &mut pre);
128
+ (r, info, pre)
129
+ }
130
+
123
131
  /// One check of exactly `source` (no own-generics application, no loop lowering first); what
124
132
  /// the driver uses to re-check a rewritten program.
125
133
  pub fn checkOnce(source: &ast::Source) -> (CheckResult<()>, TypedInfo) {
compiler/checker/src/program.rs CHANGED
@@ -42,40 +42,47 @@ pub fn closureHints(lowered: &ast::Source, info: &TypedInfo) -> plum_core::closu
42
42
  }
43
43
 
44
44
  pub(crate) fn checkSourceFull(source: &ast::Source) -> (CheckResult<()>, TypedInfo) {
45
+ checkSourceFullPre(source, &mut None)
46
+ }
47
+
48
+ /// `checkSourceFull`, which also leaves in `pre` the program it checked before union lowering:
49
+ /// trait defaults expanded, own generics applied and `for` loops lowered, numbered.
50
+ pub(crate) fn checkSourceFullPre(source: &ast::Source, pre: &mut Option<ast::Source>) -> (CheckResult<()>, TypedInfo) {
45
51
  // Type tables are keyed by node id: a program straight from a pass that built nodes
46
52
  // without numbering them (a test's rewrite) is numbered, and checked, as a copy.
47
53
  if ast::hasUnnumbered(source) {
48
54
  let mut numbered = source.clone();
49
55
  ast::numberIds(&mut numbered);
50
56
  let numbered = std::rc::Rc::new(numbered);
51
- let (result, mut info) = checkSourceFull(&numbered);
57
+ let (result, mut info) = checkSourceFullPre(&numbered, pre);
52
58
  if info.lowered.is_none() {
53
59
  info.lowered = Some(numbered);
54
60
  }
55
61
  return (result, info);
56
62
  }
57
- if let Some(mut expanded) = plum_core::trait_defaults::expandDefaults(source) {
63
+ if let Some(mut expanded) = plum_core::timing::time("expand defaults", || plum_core::trait_defaults::expandDefaults(source)) {
58
64
  // Each implementer gets its own copy of the trait defaults it inherits.
59
65
  ast::numberIds(&mut expanded);
60
66
  let expanded = std::rc::Rc::new(expanded);
61
- let (result, mut info) = checkSourceFull(&expanded);
67
+ let (result, mut info) = checkSourceFullPre(&expanded, pre);
62
68
  if info.lowered.is_none() {
63
69
  info.lowered = Some(expanded);
64
70
  }
65
71
  return (result, info);
66
72
  }
67
- if let Some(mut applied) = applyOwnGenerics(source) {
73
+ if let Some(mut applied) = plum_core::timing::time("own generics", || applyOwnGenerics(source)) {
68
74
  // Check (and let codegen compile) the copy with bare own-generic names applied.
69
75
  ast::numberIds(&mut applied);
70
76
  let applied = std::rc::Rc::new(applied);
71
- let (result, mut info) = checkSourceFull(&applied);
77
+ let (result, mut info) = checkSourceFullPre(&applied, pre);
72
78
  if info.lowered.is_none() {
73
79
  info.lowered = Some(applied);
74
80
  }
75
81
  return (result, info);
76
82
  }
77
83
  if !source.formLoops {
78
- return checkSourceOnce(source);
84
+ *pre = Some(source.clone());
85
+ return plum_core::timing::time("check once", || checkSourceOnce(source));
79
86
  }
80
87
  // `for` loops are lowered by the checker, because how a loop iterates depends
81
88
  // on the type of its source. Pass 1 checks the program and lowers each loop as
@@ -83,10 +90,11 @@ pub(crate) fn checkSourceFull(source: &ast::Source) -> (CheckResult<()>, TypedIn
83
90
  // which pass 2 checks again from scratch (types are recorded per expression
84
91
  // node id) and codegen compiles (`TypedInfo::lowered`).
85
92
  plum_core::forms::begin(source);
86
- let _ = checkSourceOnce(source);
93
+ let _ = plum_core::timing::time("check once (loops)", || checkSourceOnce(source));
87
- let mut lowered = plum_core::forms::finish(source);
94
+ let mut lowered = plum_core::timing::time("forms finish", || plum_core::forms::finish(source));
88
95
  ast::numberIds(&mut lowered);
96
+ *pre = Some(lowered.clone());
89
- let (result, mut info) = checkSourceOnce(&lowered);
97
+ let (result, mut info) = plum_core::timing::time("check once", || checkSourceOnce(&lowered));
90
98
  if info.lowered.is_none() {
91
99
  // `lowered` itself was checked.
92
100
  info.lowered = Some(std::rc::Rc::new(lowered));
@@ -144,6 +152,7 @@ pub(crate) fn checkSourceOnce(source: &ast::Source) -> (CheckResult<()>, TypedIn
144
152
  "two nodes of the checked program share {:?}",
145
153
  ast::duplicateId(source)
146
154
  );
155
+ plum_core::timing::note(|| plum_core::timing::size(source));
147
156
  resetCheck();
148
157
  withCheck(|s| {
149
158
  *s.record.borrow_mut() = Some(HashMap::new());
compiler/cli/src/program.rs CHANGED
@@ -56,13 +56,13 @@ pub fn tryCompileProgram(
56
56
  fusion: plum_driver::PassOptions,
57
57
  ) -> std::result::Result<Program, Failure> {
58
58
  let render = |e: &[plum_core::Diagnostic], codegen| Failure { codegen, text: crate::renderAll(e, file) };
59
- let mut ast = plum_core::loader::loadAndMergeDiag(file, lib_path).map_err(|e| render(&e, false))?;
59
+ let mut ast = plum_core::timing::time("load", || plum_core::loader::loadAndMergeDiag(file, lib_path)).map_err(|e| render(&e, false))?;
60
60
  // A `Result` main is compiled as the wrapper that runs it (a lowering of the program);
61
61
  // the program as written is kept to report errors in the user's own `main`.
62
62
  let written = plum_core::main_result::resultMainReturn(&ast).is_some().then(|| ast.clone());
63
63
  let resultMain = plum_core::main_result::lowerResultMain(&mut ast);
64
64
  let options = plum_wasm_codegen::CompileOptions { tests: false, passes: fusion };
65
- let out = plum_wasm_codegen::compile(&ast, &options).map_err(|mut ds| {
65
+ let out = plum_core::timing::time("compile", || plum_wasm_codegen::compile(&ast, &options)).map_err(|mut ds| {
66
66
  if let Some(written) = &written {
67
67
  // Errors in the user's own `main` are reported under its name, not the renamed one.
68
68
  let own = plum_driver::PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
compiler/core/src/lib.rs CHANGED
@@ -24,6 +24,7 @@ pub mod lower;
24
24
  pub mod main_result;
25
25
  pub mod modules;
26
26
  pub mod parser;
27
+ pub mod prune;
27
28
  pub mod purity;
28
29
  pub mod question;
29
30
  pub mod rename;
@@ -34,6 +35,7 @@ pub mod spread_paths;
34
35
  pub mod tail;
35
36
  pub mod trait_defaults;
36
37
  pub mod tests_lower;
38
+ pub mod timing;
37
39
  pub mod trmc;
38
40
  pub mod uniqueness;
39
41
  pub mod visit;
compiler/core/src/prune.rs ADDED
@@ -0,0 +1,166 @@
1
+ //! Drops the imported fns, types and constants a checked program can never reach from its
2
+ //! own fns and entry points (`main`, `export fun`, lowered tests, the game entries), before the
3
+ //! optimisation passes and codegen. Every non-generic fn is otherwise a root of the checker's
4
+ //! instantiations and gets compiled, so an imported module's helpers (std's test fixtures,
5
+ //! a `Str` method nothing calls) cost check time, pass time and wasm size in every program.
6
+ //!
7
+ //! The reachability is by name, and conservative: every name an item's AST mentions (fn and
8
+ //! method names, type and variant names, field names, even string literals) is a reference,
9
+ //! whatever its receiver. A reached type keeps each of its methods whose name is referenced
10
+ //! anywhere reached, or which the compiler calls without a call site (`IMPLICIT`). A reached
11
+ //! type reaches the traits it implements, and a reached trait references every method name it
12
+ //! declares, so a reached implementer keeps its whole trait. The caller re-checks the pruned
13
+ //! program and drops it if that fails (`plum_driver`), so a missed name can cost the
14
+ //! saving but not the program.
15
+ use crate::ast::*;
16
+ use std::collections::{HashMap, HashSet};
17
+ use std::fmt::Write;
18
+
19
+ /// Method names the compiler calls with no call site in the source: interpolation, a
20
+ /// constructor's `init`, hashing and equality, the operators, the frame entry.
21
+ const IMPLICIT: [&str; 19] = [
22
+ "concat",
23
+ "toStr", "init", "equals", "hash", "compare", "drop", "add", "sub", "mul", "div", "neg", "eq", "lt", "le", "gt",
24
+ "ge", "update", "draw",
25
+ ];
26
+
27
+ /// Built-in types the checker and codegen name themselves (literals, `?`, `[..]`, `k => v`).
28
+ const BUILTIN_TYPES: [&str; 12] = ["Int", "Float", "Unit", "Byte", "Bool", "Str", "Io", "Array", "Option", "Result", "List", "Pair"];
29
+
30
+ /// Collects every string a value's `Debug` output quotes: the names in an AST node, without
31
+ /// building the text.
32
+ struct Quoted<'a> {
33
+ out: &'a mut HashSet<String>,
34
+ cur: Option<String>,
35
+ escaped: bool,
36
+ }
37
+
38
+ impl Write for Quoted<'_> {
39
+ fn write_str(&mut self, s: &str) -> std::fmt::Result {
40
+ for c in s.chars() {
41
+ match &mut self.cur {
42
+ None => {
43
+ if c == '"' {
44
+ self.cur = Some(String::new());
45
+ }
46
+ }
47
+ Some(cur) => {
48
+ if self.escaped {
49
+ self.escaped = false;
50
+ cur.push(c);
51
+ } else if c == '\\' {
52
+ self.escaped = true;
53
+ } else if c == '"' {
54
+ let done = std::mem::take(cur);
55
+ self.cur = None;
56
+ if !done.is_empty() {
57
+ self.out.insert(done);
58
+ }
59
+ } else {
60
+ cur.push(c);
61
+ }
62
+ }
63
+ }
64
+ }
65
+ Ok(())
66
+ }
67
+ }
68
+
69
+ fn names(item: &impl std::fmt::Debug, out: &mut HashSet<String>) {
70
+ let mut q = Quoted { out, cur: None, escaped: false };
71
+ let _ = write!(q, "{item:?}");
72
+ }
73
+
74
+ /// A fn name without its generated suffix: `paint$dyn` is a copy of `paint`.
75
+ fn base(name: &str) -> &str {
76
+ name.split('$').next().unwrap_or(name)
77
+ }
78
+
79
+ /// An entry point, or a fn of the program's own file (`file`): only what the program imports
80
+ /// is pruned, so its own code compiles as written, used or not.
81
+ fn isRoot(f: &Fn, file: &str) -> bool {
82
+ (!file.is_empty() && f.file == file)
83
+ || (f.type_param.is_none() && (f.name == "main" || f.name == crate::game_entry::GAME_UPDATE || f.name == crate::game_entry::GAME_DRAW))
84
+ || f.is_export
85
+ || f.is_test
86
+ }
87
+
88
+ /// Removes what `src` cannot reach from its entry points; returns how many items went
89
+ /// (none when it has no entry point).
90
+ /// `Test` items go too: a build strips them, and `plum test` has lowered them to fns.
91
+ pub fn pruneUnreachable(src: &mut Source) -> usize {
92
+ // A program with no entry point (a library checked on its own) keeps everything.
93
+ if !src.items.iter().any(|i| matches!(i, Item::Fn(f) if isRoot(f, &src.file))) {
94
+ return 0;
95
+ }
96
+ let file = src.file.clone();
97
+ let types: HashSet<&str> = src
98
+ .items
99
+ .iter()
100
+ .filter_map(|i| match i {
101
+ Item::Enum(e) => Some(e.name.as_str()),
102
+ Item::Trait(t) => Some(t.name.as_str()),
103
+ _ => None,
104
+ })
105
+ .collect();
106
+ let traits: HashSet<&str> = src.items.iter().filter_map(|i| if let Item::Trait(t) = i { Some(t.name.as_str()) } else { None }).collect();
107
+ // A variant's name reaches its enum (`Cut` is a `Transition`).
108
+ let mut ofVariant: HashMap<&str, Vec<&str>> = HashMap::new();
109
+ for item in &src.items {
110
+ if let Item::Enum(e) = item {
111
+ for v in &e.variants {
112
+ ofVariant.entry(v.name.as_str()).or_default().push(e.name.as_str());
113
+ }
114
+ }
115
+ }
116
+ let mut refs: HashSet<String> = BUILTIN_TYPES.iter().chain(IMPLICIT.iter()).map(|s| s.to_string()).collect();
117
+ let mut kept = vec![false; src.items.len()];
118
+ let typeReached = |refs: &HashSet<String>, t: &str| {
119
+ !types.contains(t) || refs.contains(t)
120
+ };
121
+ loop {
122
+ let mut grew = false;
123
+ // Variant names reach their enums.
124
+ let viaVariants: Vec<String> = ofVariant
125
+ .iter()
126
+ .filter(|(v, _)| refs.contains(**v))
127
+ .flat_map(|(_, es)| es.iter().map(|e| e.to_string()))
128
+ .filter(|e| !refs.contains(e))
129
+ .collect();
130
+ for e in viaVariants {
131
+ refs.insert(e);
132
+ grew = true;
133
+ }
134
+ for (i, item) in src.items.iter().enumerate() {
135
+ if kept[i] {
136
+ continue;
137
+ }
138
+ let reached = match item {
139
+ Item::Fn(f) => {
140
+ isRoot(f, &file)
141
+ || match &f.type_param {
142
+ None => refs.contains(base(&f.name)),
143
+ Some(t) if traits.contains(t.as_str()) => refs.contains(t) && refs.contains(base(&f.name)),
144
+ Some(t) => typeReached(&refs, t) && refs.contains(base(&f.name)),
145
+ }
146
+ }
147
+ Item::Enum(e) => refs.contains(&e.name),
148
+ Item::Trait(t) => refs.contains(&t.name),
149
+ Item::Const(c) => refs.contains(&c.name) || c.name.rsplit(MEMBER_SEP).next().is_some_and(|n| refs.contains(n)),
150
+ Item::Test(_) => false,
151
+ };
152
+ if reached {
153
+ kept[i] = true;
154
+ grew = true;
155
+ names(item, &mut refs);
156
+ }
157
+ }
158
+ if !grew {
159
+ break;
160
+ }
161
+ }
162
+ let before = src.items.len();
163
+ let mut k = kept.into_iter();
164
+ src.items.retain(|_| k.next().unwrap_or(true));
165
+ before - src.items.len()
166
+ }
compiler/core/src/timing.rs ADDED
@@ -0,0 +1,47 @@
1
+ //! Per-phase compile timings on stderr, when `PLUM_TIMINGS` is set (`PLUM_TIMINGS=1 plum compile ..`).
2
+ //! Nested phases are indented under the phase that runs them.
3
+
4
+ use std::cell::Cell;
5
+ use std::sync::OnceLock;
6
+ use std::time::Instant;
7
+
8
+ fn enabled() -> bool {
9
+ static ON: OnceLock<bool> = OnceLock::new();
10
+ *ON.get_or_init(|| std::env::var_os("PLUM_TIMINGS").is_some())
11
+ }
12
+
13
+ thread_local! {
14
+ static DEPTH: Cell<usize> = const { Cell::new(0) };
15
+ }
16
+
17
+ /// Runs `f`, and with `PLUM_TIMINGS` set prints how long it took under `name`.
18
+ pub fn time<T>(name: &str, f: impl FnOnce() -> T) -> T {
19
+ if !enabled() {
20
+ return f();
21
+ }
22
+ let depth = DEPTH.with(|d| {
23
+ let v = d.get();
24
+ d.set(v + 1);
25
+ v
26
+ });
27
+ let start = Instant::now();
28
+ let out = f();
29
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
30
+ DEPTH.with(|d| d.set(depth));
31
+ eprintln!("time: {:indent$}{name} {ms:.1} ms", "", indent = depth * 2);
32
+ out
33
+ }
34
+
35
+ /// With `PLUM_TIMINGS` set, prints `what` (a size, a count) among the timings.
36
+ pub fn note(what: impl FnOnce() -> String) {
37
+ if enabled() {
38
+ let depth = DEPTH.with(|d| d.get());
39
+ eprintln!("time: {:indent$}- {}", "", what(), indent = depth * 2);
40
+ }
41
+ }
42
+
43
+ /// The size of a program, for `note`: its fns and the AST nodes in their bodies.
44
+ pub fn size(src: &crate::ast::Source) -> String {
45
+ let fns = src.items.iter().filter(|i| matches!(i, crate::ast::Item::Fn(_))).count();
46
+ format!("{} items, {} fns", src.items.len(), fns)
47
+ }
compiler/driver/src/lib.rs CHANGED
@@ -3,7 +3,7 @@
3
3
  //! share: a rewrite is adopted only if the rewritten program checks again.
4
4
  #![allow(non_snake_case)]
5
5
 
6
- use plum_checker::{checkOnce, checkProgram, TypedInfo};
6
+ use plum_checker::{checkOnce, checkProgramPre, TypedInfo};
7
7
  use plum_core::ast::Source;
8
8
  use plum_core::closure_spec::Hints;
9
9
  use plum_core::diag::Diagnostic;
@@ -82,17 +82,17 @@ pub fn fusionRun(copy: &mut Source, fbip: bool) -> (Vec<String>, Vec<Diagnostic>
82
82
  // here): their calls must not make production code copy.
83
83
  copy.items.retain(|i| !matches!(i, plum_core::ast::Item::Test(_)));
84
84
  let mut errors = Vec::new();
85
- let pure = plum_core::purity::pureFns(copy);
85
+ let pure = plum_core::timing::time("purity", || plum_core::purity::pureFns(copy));
86
- let mut notes = plum_core::simplify::simplify(copy, &pure);
86
+ let mut notes = plum_core::timing::time("simplify", || plum_core::simplify::simplify(copy, &pure));
87
- notes.extend(plum_core::drive::drive(copy, &pure));
87
+ notes.extend(plum_core::timing::time("drive", || plum_core::drive::drive(copy, &pure)));
88
88
  if fbip {
89
- let rep = plum_core::uniqueness::markUnique(copy);
89
+ let rep = plum_core::timing::time("uniqueness", || plum_core::uniqueness::markUnique(copy));
90
90
  notes.extend(rep.versions.iter().cloned());
91
91
  notes.extend(rep.proved.iter().map(|l| format!("unique spread at {l}")));
92
92
  notes.extend(rep.unproved.iter().map(|(l, why)| format!("uniqueness: not in place {l}: {why}")));
93
- errors = plum_core::fip::diagnostics(copy, &rep, &origins);
93
+ errors = plum_core::timing::time("fip", || plum_core::fip::diagnostics(copy, &rep, &origins));
94
94
  notes.retain(|n| !n.is_empty());
95
- notes.extend(plum_core::reuse::markReuse(copy));
95
+ notes.extend(plum_core::timing::time("reuse", || plum_core::reuse::markReuse(copy)));
96
96
  }
97
97
  notes.retain(|n| !n.is_empty());
98
98
  (notes, errors)
@@ -113,6 +113,15 @@ fn fusion(copy: &mut Source, env: &Env) -> bool {
113
113
  !notes.is_empty()
114
114
  }
115
115
 
116
+ /// Unreachable fns, types and constants out (see `plum_core::prune`).
117
+ fn prune(copy: &mut Source, env: &Env) -> bool {
118
+ let gone = plum_core::prune::pruneUnreachable(copy);
119
+ if env.explain && gone > 0 {
120
+ eprintln!("fusion: {gone} unreachable items dropped");
121
+ }
122
+ gone > 0
123
+ }
124
+
116
125
  /// Tail recursion modulo cons.
117
126
  fn trmc(copy: &mut Source, _: &Env) -> bool {
118
127
  !plum_core::trmc::rewrite(copy).is_empty()
@@ -120,7 +129,8 @@ fn trmc(copy: &mut Source, _: &Env) -> bool {
120
129
 
121
130
  /// The rewrite passes, in the order they run. Tail marks (flags set in place on the final
122
131
  /// program) run last and need no re-check.
123
- pub const PASSES: [Pass; 3] = [
132
+ pub const PASSES: [Pass; 4] = [
133
+ Pass { name: "dead code", target: Target::Pre, needsHints: false, enabled: |o| o.closureSpec || o.fusion || o.trmc, rewrite: prune },
124
134
  Pass { name: "closure specialisation", target: Target::Pre, needsHints: true, enabled: |o| o.closureSpec, rewrite: closureSpec },
125
135
  Pass { name: "fusion", target: Target::Pre, needsHints: true, enabled: |o| o.fusion, rewrite: fusion },
126
136
  Pass { name: "trmc", target: Target::Lowered, needsHints: false, enabled: |o| o.trmc, rewrite: trmc },
@@ -144,19 +154,27 @@ pub fn check(source: &Source, opts: &PassOptions) -> Result<TypedInfo, Vec<Diagn
144
154
 
145
155
  /// `check` with an explicit pass list.
146
156
  pub fn check_with(source: &Source, opts: &PassOptions, passes: &[Pass]) -> Result<TypedInfo, Vec<Diagnostic>> {
157
+ let (result, info, pre) = plum_core::timing::time("check", || checkProgramPre(source));
158
+ // The check lowered the program's loops already: reuse its pre-union program.
159
+ let pre = match pre {
160
+ Some(mut pre) => {
161
+ plum_core::trait_defaults::dropTraitBodies(&mut pre);
162
+ pre
163
+ }
147
- let (result, info) = checkProgram(source);
164
+ None => preUnionSource(source),
165
+ };
148
- let mut st = State { pre: preUnionSource(source), result, info, fip: Vec::new() };
166
+ let mut st = State { pre, result, info, fip: Vec::new() };
149
167
  if st.result.is_ok() {
150
168
  if opts.explain && !(opts.fusion && opts.fbip) && !plum_core::fip::origins(&st.pre).isEmpty() {
151
169
  eprintln!("fusion: fip fun is not enforced: it needs the uniqueness proof, which --no-fusion and --no-fbip switch off");
152
170
  }
153
171
  for pass in passes.iter().filter(|p| (p.enabled)(opts)) {
154
- runPass(pass, source, opts, &mut st);
172
+ plum_core::timing::time(pass.name, || runPass(pass, source, opts, &mut st));
155
173
  }
156
174
  }
157
175
  // Flags are set in place, so the type info, keyed by node id, stays valid.
158
176
  if let Some(lowered) = st.info.lowered.as_mut().and_then(Rc::get_mut) {
159
- plum_core::tail::markTailCalls(lowered);
177
+ plum_core::timing::time("tail marks", || plum_core::tail::markTailCalls(lowered));
160
178
  }
161
179
  if st.result.is_ok() && !st.fip.is_empty() {
162
180
  return Err(st.fip);
@@ -169,14 +187,14 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
169
187
  // original source itself); the twin `pre` is renumbered by lowering and does not share
170
188
  // them, so hints are keyed by call position: read them off the checked program and apply
171
189
  // them to its twin.
172
- let hints = if pass.needsHints {
190
+ let hints = plum_core::timing::time("hints", || if pass.needsHints {
173
191
  match st.info.lowered.clone() {
174
192
  Some(checked) => plum_checker::closureHints(&checked, &st.info),
175
193
  None => plum_checker::closureHints(original, &st.info),
176
194
  }
177
195
  } else {
178
196
  Hints::new()
179
- };
197
+ });
180
198
  let errors = RefCell::new(Vec::new());
181
199
  let env = Env { explain: opts.explain, fbip: opts.fbip, hints: &hints, errors: &errors };
182
200
  let mut copy = match pass.target {
@@ -186,7 +204,7 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
186
204
  None => return,
187
205
  },
188
206
  };
189
- let changed = (pass.rewrite)(&mut copy, &env);
207
+ let changed = plum_core::timing::time("rewrite", || (pass.rewrite)(&mut copy, &env));
190
208
  for d in errors.into_inner() {
191
209
  if !st.fip.contains(&d) {
192
210
  st.fip.push(d);
@@ -206,7 +224,7 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
206
224
  );
207
225
  // Type info is keyed by node id: check the very program kept as `lowered`, so its ids are the ones in the table.
208
226
  let kept = Rc::new(copy);
209
- let (r2, mut i2) = checkOnce(&kept);
227
+ let (r2, mut i2) = plum_core::timing::time("re-check", || checkOnce(&kept));
210
228
  match r2 {
211
229
  Ok(()) => {
212
230
  if pass.target == Target::Pre {
compiler/driver/tests/driver_tests.rs CHANGED
@@ -296,3 +296,25 @@ fn purityResolvesAMethodByItsReceiverType() {
296
296
  assert!(pure.contains("viaShip"), "{pure:?}");
297
297
  assert!(!pure.contains("viaOrb"), "{pure:?}");
298
298
  }
299
+
300
+ const PRUNE: &str = "\
301
+ import std/Int
302
+ import std/Str
303
+
304
+ fun unused(s: Str) -> Str = s.trim()
305
+
306
+ fun main() -> Int = \"abc\".length()
307
+ ";
308
+
309
+ /// What the program cannot reach from its own fns is gone before codegen: an imported
310
+ /// method nothing calls (`Str.replaceAll`) goes, the program's own unused fn and what it
311
+ /// calls (`Str.trim`) stay, and with no passes nothing is dropped.
312
+ #[test]
313
+ fn unreachableImportedFnsArePruned() {
314
+ let src = load("drv_prune", PRUNE);
315
+ let names = loweredNames(&src, &PassOptions::default());
316
+ assert!(!names.iter().any(|n| n == "replaceAll"), "{names:?}");
317
+ assert!(names.iter().any(|n| n == "unused") && names.iter().any(|n| n == "trim"), "{names:?}");
318
+ let none = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
319
+ assert!(loweredNames(&src, &none).iter().any(|n| n == "replaceAll"));
320
+ }
compiler/wasm-codegen/src/lib.rs CHANGED
@@ -112,8 +112,8 @@ pub fn compile(source: &ast::Source, opts: &CompileOptions) -> Result<Output, Ve
112
112
  let (wasm, fn_keys) = compileSourceInner(&prog.source, &extra, typed).map_err(codegenDiag)?;
113
113
  Ok(Output { wasm, fn_keys, test_names: prog.names, isGame: game })
114
114
  } else {
115
- let typed = plum_driver::check(source, &opts.passes)?;
115
+ let typed = plum_core::timing::time("check + passes", || plum_driver::check(source, &opts.passes))?;
116
- let (wasm, fn_keys) = compileSourceInner(source, &gameExports(game), typed).map_err(codegenDiag)?;
116
+ let (wasm, fn_keys) = plum_core::timing::time("codegen", || compileSourceInner(source, &gameExports(game), typed)).map_err(codegenDiag)?;
117
117
  Ok(Output { wasm, fn_keys, test_names: Vec::new(), isGame: game })
118
118
  }
119
119
  }
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs CHANGED
@@ -2294,7 +2294,7 @@ fun main() -> Int =
2294
2294
 
2295
2295
  /// `Str` is `(data, start, len)`: the type section holds exactly one struct of
2296
2296
  /// a ref to the packed `array<i8>` plus two i64s, and the only 2-field
2297
- /// array-first struct is `Buffer` itself.
2297
+ /// array-first struct is `Buffer` itself, when the program uses it.
2298
2298
  #[test]
2299
2299
  fn strIsAViewOfAPackedByteArray() {
2300
2300
  let src = "import std/Str\nimport std/Int\nimport std/Float\n\nfun main() -> Int =\n \"hello\".length()\n";
@@ -2350,8 +2350,9 @@ fn strIsAViewOfAPackedByteArray() {
2350
2350
  }
2351
2351
  }
2352
2352
  assert_eq!(one_field, 1, "expected exactly Str{{data, start, len}}");
2353
- // Buffer{data, len} still exists as its own record (Str imports it).
2353
+ // Buffer{data, len} is its own record, and absent here: nothing this program reaches
2354
+ // uses it, so the unreachable std code that would is pruned (`plum_core::prune`).
2354
- assert_eq!(buffer_like, 1);
2355
+ assert!(buffer_like <= 1, "{buffer_like}");
2355
2356
  assert_eq!(runWithCrash("strshape", src).0.unwrap(), 5);
2356
2357
  }
2357
2358