plum

#treesitter#compiler#wasm

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

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


a41fbe3 — Peter John 2026-11-06T20:52:21+05:30
Block-bodied closures, and fixes for names shared with std
compiler/checker/tests/checker/fip_test.rs CHANGED
@@ -103,6 +103,14 @@ fn a_caller_that_hands_over_keeps_it_in_place() {
103
103
  run("fip_handover", body, &PassOptions::default()).expect("compiles");
104
104
  }
105
105
 
106
+ /// F-T8-2: a fn-typed parameter named like a free fn (`keep`) is a closure call inside its own
107
+ /// fn; it neither counts as a caller of the free `keep` nor makes `keep` unresolvable.
108
+ #[test]
109
+ fn a_parameter_named_like_a_free_fn_is_not_a_call_of_it() {
110
+ let body = "fip fun upd(p: Pt) -> Pt = Pt(..p, px: 1)\nfun keep(x: Pt) -> Pt = upd(x)\nfun apply(keep: fn(Int) -> Bool, n: Int) -> Bool = keep(n)\n";
111
+ run("fip_param_named_like_fn", body, &PassOptions::default()).expect("compiles");
112
+ }
113
+
106
114
  #[test]
107
115
  fn update_inside_a_closure() {
108
116
  let body = "fip fun upd(a: Array[Int]) -> Array[Int] =\n g := || a.with(0, 1)\n g()\n";
compiler/core/src/closure_spec.rs CHANGED
@@ -706,14 +706,23 @@ impl<'h> Ctx<'h> {
706
706
  }
707
707
  Kind::Lit(c) => c.clone(),
708
708
  };
709
- let (binds, mut body) = self.instantiate(&cl, tx.spec, args, true)?;
709
+ if let Some((binds, mut body)) = self.instantiate(&cl, tx.spec, args.clone(), true) {
710
- if !binds.is_empty() || body.len() != 1 {
710
+ if binds.is_empty() && body.len() == 1 {
711
+ return match body.pop() {
712
+ Some(Stmt { kind: StmtKind::Expr(e, ..), .. }) => Some(e),
711
- return None;
713
+ _ => None,
714
+ };
715
+ }
712
716
  }
717
+ // A block closure (several statements, or arguments to bind): the call becomes a block
718
+ // value, whose last line is the closure's value. Its binders are fresh, so the block
719
+ // declares nothing that clashes with the enclosing fn.
713
- match body.pop() {
720
+ let (mut stmts, body) = self.instantiate(&cl, tx.spec, args, false)?;
714
- Some(Stmt { kind: StmtKind::Expr(e, ..), .. }) => Some(e),
721
+ if !matches!(body.last(), Some(Stmt { kind: StmtKind::Expr(..), .. })) {
715
- _ => None,
722
+ return None;
716
723
  }
724
+ stmts.extend(body);
725
+ Some(Expr::Block(Box::new(Block { stmts })))
717
726
  }
718
727
 
719
728
  /// The closure body with its binders renamed fresh, captures replaced by the copy's
compiler/core/src/loader.rs CHANGED
@@ -185,6 +185,7 @@ fn resolveFileModules(files: &mut [Loaded], lib_path: &Path) -> Loaded_<()> {
185
185
  .map(|f| crate::modules::ModuleInfo {
186
186
  name: f.path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(),
187
187
  path: displayPath(&f.path),
188
+ isStd: isStdFile(&f.path, lib_path),
188
189
  imports: f
189
190
  .source
190
191
  .imports
compiler/core/src/modules.rs CHANGED
@@ -29,6 +29,8 @@ pub struct ModuleInfo {
29
29
  pub name: String,
30
30
  /// For diagnostics.
31
31
  pub path: String,
32
+ /// A std file: in a name clash its function is the one renamed.
33
+ pub isStd: bool,
32
34
  /// `(name, file index)` of each direct import.
33
35
  pub imports: Vec<(String, usize)>,
34
36
  }
@@ -61,6 +63,10 @@ struct World {
61
63
  /// Names defined in two or more files (renamable fns / consts only).
62
64
  fnCollide: HashSet<String>,
63
65
  constCollide: HashSet<String>,
66
+ /// Per file: top-level fns that keep their name even when another file defines it too:
67
+ /// exports and `main` (the host sees those names), and the one definition a non-std file
68
+ /// has when only std files define it besides. The other definitions are renamed.
69
+ fnFixed: Vec<HashSet<String>>,
64
70
  /// Every type name: enums and structs, `primitive`s and the built-ins.
65
71
  types: HashSet<String>,
66
72
  }
@@ -71,7 +77,8 @@ fn mangle(name: &str, module: &str) -> String {
71
77
 
72
78
  impl World {
73
79
  fn global(&self, file: usize, name: &str, collide: &HashSet<String>) -> String {
80
+ let fixed = std::ptr::eq(collide, &self.fnCollide) && self.fnFixed[file].contains(name);
74
- if collide.contains(name) {
81
+ if collide.contains(name) && !fixed {
75
82
  mangle(name, &self.infos[file].name)
76
83
  } else {
77
84
  name.to_string()
@@ -83,6 +90,9 @@ pub fn resolveModules(infos: Vec<ModuleInfo>, sources: &mut [&mut Source]) -> Re
83
90
  let n = sources.len();
84
91
  let mut fns = vec![HashSet::new(); n];
85
92
  let mut consts = vec![HashSet::new(); n];
93
+ let mut fnFixed = vec![HashSet::new(); n];
94
+ let mut userCount: HashMap<String, usize> = HashMap::new();
95
+ let mut userDefs = vec![HashSet::new(); n];
86
96
  let mut fnCount: HashMap<String, usize> = HashMap::new();
87
97
  let mut constCount: HashMap<String, usize> = HashMap::new();
88
98
  for (i, s) in sources.iter().enumerate() {
@@ -91,9 +101,17 @@ pub fn resolveModules(infos: Vec<ModuleInfo>, sources: &mut [&mut Source]) -> Re
91
101
  for item in &s.items {
92
102
  match item {
93
103
  Item::Fn(f) if f.type_param.is_none() => {
104
+ // An export or `main` counts as a definition too, so a std function of the
105
+ // same name is renamed away from it (it keeps its name, see `fnFixed`).
94
- if renamable(f) && ownFns.insert(f.name.clone()) {
106
+ if !f.is_test && ownFns.insert(f.name.clone()) {
95
107
  *fnCount.entry(f.name.clone()).or_default() += 1;
96
108
  }
109
+ if !f.is_test && !renamable(f) {
110
+ fnFixed[i].insert(f.name.clone());
111
+ } else if !f.is_test && !infos[i].isStd {
112
+ *userCount.entry(f.name.clone()).or_default() += 1;
113
+ userDefs[i].insert(f.name.clone());
114
+ }
97
115
  fns[i].insert(f.name.clone());
98
116
  }
99
117
  Item::Const(c) if isModuleConst(c) => {
@@ -106,6 +124,15 @@ pub fn resolveModules(infos: Vec<ModuleInfo>, sources: &mut [&mut Source]) -> Re
106
124
  }
107
125
  }
108
126
  }
127
+ // A user's function keeps its name when no other user file or export defines it.
128
+ for i in 0..n {
129
+ for name in &userDefs[i] {
130
+ let others = (0..n).any(|j| j != i && fnFixed[j].contains(name));
131
+ if userCount[name] == 1 && !others && !fnFixed[i].contains(name) {
132
+ fnFixed[i].insert(name.clone());
133
+ }
134
+ }
135
+ }
109
136
  let collide = |m: &HashMap<String, usize>| -> HashSet<String> {
110
137
  m.iter().filter(|(_, &c)| c > 1).map(|(k, _)| k.clone()).collect()
111
138
  };
@@ -117,7 +144,7 @@ pub fn resolveModules(infos: Vec<ModuleInfo>, sources: &mut [&mut Source]) -> Re
117
144
  _ => None,
118
145
  }));
119
146
  }
120
- let world = World { fnCollide: collide(&fnCount), constCollide: collide(&constCount), infos, fns, consts, types };
147
+ let world = World { fnCollide: collide(&fnCount), constCollide: collide(&constCount), infos, fns, consts, fnFixed, types };
121
148
  // One file has no other module to resolve against.
122
149
  if n < 2 {
123
150
  return Ok(());
@@ -396,7 +423,7 @@ pub fn fnLocals(f: &Fn) -> HashSet<String> {
396
423
  fn rewriteFile(world: &World, file: usize, source: &mut Source, errors: &mut Vec<Diagnostic>) {
397
424
  for item in &mut source.items {
398
425
  match item {
399
- Item::Fn(f) if renamable(f) && world.fnCollide.contains(&f.name) => {
426
+ Item::Fn(f) if renamable(f) && world.fnCollide.contains(&f.name) && !world.fnFixed[file].contains(&f.name) => {
400
427
  f.name = mangle(&f.name, &world.infos[file].name);
401
428
  }
402
429
  Item::Const(c) if isModuleConst(c) && world.constCollide.contains(&c.name) => {
compiler/core/src/parser.rs CHANGED
@@ -1115,6 +1115,24 @@ impl<'a> AstParser<'a> {
1115
1115
  }
1116
1116
  }
1117
1117
 
1118
+ /// The last line of every path through `stmts` is a value (an expression, a nested `if`
1119
+ /// with an `else` / `match` of the same kind, or a path-ending `return` / `crash`).
1120
+ fn valueTail(stmts: &[Stmt]) -> bool {
1121
+ match stmts.last().map(|s| &s.kind) {
1122
+ Some(StmtKind::Expr(..)) => true,
1123
+ Some(StmtKind::If(i)) => {
1124
+ i.else_.is_some()
1125
+ && std::iter::once(&i.body)
1126
+ .chain(i.else_ifs.iter().map(|e| &e.body))
1127
+ .chain(i.else_.iter())
1128
+ .all(|b| Self::valueTail(&b.stmts))
1129
+ }
1130
+ Some(StmtKind::Match(m)) => m.cases.iter().all(|c| Self::valueTail(&c.body.stmts)),
1131
+ Some(StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo | StmtKind::Break | StmtKind::Continue) => true,
1132
+ _ => false,
1133
+ }
1134
+ }
1135
+
1118
1136
  fn parseClosure(&self, node: Node) -> Closure {
1119
1137
  // closure: "|" var_identifier,* "|" (expression | body)
1120
1138
  let mut params: Vec<String> = Vec::new();
@@ -1146,7 +1164,24 @@ impl<'a> AstParser<'a> {
1146
1164
  // (`|v| v`); normalize the inline form into a one-statement block so codegen and
1147
1165
  // the checker only ever see a `Block`.
1148
1166
  let body = match self.childrenOfKind(node, "body").into_iter().next() {
1167
+ Some(block_node) => {
1168
+ // A block closure's last line is its value: a trailing `if` / `match` whose
1169
+ // branches all end in a value is the value (like the inline form), not a
1170
+ // statement of type `Unit`.
1149
- Some(block_node) => self.parseBlock(block_node),
1171
+ let mut b = self.parseBlock(block_node);
1172
+ if let Some(last) = b.stmts.pop() {
1173
+ if matches!(last.kind, StmtKind::If(_) | StmtKind::Match(_)) && Self::valueTail(std::slice::from_ref(&last)) {
1174
+ let (line, col) = (last.span.startLine, last.span.startColumn);
1175
+ let span = last.span;
1176
+ let mut e = Expr::Block(Box::new(Block { stmts: vec![last] }));
1177
+ e.span = span;
1178
+ b.stmts.push(Stmt::Expr(e, line, col));
1179
+ } else {
1180
+ b.stmts.push(last);
1181
+ }
1182
+ }
1183
+ b
1184
+ }
1150
1185
  None => match node.child_by_field_name("body") {
1151
1186
  Some(expr_node) => {
1152
1187
  // A block `if` / `match` here is the closure's value, so it stays an
compiler/core/src/uniqueness.rs CHANGED
@@ -40,6 +40,7 @@
40
40
  //! Parameters and fields are solved as a greatest fixpoint (assume unique, remove what
41
41
  //! fails, repeat).
42
42
  use crate::ast::*;
43
+ use crate::rename::renameStmts;
43
44
  use std::cell::RefCell;
44
45
  use std::collections::{HashMap, HashSet};
45
46
 
@@ -1195,6 +1196,10 @@ fn lineOf(src: &Source, u: &Unit) -> usize {
1195
1196
  }
1196
1197
  }
1197
1198
 
1199
+ /// Appended to a name a fn-typed parameter shares with a free fn, in that fn's body only
1200
+ /// (see `build`): the renamed name is defined nowhere.
1201
+ const SHADOW_MARK: &str = "\u{0}shadow";
1202
+
1198
1203
  fn build(src: &Source) -> An {
1199
1204
  let mut units: Vec<Unit> = Vec::new();
1200
1205
  let mut enums: HashMap<String, Vec<String>> = HashMap::new();
@@ -1278,11 +1283,32 @@ fn build(src: &Source) -> An {
1278
1283
  }),
1279
1284
  }
1280
1285
  }
1286
+ // A fn-typed parameter named like a free fn (`keep` in `find(self, keep: fn(T) -> Bool)`)
1287
+ // shadows that fn in the whole body: its `keep(h)` is a closure call, not a call of the free
1288
+ // fn `keep`. Only that body is affected, so rename the name there to one nothing defines
1289
+ // (every call and use then reads as an unknown closure); the free fn stays resolvable.
1290
+ for u in &mut units {
1291
+ let shadow: HashSet<String> =
1292
+ u.params.iter().filter(|p| !p.plain && nameCount.contains_key(&p.name)).map(|p| p.name.clone()).collect();
1293
+ if shadow.is_empty() {
1294
+ continue;
1295
+ }
1296
+ let mark = |n: &mut String| {
1297
+ if shadow.contains(n.as_str()) {
1298
+ n.push_str(SHADOW_MARK);
1299
+ }
1300
+ };
1301
+ renameStmts(&mut u.block.stmts, &mut |n, _| mark(n));
1302
+ mutBlock(&mut u.block, &mut |e| {
1303
+ if let ExprKind::FnCall(c) = &mut e.kind {
1304
+ mark(&mut c.name);
1305
+ }
1306
+ });
1307
+ }
1281
- // A local, parameter, closure parameter or pattern binder named like a free fn shadows it:
1308
+ // A local, closure parameter or pattern binder named like a free fn shadows it: a call
1282
- // a call `f(..)` may then be a closure call, so such names are not resolvable.
1309
+ // `f(..)` may then be a closure call, so such names are not resolvable.
1283
1310
  let mut bound: HashSet<String> = HashSet::new();
1284
1311
  for u in &units {
1285
- bound.extend(u.params.iter().filter(|p| !p.plain).map(|p| p.name.clone()));
1286
1312
  let pats = |ps: &[CasePattern], bound: &mut HashSet<String>| {
1287
1313
  let mut names = vec![];
1288
1314
  ps.iter().for_each(|p| crate::visit::patternBinders(p, &mut names));
compiler/core/tests/core/closure_spec_test.rs CHANGED
@@ -239,6 +239,16 @@ fn cap_eight_copies() {
239
239
  assert_eq!(runInt("cap8", &src), 195);
240
240
  }
241
241
 
242
+ #[test]
243
+ fn block_closure_is_inlined() {
244
+ let src = withHead(
245
+ "fun main() -> Int =\n xs := [1, 2, 3, 4]\n k := 10\n y := 1000\n r := xs.fold(0, |a, x|\n y := x * k\n a + y\n )\n return r + y\n",
246
+ );
247
+ let names = copies("block_closure", &src);
248
+ assert!(names.contains(&"List.fold$c0".to_string()), "{names:?}");
249
+ assert_eq!(runInt("block_closure", &src), 1100);
250
+ }
251
+
242
252
  #[test]
243
253
  fn results_equal_original() {
244
254
  let src = withHead(
compiler/core/tests/core/loader_test.rs CHANGED
@@ -620,6 +620,33 @@ fn userTypeShadowsStdTypeOnlyWhenNotImportedDirectly() {
620
620
  assert!(err.contains("duplicate declaration 'enum::Pair'"), "{err}");
621
621
  }
622
622
 
623
+ fn fnNames(merged: &plum_core::ast::Source) -> Vec<String> {
624
+ merged
625
+ .items
626
+ .iter()
627
+ .filter_map(|i| match i {
628
+ plum_core::ast::Item::Fn(f) => Some(f.name.clone()),
629
+ _ => None,
630
+ })
631
+ .collect()
632
+ }
633
+
634
+ /// F-T8-2: a user function may share a name with a std function (`repeatUntil` in
635
+ /// std/Int). The user keeps the plain name, std's is renamed; an export keeps it too.
636
+ #[test]
637
+ fn userFunctionMaySharePlainNameWithStdFunction() {
638
+ let plain = "import std/Int\n\nfun repeatUntil(n: Int) -> Int =\n n\n\nfun main() -> Int =\n repeatUntil(1)\n";
639
+ let merged = plum_test_support::load("user_shares_std_name", plain).expect("user fn shares a std name");
640
+ let names = fnNames(&merged);
641
+ assert!(names.contains(&"repeatUntil".to_string()), "{names:?}");
642
+ assert!(names.iter().any(|n| n.starts_with("repeatUntil@")), "{names:?}");
643
+ let exported = "import std/Int\n\nexport fun repeatUntil(n: Int) -> Int =\n n\n\nfun main() -> Int =\n repeatUntil(1)\n";
644
+ let merged = plum_test_support::load("export_shares_std_name", exported).expect("export shares a std name");
645
+ let names = fnNames(&merged);
646
+ assert!(names.contains(&"repeatUntil".to_string()), "{names:?}");
647
+ assert!(names.iter().any(|n| n.starts_with("repeatUntil@")), "{names:?}");
648
+ }
649
+
623
650
  #[test]
624
651
  fn std_means_under_the_lib_path_std_dir_only() {
625
652
  let lib = tempfile::tempdir().unwrap();
compiler/tooling/tree-sitter-plum/test/corpus/closure_match_arg.txt CHANGED
@@ -73,3 +73,75 @@ fun f() -> Int =
73
73
  (expression
74
74
  (primary_expression
75
75
  (integer))))))
76
+
77
+ ================================================================================
78
+ block closure bodies
79
+ ================================================================================
80
+
81
+ fun main() =
82
+ total := xs.fold(0, |acc, x|
83
+ y := x * 2
84
+ acc + y
85
+ )
86
+ xs.each(|x|
87
+ f(x)
88
+ )
89
+
90
+ --------------------------------------------------------------------------------
91
+
92
+ (source
93
+ (fn
94
+ (fn_identifier)
95
+ (body
96
+ (assign
97
+ (var_identifier)
98
+ (expression
99
+ (primary_expression
100
+ (attribute
101
+ (primary_expression
102
+ (var_identifier))
103
+ (fn_identifier)
104
+ (fn_argument_list
105
+ (expression
106
+ (primary_expression
107
+ (integer)))
108
+ (expression
109
+ (closure
110
+ (var_identifier)
111
+ (var_identifier)
112
+ (body
113
+ (assign
114
+ (var_identifier)
115
+ (expression
116
+ (primary_expression
117
+ (binary_operator
118
+ (primary_expression
119
+ (var_identifier))
120
+ (primary_expression
121
+ (integer))))))
122
+ (expression
123
+ (primary_expression
124
+ (binary_operator
125
+ (primary_expression
126
+ (var_identifier))
127
+ (primary_expression
128
+ (var_identifier)))))))))))))
129
+ (expression
130
+ (primary_expression
131
+ (attribute
132
+ (primary_expression
133
+ (var_identifier))
134
+ (fn_identifier)
135
+ (fn_argument_list
136
+ (expression
137
+ (closure
138
+ (var_identifier)
139
+ (body
140
+ (expression
141
+ (primary_expression
142
+ (fn_call
143
+ (var_identifier)
144
+ (fn_argument_list
145
+ (expression
146
+ (primary_expression
147
+ (var_identifier)))))))))))))))))
std/Int.plum CHANGED
@@ -258,14 +258,6 @@ fun repeatUntil[S](s: S, done: fn(S) -> Bool, step: fn(S) -> S) -> S =
258
258
  else
259
259
  repeatUntil(step(s), done, step)
260
260
 
261
- # Test helper: counts its calls in `calls[0]`, then compares.
262
- fun countedIs(calls: Array[Int], x: Int, want: Int) -> Bool =
263
- calls.set(0, calls.get(0) + 1)
264
- x == want
265
-
266
- fun bump(calls: Array[Int], x: Int) -> Unit =
267
- calls.set(0, calls.get(0) + 1)
268
-
269
261
  test "range fold, each, find"
270
262
  assert 1.to(10).fold(0, |a, x| a + x) == 55
271
263
  assert 5.until(5).fold(7, |a, x| a + x) == 7
@@ -277,12 +269,17 @@ test "range fold, each, find, repeatUntil run a million iterations"
277
269
  assert 0.until(1000000).fold(0, |a, x| a + 1) == 1000000
278
270
  assert 0.until(1000000).find(|x| x == 999999).unwrapOr(-1) == 999999
279
271
  calls := Array.filled(1, 0)
280
- 0.until(1000000).each(|x| bump(calls, x))
272
+ 0.until(1000000).each(|x|
273
+ calls.set(0, calls.get(0) + 1)
274
+ )
281
275
  assert calls.get(0) == 1000000
282
276
  assert repeatUntil(0, |n| n >= 1000000, |n| n + 1) == 1000000
283
277
 
284
278
  test "range find exits early"
285
279
  calls := Array.filled(1, 0)
286
- r := 0.until(1000000).find(|x| countedIs(calls, x, 3))
280
+ r := 0.until(1000000).find(|x|
281
+ calls.set(0, calls.get(0) + 1)
282
+ x == 3
283
+ )
287
284
  assert r.unwrapOr(-1) == 3
288
285
  assert calls.get(0) == 4
std/List.plum CHANGED
@@ -129,14 +129,6 @@ fun mapCells[A, B](xs: List[A], f: fn(A) -> B) -> List[B] = match xs
129
129
  Nil => Nil
130
130
  Cons(h, t) => Cons(head: f(h), tail: mapCells(t, f))
131
131
 
132
- # Test helper: counts its calls in `calls[0]`, then compares.
133
- fun countedIs(calls: Array[Int], x: Int, want: Int) -> Bool =
134
- calls.set(0, calls.get(0) + 1)
135
- x == want
136
-
137
- fun bump(calls: Array[Int], x: Int) -> Unit =
138
- calls.set(0, calls.get(0) + 1)
139
-
140
132
  test "filter_million_constant_stack"
141
133
  xs: List[Int] := Nil
142
134
  i := 1000000
@@ -151,10 +143,16 @@ test "list fold, each, find: a million elements, find exits early"
151
143
  xs := 1.to(1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
152
144
  assert xs.fold(0, |a, x| a + 1) == 1000000
153
145
  calls := Array.filled(1, 0)
154
- xs.each(|x| bump(calls, x))
146
+ xs.each(|x|
147
+ calls.set(0, calls.get(0) + 1)
148
+ )
155
149
  assert calls.get(0) == 1000000
156
150
  assert xs.find(|x| x == 1).unwrapOr(-1) == 1
157
151
  assert xs.find(|x| x < 0).isNone()
158
152
  hits := Array.filled(1, 0)
153
+ found := xs.find(|x|
154
+ hits.set(0, hits.get(0) + 1)
155
+ x == 999998
156
+ )
159
- assert xs.find(|x| countedIs(hits, x, 999998)).unwrapOr(-1) == 999998
157
+ assert found.unwrapOr(-1) == 999998
160
158
  assert hits.get(0) == 3
tests/syntax/block_closures.plum ADDED
@@ -0,0 +1,140 @@
1
+ # Block-bodied closures: an indented body after `|params|`, the last expression is the value.
2
+ import std/Int
3
+ import std/List
4
+ import std/Str
5
+ import std/Option
6
+
7
+ struct Acc(total: Int, count: Int)
8
+
9
+ struct Tally(mut n: Int)
10
+
11
+ fun sumDoubled(n: Int) -> Int =
12
+ 1.to(n).fold(0, |acc, x|
13
+ y := x * 2
14
+ acc + y
15
+ )
16
+
17
+ # Local names reuse outer names: `y` and `acc` exist outside too.
18
+ fun shadow(n: Int) -> Int =
19
+ y := 1000
20
+ acc := 5
21
+ r := 1.to(n).fold(0, |acc, x|
22
+ y := x + 1
23
+ acc + y
24
+ )
25
+ r + y + acc
26
+
27
+ # Two closures in one function with the same local names.
28
+ fun twoClosures(n: Int) -> Int =
29
+ a := 1.to(n).fold(0, |acc, x|
30
+ t := x * 3
31
+ u := t + 1
32
+ acc + u
33
+ )
34
+ b := 1.to(n).fold(0, |acc, x|
35
+ t := x * 5
36
+ u := t - 1
37
+ acc + u
38
+ )
39
+ a * 1000 + b
40
+
41
+ fun classify(n: Int) -> Int =
42
+ 1.to(n).fold(0, |acc, x|
43
+ match x % 3
44
+ 0 => acc + 100
45
+ 1 => acc + 10
46
+ _ => acc + 1
47
+ )
48
+
49
+ fun branches(n: Int) -> Int =
50
+ 1.to(n).fold(0, |acc, x|
51
+ d := x * x
52
+ if d % 2 == 0
53
+ acc + d
54
+ else
55
+ acc - 1
56
+ )
57
+
58
+ # Nested block closures.
59
+ fun nested(n: Int) -> Int =
60
+ 1.to(n).fold(0, |acc, x|
61
+ inner := 1.to(x).fold(0, |a, z|
62
+ w := z * x
63
+ a + w
64
+ )
65
+ acc + inner
66
+ )
67
+
68
+ # A captured value is copied at creation.
69
+ fun captured() -> Int =
70
+ k := 10
71
+ f := |x|
72
+ y := x + k
73
+ y * 2
74
+ k = 99
75
+ f(1)
76
+
77
+ fun stored() -> Int =
78
+ f := |a, b|
79
+ s := a + b
80
+ s * s
81
+ f(1, 2) + f(3, 4)
82
+
83
+ fun record(n: Int) -> Int =
84
+ r := 1.to(n).fold(Acc(total: 0, count: 0), |acc, x|
85
+ t := acc.total + x
86
+ Acc(total: t, count: acc.count + 1)
87
+ )
88
+ r.total * 100 + r.count
89
+
90
+ fun eachSum(n: Int) -> Int =
91
+ t := Tally(n: 0)
92
+ 1.to(n).each(|x|
93
+ y := x * 2
94
+ t.n = t.n + y
95
+ )
96
+ t.n
97
+
98
+ fun big() -> Int =
99
+ 0.until(1000000).fold(0, |acc, x|
100
+ y := x % 7
101
+ acc + y
102
+ )
103
+
104
+ fun mapped(xs: List[Int]) -> List[Int] =
105
+ xs.map(|x|
106
+ d := x * 2
107
+ d + 1
108
+ )
109
+
110
+ test "fold with a block body"
111
+ assert sumDoubled(10) == 110
112
+ assert sumDoubled(0) == 0
113
+
114
+ test "locals reuse outer names"
115
+ assert shadow(3) == 1014
116
+ assert twoClosures(3) == 21027
117
+
118
+ test "last expression is match or if"
119
+ assert classify(6) == 222
120
+ assert branches(4) == 18
121
+
122
+ test "nested"
123
+ assert nested(3) == 25
124
+
125
+ test "captured and stored"
126
+ assert captured() == 22
127
+ assert stored() == 58
128
+
129
+ test "record accumulator"
130
+ assert record(4) == 1004
131
+
132
+ test "each"
133
+ assert eachSum(4) == 20
134
+
135
+ test "list map"
136
+ r := mapped(Cons(head: 1, tail: Cons(head: 2, tail: Nil)))
137
+ assert r.fold(0, |a, x| a * 10 + x) == 35
138
+
139
+ test "one million iterations"
140
+ assert big() == 2999997