plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
4adfed8
— Peter John
2026-11-10T10:54:21+05:30
Driver: a failing fn reverts alone; in-place updates are their own pass
- compiler/driver/src/lib.rs +266 -30
- compiler/driver/tests/driver_tests.rs +96 -0
compiler/driver/src/lib.rs
CHANGED
|
@@ -49,6 +49,9 @@ pub struct Env<'a> {
|
|
|
49
49
|
pub hints: &'a Hints,
|
|
50
50
|
/// Errors a pass found in the program it rewrote (`fip fun` sites that stayed copies).
|
|
51
51
|
pub errors: &'a RefCell<Vec<Diagnostic>>,
|
|
52
|
+
/// The `fip fun`s' own spreads, read off fusion's input: fusion may build a callee's spread
|
|
53
|
+
/// into one, and the in-place pass after it must still tell the two apart.
|
|
54
|
+
pub origins: &'a RefCell<Option<plum_core::fip::FipOrigins>>,
|
|
52
55
|
}
|
|
53
56
|
|
|
54
57
|
/// One rewrite pass: changes the program in place, returns whether anything changed.
|
|
@@ -56,6 +59,11 @@ pub struct Pass {
|
|
|
56
59
|
pub name: &'static str,
|
|
57
60
|
pub target: Target,
|
|
58
61
|
pub needsHints: bool,
|
|
62
|
+
/// Each rewritten fn means what it meant before, on its own: when the rewrite fails its
|
|
63
|
+
/// re-check, the fns the errors name can go back to their old bodies (and the fns the
|
|
64
|
+
/// pass added with them) while the rest is kept. A pass whose rewrites depend on each
|
|
65
|
+
/// other across fns (the uniqueness proof) is adopted whole or not at all.
|
|
66
|
+
pub perFn: bool,
|
|
59
67
|
pub enabled: fn(&PassOptions) -> bool,
|
|
60
68
|
pub rewrite: fn(&mut Source, &Env) -> bool,
|
|
61
69
|
}
|
|
@@ -64,6 +72,42 @@ fn closureSpec(copy: &mut Source, env: &Env) -> bool {
|
|
|
64
72
|
!plum_core::closure_spec::specialiseWith(copy, env.hints).is_empty()
|
|
65
73
|
}
|
|
66
74
|
|
|
75
|
+
/// Purity -> simplify -> drive: the `fusion` pass; returns its notes.
|
|
76
|
+
pub fn driveNotes(copy: &mut Source) -> Vec<String> {
|
|
77
|
+
// A build never runs `test` blocks (`plum test` lowers them to fns first, so none is left
|
|
78
|
+
// here): their calls must not make production code copy.
|
|
79
|
+
copy.items.retain(|i| !matches!(i, plum_core::ast::Item::Test(_)));
|
|
80
|
+
let pure = plum_core::timing::time("purity", || plum_core::purity::pureFns(copy));
|
|
81
|
+
let mut notes = plum_core::timing::time("simplify", || plum_core::simplify::simplify(copy, &pure));
|
|
82
|
+
notes.extend(plum_core::timing::time("drive", || plum_core::drive::drive(copy, &pure)));
|
|
83
|
+
notes.retain(|n| !n.is_empty());
|
|
84
|
+
notes
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/// Uniqueness -> fip -> reuse: the `in place` pass; returns its notes and the errors of the
|
|
88
|
+
/// `fip fun`s whose spreads the proof left as copies. `origins`: the `fip fun`s' spreads before
|
|
89
|
+
/// fusion (`fip::origins`), when it ran; else they are read off `copy`.
|
|
90
|
+
pub fn inPlaceRun(copy: &mut Source, origins: Option<&plum_core::fip::FipOrigins>) -> (Vec<String>, Vec<Diagnostic>) {
|
|
91
|
+
let own;
|
|
92
|
+
let origins = match origins {
|
|
93
|
+
Some(o) => o,
|
|
94
|
+
None => {
|
|
95
|
+
own = plum_core::fip::origins(copy);
|
|
96
|
+
&own
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
copy.items.retain(|i| !matches!(i, plum_core::ast::Item::Test(_)));
|
|
100
|
+
let rep = plum_core::timing::time("uniqueness", || plum_core::uniqueness::markUnique(copy));
|
|
101
|
+
let mut notes: Vec<String> = rep.versions.iter().cloned().collect();
|
|
102
|
+
notes.extend(rep.proved.iter().map(|l| format!("unique spread at {l}")));
|
|
103
|
+
notes.extend(rep.unproved.iter().map(|(l, why)| format!("uniqueness: not in place {l}: {why}")));
|
|
104
|
+
let errors = plum_core::timing::time("fip", || plum_core::fip::diagnostics(copy, &rep, origins));
|
|
105
|
+
notes.retain(|n| !n.is_empty());
|
|
106
|
+
notes.extend(plum_core::timing::time("reuse", || plum_core::reuse::markReuse(copy)));
|
|
107
|
+
notes.retain(|n| !n.is_empty());
|
|
108
|
+
(notes, errors)
|
|
109
|
+
}
|
|
110
|
+
|
|
67
111
|
/// Purity -> simplify -> drive -> uniqueness -> reuse; returns every note (empty = nothing changed).
|
|
68
112
|
pub fn fusionNotes(copy: &mut Source) -> Vec<String> {
|
|
69
113
|
fusionNotesWith(copy, true)
|
|
@@ -98,18 +142,31 @@ pub fn fusionRun(copy: &mut Source, fbip: bool) -> (Vec<String>, Vec<Diagnostic>
|
|
|
98
142
|
(notes, errors)
|
|
99
143
|
}
|
|
100
144
|
|
|
145
|
+
fn explainNotes(env: &Env, notes: &[String]) {
|
|
146
|
+
if env.explain {
|
|
147
|
+
for n in notes {
|
|
148
|
+
eprintln!("fusion: {}", plum_core::diag::sourceName(n));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
101
153
|
fn fusion(copy: &mut Source, env: &Env) -> bool {
|
|
102
154
|
// The checker's receiver types go onto the method calls first: purity and the uniqueness
|
|
103
155
|
// proof then resolve `x.m()` to `Type.m`, and the stamp travels with the call when drive
|
|
104
156
|
// inlines or copies it.
|
|
105
157
|
plum_core::closure_spec::stampReceivers(copy, env.hints);
|
|
158
|
+
*env.origins.borrow_mut() = Some(plum_core::fip::origins(copy));
|
|
159
|
+
let notes = driveNotes(copy);
|
|
160
|
+
explainNotes(env, ¬es);
|
|
161
|
+
!notes.is_empty()
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/// In-place updates, a pass of its own after fusion: a dropped fusion rewrite keeps them.
|
|
165
|
+
fn inPlace(copy: &mut Source, env: &Env) -> bool {
|
|
166
|
+
plum_core::closure_spec::stampReceivers(copy, env.hints);
|
|
106
|
-
let (notes, errors) =
|
|
167
|
+
let (notes, errors) = inPlaceRun(copy, env.origins.borrow().as_ref());
|
|
107
168
|
env.errors.borrow_mut().extend(errors);
|
|
108
|
-
if env.explain {
|
|
109
|
-
|
|
169
|
+
explainNotes(env, ¬es);
|
|
110
|
-
eprintln!("fusion: {}", plum_core::diag::sourceName(n));
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
170
|
!notes.is_empty()
|
|
114
171
|
}
|
|
115
172
|
|
|
@@ -129,13 +186,24 @@ fn trmc(copy: &mut Source, _: &Env) -> bool {
|
|
|
129
186
|
|
|
130
187
|
/// The rewrite passes, in the order they run. Tail marks (flags set in place on the final
|
|
131
188
|
/// program) run last and need no re-check.
|
|
132
|
-
pub const PASSES: [Pass;
|
|
189
|
+
pub const PASSES: [Pass; 5] = [
|
|
133
|
-
Pass { name: "dead code", target: Target::Pre, needsHints: false, enabled: |o| o.closureSpec || o.fusion || o.trmc, rewrite: prune },
|
|
190
|
+
Pass { name: "dead code", target: Target::Pre, needsHints: false, perFn: false, enabled: |o| o.closureSpec || o.fusion || o.trmc, rewrite: prune },
|
|
134
|
-
Pass { name: "closure specialisation", target: Target::Pre, needsHints: true, enabled: |o| o.closureSpec, rewrite: closureSpec },
|
|
191
|
+
Pass { name: "closure specialisation", target: Target::Pre, needsHints: true, perFn: true, enabled: |o| o.closureSpec, rewrite: closureSpec },
|
|
135
|
-
Pass { name: "fusion", target: Target::Pre, needsHints: true, enabled: |o| o.fusion, rewrite: fusion },
|
|
192
|
+
Pass { name: "fusion", target: Target::Pre, needsHints: true, perFn: true, enabled: |o| o.fusion, rewrite: fusion },
|
|
193
|
+
Pass { name: "in place", target: Target::Pre, needsHints: true, perFn: false, enabled: |o| o.fusion && o.fbip, rewrite: inPlace },
|
|
136
|
-
Pass { name: "trmc", target: Target::Lowered, needsHints: false, enabled: |o| o.trmc, rewrite: trmc },
|
|
194
|
+
Pass { name: "trmc", target: Target::Lowered, needsHints: false, perFn: true, enabled: |o| o.trmc, rewrite: trmc },
|
|
137
195
|
];
|
|
138
196
|
|
|
197
|
+
/// A rewrite that failed its re-check: the pass, whether only some fns were reverted (the
|
|
198
|
+
/// rest kept), and the first errors.
|
|
199
|
+
#[derive(Clone, Debug)]
|
|
200
|
+
pub struct Dropped {
|
|
201
|
+
pub pass: &'static str,
|
|
202
|
+
/// The fns put back (or, for fns the pass added, removed); empty when the whole rewrite was dropped.
|
|
203
|
+
pub reverted: Vec<String>,
|
|
204
|
+
pub errors: Vec<String>,
|
|
205
|
+
}
|
|
206
|
+
|
|
139
207
|
/// The state the passes thread through: the pre-union program and the checked result.
|
|
140
208
|
struct State {
|
|
141
209
|
pre: Source,
|
|
@@ -143,6 +211,9 @@ struct State {
|
|
|
143
211
|
info: TypedInfo,
|
|
144
212
|
/// `fip fun` violations, kept even when the rewrite that found them is dropped.
|
|
145
213
|
fip: Vec<Diagnostic>,
|
|
214
|
+
dropped: Vec<Dropped>,
|
|
215
|
+
/// See `Env.origins`.
|
|
216
|
+
origins: RefCell<Option<plum_core::fip::FipOrigins>>,
|
|
146
217
|
}
|
|
147
218
|
|
|
148
219
|
/// Checks `source`, then runs the enabled passes of `PASSES` in order, each adopted only if
|
|
@@ -154,6 +225,11 @@ pub fn check(source: &Source, opts: &PassOptions) -> Result<TypedInfo, Vec<Diagn
|
|
|
154
225
|
|
|
155
226
|
/// `check` with an explicit pass list.
|
|
156
227
|
pub fn check_with(source: &Source, opts: &PassOptions, passes: &[Pass]) -> Result<TypedInfo, Vec<Diagnostic>> {
|
|
228
|
+
checkReport(source, opts, passes).0
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/// `check_with`, and every rewrite that failed its re-check (wholly or partly dropped).
|
|
232
|
+
pub fn checkReport(source: &Source, opts: &PassOptions, passes: &[Pass]) -> (Result<TypedInfo, Vec<Diagnostic>>, Vec<Dropped>) {
|
|
157
233
|
let (result, info, pre) = plum_core::timing::time("check", || checkProgramPre(source));
|
|
158
234
|
// The check lowered the program's loops already: reuse its pre-union program.
|
|
159
235
|
let pre = match pre {
|
|
@@ -163,7 +239,7 @@ pub fn check_with(source: &Source, opts: &PassOptions, passes: &[Pass]) -> Resul
|
|
|
163
239
|
}
|
|
164
240
|
None => preUnionSource(source),
|
|
165
241
|
};
|
|
166
|
-
let mut st = State { pre, result, info, fip: Vec::new() };
|
|
242
|
+
let mut st = State { pre, result, info, fip: Vec::new(), dropped: Vec::new(), origins: RefCell::new(None) };
|
|
167
243
|
if st.result.is_ok() {
|
|
168
244
|
if opts.explain && !(opts.fusion && opts.fbip) && !plum_core::fip::origins(&st.pre).isEmpty() {
|
|
169
245
|
eprintln!("fusion: fip fun is not enforced: it needs the uniqueness proof, which --no-fusion and --no-fbip switch off");
|
|
@@ -177,9 +253,9 @@ pub fn check_with(source: &Source, opts: &PassOptions, passes: &[Pass]) -> Resul
|
|
|
177
253
|
plum_core::timing::time("tail marks", || plum_core::tail::markTailCalls(lowered));
|
|
178
254
|
}
|
|
179
255
|
if st.result.is_ok() && !st.fip.is_empty() {
|
|
180
|
-
return Err(st.fip);
|
|
256
|
+
return (Err(st.fip), st.dropped);
|
|
181
257
|
}
|
|
182
|
-
st.result.map(|()| st.info)
|
|
258
|
+
(st.result.map(|()| st.info), st.dropped)
|
|
183
259
|
}
|
|
184
260
|
|
|
185
261
|
fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
|
|
@@ -196,7 +272,7 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
|
|
|
196
272
|
Hints::new()
|
|
197
273
|
});
|
|
198
274
|
let errors = RefCell::new(Vec::new());
|
|
199
|
-
let env = Env { explain: opts.explain, fbip: opts.fbip, hints: &hints, errors: &errors };
|
|
275
|
+
let env = Env { explain: opts.explain, fbip: opts.fbip, hints: &hints, errors: &errors, origins: &st.origins };
|
|
200
276
|
let mut copy = match pass.target {
|
|
201
277
|
Target::Pre => st.pre.clone(),
|
|
202
278
|
Target::Lowered => match st.info.lowered.as_ref() {
|
|
@@ -223,29 +299,189 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
|
|
|
223
299
|
plum_core::ast::duplicateId(©)
|
|
224
300
|
);
|
|
225
301
|
// Type info is keyed by node id: check the very program kept as `lowered`, so its ids are the ones in the table.
|
|
226
|
-
let kept = Rc::new(copy);
|
|
227
|
-
let (r2,
|
|
302
|
+
let (r2, i2, kept) = plum_core::timing::time("re-check", || recheck(copy));
|
|
228
303
|
match r2 {
|
|
304
|
+
Ok(()) => adopt(pass, st, kept, i2),
|
|
229
|
-
|
|
305
|
+
Err(errs) => {
|
|
306
|
+
let first: Vec<String> = errs.iter().take(3).map(|e| format!("{}:{}: {}", e.line, e.column, e.message)).collect();
|
|
307
|
+
let base = match pass.target {
|
|
308
|
+
Target::Pre => Some(&st.pre),
|
|
309
|
+
Target::Lowered => st.info.lowered.as_deref(),
|
|
310
|
+
};
|
|
230
|
-
|
|
311
|
+
let partial = match base {
|
|
312
|
+
Some(base) if pass.perFn => plum_core::timing::time("revert", || revertFailing(base, &kept, errs)),
|
|
313
|
+
_ => None,
|
|
314
|
+
};
|
|
315
|
+
if opts.explain {
|
|
316
|
+
match &partial {
|
|
317
|
+
Some((reverted, ..)) => eprintln!("fusion: {} kept, but for {}: they failed its re-check", pass.name, reverted.join(", ")),
|
|
318
|
+
None => eprintln!("fusion: {} dropped: the rewritten program failed its re-check", pass.name),
|
|
319
|
+
}
|
|
231
|
-
|
|
320
|
+
for e in &first {
|
|
321
|
+
eprintln!("fusion: {e}");
|
|
322
|
+
}
|
|
232
323
|
}
|
|
324
|
+
match partial {
|
|
233
|
-
|
|
325
|
+
Some((reverted, kept, i2)) => {
|
|
234
|
-
|
|
326
|
+
st.dropped.push(Dropped { pass: pass.name, reverted, errors: first });
|
|
235
|
-
|
|
327
|
+
adopt(pass, st, kept, i2);
|
|
328
|
+
}
|
|
329
|
+
None => st.dropped.push(Dropped { pass: pass.name, reverted: Vec::new(), errors: first }),
|
|
236
330
|
}
|
|
237
|
-
st.result = Ok(());
|
|
238
|
-
st.info = i2;
|
|
239
331
|
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
fn recheck(copy: Source) -> (Result<(), Vec<Diagnostic>>, TypedInfo, Rc<Source>) {
|
|
336
|
+
let kept = Rc::new(copy);
|
|
337
|
+
let (r, i) = checkOnce(&kept);
|
|
338
|
+
(r, i, kept)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
fn adopt(pass: &Pass, st: &mut State, kept: Rc<Source>, mut i2: TypedInfo) {
|
|
342
|
+
if pass.target == Target::Pre {
|
|
343
|
+
st.pre = (*kept).clone();
|
|
344
|
+
}
|
|
345
|
+
// A pre-union program is lowered by its check; an already lowered one is kept as is.
|
|
346
|
+
if pass.target == Target::Lowered || i2.lowered.is_none() {
|
|
347
|
+
i2.lowered = Some(kept);
|
|
348
|
+
}
|
|
240
|
-
|
|
349
|
+
st.result = Ok(());
|
|
350
|
+
st.info = i2;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
fn fnKey(f: &plum_core::ast::Fn) -> String {
|
|
241
|
-
|
|
354
|
+
match &f.type_param {
|
|
355
|
+
Some(t) => format!("{}.{}", t, f.name),
|
|
356
|
+
None => f.name.clone(),
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/// The fn names a re-check error is about, innermost first: the `in X[..]` instantiation
|
|
361
|
+
/// chain and a `fn 'x'` prefix.
|
|
362
|
+
fn namesIn(msg: &str) -> Vec<String> {
|
|
363
|
+
let mut out = Vec::new();
|
|
364
|
+
let mut rest = msg;
|
|
365
|
+
while let Some(i) = rest.find("in ") {
|
|
366
|
+
let at = &rest[i + 3..];
|
|
367
|
+
let end = at.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '.' || c == '$')).unwrap_or(at.len());
|
|
368
|
+
if end > 0 && at[end..].starts_with('[') && (i == 0 || rest[..i].ends_with(": ") || rest[..i].ends_with(' ')) {
|
|
369
|
+
out.push(at[..end].to_string());
|
|
370
|
+
}
|
|
371
|
+
rest = &at[end..];
|
|
372
|
+
}
|
|
373
|
+
if let Some(i) = msg.find("fn '") {
|
|
374
|
+
let at = &msg[i + 4..];
|
|
375
|
+
if let Some(e) = at.find('\'') {
|
|
376
|
+
out.push(at[..e].to_string());
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
out.reverse();
|
|
380
|
+
out
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/// A failed per-fn rewrite with the fns the errors blame put back as they were in `base`
|
|
242
|
-
|
|
384
|
+
/// (a fn the pass added is removed, with every rewritten fn that calls it), re-checked; a
|
|
385
|
+
/// few rounds, each blaming the fns its errors name. `None` when no round checks or an
|
|
386
|
+
/// error names no rewritten fn: the whole rewrite is then dropped.
|
|
387
|
+
fn revertFailing(base: &Source, rewritten: &Source, mut errs: Vec<Diagnostic>) -> Option<(Vec<String>, Rc<Source>, TypedInfo)> {
|
|
388
|
+
use plum_core::ast::Item;
|
|
389
|
+
use std::collections::{HashMap, HashSet};
|
|
390
|
+
let old: HashMap<String, &plum_core::ast::Fn> =
|
|
391
|
+
base.items.iter().filter_map(|i| if let Item::Fn(f) = i { Some((fnKey(f), f)) } else { None }).collect();
|
|
392
|
+
let mut cur = rewritten.clone();
|
|
393
|
+
let mut reverted: Vec<String> = Vec::new();
|
|
394
|
+
for _ in 0..6 {
|
|
395
|
+
let now: HashMap<String, &plum_core::ast::Fn> =
|
|
396
|
+
cur.items.iter().filter_map(|i| if let Item::Fn(f) = i { Some((fnKey(f), f)) } else { None }).collect();
|
|
397
|
+
let changed = |k: &String| now.get(k).is_some_and(|f| old.get(k).is_none_or(|o| !sameFn(o, f)));
|
|
398
|
+
// by key, or a method's bare name in a `fn 'name'` prefix
|
|
399
|
+
let byName = |n: &str| -> Vec<String> {
|
|
400
|
+
if now.contains_key(n) {
|
|
401
|
+
return vec![n.to_string()];
|
|
402
|
+
}
|
|
403
|
+
now.keys().filter(|k| k.rsplit('.').next() == Some(n)).cloned().collect()
|
|
404
|
+
};
|
|
405
|
+
// An error in a fn the pass left alone follows from one it changed (a call of `bad`
|
|
406
|
+
// after `bad`'s signature changed): the next round's re-check tells.
|
|
407
|
+
let mut blamed: HashSet<String> = HashSet::new();
|
|
243
|
-
|
|
408
|
+
for e in &errs {
|
|
409
|
+
let names = namesIn(&e.message);
|
|
410
|
+
blamed.extend(names.iter().flat_map(|n| byName(n)).find(|k| changed(k)));
|
|
411
|
+
}
|
|
412
|
+
if blamed.is_empty() {
|
|
413
|
+
return None;
|
|
414
|
+
}
|
|
415
|
+
// a removed fn takes every fn calling it along: put back if old, removed if new
|
|
416
|
+
let mut removed: HashSet<String> = blamed.iter().filter(|k| !old.contains_key(*k)).cloned().collect();
|
|
417
|
+
let mut back: HashSet<String> = blamed.iter().filter(|k| old.contains_key(*k)).cloned().collect();
|
|
418
|
+
loop {
|
|
419
|
+
let gone: HashSet<String> = removed.iter().map(|k| k.rsplit('.').next().unwrap_or(k).to_string()).collect();
|
|
420
|
+
let mut more = false;
|
|
421
|
+
for (k, f) in &now {
|
|
244
|
-
|
|
422
|
+
if removed.contains(k) || back.contains(k) || !changed(k) || !calls(f, &gone) {
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
if old.contains_key(k) {
|
|
426
|
+
back.insert(k.clone());
|
|
427
|
+
} else {
|
|
428
|
+
removed.insert(k.clone());
|
|
245
429
|
}
|
|
430
|
+
more = true;
|
|
431
|
+
}
|
|
432
|
+
if !more {
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
drop(now);
|
|
437
|
+
cur.items.retain(|i| !matches!(i, Item::Fn(f) if removed.contains(&fnKey(f))));
|
|
438
|
+
for i in &mut cur.items {
|
|
439
|
+
if let Item::Fn(f) = i {
|
|
440
|
+
if let Some(o) = back.get(&fnKey(f)).and_then(|k| old.get(k)) {
|
|
441
|
+
*f = (*o).clone();
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
reverted.extend(removed.into_iter().chain(back));
|
|
446
|
+
plum_core::ast::numberIds(&mut cur);
|
|
447
|
+
let (r, i, kept) = recheck(cur.clone());
|
|
448
|
+
match r {
|
|
449
|
+
Ok(()) => {
|
|
450
|
+
reverted.sort();
|
|
451
|
+
reverted.dedup();
|
|
452
|
+
return Some((reverted, kept, i));
|
|
453
|
+
}
|
|
454
|
+
Err(e) => errs = e,
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
None
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/// The same fn, ignoring node ids (a pass renumbers what it touches).
|
|
461
|
+
fn sameFn(a: &plum_core::ast::Fn, b: &plum_core::ast::Fn) -> bool {
|
|
462
|
+
a == b
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/// Whether `f` calls (or passes along) a fn named one of `names`.
|
|
466
|
+
fn calls(f: &plum_core::ast::Fn, names: &std::collections::HashSet<String>) -> bool {
|
|
467
|
+
use plum_core::ast::{AttrKind, ExprKind, FnBody};
|
|
468
|
+
let mut hit = false;
|
|
469
|
+
let mut cb = |e: &plum_core::ast::Expr| match &e.kind {
|
|
470
|
+
ExprKind::FnCall(c) => hit |= names.contains(&c.name),
|
|
471
|
+
ExprKind::Attribute(a) => {
|
|
472
|
+
if let AttrKind::Method(c) = &a.attr {
|
|
473
|
+
hit |= names.contains(&c.name);
|
|
246
474
|
}
|
|
247
475
|
}
|
|
476
|
+
ExprKind::Var(v) => hit |= names.contains(v),
|
|
477
|
+
_ => {}
|
|
478
|
+
};
|
|
479
|
+
match &f.body {
|
|
480
|
+
FnBody::Expr(e) => plum_core::visit::walkRef(e, &mut cb),
|
|
481
|
+
FnBody::Block(b) => plum_core::visit::walkBlockRef(b, &mut cb),
|
|
482
|
+
FnBody::Extern => {}
|
|
248
483
|
}
|
|
484
|
+
hit
|
|
249
485
|
}
|
|
250
486
|
|
|
251
487
|
/// The checked program before union lowering: own generics applied and `for` loops lowered.
|
compiler/driver/tests/driver_tests.rs
CHANGED
|
@@ -64,6 +64,7 @@ fn aRewriteThatFailsItsRecheckIsDropped() {
|
|
|
64
64
|
name: "break",
|
|
65
65
|
target: Target::Pre,
|
|
66
66
|
needsHints: false,
|
|
67
|
+
perFn: false,
|
|
67
68
|
enabled: |_| true,
|
|
68
69
|
rewrite: breakProgram,
|
|
69
70
|
};
|
|
@@ -318,3 +319,98 @@ fn unreachableImportedFnsArePruned() {
|
|
|
318
319
|
let none = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
|
|
319
320
|
assert!(loweredNames(&src, &none).iter().any(|n| n == "replaceAll"));
|
|
320
321
|
}
|
|
322
|
+
|
|
323
|
+
/// `tests/core/passes_upcasts.plum`, with a `main` that reaches each of its fns.
|
|
324
|
+
fn upcastsSource() -> String {
|
|
325
|
+
let body = std::fs::read_to_string(plum_test_support::repoRoot().join("tests/core/passes_upcasts.plum")).expect("reads");
|
|
326
|
+
let at = body.find("\ntest ").expect("has tests");
|
|
327
|
+
let main = "\nfun main() -> Int = grp(3, Nil).v.area() + holders([Sq(s: 2)]).length() + outer[Str, Int](Box(v: 3)) + caller[Str, Int](Box(v: 3), 4)\n";
|
|
328
|
+
format!("{}{main}{}", &body[..at], &body[at..])
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/// Wrappers and closures that upcast to a trait, a closure naming its fn's generics and a
|
|
332
|
+
/// call with type arguments passing a capturing closure: every pass is kept, and the
|
|
333
|
+
/// capturing closure is still specialised (`apply$c..`, its copy, is called).
|
|
334
|
+
#[test]
|
|
335
|
+
fn upcastsAndGenericClosuresDropNoPass() {
|
|
336
|
+
let src = load("drv_upcasts", &upcastsSource());
|
|
337
|
+
let (r, dropped) = plum_driver::checkReport(&src, &PassOptions::default(), &PASSES);
|
|
338
|
+
let info = r.expect("checks");
|
|
339
|
+
assert!(dropped.is_empty(), "{dropped:?}");
|
|
340
|
+
let names = fnNames(info.lowered.as_ref().unwrap());
|
|
341
|
+
assert!(names.iter().any(|n| n.starts_with("apply$c")), "{names:?}");
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const PARTIAL: &str = "\
|
|
345
|
+
import std/Int
|
|
346
|
+
|
|
347
|
+
fun good(n: Int) -> Int = n + 1
|
|
348
|
+
|
|
349
|
+
fun bad(n: Int) -> Int = n * 2
|
|
350
|
+
|
|
351
|
+
fun main() -> Int = good(1) + bad(2)
|
|
352
|
+
";
|
|
353
|
+
|
|
354
|
+
/// Breaks `bad` (its result made a `Bool`) and adds a copy of `good` named `added`.
|
|
355
|
+
fn breakOne(copy: &mut Source, _: &Env) -> bool {
|
|
356
|
+
let mut added = None;
|
|
357
|
+
for item in &mut copy.items {
|
|
358
|
+
if let Item::Fn(f) = item {
|
|
359
|
+
if f.name == "bad" {
|
|
360
|
+
f.returns = Some(plum_core::ast::Type { name: "Bool".to_string(), generics: vec![] });
|
|
361
|
+
}
|
|
362
|
+
if f.name == "good" {
|
|
363
|
+
let mut g = f.clone();
|
|
364
|
+
g.name = "added".to_string();
|
|
365
|
+
plum_core::ast::refreshFnIds(&mut g);
|
|
366
|
+
added = Some(g);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
copy.items.push(Item::Fn(added.expect("good")));
|
|
371
|
+
true
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/// A per-fn rewrite that fails its re-check in one fn keeps the rest: `bad` goes back to
|
|
375
|
+
/// its old body, `added` stays. A whole-program pass loses both.
|
|
376
|
+
#[test]
|
|
377
|
+
fn aFailingFnRevertsAloneInAPerFnPass() {
|
|
378
|
+
let src = load("drv_partial", PARTIAL);
|
|
379
|
+
let opts = PassOptions::default();
|
|
380
|
+
for perFn in [true, false] {
|
|
381
|
+
let pass = Pass { name: "break one", target: Target::Pre, needsHints: false, perFn, enabled: |_| true, rewrite: breakOne };
|
|
382
|
+
let (r, dropped) = plum_driver::checkReport(&src, &opts, &[pass]);
|
|
383
|
+
let names = fnNames(r.expect("still checks").lowered.as_ref().unwrap());
|
|
384
|
+
assert_eq!(names.iter().any(|n| n == "added"), perFn, "{dropped:?}");
|
|
385
|
+
assert_eq!(dropped.len(), 1, "{dropped:?}");
|
|
386
|
+
assert_eq!(dropped[0].reverted, if perFn { vec!["bad".to_string()] } else { vec![] });
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/// Every game (and the scene-tree benchmark) builds with every pass kept: a rewrite that
|
|
391
|
+
/// fails its re-check, even in one fn, is reported here.
|
|
392
|
+
#[test]
|
|
393
|
+
fn everyGameKeepsEveryPass() {
|
|
394
|
+
let root = plum_test_support::repoRoot();
|
|
395
|
+
let mut files: Vec<std::path::PathBuf> = Vec::new();
|
|
396
|
+
for dir in ["examples/games", "examples/games/kids"] {
|
|
397
|
+
for e in std::fs::read_dir(root.join(dir)).expect("games") {
|
|
398
|
+
let p = e.unwrap().path();
|
|
399
|
+
if p.extension().is_some_and(|x| x == "plum") {
|
|
400
|
+
files.push(p);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
files.push(root.join("benchmarks/scene_trees/scene_tree.plum"));
|
|
405
|
+
assert!(files.len() >= 5, "{files:?}");
|
|
406
|
+
let mut bad = Vec::new();
|
|
407
|
+
for f in &files {
|
|
408
|
+
let src = plum_core::loader::loadAndMergeDiag(f, &root).unwrap_or_else(|e| panic!("{}: {e:?}", f.display()));
|
|
409
|
+
let (r, dropped) = plum_driver::checkReport(&src, &PassOptions::default(), &PASSES);
|
|
410
|
+
r.unwrap_or_else(|e| panic!("{}: {e:?}", f.display()));
|
|
411
|
+
if !dropped.is_empty() {
|
|
412
|
+
bad.push(format!("{}: {dropped:?}", f.display()));
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
assert!(bad.is_empty(), "{}", bad.join("\n"));
|
|
416
|
+
}
|