plum

#treesitter#compiler#wasm

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

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


c450bb9 — Peter John 2026-11-13T21:26:27+05:30
list literal items and `Range` statics: an item of a list literal is a value, a spread `..xs` (a `List`, an `Option`: its value or nothing, a `Range`) or a conditional item `if c then x` / `if c then ..xs` (added only when `c` holds; the condition may bind, `if Some(v) := o then v`; `if c then x else y` stays one value); no `for` item (spread a `map`); grammar: `spread_argument` and a new `list_if` in `list_literal` (format and corpus too); the parser lowers the items (core/list_items.rs) so the literal is built once from the back, items running left to right: a value is `Cons(head: x, tail: rest)`, a spread `xs.spreadOnto(rest)` (std: `List.spreadOnto` copies its cells with the TRMC loop `appendCells` and returns the list itself when `rest` is empty, so a spread that ends a literal is shared; `Option.spreadOnto`, `Range.spreadOnto`), an `if` item that ends the literal `if c then Cons(x, Nil) else Nil`, one whose item and rest are all plain (no call) binds the rest once (`{ __li1 := rest; if c then Cons(x, __li1) else __li1 }`), else it runs first as an `Option` (`(if c then Some(x) else None).spreadOnto(rest)`; `if c then ..xs` binds `Some(xs)` and matches); checker: a covariant receiver widens to its expected result when its arguments fail (`..self.rings` then a `Label` in a `List<View>` literal: `rings.spreadOnto(..)` is checked as a `List<View>`'s and the receiver upcast; `widenReceiverTo`); in orbitrunner's view fusion merges several upcasts into the spread loops (`appendCells$__upcast4`, `spreadOnto$__upcast3`), the others are an upcast then a copy; `Range.until(start, end)`, `Range.to(start, end)` and `Range.downTo(start, end)` are statics of std's `struct Range` and the `Int.until`/`Int.to`/`Int.downTo` methods are gone (246 callers converted: std, examples, tests, benchmarks, fixtures, Rust inline programs, docs; Map's and Set's own `until` untouched); `Range.map` (a `List`, TRMC); std/Int and std/Option import std/collections/List, so a program with std/Int has `List` (the import hint for a list literal is tested on a program with std/App only); no pass matched on the method's name: benchmarks/ranges/range_fold.plum, 20 passes of 10,000,000, fold 0.92 s before and 0.89 s after, `for` 1.35 s and 1.36 s; views as one literal each: orbitrunner's play (`starsFrom`/`lifeIcons` are `..Range.until(0, Star.Count).map(..)`/`..Range.until(0, self.lives).map(..)`, `Star.Count`), balloonpop's playground (`sky` inlined, `if self.partying() then ..self.party()`, `confettiFrom` is `confetto` mapped over `Range.until(0, PlaygroundScreen.Confetti)`), std/game's test view `Viewed`, the web-test stress fixture (`rangeLink` gone); tests: tests/syntax/list_items.plum (each item form, nesting, empty spreads, `Option`/`Range` spreads, binds, order around effects and plain items, covariant spreads, a 100,000-item spread) in all three modes; trmc tests look at the program's own `filter`/`map` (std's `List` is now loaded with std/Int), two match codegen tests compile without fusion (it now folds their constant calls into `main`), the LSP test completes `Range.` statics; docs: language.md (list literal items, the ranges, Coercion's sample and receiver rule), game.md (the view as one literal)
Files changed (109) hide show
  1. benchmarks/ranges/range_fold.plum +33 -0
  2. benchmarks/screen_views/orbit.plum +1 -1
  3. benchmarks/screen_views/scale.plum +3 -3
  4. compiler/checker/src/infer.rs +9 -0
  5. compiler/checker/src/upcasts.rs +36 -0
  6. compiler/checker/tests/checker/features/review_fixes.rs +5 -1
  7. compiler/checker/tests/checker/fip_test.rs +3 -3
  8. compiler/cli/tests/cli/fusion_agree_test.rs +8 -8
  9. compiler/cli/tests/cli/no_fbip_test.rs +1 -1
  10. compiler/core/src/lib.rs +1 -0
  11. compiler/core/src/list_items.rs +197 -0
  12. compiler/core/src/parser.rs +32 -22
  13. compiler/core/tests/core/trmc_test.rs +19 -4
  14. compiler/game/web-test/fixtures/stress_state_view.plum +12 -12
  15. compiler/lsp/src/main.rs +14 -13
  16. compiler/tooling/tree-sitter-plum/grammar.js +17 -2
  17. compiler/tooling/tree-sitter-plum/queries/plum/format.scm +7 -0
  18. compiler/tooling/tree-sitter-plum/src/grammar.json +0 -0
  19. compiler/tooling/tree-sitter-plum/src/node-types.json +0 -0
  20. compiler/tooling/tree-sitter-plum/src/parser.c +0 -0
  21. compiler/tooling/tree-sitter-plum/test/corpus/list_literal.txt +72 -0
  22. compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +4 -1
  23. compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs +4 -1
  24. docs/game.md +14 -14
  25. docs/imperative-vs-functional.md +1 -1
  26. docs/language.md +27 -5
  27. examples/arrays.plum +3 -3
  28. examples/control_flow.plum +2 -2
  29. examples/games/balloonpop/screens/PlaygroundScreen.plum +23 -28
  30. examples/games/game_loop.plum +1 -1
  31. examples/games/orbitrunner/actors/Star.plum +2 -0
  32. examples/games/orbitrunner/screens/PlayingScreen.plum +15 -23
  33. examples/generics.plum +1 -1
  34. examples/maps.plum +1 -1
  35. examples/sequences.plum +3 -3
  36. examples/structs_records.plum +1 -1
  37. std/Int.plum +33 -16
  38. std/Option.plum +6 -0
  39. std/Slice.plum +3 -3
  40. std/collections/Deque.plum +2 -2
  41. std/collections/List.plum +11 -0
  42. std/collections/Map.plum +1 -1
  43. std/collections/Set.plum +1 -1
  44. std/game/Game.plum +2 -2
  45. std/game/ScreenSlice.plum +1 -1
  46. std/game/TestRig.plum +2 -2
  47. std/game/Tween.plum +1 -1
  48. tests/benchmarks/screen_views/orbit.plum +2 -2
  49. tests/core/type_param_names.plum +1 -1
  50. tests/examples/arrays.plum +1 -1
  51. tests/examples/control_flow.plum +11 -11
  52. tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +6 -6
  53. tests/examples/games/game_loop.plum +2 -2
  54. tests/examples/games/orbitrunner/actors/Ship.plum +4 -4
  55. tests/examples/games/orbitrunner/actors/Star.plum +2 -2
  56. tests/examples/games/orbitrunner/screens/PlayingScreen.plum +4 -4
  57. tests/examples/generics.plum +1 -1
  58. tests/examples/sequences.plum +3 -3
  59. tests/examples/unions.plum +2 -2
  60. tests/fbip/aliasing.plum +5 -5
  61. tests/fbip/fuzz/gen.pl +6 -6
  62. tests/fbip/last_use_moves.plum +2 -2
  63. tests/fbip/map_persistence/snapshot.plum +1 -1
  64. tests/fbip/moves_into_fields.plum +4 -4
  65. tests/fbip/receiver_stamps.plum +1 -1
  66. tests/fbip/slice_shapes.plum +4 -4
  67. tests/fbip_probes/array_set.plum +1 -1
  68. tests/fbip_probes/map_set_get.plum +2 -2
  69. tests/fbip_probes/struct_spread.plum +1 -1
  70. tests/param_defaults.plum +1 -1
  71. tests/port/game/determinism.plum +3 -3
  72. tests/port/game/replay.plum +2 -2
  73. tests/port/game/routing.plum +1 -1
  74. tests/port/game/screens.plum +1 -1
  75. tests/std/Decimal.plum +1 -1
  76. tests/std/Int.plum +14 -14
  77. tests/std/Slice.plum +1 -1
  78. tests/std/base64.plum +2 -2
  79. tests/std/collections.plum +3 -3
  80. tests/std/collections/BPlusTree.plum +6 -6
  81. tests/std/collections/BTree.plum +7 -7
  82. tests/std/collections/Bvh.plum +5 -5
  83. tests/std/collections/FenwickTree.plum +3 -3
  84. tests/std/collections/Hamt.plum +5 -5
  85. tests/std/collections/Heap.plum +3 -3
  86. tests/std/collections/IntervalTree.plum +2 -2
  87. tests/std/collections/KdTree.plum +4 -4
  88. tests/std/collections/LeftistHeap.plum +2 -2
  89. tests/std/collections/List.plum +4 -4
  90. tests/std/collections/Map.plum +7 -7
  91. tests/std/collections/PairingHeap.plum +2 -2
  92. tests/std/collections/Quadtree.plum +5 -5
  93. tests/std/collections/RadixTree.plum +1 -1
  94. tests/std/collections/SegmentTree.plum +3 -3
  95. tests/std/collections/Set.plum +2 -2
  96. tests/std/collections/Trie.plum +1 -1
  97. tests/std/collections/UnionFind.plum +6 -6
  98. tests/std/encoding/Json.plum +2 -2
  99. tests/std/game/History.plum +1 -1
  100. tests/std/game/Input.plum +1 -1
  101. tests/std/game/Screen.plum +1 -1
  102. tests/std/game/Tween.plum +2 -2
  103. tests/std/game/View.plum +6 -6
  104. tests/std/map_model.plum +2 -2
  105. tests/std/math/Random.plum +3 -3
  106. tests/std/slice_sort.plum +1 -1
  107. tests/syntax/block_closures.plum +11 -11
  108. tests/syntax/list_items.plum +151 -0
  109. tests/wasm_codegen/e2e_types/user_type_shadows_std_pair_imported_by_std.plum +1 -1
benchmarks/ranges/range_fold.plum ADDED
@@ -0,0 +1,33 @@
1
+ # A range fold, a `for` over a range and a range mapped to a list, written with the
2
+ # `Range.until` static: `plum build benchmarks/ranges/range_fold.plum -o /tmp/rf`, then time
3
+ # `/tmp/rf fold`, `/tmp/rf for` and `/tmp/rf map` (process CPU time).
4
+ #
5
+ # 2026-11-13, debug compiler, wasmtime, 20 passes of 10,000,000: the `Int.until` method the
6
+ # static replaced (`0.until(n)`, built with the compiler before) took the same time: `fold`
7
+ # 0.92 s before, 0.89 s after; `for` 1.35 s before, 1.36 s after (no pass matches on the
8
+ # method's name). `map` (new with the static, 20 passes of 1,000,000) takes 0.01 s: fusion
9
+ # folds the mapped list away.
10
+ import std/Io
11
+ import std/Int
12
+ import std/Str
13
+ import std/Slice
14
+ import std/App
15
+ import std/collections/List
16
+
17
+ struct Acc(mut n: Int)
18
+
19
+ primitive RangeFold[App] =
20
+ fun main(io: Io) =
21
+ mode := io.args().at(0)
22
+ a := Acc(n: 0)
23
+ if mode == "fold"
24
+ for r := range 20
25
+ a.n = a.n + Range.until(0, 10000000).fold(r, |s, i| s + i % 7)
26
+ else if mode == "for"
27
+ for r := range 20
28
+ for i := range Range.until(0, 10000000)
29
+ a.n = a.n + i % 7
30
+ else
31
+ for r := range 20
32
+ a.n = a.n + Range.until(0, 1000000).map(|i| i % 7).fold(0, |s, i| s + i)
33
+ io.printLn(a.n.toStr())
benchmarks/screen_views/orbit.plum CHANGED
@@ -60,7 +60,7 @@ primitive OrbitBench[App] =
60
60
  next
61
61
 
62
62
  fun play(io: Io, seed: Int, paint: Bool, ticks: Int) -> Int =
63
- g := 0.until(ticks).fold(gameOf(seed), |cur, t| tickOnce(io, cur, Timing.script(seed, t), paint))
63
+ g := Range.until(0, ticks).fold(gameOf(seed), |cur, t| tickOnce(io, cur, Timing.script(seed, t), paint))
64
64
  Timing.hash([state(playingOf(g)), 0])
65
65
 
66
66
  fun main(io: Io) =
benchmarks/screen_views/scale.plum CHANGED
@@ -73,16 +73,16 @@ primitive ScaleBench[App] =
73
73
  # `ticks` ticks of `s` on an 800 by 600 screen, with no host (a test's).
74
74
  fun run(io: Io, s: CrowdScreen, ticks: Int) -> CrowdScreen =
75
75
  only: Screen := s
76
- crowdOf(0.until(ticks).fold(Game(screens: [only]), |g, t| g.step(io, Input.create(), Clock.Tick, Vec2(x: 800.0, y: 600.0))))
76
+ crowdOf(Range.until(0, ticks).fold(Game(screens: [only]), |g, t| g.step(io, Input.create(), Clock.Tick, Vec2(x: 800.0, y: 600.0))))
77
77
 
78
78
  fun main(io: Io) =
79
79
  args := io.args()
80
80
  paint := args.length() > 0 && args.at(0) == "paint"
81
81
  hand := args.length() > 1 && args.at(1) == "hand"
82
82
  only: Screen := CrowdScreen.of(hand, ScaleBench.Count)
83
- warm := 0.until(20).fold(Game(screens: [only]), |g, t| ScaleBench.tickOnce(io, g, paint))
83
+ warm := Range.until(0, 20).fold(Game(screens: [only]), |g, t| ScaleBench.tickOnce(io, g, paint))
84
84
  t0 := io.nowMicros()
85
- done := 0.until(200).fold(warm, |g, t| ScaleBench.tickOnce(io, g, paint))
85
+ done := Range.until(0, 200).fold(warm, |g, t| ScaleBench.tickOnce(io, g, paint))
86
86
  total := io.nowMicros() - t0
87
87
  io.printLn("us {Int(total)} ticks 200 checksum {ScaleBench.crowdOf(done).frameSum()}")
88
88
 
compiler/checker/src/infer.rs CHANGED
@@ -824,6 +824,15 @@ pub(crate) fn inferExprInner(
824
824
  checkStaticUse(&attr.object, &obj_ty, &call.name, ctx)?;
825
825
  let r = inferMethodCallWith(&obj_ty, call.name.as_str(), &call.args, &call.type_args, env, ctx, expected);
826
826
  if r.is_err() {
827
+ // `ring.spreadOnto(rest)` on a `List<Ring>` where a `List<View>` is
828
+ // expected: the receiver widens to what the result must be.
829
+ if let Some(wider) = expected.and_then(|want| widenReceiverTo(&obj_ty, call, want, ctx)) {
830
+ if let Ok(t) = inferMethodCallWith(&wider, call.name.as_str(), &call.args, &call.type_args, env, ctx, expected) {
831
+ if tryUpcast(&wider, &obj_ty, &attr.object) {
832
+ return Ok(t);
833
+ }
834
+ }
835
+ }
827
836
  // `back.append(views)` on a `List<Box>`: the receiver widens to the
828
837
  // join (`List<View>`) and is upcast there.
829
838
  if let Some(wider) = widenReceiver(&obj_ty, call, env, ctx) {
compiler/checker/src/upcasts.rs CHANGED
@@ -133,6 +133,42 @@ pub(crate) fn widenReceiver(obj_ty: &PlumType, call: &ast::FnCall, env: &TypeEnv
133
133
  changed.then(|| PlumType::TApp(n.clone(), widened))
134
134
  }
135
135
 
136
+ /// `xs.spreadOnto(rest)` on a `List<Ring>` where a `List<View>` is expected (a list literal's
137
+ /// spread): the receiver of a method of a covariant container, widened so the method's result
138
+ /// is the expected type, when each of its arguments widens to what that asks (`Ring` is a
139
+ /// `View`). `None` when the result says nothing wider.
140
+ pub(crate) fn widenReceiverTo(obj_ty: &PlumType, call: &ast::FnCall, expected: &PlumType, ctx: &CheckCtx) -> Option<PlumType> {
141
+ let obj = resolveRecorded(obj_ty);
142
+ let PlumType::TApp(n, targs) = &obj else { return None };
143
+ let want = resolveRecorded(expected);
144
+ if !isCovariant(n) || !closed(&obj) || !closed(&want) {
145
+ return None;
146
+ }
147
+ let sig = ctx.methods.get(&(n.clone(), call.name.clone()))?;
148
+ let gens = enumGenericsOf(n, ctx).to_vec();
149
+ if gens.len() != targs.len() {
150
+ return None;
151
+ }
152
+ let vars: Vec<PlumType> = gens.iter().map(|_| freshVar()).collect();
153
+ let owner: BTreeMap<String, PlumType> = gens.iter().cloned().zip(vars.iter().cloned()).collect();
154
+ let PlumType::TFun(_, ret) = instSig(sig, &owner) else { return None };
155
+ let mut binds = Binds::new();
156
+ bindMatch(&ret, &want, &mut binds);
157
+ let mut widened = Vec::new();
158
+ for (v, a) in vars.iter().zip(targs) {
159
+ let b = resolveRecorded(&substVars(v, &binds));
160
+ if !closed(&b) {
161
+ widened.push(a.clone());
162
+ } else if &b == a || elemUpcast(&b, a) {
163
+ widened.push(b);
164
+ } else {
165
+ return None;
166
+ }
167
+ }
168
+ let wider = PlumType::TApp(n.clone(), widened);
169
+ (wider != obj).then_some(wider)
170
+ }
171
+
136
172
  /// The type a value of `a` and a value of `b` both are: the same type, a trait object one of
137
173
  /// them is and the other implements, else the most specific trait they share (`Mine` and
138
174
  /// `Orb`, both `Actor`s and so `View`s, join at `Actor`). When several are (`Box` and
compiler/checker/tests/checker/features/review_fixes.rs CHANGED
@@ -211,6 +211,10 @@ fn failingCompareInATestIsAtTheAssert() {
211
211
 
212
212
  #[test]
213
213
  fn listLiteralWithoutStdListSaysToImportIt() {
214
+ // Only std/App: std/Int (and so std/Option) imports std/collections/List, for `Range.map`
215
+ // and a list literal's spreads.
214
- let es = diags("primitive Main[App] =\n fun main() -> Int =\n xs := [1, 2]\n 1\n");
216
+ let (_dir, path) = write("import std/App\nprimitive Main[App] =\n fun main() =\n xs := [true, false]\n");
217
+ let source = plum_core::loader::loadAndMergeDiag(&path, &plum_test_support::repoRoot()).expect("loads");
218
+ let es = plum_driver::check(&source, &plum_driver::PassOptions::default()).expect_err("no List");
215
219
  assert!(es.iter().any(|e| e.message.contains("import std/collections/List")), "{es:?}");
216
220
  }
compiler/checker/tests/checker/fip_test.rs CHANGED
@@ -152,20 +152,20 @@ const FOLD_HEAD: &str = "struct Cl(label: Str, n: Int)\n";
152
152
  /// an argument never runs.
153
153
  #[test]
154
154
  fn a_fip_fun_called_from_a_specialised_closure_compiles() {
155
- let body = format!("{FOLD_HEAD}primitive Main =\n fip fun stepCl(c: Cl, i: Int) -> Cl = Cl(..c, n: c.n + i)\n\n fun run(k: Int) -> Cl = 0.until(k).fold(Cl(label: \"a\", n: 0), |acc, i| stepCl(acc, i))\n");
155
+ let body = format!("{FOLD_HEAD}primitive Main =\n fip fun stepCl(c: Cl, i: Int) -> Cl = Cl(..c, n: c.n + i)\n\n fun run(k: Int) -> Cl = Range.until(0, k).fold(Cl(label: \"a\", n: 0), |acc, i| stepCl(acc, i))\n");
156
156
  run("fip_fold_named", &body, &PassOptions::default()).expect("compiles");
157
157
  }
158
158
 
159
159
  #[test]
160
160
  fn a_spread_in_a_specialised_closure_of_a_fip_fun_compiles() {
161
- let body = format!("{FOLD_HEAD}primitive Main =\n fip fun run(k: Int) -> Cl = 0.until(k).fold(Cl(label: \"a\", n: 0), |acc, i| Cl(..acc, n: acc.n + i))\n");
161
+ let body = format!("{FOLD_HEAD}primitive Main =\n fip fun run(k: Int) -> Cl = Range.until(0, k).fold(Cl(label: \"a\", n: 0), |acc, i| Cl(..acc, n: acc.n + i))\n");
162
162
  run("fip_fold_spread", &body, &PassOptions::default()).expect("compiles");
163
163
  }
164
164
 
165
165
  /// The value folded over is read after the fold: its spread in the copy can't be in place.
166
166
  #[test]
167
167
  fn a_spread_in_a_specialised_closure_with_a_shared_seed_is_an_error() {
168
- let body = format!("{FOLD_HEAD}primitive Main =\n fip fun run(k: Int, s: Cl) -> Int =\n r := 0.until(k).fold(s, |acc, i| Cl(..acc, n: acc.n + i))\n r.n + s.n\n");
168
+ let body = format!("{FOLD_HEAD}primitive Main =\n fip fun run(k: Int, s: Cl) -> Int =\n r := Range.until(0, k).fold(s, |acc, i| Cl(..acc, n: acc.n + i))\n r.n + s.n\n");
169
169
  assert_eq!(errs("fip_fold_shared", &body).len(), 1);
170
170
  }
171
171
 
compiler/cli/tests/cli/fusion_agree_test.rs CHANGED
@@ -70,14 +70,14 @@ fn closureCopiesInTailPositionAgree() {
70
70
  ("list_find_body", "primitive Main[App] =\n fun big(xs: List<Int>) -> Option<Int> = xs.find(|x| x > 1)\n\n fun main() -> Int = Main.big([1, 2, 3]).unwrapOr(-1)\n", "2"),
71
71
  ("list_find_empty", "primitive Main[App] =\n fun big(xs: List<Int>) -> Option<Int> = xs.find(|x| x > 1)\n\n fun main() -> Int = Main.big([]).unwrapOr(-1)\n", "-1"),
72
72
  ("list_find_miss", "primitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3]\n xs.find(|x| x > 9).unwrapOr(-1)\n", "-1"),
73
- ("range_fold_tail", "primitive Main[App] =\n fun main() -> Int = 1.to(3).fold(0, |a, x| a + x)\n", "6"),
73
+ ("range_fold_tail", "primitive Main[App] =\n fun main() -> Int = Range.to(1, 3).fold(0, |a, x| a + x)\n", "6"),
74
- ("range_fold_body", "primitive Main[App] =\n fun sum(n: Int) -> Int = 0.until(n).fold(0, |a, x| a + x)\n\n fun main() -> Int = Main.sum(4)\n", "6"),
74
+ ("range_fold_body", "primitive Main[App] =\n fun sum(n: Int) -> Int = Range.until(0, n).fold(0, |a, x| a + x)\n\n fun main() -> Int = Main.sum(4)\n", "6"),
75
- ("range_fold_empty", "primitive Main[App] =\n fun main() -> Int = 5.until(5).fold(7, |a, x| a + x)\n", "7"),
75
+ ("range_fold_empty", "primitive Main[App] =\n fun main() -> Int = Range.until(5, 5).fold(7, |a, x| a + x)\n", "7"),
76
- ("range_each_tail", "primitive Main[App] =\n fun main(io: Io) = 1.to(2).each(|x| io.printLn(\"{x}\"))\n", "1\n2"),
76
+ ("range_each_tail", "primitive Main[App] =\n fun main(io: Io) = Range.to(1, 2).each(|x| io.printLn(\"{x}\"))\n", "1\n2"),
77
- ("range_each_empty", "primitive Main[App] =\n fun main(io: Io) = 5.until(5).each(|x| io.printLn(\"{x}\"))\n", ""),
77
+ ("range_each_empty", "primitive Main[App] =\n fun main(io: Io) = Range.until(5, 5).each(|x| io.printLn(\"{x}\"))\n", ""),
78
- ("range_find_tail", "primitive Main[App] =\n fun main() -> Int = 1.to(3).find(|x| x > 1).unwrapOr(-1)\n", "2"),
78
+ ("range_find_tail", "primitive Main[App] =\n fun main() -> Int = Range.to(1, 3).find(|x| x > 1).unwrapOr(-1)\n", "2"),
79
- ("range_find_body", "primitive Main[App] =\n fun big(n: Int) -> Option<Int> = 0.until(n).find(|x| x > 1)\n\n fun main() -> Int = Main.big(4).unwrapOr(-1)\n", "2"),
79
+ ("range_find_body", "primitive Main[App] =\n fun big(n: Int) -> Option<Int> = Range.until(0, n).find(|x| x > 1)\n\n fun main() -> Int = Main.big(4).unwrapOr(-1)\n", "2"),
80
- ("range_find_empty", "primitive Main[App] =\n fun big(n: Int) -> Option<Int> = 0.until(n).find(|x| x > 1)\n\n fun main() -> Int = Main.big(0).unwrapOr(-1)\n", "-1"),
80
+ ("range_find_empty", "primitive Main[App] =\n fun big(n: Int) -> Option<Int> = Range.until(0, n).find(|x| x > 1)\n\n fun main() -> Int = Main.big(0).unwrapOr(-1)\n", "-1"),
81
81
  ];
82
82
  let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
83
83
  let dir = crate::common::Scratch::at(std::env::temp_dir().join(format!("plum_tail_copies_{}", std::process::id())));
compiler/cli/tests/cli/no_fbip_test.rs CHANGED
@@ -11,7 +11,7 @@ fn plumBin() -> std::path::PathBuf {
11
11
  path
12
12
  }
13
13
 
14
- const SRC: &str = "import std/Int\nimport std/Str\nimport std/Io\nimport std/App\nstruct Cell(label: Str, n: Int)\n\nprimitive Src =\n fun bump(c: Cell) -> Cell = Cell(..c, n: c.n + 1)\n\nprimitive Main[App] =\n fun main(io: Io) =\n c := 0.until(10).fold(Cell(label: \"c\", n: 0), |cur, i| Src.bump(cur))\n io.printLn(\"{c.n}\")\n";
14
+ const SRC: &str = "import std/Int\nimport std/Str\nimport std/Io\nimport std/App\nstruct Cell(label: Str, n: Int)\n\nprimitive Src =\n fun bump(c: Cell) -> Cell = Cell(..c, n: c.n + 1)\n\nprimitive Main[App] =\n fun main(io: Io) =\n c := Range.until(0, 10).fold(Cell(label: \"c\", n: 0), |cur, i| Src.bump(cur))\n io.printLn(\"{c.n}\")\n";
15
15
 
16
16
  fn run(src: &std::path::Path, flags: &[&str]) -> (String, String) {
17
17
  let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
compiler/core/src/lib.rs CHANGED
@@ -19,6 +19,7 @@ pub mod forms;
19
19
  pub mod game_entry;
20
20
  pub mod generics;
21
21
  pub mod layout;
22
+ pub mod list_items;
22
23
  pub mod loader;
23
24
  pub mod lower;
24
25
  pub mod main_result;
compiler/core/src/list_items.rs ADDED
@@ -0,0 +1,197 @@
1
+ //! A list literal's items, lowered by the parser to plain expressions.
2
+ //!
3
+ //! An item is a value (`x`), a spread (`..xs`: every element of a `List`, the value of a
4
+ //! `Some`, nothing for `None`, the ints of a `Range`) or a conditional item (`if c then x`,
5
+ //! `if c then ..xs`: added only when `c` holds). `if c then x else y` is a value.
6
+ //!
7
+ //! The literal is built once, from the back, with no `append` chain: a value is
8
+ //! `Cons(head: x, tail: rest)`, a spread is `xs.spreadOnto(rest)` (each type that can be spread
9
+ //! has one: `List` copies its cells in front of `rest` with a TRMC loop and returns itself when
10
+ //! `rest` is empty, so a spread at the end shares the list). Items run left to right, as
11
+ //! written: in `Cons(head: x, tail: rest)` and in `xs.spreadOnto(rest)` the item runs before
12
+ //! `rest`. A conditional item needs `rest` in both branches, so `rest` is bound once:
13
+ //!
14
+ //! * when `rest` is `Nil` (the item is last) it is written twice: `if c then Cons(head: x, tail:
15
+ //! Nil) else Nil`;
16
+ //! * when the item and every item of `rest` are plain (no call: a variable, a field, a
17
+ //! literal, a constructor, an operator or an interpolation of those), nothing runs that
18
+ //! could tell the order: `{ __li1 := rest; if c then Cons(head: x, tail: __li1) else __li1 }`;
19
+ //! * else the item runs first as an `Option`: `(if c then Some(value: x) else None).spreadOnto(rest)`
20
+ //! (`if c then ..xs` binds `xs` in a `Some` the same way and spreads it in a `match`).
21
+ use crate::ast::*;
22
+
23
+ /// One item of a list literal.
24
+ pub enum ListItem {
25
+ Value(Expr),
26
+ Spread(Expr),
27
+ /// `if cond then item`: `item` is a `Value` or a `Spread`.
28
+ If(Expr, Box<ListItem>),
29
+ }
30
+
31
+ /// Whether running `e` can't be seen by other code: no call, no block, nothing that binds.
32
+ /// A constructor (`Label(..)`, `Some(v)`) builds a value; an interpolation calls `toStr`,
33
+ /// which is taken to be plain.
34
+ fn plain(e: &Expr) -> bool {
35
+ match &e.kind {
36
+ ExprKind::Int(_) | ExprKind::Float(_) | ExprKind::BoolLit(_) | ExprKind::Self_ | ExprKind::Var(_) | ExprKind::TypeName(_) => true,
37
+ ExprKind::Closure(_) => true,
38
+ ExprKind::String(s) => s.parts.iter().all(|p| match p {
39
+ StringPart::Text(_) => true,
40
+ StringPart::Interp(e) => plain(e),
41
+ }),
42
+ ExprKind::Binary(b) => plain(&b.left) && plain(&b.right),
43
+ ExprKind::Unary(u) => plain(&u.operand),
44
+ ExprKind::Bool(b) => plain(&b.left) && plain(&b.right),
45
+ ExprKind::Not(e) => plain(e),
46
+ ExprKind::Compare(c) => plain(&c.left) && plain(&c.right),
47
+ ExprKind::InlineIf(i) => plain(&i.condition) && plain(&i.then) && plain(&i.else_),
48
+ ExprKind::Attribute(a) => matches!(a.attr, AttrKind::Field(_)) && plain(&a.object),
49
+ ExprKind::ClassCall(c) => c.fields.iter().all(|f| plain(&f.value)) && c.spread.as_deref().is_none_or(plain),
50
+ ExprKind::FnCall(c) => {
51
+ c.name.chars().next().is_some_and(|ch| ch.is_ascii_uppercase())
52
+ && c.args.iter().all(|a| match a {
53
+ Arg::Positional(e) | Arg::Keyword { value: e, .. } => plain(e),
54
+ })
55
+ }
56
+ _ => false,
57
+ }
58
+ }
59
+
60
+ fn itemPlain(item: &ListItem) -> bool {
61
+ match item {
62
+ ListItem::Value(e) | ListItem::Spread(e) => plain(e),
63
+ ListItem::If(c, i) => plain(c) && itemPlain(i),
64
+ }
65
+ }
66
+
67
+ fn nil() -> Expr {
68
+ Expr::TypeName("Nil".to_string())
69
+ }
70
+
71
+ fn cons(head: Expr, tail: Expr) -> Expr {
72
+ Expr::ClassCall(ClassCall {
73
+ type_name: "Cons".to_string(),
74
+ fields: vec![FieldArg { name: "head".to_string(), value: head }, FieldArg { name: "tail".to_string(), value: tail }],
75
+ generics: vec![],
76
+ spread: None,
77
+ unique: false,
78
+ reuse: None,
79
+ reboxed: vec![],
80
+ })
81
+ }
82
+
83
+ fn spreadOnto(xs: Expr, rest: Expr, line: usize, column: usize) -> Expr {
84
+ Expr::Attribute(Box::new(AttributeExpr {
85
+ object: xs,
86
+ attr: AttrKind::Method(FnCall {
87
+ name: "spreadOnto".to_string(),
88
+ args: vec![Arg::Positional(rest)],
89
+ line,
90
+ column,
91
+ tail: TailKind::NotTail,
92
+ recv: None,
93
+ type_args: Vec::new(),
94
+ }),
95
+ }))
96
+ }
97
+
98
+ fn declare(name: &str, value: Expr) -> Stmt {
99
+ Stmt::Assign(Assign {
100
+ targets: vec![AssignTarget::Var(name.to_string())],
101
+ values: vec![value],
102
+ declare: true,
103
+ ty: None,
104
+ isSynthetic: false,
105
+ })
106
+ }
107
+
108
+ fn inlineIf(condition: Expr, then: Expr, else_: Expr) -> Expr {
109
+ Expr::InlineIf(Box::new(InlineIf { condition, then, else_ }))
110
+ }
111
+
112
+ fn block(stmts: Vec<Stmt>, value: Expr) -> Expr {
113
+ let mut stmts = stmts;
114
+ stmts.push(Stmt::Expr(value, 0, 0));
115
+ Expr::Block(Box::new(Block { stmts }))
116
+ }
117
+
118
+ /// `item` in front of `rest` (`item` is not an `If`).
119
+ fn front(item: ListItem, rest: Expr, line: usize, column: usize) -> Expr {
120
+ match item {
121
+ ListItem::Value(x) => cons(x, rest),
122
+ ListItem::Spread(xs) => spreadOnto(xs, rest, line, column),
123
+ ListItem::If(..) => unreachable!("an `if` item holds a value or a spread"),
124
+ }
125
+ }
126
+
127
+ /// The literal of `items`, built from the back. `fresh` names a temporary.
128
+ pub fn lower(items: Vec<ListItem>, line: usize, column: usize, fresh: &mut dyn FnMut() -> String) -> Expr {
129
+ // `restPlain[i]`: every item after `i` is plain.
130
+ let mut restPlain = vec![true; items.len()];
131
+ for i in (0..items.len().saturating_sub(1)).rev() {
132
+ restPlain[i] = restPlain[i + 1] && itemPlain(&items[i + 1]);
133
+ }
134
+ let mut out = nil();
135
+ let mut outIsNil = true;
136
+ for (i, item) in items.into_iter().enumerate().rev() {
137
+ out = match item {
138
+ ListItem::If(cond, inner) => {
139
+ if outIsNil {
140
+ inlineIf(cond, front(*inner, nil(), line, column), nil())
141
+ } else if restPlain[i] && plain(&cond) && itemPlain(&inner) {
142
+ let tmp = fresh();
143
+ let then = front(*inner, Expr::Var(tmp.clone()), line, column);
144
+ block(vec![declare(&tmp, out)], inlineIf(cond, then, Expr::Var(tmp)))
145
+ } else {
146
+ match *inner {
147
+ ListItem::Spread(xs) => {
148
+ // `{ __o := if c then Some(value: xs) else None; __r := rest; match __o .. }`
149
+ let (o, r, v) = (fresh(), fresh(), fresh());
150
+ let some = Expr::ClassCall(ClassCall {
151
+ type_name: "Some".to_string(),
152
+ fields: vec![FieldArg { name: "value".to_string(), value: xs }],
153
+ generics: vec![],
154
+ spread: None,
155
+ unique: false,
156
+ reuse: None,
157
+ reboxed: vec![],
158
+ });
159
+ let picked = inlineIf(
160
+ Expr::Bind(Box::new(BindExpr {
161
+ case: Case {
162
+ patterns: vec![CasePattern::Class { name: "Some".to_string(), fields: vec![CasePattern::Name(v.clone())], id: NodeId(0) }],
163
+ guard: None,
164
+ body: Block { stmts: vec![Stmt::Expr(Expr::BoolLit(true), 0, 0)] },
165
+ },
166
+ value: Expr::Var(o.clone()),
167
+ })),
168
+ spreadOnto(Expr::Var(v), Expr::Var(r.clone()), line, column),
169
+ Expr::Var(r.clone()),
170
+ );
171
+ block(
172
+ vec![declare(&o, inlineIf(cond, some, Expr::TypeName("None".to_string()))), declare(&r, out)],
173
+ picked,
174
+ )
175
+ }
176
+ other => {
177
+ let ListItem::Value(x) = other else { unreachable!("an `if` item holds a value or a spread") };
178
+ let some = Expr::ClassCall(ClassCall {
179
+ type_name: "Some".to_string(),
180
+ fields: vec![FieldArg { name: "value".to_string(), value: x }],
181
+ generics: vec![],
182
+ spread: None,
183
+ unique: false,
184
+ reuse: None,
185
+ reboxed: vec![],
186
+ });
187
+ spreadOnto(inlineIf(cond, some, Expr::TypeName("None".to_string())), out, line, column)
188
+ }
189
+ }
190
+ }
191
+ }
192
+ other => front(other, out, line, column),
193
+ };
194
+ outIsNil = false;
195
+ }
196
+ out
197
+ }
compiler/core/src/parser.rs CHANGED
@@ -8,6 +8,8 @@ pub struct AstParser<'a> {
8
8
  litErrors: std::cell::RefCell<Vec<(usize, usize, String)>>,
9
9
  /// Malformed nodes that got a placeholder instead of a real value.
10
10
  malformed: std::cell::RefCell<Vec<crate::diag::Diagnostic>>,
11
+ /// The last temporary a list literal's lowering named (`__li<n>`).
12
+ fresh: std::cell::Cell<usize>,
11
13
  }
12
14
 
13
15
  impl<'a> AstParser<'a> {
@@ -16,6 +18,7 @@ impl<'a> AstParser<'a> {
16
18
  source: source.as_bytes(),
17
19
  litErrors: std::cell::RefCell::new(Vec::new()),
18
20
  malformed: std::cell::RefCell::new(Vec::new()),
21
+ fresh: std::cell::Cell::new(0),
19
22
  }
20
23
  }
21
24
 
@@ -1586,10 +1589,10 @@ impl<'a> AstParser<'a> {
1586
1589
  Expr::Attribute(Box::new(AttributeExpr { object, attr }))
1587
1590
  }
1588
1591
 
1589
- /// list_literal: "[" (expression | pair_argument),* "]"
1592
+ /// list_literal: "[" (expression | pair_argument | spread_argument | list_if),* "]"
1590
1593
  ///
1591
1594
  /// Pure sugar: `[a, b]` is `Cons(head: a, tail: Cons(head: b, tail: Nil))`
1592
- /// (std's `List`), `[]` is `Nil`, and `[k => v, ..]` is
1595
+ /// (std's `List`), `[]` is `Nil`, spreads and `if` items are lowered by `list_items`, and `[k => v, ..]` is
1593
1596
  /// `Map.empty().with(k, v)...`. A
1594
1597
  /// literal mixing pairs and plain values is an error (reported through
1595
1598
  /// `Source::formErrors`, then parsed as if every element were a value).
@@ -1630,30 +1633,37 @@ impl<'a> AstParser<'a> {
1630
1633
  return out;
1631
1634
  }
1632
1635
  // Built back to front: `[a, b]` is `Cons(head: a, tail: Cons(head: b, tail: Nil))`.
1633
- let mut out = Expr::TypeName("Nil".to_string());
1634
1636
  if elems.is_empty() {
1635
1637
  // `[]`: a `Nil` whose span is the two brackets (see `ast::isEmptyListLiteral`).
1638
+ let mut out = Expr::TypeName("Nil".to_string());
1636
1639
  out.span = Span { startLine: line, startColumn: column, endLine: line, endColumn: column + 2 };
1640
+ return out;
1637
1641
  }
1642
+ let item = |e: Node| -> crate::list_items::ListItem {
1638
- for e in elems.into_iter().rev() {
1643
+ use crate::list_items::ListItem;
1644
+ let value = |name: &str| e.child_by_field_name(name).map(expr).unwrap_or_else(|| self.missing(e));
1639
- let value = match e.kind() {
1645
+ match e.kind() {
1640
- "pair_argument" => e.named_child(0).map(expr).unwrap_or_else(|| self.missing(node)),
1646
+ "pair_argument" => ListItem::Value(e.named_child(0).map(expr).unwrap_or_else(|| self.missing(node))),
1647
+ "spread_argument" => ListItem::Spread(value("value")),
1648
+ "list_if" => {
1649
+ let then = match e.child_by_field_name("then") {
1650
+ Some(t) if t.kind() == "spread_argument" => {
1651
+ ListItem::Spread(t.child_by_field_name("value").map(expr).unwrap_or_else(|| self.missing(t)))
1652
+ }
1641
- _ => expr(e),
1653
+ Some(t) => ListItem::Value(expr(t)),
1654
+ None => ListItem::Value(self.missing(e)),
1642
- };
1655
+ };
1643
- out = Expr::ClassCall(ClassCall {
1644
- type_name: "Cons".to_string(),
1656
+ ListItem::If(value("condition"), Box::new(then))
1645
- fields: vec![
1646
- FieldArg { name: "head".to_string(), value },
1647
- FieldArg { name: "tail".to_string(), value: out },
1648
- ],
1649
- generics: vec![],
1650
- spread: None,
1651
- unique: false,
1652
- reuse: None,
1653
- reboxed: vec![],
1654
- });
1655
- }
1657
+ }
1658
+ _ => ListItem::Value(expr(e)),
1659
+ }
1656
- out
1660
+ };
1661
+ let items = elems.into_iter().map(item).collect();
1662
+ crate::list_items::lower(items, line, column, &mut || {
1663
+ let n = self.fresh.get() + 1;
1664
+ self.fresh.set(n);
1665
+ format!("__li{n}")
1666
+ })
1657
1667
  }
1658
1668
 
1659
1669
  fn parseQuestionExpression(&self, node: Node) -> Expr {
compiler/core/tests/core/trmc_test.rs CHANGED
@@ -62,10 +62,18 @@ fn isRewritten(name: &str, src: &str, fnName: &str) -> bool {
62
62
  let source = load(name, src);
63
63
  let info = typedSource(&source).unwrap_or_else(|e| panic!("check: {e:?}"));
64
64
  let lowered = info.lowered.expect("lowered program");
65
+ // The program's own fn of that name, else std's (`List.filter`).
66
+ let named: Vec<&plum_core::ast::Fn> = lowered
67
+ .items
68
+ .iter()
65
- lowered.items.iter().any(|i| match i {
69
+ .filter_map(|i| match i {
66
- plum_core::ast::Item::Fn(f) if f.name == fnName => format!("{:?}", f.body).contains("__tc_acc"),
70
+ plum_core::ast::Item::Fn(f) if f.name == fnName => Some(f),
67
- _ => false,
71
+ _ => None,
68
- })
72
+ })
73
+ .collect();
74
+ let own: Vec<&&plum_core::ast::Fn> = named.iter().filter(|f| !fromStd(f)).collect();
75
+ let pick: Vec<&plum_core::ast::Fn> = if own.is_empty() { named.clone() } else { own.into_iter().copied().collect() };
76
+ pick.iter().any(|f| format!("{:?}", f.body).contains("__tc_acc"))
69
77
  }
70
78
 
71
79
  /// Direct unit check of the pass on a lowered program.
@@ -82,9 +90,16 @@ fn rewrittenNames(name: &str, src: &str) -> Vec<String> {
82
90
  plum_core::forms::finish(&s)
83
91
  };
84
92
  s = lowered;
93
+ // The test's own fns: std's `List` (loaded with std/Int) has a `filter` and a `map` too.
94
+ s.items.retain(|i| !matches!(i, plum_core::ast::Item::Fn(f) if fromStd(f)));
85
95
  plum_core::trmc::rewrite(&mut s)
86
96
  }
87
97
 
98
+ /// A fn of std (`List.filter`), not of the test program.
99
+ fn fromStd(f: &plum_core::ast::Fn) -> bool {
100
+ f.file.split('/').any(|seg| seg == "std")
101
+ }
102
+
88
103
  const HEAD: &str = "import std/Str\n\
89
104
  import std/Int\n\
90
105
  import std/Bool\nimport std/App\n\
compiler/game/web-test/fixtures/stress_state_view.plum CHANGED
@@ -44,10 +44,6 @@ primitive StressStateView[App] =
44
44
  const WorldW = 1600
45
45
  const WorldH = 900
46
46
 
47
- # The list f(i), f(i + 1) ... f(n - 1).
48
- fun rangeLink(i: Int, n: Int, f: fn(Int) -> View) -> List<View> =
49
- if i >= n then Nil else Cons(head: f(i), tail: rangeLink(i + 1, n, f))
50
-
51
47
  fun wrap(v: Float, span: Float) -> Float = v - span * Float(Int(v / span))
52
48
 
53
49
  fun pulseAnim() -> Anim =
@@ -94,21 +90,25 @@ enum StressAction = Ticked(dt: Float) | Clicked(i: Int)
94
90
  # compares a press with.
95
91
  struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks: Int, sheet: Texture, white: Texture, buttons: List<Box>, anim: Anim) =
96
92
  fun create(sheet: Texture, white: Texture) -> ViewScreen =
97
- none: List<Box> := Nil
98
- buttons := 0.until(StressStateView.Buttons).fold(none, |acc, i| Cons(Box(x: Float(i % 10 * 70 + 10), y: Float(i / 10 * 30 + 10), w: 64.0, h: 24.0, color: Color.rgb(0.2, 0.2, 0.3), touch: Enabled), acc)).reverse()
93
+ buttons := Range.until(0, StressStateView.Buttons).map(|i| Box(x: Float(i % 10 * 70 + 10), y: Float(i / 10 * 30 + 10), w: 64.0, h: 24.0, color: Color.rgb(0.2, 0.2, 0.3), touch: Enabled))
99
94
  ViewScreen(clock: 0.0, frames: 0, clicks: 0, sheet: sheet, white: white, buttons: buttons, anim: StressStateView.pulseAnim())
100
95
 
101
96
  fun name(self) -> Str = "view"
102
97
 
103
98
  fun background(self) -> Color = Color.rgb(0.05, 0.06, 0.1)
104
99
 
105
- fun view(self) -> List<View> =
106
- world := Scaled(scale: 0.8, children: StressStateView.rangeLink(0, StressStateView.Groups, |gi| self.spinner(gi)).append(StressStateView.rangeLink(0, StressStateView.Pulsers, |i| self.pulser(i))).append(StressStateView.rangeLink(0, StressStateView.Rects, |i| self.rect(i))).append(StressStateView.rangeLink(0, StressStateView.Circles, |i| self.circle(i))).append(StressStateView.rangeLink(0, StressStateView.Texts, |i| self.counter(i))))
107
- labels := StressStateView.rangeLink(0, StressStateView.Buttons, |i| self.buttonLabel(i))
108
- Cons(world, self.buttons.append(labels))
100
+ fun view(self) -> List<View> = [
101
+ Scaled(scale: 0.8, children: [
102
+ ..Range.until(0, StressStateView.Groups).map(|gi| self.spinner(gi)),
103
+ ..Range.until(0, StressStateView.Pulsers).map(|i| self.pulser(i)),
104
+ ..Range.until(0, StressStateView.Rects).map(|i| self.rect(i)),
105
+ ..Range.until(0, StressStateView.Circles).map(|i| self.circle(i)),
106
+ ..Range.until(0, StressStateView.Texts).map(|i| self.counter(i))]),
107
+ ..self.buttons,
108
+ ..Range.until(0, StressStateView.Buttons).map(|i| self.buttonLabel(i))]
109
109
 
110
110
  fun onPress(self, target: View, at: Vec2) -> Option<StressAction> =
111
- 0.until(StressStateView.Buttons).find(|i| @sameRef(target, self.buttons.at(i))).map(|i| Clicked(i: i))
111
+ Range.until(0, StressStateView.Buttons).find(|i| @sameRef(target, self.buttons.at(i))).map(|i| Clicked(i: i))
112
112
 
113
113
  fun tick(self, dt: Float) -> Option<StressAction> = Some(Ticked(dt: dt))
114
114
 
@@ -117,7 +117,7 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
117
117
  Clicked(_) => ViewScreen(..self, clicks: self.clicks + 1)
118
118
 
119
119
  fun spinner(self, gi: Int) -> View =
120
- Spinner(x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.24 * self.clock, children: StressStateView.rangeLink(0, StressStateView.Sprites / StressStateView.Groups, |j| self.dancer(gi, j)))
120
+ Spinner(x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.24 * self.clock, children: Range.until(0, StressStateView.Sprites / StressStateView.Groups).map(|j| self.dancer(gi, j)))
121
121
 
122
122
  fun dancer(self, gi: Int, j: Int) -> View =
123
123
  i := gi * {StressStateView.Sprites / StressStateView.Groups} + j
compiler/lsp/src/main.rs CHANGED
@@ -630,24 +630,25 @@ mod tests {
630
630
  let _ = std::fs::remove_dir_all(&dir);
631
631
  }
632
632
 
633
- /// `10.` on an Int literal (and on an Int variable) offers until/to/downTo.
633
+ /// `Range.` offers the statics `until`, `to` and `downTo`; an Int has no range methods
634
+ /// any more (`10.until(20)` is `Range.until(10, 20)`).
634
635
  #[test]
635
- fn memberCompletionOnIntOffersRangeMethods() {
636
+ fn memberCompletionOnRangeOffersItsStatics() {
636
637
  let dir = std::env::temp_dir().join(format!("plum-lsp-int-{}", std::process::id()));
637
638
  std::fs::create_dir_all(&dir).unwrap();
638
639
  let path = dir.join("t.plum");
639
- let text = "module t\nimport std/Int\nimport std/Float\nimport std/App\nprimitive Main[App] =\n fun main() =\n n := 5\n n.zzzzzz\n 10.zzzzzz\n";
640
+ let text = "module t\nimport std/Int\nimport std/Float\nimport std/App\nprimitive Main[App] =\n fun main() =\n n := 5\n n.zzzzzz\n Range.zzzzzz\n";
640
641
  std::fs::write(&path, text).unwrap();
641
- for (line, recv) in [(6, "n"), (7, "10")] {
642
- let items = memberCompletionFor(&path, &repoRoot(), text, line, recv);
642
+ let items = memberCompletionFor(&path, &repoRoot(), text, 6, "n");
643
- let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
643
+ let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
644
+ for gone in ["until", "to", "downTo", "times"] {
645
+ assert!(!labels.contains(&gone), "{gone} on an Int: {labels:?}");
646
+ }
647
+ assert!(labels.contains(&"abs"), "{labels:?}");
648
+ let items = memberCompletionFor(&path, &repoRoot(), text, 7, "Range");
649
+ let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
644
- for want in ["until", "to", "downTo"] {
650
+ for want in ["until", "to", "downTo"] {
645
- assert!(
646
- labels.contains(&want),
647
- "missing {want} for {recv} in {labels:?}"
648
- );
649
- }
650
- assert!(!labels.contains(&"times"), "{labels:?}");
651
+ assert!(labels.contains(&want), "missing {want} for Range in {labels:?}");
651
652
  }
652
653
  let _ = std::fs::remove_dir_all(&dir);
653
654
  }
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -736,15 +736,30 @@ module.exports = grammar({
736
736
  seq(field("key", $.expression), "=>", field("value", $.expression)),
737
737
 
738
738
  // List literal: `[1, 2, 3]`, `[]`, `["a" => 1]` (pair elements). Only at
739
+ // expression start. An item may be a spread (`..xs`: every element of a list,
740
+ // or the value of an `Option`) or a `list_if` (`if c then x`: added only when
739
- // expression start.
741
+ // `c` holds).
740
742
  list_literal: ($) =>
741
743
  seq(
742
744
  "[",
743
- optional(commaSep1(choice($.expression, $.pair_argument))),
745
+ optional(commaSep1(choice($.expression, $.pair_argument, $.spread_argument, $.list_if))),
744
746
  optional(","),
745
747
  "]",
746
748
  ),
747
749
 
750
+ // `if c then x` in a list literal: `x` is an item only when `c` holds. With an
751
+ // `else` it is an `inline_if_expression`, one item either way.
752
+ list_if: ($) =>
753
+ prec.right(
754
+ PREC.conditional,
755
+ seq(
756
+ "if",
757
+ field("condition", choice($.expression, $.bind_condition)),
758
+ "then",
759
+ field("then", choice($.expression, $.spread_argument)),
760
+ ),
761
+ ),
762
+
748
763
  class_call: ($) =>
749
764
  prec(PREC.call, seq(
750
765
  field("type", $.type_identifier),
compiler/tooling/tree-sitter-plum/queries/plum/format.scm CHANGED
@@ -94,6 +94,13 @@
94
94
  "else"
95
95
  ] @prepend_space @append_space)
96
96
 
97
+ ; `if c then x` as a list literal's item.
98
+ (list_if
99
+ "if" @append_space)
100
+
101
+ (list_if
102
+ "then" @prepend_space @append_space)
103
+
97
104
  ; ============================================================
98
105
  ; Keywords — space after (Topiary inserts NO whitespace at all
99
106
  ; between adjacent leaves unless a query says to; every keyword
compiler/tooling/tree-sitter-plum/src/grammar.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/node-types.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/parser.c CHANGED
Binary file
compiler/tooling/tree-sitter-plum/test/corpus/list_literal.txt CHANGED
@@ -73,3 +73,75 @@ primitive Main[App] =
73
73
  (type
74
74
  (type_identifier)))
75
75
  (class_argument_list)))))))))
76
+
77
+ ==================
78
+ list literal items: spreads and if items
79
+ ==================
80
+
81
+ primitive Main =
82
+ fun f(c: Bool) -> List<Int> = [1, ..xs, if c then 2, if c then 3 else 4, if Some(v) := o then v, if c then ..ys]
83
+
84
+ ---
85
+
86
+ (source
87
+ (primitive
88
+ (type_identifier)
89
+ (fn
90
+ (fn_identifier)
91
+ (param
92
+ (var_identifier)
93
+ (type
94
+ (type_identifier)))
95
+ (type
96
+ (type_identifier)
97
+ (type
98
+ (type_identifier)))
99
+ (expression
100
+ (primary_expression
101
+ (list_literal
102
+ (expression
103
+ (primary_expression
104
+ (integer)))
105
+ (spread_argument
106
+ (expression
107
+ (primary_expression
108
+ (var_identifier))))
109
+ (list_if
110
+ (expression
111
+ (primary_expression
112
+ (var_identifier)))
113
+ (expression
114
+ (primary_expression
115
+ (integer))))
116
+ (expression
117
+ (inline_if_expression
118
+ (expression
119
+ (primary_expression
120
+ (var_identifier)))
121
+ (expression
122
+ (primary_expression
123
+ (integer)))
124
+ (expression
125
+ (primary_expression
126
+ (integer)))))
127
+ (list_if
128
+ (bind_condition
129
+ (bind_pattern
130
+ (bind_class_pattern
131
+ (type_identifier)
132
+ (bind_pattern
133
+ (var_identifier))))
134
+ (expression
135
+ (primary_expression
136
+ (var_identifier))))
137
+ (expression
138
+ (primary_expression
139
+ (var_identifier))))
140
+ (list_if
141
+ (expression
142
+ (primary_expression
143
+ (var_identifier)))
144
+ (spread_argument
145
+ (expression
146
+ (primary_expression
147
+ (var_identifier)))))))))))
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs CHANGED
@@ -246,7 +246,10 @@ fn stringInterpolationOfAFloatIsAClearError() {
246
246
  #[test]
247
247
  fn lastCaseOfAnExhaustiveMatchIsNotTested() {
248
248
  let src = "import std/Int\nimport std/App\nenum Shape =\n | Circle(r: Int)\n | Rect(w: Int, h: Int)\n\nprimitive Main[App] =\n fun areaOf(s: Shape) -> Int =\n match s\n Circle(r) => r * r * 3\n Rect(w, h) => w * h\n\n fun main() -> Int =\n Main.areaOf(Rect(w: 2, h: 5)) + Main.areaOf(Circle(r: 1))\n";
249
+ // Without fusion, which may fold the two calls of constants into `main`.
249
- let bytes = plum_test_support::compile("lastcase", src);
250
+ let source = plum_test_support::load("lastcase", src).expect("loads");
251
+ let opts = CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
252
+ let bytes = compile(&source, &opts).expect("compiles").wasm;
250
253
  let ops = namedBodies(&bytes).into_iter().find(|(n, _)| n == "Main.areaOf").expect("areaOf").1;
251
254
  assert_eq!(ops.iter().filter(|o| o.starts_with("RefTest")).count(), 1, "{ops:?}");
252
255
  assert_eq!(plum_test_support::runInt("lastcase", src), 13);
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs CHANGED
@@ -65,7 +65,10 @@ fn variantDowncastStays() {
65
65
  enum Shape =\n | Circle(r: Int)\n | Rect(w: Int, h: Int)\n\n\
66
66
  primitive Main[App] =\n fun areaOf(s: Shape) -> Int =\n match s\n Circle(r) => r * r * 3\n Rect(w, h) => w * h\n\n \
67
67
  fun main() -> Int =\n Main.areaOf(Rect(w: 2, h: 5)) + Main.areaOf(Circle(r: 1))\n";
68
+ // Without fusion, which may fold the two calls of constants into `main`.
68
- let all = bodies(&compile("variantcast", src));
69
+ let source = plum_test_support::load("variantcast", src).expect("loads");
70
+ let opts = plum_wasm_codegen::CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
71
+ let all = bodies(&plum_wasm_codegen::compile(&source, &opts).expect("compiles").wasm);
69
72
  let ops = body(&all, "Main.areaOf");
70
73
  assert!(ops.iter().any(|o| o.starts_with("RefCast") || o.starts_with("BrOnCast")), "{ops:?}");
71
74
  assert_eq!(runInt("variantcast", src), 13);
docs/game.md CHANGED
@@ -87,22 +87,22 @@ primitive Clicks[App] =
87
87
  A screen's `view(self) -> List<View>` is what the frame shows: a list of views, placed in the world's coordinates, made from the screen's fields. Orbit Runner's play:
88
88
 
89
89
  ```plum
90
- fun view(self) -> List<View> =
90
+ fun view(self) -> List<View> = [
91
- back := [Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16))]
91
+ Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16)),
92
+ ..Range.until(0, Star.Count).map(|i| Star(index: i, clock: self.clock)),
93
+ ..self.mines,
94
+ ..self.orbs,
92
- ship := if self.over then Nil else [self.ship]
95
+ if !self.over then self.ship,
93
- hud := [
96
+ ..self.rings,
94
- Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
97
+ Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
95
- Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow)]
98
+ Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow),
96
- over := if self.over
99
+ ..Range.until(0, self.lives).map(|i| Sprite.cell(Arena.W - 40.0 - Float(i) * 36.0, 12.0, self.assets.sheet, 32.0, 32.0, 0.0, 0.0, Sheet.Cell, Sheet.Cell, 0)),
97
- [Overlay.of(Arena.W, Arena.H, [
100
+ if self.over then Overlay.of(Arena.W, Arena.H, [
98
- Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
101
+ Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
99
- Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
102
+ Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
100
- else
101
- Nil
102
- back.append(starsFrom(0, self.clock)).append(self.mines).append(self.orbs).append(ship).append(self.rings).append(hud).append(lifeIcons(0, self.lives, self.assets.sheet)).append(over)
103
103
  ```
104
104
 
105
- What shows only sometimes is left out (the ship once the run is over, the game over panel until it is), what repeats is a list made by a function or a fold, and a list the screen holds is appended as it is. Nothing is annotated: `back` is a `List<Box>` and `hud` a `List<Label>`, and each list widens to a `List<View>` where it is used (a `List<Mine>` is a `List<View>`, rebuilt as one there; see [Coercion](language.md#coercion)). Later items draw over earlier ones. (Master writes the same view as one list literal with `if`, `for` and `..` elements, which this dialect's list literals don't have.)
105
+ The view is one list literal, its items in drawing order (later items draw over earlier ones). What shows only sometimes is an `if` item (the ship until the run is over, the game over panel once it is), what repeats is a spread of a `map` over a range (forty stars, one icon a life), and a list the screen holds is spread as it is (`..self.mines`). Nothing is annotated: the literal is a `List<View>` because `view` returns one, and each spread `List<Mine>` widens to it (rebuilt as a `List<View>` there; see [Coercion](language.md#coercion) and [list literal items](language.md#lists-slices-and-maps)).
106
106
 
107
107
  - **Drawn, not live.** The view is made again every time it is walked (to draw, to hit-test a press), and an item made inside it keeps nothing from one walk to the next. So each takes plain values read from the fields (a `Label`'s `text`, a `Sprite`'s `frame`). A `Group` or an `Overlay` in a view has the children it is made with as its own `view`, and an actor with a view of its own draws that, so views nest.
108
108
  - **Two kinds of item.** An actor the screen holds in a field and names in its view (the ship, each mine of `self.mines`) is the very object in the field when the frame is drawn: a press on it reaches the screen as that object ([Clicks](#clicks)), and `@sameRef(target, self.box)` tells which. The game steps it through the screen's `stepped`, which returns the screen with the actor's next version. An item made inside `view` (the score label, the stars, the game over panel) is a new object every frame, made from the fields.
docs/imperative-vs-functional.md CHANGED
@@ -60,7 +60,7 @@ So on this evidence, wider proof coverage wouldn't change the scene result, and
60
60
 
61
61
  - `for`, `while`, the closure fold, the struct-state loop and `findFirst` can't be told apart between master and the branch at this load.
62
62
  - The `for` gap reported earlier as +28% read about +7% here, with one branch run of 105 ms left out. The noise is too large to confirm or rule out +28%.
63
- - One clear loss: summing with `0.until(n).fold(..)`, the replacement for a local `total = total + i`, took 42 to 66 ms for 50 million passes against 13 to 14 ms on master. A hand-written tail-recursive fold with a closure takes 13 to 14 ms, so the cost is specific to `Range.fold`.
63
+ - One clear loss: summing with `Range.until(0, n).fold(..)`, the replacement for a local `total = total + i`, took 42 to 66 ms for 50 million passes against 13 to 14 ms on master. A hand-written tail-recursive fold with a closure takes 13 to 14 ms, so the cost is specific to `Range.fold`.
64
64
 
65
65
  ## What the noise doesn't support
66
66
 
docs/language.md CHANGED
@@ -387,6 +387,28 @@ primitive Demo[App] =
387
387
 
388
388
  A `List` is `Nil` or `Cons(head, tail)`, so you can match on it. Indexing a `List` is slow, so reach for a `Slice` when you need it.
389
389
 
390
+ **Items of a list literal:** besides a value, an item can be a spread or a conditional item, so a list put together from parts is one literal:
391
+
392
+ - `..xs` puts in every element of `xs`, in order: a `List`, an `Option` (its value, or nothing for `None`) or a `Range` (`..Range.until(0, n).map(|i| ..)` for one element per number). An empty spread adds nothing.
393
+ - `if c then x` puts in `x` only when `c` holds, and `if c then ..xs` the elements of `xs`. A condition can bind: `if Some(s) := self.ship then s`. `if c then x else y` is an ordinary value, one item either way. There is no `for` item: spread a `map`.
394
+
395
+ ```plum
396
+ import std/Int
397
+ import std/Bool
398
+ import std/Option
399
+ import std/collections/List
400
+ import std/App
401
+
402
+ primitive Demo[App] =
403
+ fun main() -> List<Int> =
404
+ xs := [2, 3]
405
+ extra: Option<Int> := Some(9)
406
+ big := false
407
+ [1, ..xs, if big then 100, ..extra, ..Range.until(0, 3).map(|i| i * 10)] # [1, 2, 3, 9, 0, 10, 20]
408
+ ```
409
+
410
+ Items run left to right, as written, and the list is built once, from its last item back: a value is one new cell, a spread copies the cells of what it spreads (a spread that ends the literal is shared, not copied), and nothing is appended to a list already built. Spreads are covariant like any `List`: `..self.orbs`, a `List<Orb>`, goes into a `List<View>`.
411
+
390
412
  An empty list `[]` needs its type where it is written: an annotation (`xs: List<Int> := []`), the parameter, field or return type it is given to, a sibling element (`[[], [1]]`), or the rest of its own statement (`xs.fold([], |acc, x| Cons(head: x, tail: acc))`). A later statement doesn't type it: `e := []` alone is an error at the `[]`.
391
413
 
392
414
  A `Map` is persistent, like a `List`: `m.with(k, v)` and `m.remove(k)` return a new map that shares most of its nodes with `m`, and `m` stays as it was. A map literal `[k => v, ..]` is `Map.empty().with(k, v)...`, so a later duplicate key wins. Keys are kept in order by their `compare` method, which `Int`, `Float`, `Str`, `Bool` and `Byte` have and a struct can define, and every walk goes in key order. See [the standard library](std.md#collections).
@@ -411,7 +433,7 @@ primitive Demo[App] =
411
433
  total := Tally(n: 0)
412
434
  for i := range 10 # 0, 1, ... 9
413
435
  total.n = total.n + i
414
- for i := range 2.until(10) # 2 to 9; also to, downTo, stepBy
436
+ for i := range Range.until(2, 10) # 2 to 9; also Range.to, Range.downTo, stepBy
415
437
  total.n = total.n + i
416
438
  for x := range [1, 2, 3] # a List, Slice or Array
417
439
  total.n = total.n + x
@@ -428,7 +450,7 @@ import std/Option
428
450
 
429
451
  primitive Loops =
430
452
  fun sumSkippingThree(limit: Int) -> Int =
431
- 0.until(limit).fold(0, |total, i|
453
+ Range.until(0, limit).fold(0, |total, i|
432
454
  if i == 3
433
455
  total
434
456
  else
@@ -445,7 +467,7 @@ primitive Loops =
445
467
  sumDigits(n / 10, total + n % 10)
446
468
  ```
447
469
 
448
- A `Slice` is folded over its indexes: `0.until(xs.length()).fold(0, |sum, i| sum + xs.at(i))`. A range (`until`, `to`, `downTo`, `stepBy`) has `fold`, `each`, `find`, `any` and `all`; `find`, `any` and `all` stop at the first element that decides. `Int.repeatUntil(start, done, step)` applies `step` until `done` holds and gives back the last state. Every one of these runs in constant stack.
470
+ A `Slice` is folded over its indexes: `Range.until(0, xs.length()).fold(0, |sum, i| sum + xs.at(i))`. A range (`Range.until(start, end)`, `Range.to(start, end)`, `Range.downTo(start, end)`, `.stepBy(n)`) has `fold`, `each`, `find`, `any`, `all` and `map` (a `List`); `find`, `any` and `all` stop at the first element that decides. `Int.repeatUntil(start, done, step)` applies `step` until `done` holds and gives back the last state. Every one of these runs in constant stack.
449
471
 
450
472
  Make your own type loopable by giving it `next`. Return `None` when done, or `Some` of the value and the remaining sequence:
451
473
 
@@ -777,14 +799,14 @@ primitive Demo[App] =
777
799
  fun all(rects: List<Rect>, big: Bool) -> List<Shape> =
778
800
  mixed := [Rect(w: 1, h: 2), Dot(r: 3)]
779
801
  dot := if big then Nil else [Dot(r: 1)]
780
- rects.append(mixed).append(dot)
802
+ [..rects, ..mixed, ..dot]
781
803
 
782
804
  fun main() -> Int = Demo.total(Demo.all([Rect(w: 2, h: 2)], false))
783
805
  ```
784
806
 
785
807
  - **The expected type flows in.** A declared type (of a parameter, a result, a field or an annotated local) types a list literal, `Nil`, `None`, the branches of an `if` or `match`, a block's value and a closure's result: in a `List<Shape>` slot, `[Rect(..), Dot(..)]` is built as a `List<Shape>`.
786
808
  - **A local takes its value's type, and widens where it is used.** `rects := [Rect(..)]` is a `List<Rect>`; given as a `List<Shape>` (an argument, the result, a list's tail) it is upcast there.
787
- - **A receiver widens to its arguments.** `rects.append(mixed)`, a `List<Rect>` given a `List<Shape>`, is the `append` of a `List<Shape>`: the receiver is upcast. Two lists of different implementers join at their trait: `rects.append(dots)` is a `List<Shape>`.
809
+ - **A receiver widens to its arguments, or to its expected result.** `rects.append(mixed)`, a `List<Rect>` given a `List<Shape>`, is the `append` of a `List<Shape>`: the receiver is upcast. Two lists of different implementers join at their trait: `rects.append(dots)` is a `List<Shape>`. In a `List<Shape>` literal, `..rects` is spread as a `List<Shape>`.
788
810
  - **With nothing expected, values of several types join at their trait.** A literal (`[Rect(..), Dot(..)]`) or the branches of an `if` or `match` (`if big then Rect(..) else Dot(..)`) take the one trait their types share; when they share several (`View`, `Sized` and `Touch`), the one along each type's first listed trait, its kind. Two values that share no trait, or no one trait, are an error.
789
811
 
790
812
  ### Errors
examples/arrays.plum CHANGED
@@ -16,17 +16,17 @@ primitive Arrays =
16
16
  # unboxed wasm arrays (i64 / f64 / i32 elements), not boxed anyref arrays.
17
17
  fun sumInts(n: Int) -> Int =
18
18
  a := Array.filled(n, 3)
19
- 0.until(n).fold(0, |total, i| total + a.at(i))
19
+ Range.until(0, n).fold(0, |total, i| total + a.at(i))
20
20
 
21
21
  fun sumFloats(n: Int) -> Float =
22
22
  a := Array.filled(n, 0.5)
23
- 0.until(n).fold(0.0, |total, i| total + a.at(i))
23
+ Range.until(0, n).fold(0.0, |total, i| total + a.at(i))
24
24
 
25
25
  fun countTrue(n: Int) -> Int =
26
26
  a := Array.filled(n, false)
27
27
  a.set(1, true)
28
28
  a.set(3, true)
29
- 0.until(n).fold(0, |count, i| if a.at(i) then count + 1 else count)
29
+ Range.until(0, n).fold(0, |count, i| if a.at(i) then count + 1 else count)
30
30
 
31
31
  fun first<T>(a: Array<T>) -> T =
32
32
  a.at(0)
examples/control_flow.plum CHANGED
@@ -32,7 +32,7 @@ primitive ControlFlow =
32
32
  # so far and returns the next one. A branch that returns `total` unchanged skips
33
33
  # an element.
34
34
  fun sumSkippingThree(limit: Int) -> Int =
35
- 0.until(limit).fold(0, |total, i|
35
+ Range.until(0, limit).fold(0, |total, i|
36
36
  if i == 3
37
37
  total
38
38
  else
@@ -92,7 +92,7 @@ primitive ControlFlow =
92
92
  sum.n
93
93
 
94
94
  fun firstOver(xs: Slice<Int>, limit: Int) -> Int =
95
- hit := 0.until(xs.length()).find(|i| xs.at(i) > limit)
95
+ hit := Range.until(0, xs.length()).find(|i| xs.at(i) > limit)
96
96
  match hit
97
97
  Some(i) => xs.at(i)
98
98
  None => -1
examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -42,12 +42,13 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
42
42
  const Count = 6
43
43
  const PartyEvery = 10
44
44
  const PartyTime = 2.5
45
+ const Confetti = 30
45
46
 
46
47
  fun seeded(seed: Int, assets: Assets) -> PlaygroundScreen =
47
48
  empty := PlaygroundScreen(
48
49
  rng: Random.seeded(seed), assets: assets, pops: 0, partyAt: -100.0, popsHeard: 0, partiesHeard: 0, newPop: false, newParty: false,
49
50
  hearPop: false, hearParty: false, clock: 0.0, balloons: Nil)
50
- 0.until(PlaygroundScreen.Count).fold(empty, |s, i|
51
+ Range.until(0, PlaygroundScreen.Count).fold(empty, |s, i|
51
52
  sp := Balloon.spawn(Balloon.FirstId + i, s.rng, Float(i) * 110.0 - Arena.H * 0.6, 0.0)
52
53
  PlaygroundScreen(..s, rng: sp.rng, balloons: s.balloons.append([sp.balloon])))
53
54
 
@@ -57,7 +58,15 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
57
58
 
58
59
  fun background(self) -> Color = Color.rgb(0.55, 0.8, 1.0)
59
60
 
60
- fun view(self) -> List<View> = sky(self.clock).append(self.balloons).append(self.party())
61
+ fun view(self) -> List<View> = [
62
+ Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.55, 0.8, 1.0)),
63
+ Box.of(0.0, 0.0, Arena.W, 200.0, Color.rgb(0.45, 0.72, 0.98)),
64
+ Circle.of(690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35)),
65
+ ..cloud(wrapX(120.0 + self.clock * 12.0), 130.0),
66
+ ..cloud(wrapX(520.0 + self.clock * 8.0), 220.0),
67
+ Box.of(0.0, Arena.H - 50.0, Arena.W, 50.0, Color.rgb(0.4, 0.78, 0.35)),
68
+ ..self.balloons,
69
+ if self.partying() then ..self.party()]
61
70
 
62
71
  fun hud(self, window: Vec2) -> List<View> = [
63
72
  Box.of(16.0, 14.0, 170.0, 56.0, Color.White.withAlpha(0.7)),
@@ -116,16 +125,13 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
116
125
  fun partyingAt(self, clock: Float) -> Bool = clock - self.partyAt < PlaygroundScreen.PartyTime
117
126
 
118
127
  fun party(self) -> List<View> =
119
- if !self.partying()
120
- Nil
121
- else
122
- age := self.clock - self.partyAt
128
+ age := self.clock - self.partyAt
123
- k := partyScale(age)
129
+ k := partyScale(age)
124
- cx := Arena.W / 2.0
130
+ cx := Arena.W / 2.0
131
+ [
125
- titles := [
132
+ ..Range.until(0, PlaygroundScreen.Confetti).map(|i| confetto(i, age)),
126
- Label.of(cx, 250.0 - 40.0 * k, "Hooray!", 72.0 * k, Color.rgb(0.95, 0.3, 0.5), Centre),
133
+ Label.of(cx, 250.0 - 40.0 * k, "Hooray!", 72.0 * k, Color.rgb(0.95, 0.3, 0.5), Centre),
127
- Label.of(cx, 250.0 + 40.0 * k, "{self.pops} balloons!", 40.0 * k, Color.rgb(0.15, 0.15, 0.3), Centre)]
134
+ Label.of(cx, 250.0 + 40.0 * k, "{self.pops} balloons!", 40.0 * k, Color.rgb(0.15, 0.15, 0.3), Centre)]
128
- confettiFrom(0, age).append(titles)
129
135
 
130
136
  fun partyScale(age: Float) -> Float =
131
137
  if age < 0.25
@@ -135,22 +141,11 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
135
141
  lap := lap0 - 0.8 * Float(Int(lap0 / 0.8))
136
142
  if lap < 0.4 then 1.4 * {1.0 - 0.15 * lap / 0.4} else 1.4 * 0.85 * {1.0 + {1.0 / 0.85 - 1.0} * {lap - 0.4} / 0.4}
137
143
 
138
- fun confettiFrom(i: Int, age: Float) -> List<View> =
144
+ fun confetto(i: Int, age: Float) -> Box =
139
- if i >= 30
140
- Nil
141
- else
142
- x := Float({i * 7919} % 800)
145
+ x := Float({i * 7919} % 800)
143
- y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
146
+ y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
144
- wob := 10.0 * Math.sin(age * 4.0 + Float(i))
147
+ wob := 10.0 * Math.sin(age * 4.0 + Float(i))
145
- Cons(Box.of(x + wob, y, 12.0, 12.0, Hue.of(i).color), confettiFrom(i + 1, age))
148
+ Box.of(x + wob, y, 12.0, 12.0, Hue.of(i).color)
146
-
147
- fun sky(clock: Float) -> List<View> =
148
- back := [
149
- Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.55, 0.8, 1.0)),
150
- Box.of(0.0, 0.0, Arena.W, 200.0, Color.rgb(0.45, 0.72, 0.98)),
151
- Circle.of(690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35))]
152
- grass := [Box.of(0.0, Arena.H - 50.0, Arena.W, 50.0, Color.rgb(0.4, 0.78, 0.35))]
153
- back.append(cloud(wrapX(120.0 + clock * 12.0), 130.0)).append(cloud(wrapX(520.0 + clock * 8.0), 220.0)).append(grass)
154
149
 
155
150
  fun wrapX(x: Float) -> Float =
156
151
  span := Arena.W + 200.0
examples/games/game_loop.plum CHANGED
@@ -58,7 +58,7 @@ enum Event =
58
58
 
59
59
  struct Stats(spawned: Int, removed: Int) =
60
60
  fun run(frames: Int, ps: Slice<Particle>) -> Stats =
61
- 0.until(frames).fold(Stats(spawned: 0, removed: 0), |stats, frame|
61
+ Range.until(0, frames).fold(Stats(spawned: 0, removed: 0), |stats, frame|
62
62
  spawned := if frame % 10 == 0
63
63
  ps.push(Particle(pos: Vec2(x: 0.0, y: 0.0), vel: Vec2(x: 2.0, y: 1.0), life: 25))
64
64
  stats.spawned + 1
examples/games/orbitrunner/actors/Star.plum CHANGED
@@ -10,6 +10,8 @@ import std/game/View
10
10
  import std/game/Circle
11
11
 
12
12
  struct Star[View](index: Int, clock: Float) =
13
+ const Count = 40
14
+
13
15
  fun r(self) -> Float = 1.0 + Float(self.index % 3) * 0.5
14
16
 
15
17
  fun place(self) -> Place = Place.at(Float({self.index * 7919} % 800), Float({self.index * 104729} % 600))
examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -70,24 +70,24 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
70
70
  fun stepped(self, dt: Float) -> PlayingScreen =
71
71
  PlayingScreen(..self, mines: Views.stepAll(self.mines, dt), orbs: Views.stepAll(self.orbs, dt), ship: self.ship.step(dt), rings: Views.stepAll(self.rings, dt))
72
72
 
73
- fun view(self) -> List<View> =
73
+ fun view(self) -> List<View> = [
74
- back := [Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16))]
74
+ Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16)),
75
+ ..Range.until(0, Star.Count).map(|i| Star(index: i, clock: self.clock)),
76
+ ..self.mines,
77
+ ..self.orbs,
75
- ship := if self.over then Nil else [self.ship]
78
+ if !self.over then self.ship,
76
- hud := [
79
+ ..self.rings,
77
- Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
80
+ Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
78
- Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow)]
81
+ Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow),
79
- over := if self.over
82
+ ..Range.until(0, self.lives).map(|i| Sprite.cell(Arena.W - 40.0 - Float(i) * 36.0, 12.0, self.assets.sheet, 32.0, 32.0, 0.0, 0.0, Sheet.Cell, Sheet.Cell, 0)),
80
- [Overlay.of(Arena.W, Arena.H, [
83
+ if self.over then Overlay.of(Arena.W, Arena.H, [
81
- Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
84
+ Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
82
- Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
85
+ Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
83
- else
84
- Nil
85
- back.append(starsFrom(0, self.clock)).append(self.mines).append(self.orbs).append(ship).append(self.rings).append(hud).append(lifeIcons(0, self.lives, self.assets.sheet)).append(over)
86
86
 
87
87
  fun deal(self) -> PlayingScreen =
88
88
  fresh := PlayingScreen(..self, clock: 0.0, ship: Ship.create(self.assets.sheet), orbs: Nil, mines: Nil, rings: Nil)
89
- withOrbs := 0.until(PlayingScreen.OrbCount).fold(fresh, |s, i| s.newOrb(i))
89
+ withOrbs := Range.until(0, PlayingScreen.OrbCount).fold(fresh, |s, i| s.newOrb(i))
90
- 0.until(Mine.countFor(0)).fold(withOrbs, |s, i| s.newMine())
90
+ Range.until(0, Mine.countFor(0)).fold(withOrbs, |s, i| s.newMine())
91
91
 
92
92
  fun newOrb(self, i: Int) -> PlayingScreen =
93
93
  sp := Motion.spawn(self.rng, self.ship.at.x, self.ship.at.y, 120.0, 40.0)
@@ -162,14 +162,6 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
162
162
  StartOver => self.assets.startMusic(io)
163
163
  _ => Unit
164
164
 
165
- fun starsFrom(i: Int, clock: Float) -> List<View> = if i >= 40 then Nil else Cons(Star(index: i, clock: clock), starsFrom(i + 1, clock))
166
-
167
- fun lifeIcons(i: Int, lives: Int, sheet: Texture) -> List<View> =
168
- if i >= lives
169
- Nil
170
- else
171
- Cons(Sprite.cell(Arena.W - 40.0 - Float(i) * 36.0, 12.0, sheet, 32.0, 32.0, 0.0, 0.0, Sheet.Cell, Sheet.Cell, 0), lifeIcons(i + 1, lives, sheet))
172
-
173
165
  fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool = Math.hypot(ax - bx, ay - by) < ra + rb
174
166
 
175
167
  struct Caught(orbs: List<Orb>, rng: Random, points: Int)
examples/generics.plum CHANGED
@@ -57,7 +57,7 @@ primitive Generics =
57
57
  s.name()
58
58
 
59
59
  fun sumWith<T>(xs: Slice<T>, num: Num<T>) -> T =
60
- 0.until(xs.length()).fold(num.zero, |acc, i| num.add(acc, xs.at(i)))
60
+ Range.until(0, xs.length()).fold(num.zero, |acc, i| num.add(acc, xs.at(i)))
61
61
 
62
62
  fun unboxed(b: GenericBox<Int>) -> Int =
63
63
  b.getValue()
examples/maps.plum CHANGED
@@ -24,4 +24,4 @@ primitive Maps =
24
24
  # Fills a map with `n` points: each `with` is handed the map the last one made.
25
25
  fun points(n: Int) -> Map<Int, MapPoint> =
26
26
  start: Map<Int, MapPoint> := Map.empty()
27
- 0.until(n).fold(start, |m, i| m.with(i, MapPoint(x: Float(i), y: Float(i) * 2.0)))
27
+ Range.until(0, n).fold(start, |m, i| m.with(i, MapPoint(x: Float(i), y: Float(i) * 2.0)))
examples/sequences.plum CHANGED
@@ -44,8 +44,8 @@ primitive Sequences =
44
44
  # The 8 neighbours of (x, y), as one list of (x, y) pairs.
45
45
  fun neighbours(x: Int, y: Int) -> List<Pair<Int, Int>> =
46
46
  none: List<Pair<Int, Int>> := Nil
47
- found := 0.until(3).fold(none, |cells, dx|
47
+ found := Range.until(0, 3).fold(none, |cells, dx|
48
- 0.until(3).fold(cells, |row, dy|
48
+ Range.until(0, 3).fold(cells, |row, dy|
49
49
  if dx != 1 || dy != 1
50
50
  Cons(head: Pair(first: x + dx - 1, second: y + dy - 1), tail: row)
51
51
  else
@@ -55,7 +55,7 @@ primitive Sequences =
55
55
  found.reverse()
56
56
 
57
57
  fun firstBig(xs: Slice<Int>) -> Int =
58
- hit := 0.until(xs.length()).find(|i| xs.at(i) > 10)
58
+ hit := Range.until(0, xs.length()).find(|i| xs.at(i) > 10)
59
59
  match hit
60
60
  Some(i) => xs.at(i)
61
61
  None => -1
examples/structs_records.plum CHANGED
@@ -86,7 +86,7 @@ primitive StructsRecords =
86
86
  Vec2(x: x, y: y)
87
87
 
88
88
  fun sumLoopBoxes() -> Int =
89
- 0.until(5).fold(0, |total, i|
89
+ Range.until(0, 5).fold(0, |total, i|
90
90
  b := LoopBox(v: i)
91
91
  total + b.v
92
92
  )
std/Int.plum CHANGED
@@ -7,6 +7,7 @@ import std/Pair
7
7
  import std/Option
8
8
  import std/Result
9
9
  import std/Array
10
+ import std/collections/List
10
11
 
11
12
  # Why `Int.parse` / `Float.parse` failed: not a number, or one past Int's range.
12
13
  enum NumError = BadNumStr | NumOverflow
@@ -152,21 +153,6 @@ primitive Int =
152
153
  fun toStr(self) -> Str =
153
154
  intToStr(self)
154
155
 
155
- # ---- ranges: `for i := range 2.until(6)` ----
156
- # Empty ranges (`5.until(5)`, `1.downTo(2)`) iterate zero times.
157
-
158
- # self, self + 1, ... end - 1
159
- fun until(self, end: Int) -> Range =
160
- Range(start: self, stop: end, step: 1)
161
-
162
- # self, self + 1, ... end (inclusive)
163
- fun to(self, end: Int) -> Range =
164
- Range(start: self, stop: end + 1, step: 1)
165
-
166
- # self, self - 1, ... end (inclusive)
167
- fun downTo(self, end: Int) -> Range =
168
- Range(start: self, stop: end - 1, step: -1)
169
-
170
156
  # ---- static helpers (no `self`) ----
171
157
 
172
158
  # Plain decimal rendering of an `Int` — factored out of `Float.toStr` so the
@@ -239,9 +225,23 @@ primitive Int =
239
225
  repeatUntil(step(s), done, step)
240
226
 
241
227
  # The ints `start`, `start + step`, ... up to (excluding) `stop`; counting down
242
- # when `step` is negative. A `for x := range v` source via `next`.
228
+ # when `step` is negative. A `for x := range v` source via `next`. Made by
229
+ # `Range.until`, `Range.to` and `Range.downTo`; an empty range (`Range.until(5, 5)`,
230
+ # `Range.downTo(1, 2)`) iterates zero times.
243
231
  struct Range(start: Int, stop: Int, step: Int) =
244
232
 
233
+ # start, start + 1, ... end - 1: `for i := range Range.until(2, 6)`
234
+ fun until(start: Int, end: Int) -> Range =
235
+ Range(start: start, stop: end, step: 1)
236
+
237
+ # start, start + 1, ... end (inclusive)
238
+ fun to(start: Int, end: Int) -> Range =
239
+ Range(start: start, stop: end + 1, step: 1)
240
+
241
+ # start, start - 1, ... end (inclusive)
242
+ fun downTo(start: Int, end: Int) -> Range =
243
+ Range(start: start, stop: end - 1, step: -1)
244
+
245
245
  fun next(self) -> Option<Pair<Int, Range>> =
246
246
  more := if self.step > 0 then self.start < self.stop else self.start > self.stop
247
247
  if more then Some(Pair(first: self.start, second: Range(start: self.start + self.step, stop: self.stop, step: self.step))) else None
@@ -280,6 +280,23 @@ struct Range(start: Int, stop: Int, step: Int) =
280
280
  fun all(self, pred: fn(Int) -> Bool) -> Bool =
281
281
  self.find(|x| !pred(x)).isNone()
282
282
 
283
+ # `f` of each element, in order, as a list: `Range.until(0, 3).map(|i| i * i)` is `[0, 1, 4]`.
284
+ # A loop (TRMC), constant stack.
285
+ fun map<B>(self, f: fn(Int) -> B) -> List<B> =
286
+ more := if self.step > 0 then self.start < self.stop else self.start > self.stop
287
+ if more
288
+ Cons(head: f(self.start), tail: Range(start: self.start + self.step, stop: self.stop, step: self.step).map(f))
289
+ else
290
+ Nil
291
+
292
+ # The elements in front of `rest`: a list literal's spread (`[..Range.until(0, 3), 9]`).
293
+ fun spreadOnto(self, rest: List<Int>) -> List<Int> =
294
+ more := if self.step > 0 then self.start < self.stop else self.start > self.stop
295
+ if more
296
+ Cons(head: self.start, tail: Range(start: self.start + self.step, stop: self.stop, step: self.step).spreadOnto(rest))
297
+ else
298
+ rest
299
+
283
300
  # Every `by`-th element, starting with the first (`by` > 0).
284
301
  fun stepBy(self, by: Int) -> Range =
285
302
  Range(start: self.start, stop: self.stop, step: if self.step > 0 then by else -by)
std/Option.plum CHANGED
@@ -3,6 +3,7 @@ module std
3
3
  import std/Str
4
4
  import std/Int
5
5
  import std/Result
6
+ import std/collections/List
6
7
 
7
8
  # A value that may be absent: `None`, or `Some(value)`.
8
9
  enum Option<T> =
@@ -45,6 +46,11 @@ enum Option<T> =
45
46
  fun unwrapFailed(self, msg: Str) -> T =
46
47
  crash msg
47
48
 
49
+ # The value in front of `rest`, or `rest` for None: a list literal's spread (`[a, ..opt]`).
50
+ fun spreadOnto(self, rest: List<T>) -> List<T> = match self
51
+ None => rest
52
+ Some(v) => Cons(head: v, tail: rest)
53
+
48
54
  # `Ok(value)` for Some, `Err(error)` for None.
49
55
  fun okOr<E>(self, err: E) -> Result<T, E> = match self
50
56
  None => Err(err)
std/Slice.plum CHANGED
@@ -171,7 +171,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
171
171
  # removes the element at i'th index of the list (out of range is a no-op)
172
172
  fun removeAt(self, i: Int) =
173
173
  if i >= 0 && i < self.size
174
- for j := range i.until(self.size - 1)
174
+ for j := range Range.until(i, self.size - 1)
175
175
  self.data.set(self.start + j, self.data.at(self.start + j + 1))
176
176
  self.size = self.size - 1
177
177
 
@@ -252,7 +252,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
252
252
  result := Slice<T>()
253
253
  s := if start < 0 then 0 else start
254
254
  e := if end > self.size then self.size else end
255
- for i := range s.until(e)
255
+ for i := range Range.until(s, e)
256
256
  result.push(self.data.at(self.start + i))
257
257
  result
258
258
 
@@ -273,7 +273,7 @@ struct Slice<T>(mut data: Array<T>, mut start: Int, mut size: Int, mut cap: Int)
273
273
  # advanced generator.
274
274
  fun shuffle(self, rng: Random) -> Rolled<Slice<T>> =
275
275
  result := self.sublist(0, self.size)
276
- final := {result.size - 1}.downTo(1).fold(rng, |gen, i|
276
+ final := Range.downTo(result.size - 1, 1).fold(rng, |gen, i|
277
277
  d := gen.nextIntBelow(i + 1)
278
278
  j := d.value
279
279
  vi := result.data.at(result.start + i)
std/collections/Deque.plum CHANGED
@@ -90,7 +90,7 @@ struct Deque<T>(mut buf: Array<T>, mut head: Int, mut size: Int) =
90
90
 
91
91
  # Left fold from front to back: `f(f(f(acc, front), second), third)`.
92
92
  fun fold<A>(self, acc: A, f: fn(A, T) -> A) -> A =
93
- 0.until(self.size).fold(acc, |a, i| f(a, self.buf.at({self.head + i} % self.buf.length())))
93
+ Range.until(0, self.size).fold(acc, |a, i| f(a, self.buf.at({self.head + i} % self.buf.length())))
94
94
 
95
95
  # Calls `f` on each element, front to back.
96
96
  fun each(self, f: fn(T) -> Unit) -> Unit =
@@ -106,4 +106,4 @@ struct Deque<T>(mut buf: Array<T>, mut head: Int, mut size: Int) =
106
106
  # `==` and `!=`: the same length and the elements `==` in order, front to back (where
107
107
  # each sits in the ring, and the capacity, don't count).
108
108
  fun eq(self, o: Deque<T>) -> Bool =
109
- self.size == o.size && 0.until(self.size).all(|i| self.at(i) == o.at(i))
109
+ self.size == o.size && Range.until(0, self.size).all(|i| self.at(i) == o.at(i))
std/collections/List.plum CHANGED
@@ -79,6 +79,17 @@ enum List<T> =
79
79
  fun append(self, ys: List<T>) -> List<T> =
80
80
  self.reverse().revOnto(ys)
81
81
 
82
+ # `self` in front of `rest`: a list literal's spread (`[a, ..xs, b]`) is `xs.spreadOnto(rest)`.
83
+ # Copies `self`'s cells once (a loop, constant stack); with `rest` empty it is `self`, shared.
84
+ fun spreadOnto(self, rest: List<T>) -> List<T> = match rest
85
+ Nil => self
86
+ Cons(_, _) => self.appendCells(rest)
87
+
88
+ # `spreadOnto`'s loop: a constructor wrapped self call, rewritten to a loop (TRMC).
89
+ fun appendCells(self, ys: List<T>) -> List<T> = match self
90
+ Nil => ys
91
+ Cons(h, t) => Cons(head: h, tail: t.appendCells(ys))
92
+
82
93
  # The iterator step: `Some(Pair(head, tail))`, or None once the list is done.
83
94
  fun next(self) -> Option<Pair<T, List<T>>> = match self
84
95
  Nil => None
std/collections/Map.plum CHANGED
@@ -464,7 +464,7 @@ enum Map<K, V> =
464
464
  else
465
465
  a := self.entries()
466
466
  b := o.entries()
467
- 0.until(a.length()).find(|i| a.at(i).first.compare(b.at(i).first) != 0 || a.at(i).second != b.at(i).second).isNone()
467
+ Range.until(0, a.length()).find(|i| a.at(i).first.compare(b.at(i).first) != 0 || a.at(i).second != b.at(i).second).isNone()
468
468
 
469
469
  # The entries in key order, written like a literal: `[1 => one, 2 => two]`.
470
470
  fun toStr(self) -> Str =
std/collections/Set.plum CHANGED
@@ -140,7 +140,7 @@ struct Set<T>(map: Map<T, Bool>) =
140
140
  else
141
141
  a := self.toSlice()
142
142
  b := o.toSlice()
143
- 0.until(a.length()).find(|i| a.at(i).compare(b.at(i)) != 0).isNone()
143
+ Range.until(0, a.length()).find(|i| a.at(i).compare(b.at(i)) != 0).isNone()
144
144
 
145
145
  # The members, ascending: `[1, 2, 3]`.
146
146
  fun toStr(self) -> Str =
std/game/Game.plum CHANGED
@@ -429,7 +429,7 @@ struct Game(screens: List<Screen>) =
429
429
  # aside.
430
430
  fun heardIn(input: Input, pointer: Vec2) -> Bool =
431
431
  evs := input.events
432
- 0.until(evs.length()).fold(Pair(first: false, second: pointer), |acc, i|
432
+ Range.until(0, evs.length()).fold(Pair(first: false, second: pointer), |acc, i|
433
433
  e := evs.at(i)
434
434
  match e
435
435
  PointerMove(x, y) => Pair(first: acc.first || x != acc.second.x || y != acc.second.y, second: Vec2(x: x, y: y))
@@ -441,4 +441,4 @@ struct Game(screens: List<Screen>) =
441
441
  # Where the pointer is after the tick's events.
442
442
  fun lastPointer(input: Input, pointer: Vec2) -> Vec2 =
443
443
  evs := input.events
444
- 0.until(evs.length()).fold(pointer, |p, i| evs.at(i).position().unwrapOr(p))
444
+ Range.until(0, evs.length()).fold(pointer, |p, i| evs.at(i).position().unwrapOr(p))
std/game/ScreenSlice.plum CHANGED
@@ -115,7 +115,7 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
115
115
  acted := Slice<Bool>()
116
116
  Effects.startDispatch(ActionSink(queue: q))
117
117
  evs := d.input.events
118
- afterEvents := 0.until(evs.length()).fold(s, |cur, i| Delivery.eventInto<A, S>(cur, d, evs.at(i), q, acted))
118
+ afterEvents := Range.until(0, evs.length()).fold(s, |cur, i| Delivery.eventInto<A, S>(cur, d, evs.at(i), q, acted))
119
119
  h := afterEvents.held(d.input)
120
120
  afterHeld := match h
121
121
  Some(a) =>
std/game/TestRig.plum CHANGED
@@ -163,7 +163,7 @@ struct TestRig<S>(
163
163
 
164
164
  fun tick(self, dt: Float = Clock.Tick) -> TestRig<S> = self.forget().step(dt)
165
165
 
166
- fun ticks(self, n: Int) -> TestRig<S> = 0.until(n).fold(self.forget(), |r, i| r.step(Clock.Tick))
166
+ fun ticks(self, n: Int) -> TestRig<S> = Range.until(0, n).fold(self.forget(), |r, i| r.step(Clock.Tick))
167
167
 
168
168
  # One host frame `frameDt` seconds long with `input`, as the host runs it: the ticks it
169
169
  # covers. The input waiting and what is held are not used.
@@ -312,4 +312,4 @@ struct TestRig<S>(
312
312
 
313
313
  # Every tick of `r` played now (a game made from `r.seed`).
314
314
  fun replay(self, r: Replay) -> TestRig<S> =
315
- 0.until(r.length()).fold(self.forget(), |t, i| t.ran1(r.at(i), Clock.Tick))
315
+ Range.until(0, r.length()).fold(self.forget(), |t, i| t.ran1(r.at(i), Clock.Tick))
std/game/Tween.plum CHANGED
@@ -65,7 +65,7 @@ enum Easing =
65
65
  CubicInOut => Easing.powInOut(t, 3)
66
66
 
67
67
  # `t` to the power `p`.
68
- fun powIn(t: Float, p: Int) -> Float = 0.until(p).fold(1.0, |r, i| r * t)
68
+ fun powIn(t: Float, p: Int) -> Float = Range.until(0, p).fold(1.0, |r, i| r * t)
69
69
 
70
70
  # scene2d's `PowOut`: 1 - (1 - t)^p, written as it does.
71
71
  fun powOut(t: Float, p: Int) -> Float =
tests/benchmarks/screen_views/orbit.plum CHANGED
@@ -19,7 +19,7 @@ import std/Test
19
19
  primitive OrbitTest[UnitTest] =
20
20
  # the driver's run is the game's: the same seed reaches the same state
21
21
  fun theDriversRunIsTheGamesTheSame() =
22
- a := 0.until(600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t), Clock.Tick, Vec2(x: 800.0, y: 600.0)))
22
+ a := Range.until(0, 600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t), Clock.Tick, Vec2(x: 800.0, y: 600.0)))
23
- b := 0.until(600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t), Clock.Tick, Vec2(x: 800.0, y: 600.0)))
23
+ b := Range.until(0, 600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t), Clock.Tick, Vec2(x: 800.0, y: 600.0)))
24
24
  assert OrbitBench.state(OrbitBench.playingOf(a)) == OrbitBench.state(OrbitBench.playingOf(b))
25
25
  assert OrbitBench.state(OrbitBench.playingOf(a)) != OrbitBench.state(OrbitBench.make(7))
tests/core/type_param_names.plum CHANGED
@@ -61,7 +61,7 @@ primitive TypeParamNamesTest[UnitTest] =
61
61
  S(k) => k
62
62
  N => 0
63
63
  assert n == 3
64
- assert 1.to(4).fold(0, |a, x| a + x) == 10
64
+ assert Range.to(1, 4).fold(0, |a, x| a + x) == 10
65
65
 
66
66
  fun wrap<X>(x: X) -> T<X> =
67
67
  T(v: x)
tests/examples/arrays.plum CHANGED
@@ -108,7 +108,7 @@ primitive ArraysTest[UnitTest] =
108
108
  assert w.points.get(0)!.y == 2.0
109
109
 
110
110
  fun probePushGrowthShrinkSingleLeaf() =
111
- a := 0.until(50).fold(Array<One>(), |grown, i| grown.push(One(n: i)))
111
+ a := Range.until(0, 50).fold(Array<One>(), |grown, i| grown.push(One(n: i)))
112
112
  assert a.length() == 50
113
113
  assert a.at(49).n == 49
114
114
  b := a.resize(10)
tests/examples/control_flow.plum CHANGED
@@ -115,49 +115,49 @@ primitive ControlFlowTest[UnitTest] =
115
115
  # range_until_to_downTo: bounds incl. empty ranges
116
116
  fun rangeUntilToDownToBoundsInclEmptyRanges() =
117
117
  a := Tally(n: 0)
118
- for i := range 2.until(6)
118
+ for i := range Range.until(2, 6)
119
119
  a.n = a.n + i
120
120
  assert a.n == 14
121
121
  b := Tally(n: 0)
122
- for i := range 1.to(4)
122
+ for i := range Range.to(1, 4)
123
123
  b.n = b.n + i
124
124
  assert b.n == 10
125
125
  c := Tally(n: 0)
126
- for i := range 4.downTo(1)
126
+ for i := range Range.downTo(4, 1)
127
127
  c.n = c.n * 10 + i
128
128
  assert c.n == 4321
129
129
  runs := Tally(n: 0)
130
- for _ := range 5.until(5)
130
+ for _ := range Range.until(5, 5)
131
131
  runs.n = runs.n + 1
132
- for _ := range 1.downTo(2)
132
+ for _ := range Range.downTo(1, 2)
133
133
  runs.n = runs.n + 1
134
- for _ := range 3.to(2)
134
+ for _ := range Range.to(3, 2)
135
135
  runs.n = runs.n + 1
136
136
  assert runs.n == 0
137
137
 
138
138
  # range_stepBy: stepBy on until and to
139
139
  fun rangeStepByStepByOnUntilAndTo() =
140
140
  total := Tally(n: 0)
141
- for i := range 0.until(10).stepBy(3)
141
+ for i := range Range.until(0, 10).stepBy(3)
142
142
  total.n = total.n + i
143
143
  assert total.n == 18
144
- for i := range 1.to(10).stepBy(4)
144
+ for i := range Range.to(1, 10).stepBy(4)
145
145
  total.n = total.n + i
146
146
  assert total.n == 18 + 15
147
147
 
148
148
  # range_filter: an if in the body filters an Int range
149
149
  fun rangeFilterAnIfInTheBodyFilters() =
150
150
  evens := Tally(n: 0)
151
- for i := range 0.until(10)
151
+ for i := range Range.until(0, 10)
152
152
  if i % 2 == 0
153
153
  evens.n = evens.n + 1
154
154
  assert evens.n == 5
155
155
  down := Tally(n: 0)
156
- for i := range 9.downTo(0).stepBy(4)
156
+ for i := range Range.downTo(9, 0).stepBy(4)
157
157
  down.n = down.n * 10 + i
158
158
  assert down.n == 951
159
159
  kept := Tally(n: 0)
160
- for i := range 0.until(6)
160
+ for i := range Range.until(0, 6)
161
161
  if i >= 3
162
162
  kept.n = kept.n + i
163
163
  assert kept.n == 12
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -69,7 +69,7 @@ primitive PlaygroundScreenTest[UnitTest] =
69
69
  assert u.screen.balloons.at(0).y > Arena.H
70
70
 
71
71
  fun everyTenthPopStartsAPartyThatEnds() =
72
- t := 0.until(9).fold(PlaygroundScreenHelpers.field(io, 3), |r, i| r.dispatch(Popped(at: -50.0)))
72
+ t := Range.until(0, 9).fold(PlaygroundScreenHelpers.field(io, 3), |r, i| r.dispatch(Popped(at: -50.0)))
73
73
  assert !t.screen.partying()
74
74
  u := PlaygroundScreenHelpers.centred(t).clickAt(400.0, 300.0).tick(0.0)
75
75
  assert u.screen.pops == 10
@@ -80,7 +80,7 @@ primitive PlaygroundScreenTest[UnitTest] =
80
80
  # the game counts pops as they are dispatched and plays one pop a tick, and the fanfare
81
81
  fun theGameCountsPopsAsTheyAreDispatched() =
82
82
  t := PlaygroundScreenHelpers.field(io, 3)
83
- f := 0.until(8).fold(t.screen, |s, i| s.popped(-50.0))
83
+ f := Range.until(0, 8).fold(t.screen, |s, i| s.popped(-50.0))
84
84
  u := PlaygroundScreenHelpers.stillAt(PlaygroundScreenHelpers.stillAt(PlaygroundScreenHelpers.stillAt(PlaygroundScreenHelpers.poked(t, f), 0, 200.0, 300.0), 1, 400.0, 300.0), 2, 600.0, 300.0)
85
85
  v := u.clickAt(200.0, 300.0).clickAt(400.0, 300.0).tick()
86
86
  assert v.screen.pops == 10
@@ -115,7 +115,7 @@ primitive PlaygroundScreenTest[UnitTest] =
115
115
 
116
116
  # the screen counts pops, every tenth starts a party, and a tick hears them once
117
117
  fun theScreenCountsPopsEveryTenthStartsA() =
118
- s := 0.until(9).fold(PlaygroundScreenHelpers.field(io, 3).screen, |p, i| p.popped(Float(i)))
118
+ s := Range.until(0, 9).fold(PlaygroundScreenHelpers.field(io, 3).screen, |p, i| p.popped(Float(i)))
119
119
  assert s.pops == 9
120
120
  assert !s.partyingAt(9.0)
121
121
  t := s.popped(12.0)
@@ -130,7 +130,7 @@ primitive PlaygroundScreenTest[UnitTest] =
130
130
  assert h2.popsHeard == 1
131
131
 
132
132
  fun aRecordedRunReplaysToTheSameBalloons() =
133
- a := 0.until(900).fold(PlaygroundScreenHelpers.field(io, 21).record(21), |r, f| r.frame(PlaygroundScreenHelpers.runInput(f), 0.0166 + Float(f % 3) * 0.004 - 0.004))
133
+ a := Range.until(0, 900).fold(PlaygroundScreenHelpers.field(io, 21).record(21), |r, f| r.frame(PlaygroundScreenHelpers.runInput(f), 0.0166 + Float(f % 3) * 0.004 - 0.004))
134
134
  r := a.recorded()
135
135
  assert r.length() == a.game.ticks
136
136
  assert a.screen.pops > 0
@@ -209,13 +209,13 @@ primitive PlaygroundScreenHelpers =
209
209
 
210
210
  fun sameField(a: PlaygroundScreen, b: PlaygroundScreen) -> Bool =
211
211
  a.pops == b.pops && a.clock == b.clock && a.partyAt == b.partyAt && a.rng.seed == b.rng.seed
212
- && 0.until(a.balloons.length()).all(|i|
212
+ && Range.until(0, a.balloons.length()).all(|i|
213
213
  p := a.balloons.at(i)
214
214
  q := b.balloons.at(i)
215
215
  p.x == q.x && p.y == q.y && p.hue == q.hue && p.poppedAt == q.poppedAt)
216
216
 
217
217
  fun framesFrom(t: TestRig<PlaygroundScreen>, from: Int, n: Int) -> TestRig<PlaygroundScreen> =
218
- 0.until(n).fold(t, |r, f| r.frame(runInput(from + f), Clock.Tick))
218
+ Range.until(0, n).fold(t, |r, f| r.frame(runInput(from + f), Clock.Tick))
219
219
 
220
220
  fun untilPops(t: TestRig<PlaygroundScreen>, f: Int, pops: Int) -> TestRig<PlaygroundScreen> =
221
221
  if t.screen.pops >= pops || f >= 900 then t else untilPops(t.frame(runInput(f), Clock.Tick), f + 1, pops)
tests/examples/games/game_loop.plum CHANGED
@@ -19,8 +19,8 @@ primitive GameLoopTest[UnitTest] =
19
19
  fun survivorsHaveMovedAndAgedTheExpectedAmount() =
20
20
  ps := Slice<Particle>()
21
21
  _ := Stats.run(100, ps)
22
- x := 0.until(ps.length()).fold(0.0, |total, i| total + ps.at(i).pos.x)
22
+ x := Range.until(0, ps.length()).fold(0.0, |total, i| total + ps.at(i).pos.x)
23
- life := 0.until(ps.length()).fold(0, |total, i| total + ps.at(i).life)
23
+ life := Range.until(0, ps.length()).fold(0, |total, i| total + ps.at(i).life)
24
24
  # spawned on frames 80 and 90: 20 and 10 steps of +1.0, 5 and 15 life left
25
25
  assert x == 30.0
26
26
  assert life == 20
tests/examples/games/orbitrunner/actors/Ship.plum CHANGED
@@ -17,11 +17,11 @@ primitive ShipTest[UnitTest] =
17
17
  ship := Ship.startAt(Texture.none(), 400.0, 300.0).steer(1.0, 0.0).step(0.1)
18
18
  assert ship.vx > 0.0
19
19
  assert ship.at.x > 400.0
20
- slow := 0.until(30).fold(ship.steer(0.0, 0.0), |s, i| s.step(0.1))
20
+ slow := Range.until(0, 30).fold(ship.steer(0.0, 0.0), |s, i| s.step(0.1))
21
21
  assert slow.vx < ship.vx / 4.0
22
22
 
23
23
  fun theShipStopsAtTheArenaWalls() =
24
- ship := 0.until(20).fold(Ship.startAt(Texture.none(), 20.0, 20.0).steer(-1.0, -1.0), |s, i| s.step(0.1))
24
+ ship := Range.until(0, 20).fold(Ship.startAt(Texture.none(), 20.0, 20.0).steer(-1.0, -1.0), |s, i| s.step(0.1))
25
25
  assert ship.at.x == Ship.Radius
26
26
  assert ship.at.y == Ship.Radius
27
27
  assert ship.vx == 0.0
@@ -30,12 +30,12 @@ primitive ShipTest[UnitTest] =
30
30
  fun itsViewIsAGlowAndASprite() =
31
31
  ship := Ship.create(Texture.none())
32
32
  assert ship.view().length() == 2
33
- later := 0.until(5).fold(ship, |s, i| s.step(0.02))
33
+ later := Range.until(0, 5).fold(ship, |s, i| s.step(0.02))
34
34
  sprite := match later.view().at(1)
35
35
  Sprite as s => s.frameX()
36
36
  _ => -1.0
37
37
  assert sprite == Sheet.Cell
38
- blinks := 0.until(60).fold(Blinks(ship: later.hurtFor(Ship.HurtTime), n: 0), |b, i|
38
+ blinks := Range.until(0, 60).fold(Blinks(ship: later.hurtFor(Ship.HurtTime), n: 0), |b, i|
39
39
  next := b.ship.step(0.02)
40
40
  Blinks(ship: next, n: if next.visible() then b.n else b.n + 1))
41
41
  assert blinks.n > 0 && blinks.n < 60
tests/examples/games/orbitrunner/actors/Star.plum CHANGED
@@ -12,7 +12,7 @@ import std/Test
12
12
  primitive StarTest[UnitTest] =
13
13
  # a star twinkles between 0.05 and 0.45 as the clock runs
14
14
  fun aStarTwinklesBetween005And0() =
15
- low := 0.until(200).fold(1.0, |m, i| m.min(Star(index: 4, clock: Float(i + 1) * 0.05).twinkle()))
15
+ low := Range.until(0, 200).fold(1.0, |m, i| m.min(Star(index: 4, clock: Float(i + 1) * 0.05).twinkle()))
16
- high := 0.until(200).fold(0.0, |m, i| m.max(Star(index: 4, clock: Float(i + 1) * 0.05).twinkle()))
16
+ high := Range.until(0, 200).fold(0.0, |m, i| m.max(Star(index: 4, clock: Float(i + 1) * 0.05).twinkle()))
17
17
  assert low >= 0.05 && low < 0.1
18
18
  assert high <= 0.45 && high > 0.4
tests/examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -73,7 +73,7 @@ primitive PlayingScreenTest[UnitTest] =
73
73
  assert PlayingScreenHelpers.icons(t) == PlayingScreen.StartLives - 1
74
74
  assert t.screen.ship.hurt > 0.0
75
75
  safe := PlayingScreenHelpers.mineAway(t)
76
- blinks := 0.until(100).fold(Run(rig: safe, overs: 0, restarts: 0), |r, i|
76
+ blinks := Range.until(0, 100).fold(Run(rig: safe, overs: 0, restarts: 0), |r, i|
77
77
  next := r.rig.tick(0.016)
78
78
  Run(rig: next, overs: if next.screen.ship.lit() then r.overs else r.overs + 1, restarts: if next.screen.ship.lit() then r.restarts + 1 else r.restarts))
79
79
  assert blinks.overs > 0
@@ -153,7 +153,7 @@ primitive PlayingScreenTest[UnitTest] =
153
153
  mine := p.mines.at(0)
154
154
  grown := started.tick(0.1)
155
155
  assert grown.screen.rings.at(0).age > 0.09
156
- later := 0.until(10).fold(grown.hold(Key.Right), |r, i| r.tick(0.1))
156
+ later := Range.until(0, 10).fold(grown.hold(Key.Right), |r, i| r.tick(0.1))
157
157
  q := later.screen
158
158
  assert q.mines.at(0).at.x == mine.at.x
159
159
  assert q.mines.at(0).at.rotation == mine.at.rotation
@@ -408,8 +408,8 @@ primitive PlayingScreenHelpers =
408
408
  && a.ship.at.x == b.ship.at.x && a.ship.at.y == b.ship.at.y && a.ship.vx == b.ship.vx && a.ship.vy == b.ship.vy
409
409
  && a.ship.hurt == b.ship.hurt && a.ship.clock == b.ship.clock
410
410
  && a.orbs.length() == b.orbs.length() && a.mines.length() == b.mines.length()
411
- && 0.until(a.orbs.length()).all(|i| a.orbs.at(i).at.x == b.orbs.at(i).at.x && a.orbs.at(i).at.y == b.orbs.at(i).at.y)
411
+ && Range.until(0, a.orbs.length()).all(|i| a.orbs.at(i).at.x == b.orbs.at(i).at.x && a.orbs.at(i).at.y == b.orbs.at(i).at.y)
412
- && 0.until(a.mines.length()).all(|i| a.mines.at(i).at.x == b.mines.at(i).at.x && a.mines.at(i).at.y == b.mines.at(i).at.y)
412
+ && Range.until(0, a.mines.length()).all(|i| a.mines.at(i).at.x == b.mines.at(i).at.x && a.mines.at(i).at.y == b.mines.at(i).at.y)
413
413
 
414
414
  fun runInput(i: Int, p: PlayingScreen) -> Input =
415
415
  s := p.ship.at
tests/examples/generics.plum CHANGED
@@ -134,7 +134,7 @@ primitive GenericsTest[UnitTest] =
134
134
  names := Slice<Str>()
135
135
  for s := range shapes
136
136
  names.push(s.name())
137
- total := 0.until(shapes.length()).fold(0.0, |sum, i| sum + shapes.at(i).area())
137
+ total := Range.until(0, shapes.length()).fold(0.0, |sum, i| sum + shapes.at(i).area())
138
138
  assert names.join(",") == "circle,circle"
139
139
  assert total == 39.0
140
140
 
tests/examples/sequences.plum CHANGED
@@ -42,7 +42,7 @@ primitive SequencesTest[UnitTest] =
42
42
  fromList.n = fromList.n * 10 + x
43
43
  assert fromList.n == 123
44
44
  fromRange := Tally(n: 0)
45
- for i := range 1.to(9).stepBy(4)
45
+ for i := range Range.to(1, 9).stepBy(4)
46
46
  fromRange.n = fromRange.n * 10 + i
47
47
  assert fromRange.n == 159
48
48
 
@@ -83,7 +83,7 @@ primitive SequencesTest[UnitTest] =
83
83
  fun sumOfHpOfMyTeamFilterMap() =
84
84
  units := Sequences.army()
85
85
  me := units.at(0)
86
- total := 0.until(units.length()).fold(0.0, |sum, i|
86
+ total := Range.until(0, units.length()).fold(0.0, |sum, i|
87
87
  u := units.at(i)
88
88
  if u.team == me.team
89
89
  sum + u.hp
@@ -112,7 +112,7 @@ primitive SequencesTest[UnitTest] =
112
112
  fun firstEnemyInRangeFilterFind() =
113
113
  units := Sequences.army()
114
114
  me := units.at(0)
115
- hit := 0.until(units.length()).find(|i|
115
+ hit := Range.until(0, units.length()).find(|i|
116
116
  u := units.at(i)
117
117
  u.team != me.team && Sequences.dist2(u.x, u.y, me.x, me.y) < 4.0
118
118
  )
tests/examples/unions.plum CHANGED
@@ -19,7 +19,7 @@ primitive UnionsTest[UnitTest] =
19
19
  xs := Slice<Shape>()
20
20
  xs.push(Circle(r: 1.0))
21
21
  xs.push(Rectangle(w: 2.0, h: 3.0))
22
- sum := 0.until(xs.length()).fold(0.0, |acc, i| acc + xs.at(i).area())
22
+ sum := Range.until(0, xs.length()).fold(0.0, |acc, i| acc + xs.at(i).area())
23
23
  assert sum == 9.0
24
24
 
25
25
  # tree_generic
@@ -69,7 +69,7 @@ primitive UnionsTest[UnitTest] =
69
69
  xs.push(JInt(v: 1))
70
70
  xs.push(JStr(v: "a"))
71
71
  xs.push(JFloat(v: 2.5))
72
- n := 0.until(xs.length()).fold(0, |acc, i| acc + xs.at(i).describeJv().length())
72
+ n := Range.until(0, xs.length()).fold(0, |acc, i| acc + xs.at(i).describeJv().length())
73
73
  assert n == 3 + 5 + 5
74
74
 
75
75
  # tags and per-tag values
tests/fbip/aliasing.plum CHANGED
@@ -146,7 +146,7 @@ primitive AliasingTest[UnitTest] =
146
146
  fun aSharedValuePassedThroughAMethodThen() =
147
147
  a := Cell(label: "a", n: 0)
148
148
  v := a.same()
149
- last := 0.until(3).fold(v, |cur, i| cur.bumped())
149
+ last := Range.until(0, 3).fold(v, |cur, i| cur.bumped())
150
150
  assert a.n == 0
151
151
  assert last.n == 3
152
152
 
@@ -189,7 +189,7 @@ primitive AliasingTest[UnitTest] =
189
189
  fun aLoopKeepingThePreviousValue() =
190
190
  v := Cell(label: "v", n: 0)
191
191
  prev := Slice<Cell>()
192
- last := 0.until(3).fold(v, |cur, i|
192
+ last := Range.until(0, 3).fold(v, |cur, i|
193
193
  prev.push(cur)
194
194
  cur.bumped()
195
195
  )
@@ -203,7 +203,7 @@ primitive AliasingTest[UnitTest] =
203
203
  start := Cell(label: "s", n: 0)
204
204
  keepIt := Holder(a: start, b: start)
205
205
  v := start
206
- last := 0.until(3).fold(v, |cur, i| bump(cur))
206
+ last := Range.until(0, 3).fold(v, |cur, i| bump(cur))
207
207
  assert last.n == 3
208
208
  assert start.n == 0
209
209
  assert keepIt.a.n == 0
@@ -263,7 +263,7 @@ primitive AliasingTest[UnitTest] =
263
263
 
264
264
  fun aFreshValueHandedOverRepeatedlyIsCorrect() =
265
265
  v := Cell(label: "f", n: 0)
266
- last := 0.until(4).fold(v, |cur, i| cur.bumped())
266
+ last := Range.until(0, 4).fold(v, |cur, i| cur.bumped())
267
267
  assert last.n == 4
268
268
  w := twice(shared("w", 10))
269
269
  assert w.n == 12
@@ -289,7 +289,7 @@ primitive AliasingTest[UnitTest] =
289
289
  fun aReturnedParameterHandedOverInALoop() =
290
290
  xs := Slice<Cell>()
291
291
  v := Cell(label: "v", n: 0)
292
- last := 0.until(3).fold(v, |cur, i|
292
+ last := Range.until(0, 3).fold(v, |cur, i|
293
293
  stored := reg(xs, cur)
294
294
  bump(stored)
295
295
  )
tests/fbip/fuzz/gen.pl CHANGED
@@ -54,16 +54,16 @@ for my $n (1..(6+r(12))) {
54
54
  elsif ($k==33) { $s = "spin($V, ".r(4).")"; }
55
55
  elsif ($k==34) { $s = "spin2($V, ".r(4).")"; }
56
56
  elsif ($k==35) { $s = "spin3($V, ".r(3).")"; }
57
- elsif ($k==36) { $s = "0.until(".r(4).").fold($V, |acc, i| ".pick("acc.inc()", "P(..acc, a: acc.a + i)", "pass(acc, $V2)", "bump(acc)", "P(..acc, b: acc.a + $V.b)").")"; }
57
+ elsif ($k==36) { $s = "Range.until(0, ".r(4).").fold($V, |acc, i| ".pick("acc.inc()", "P(..acc, a: acc.a + i)", "pass(acc, $V2)", "bump(acc)", "P(..acc, b: acc.a + $V.b)").")"; }
58
- elsif ($k==37) { $s = "0.until(".r(4).").fold($W.p, |acc, i| ".pick("acc.inc()", "pass(acc, acc)", "P(..acc, a: i)").")"; }
58
+ elsif ($k==37) { $s = "Range.until(0, ".r(4).").fold($W.p, |acc, i| ".pick("acc.inc()", "pass(acc, acc)", "P(..acc, a: i)").")"; }
59
59
  elsif ($k==43) { $s = "rtick($V)"; }
60
60
  elsif ($k==44) { $s = "rleak(".pick("R(n: $V.a, p: $V)", "R(p: bump($V), n: $V.a)", "R(p: $V, n: 0).tick()").")"; }
61
61
  elsif ($k==46) { $s = pick("vup($V)", "vup(vup($V))", "vup(mk(1, 2))", "pass(vup($V), $V2)"); }
62
62
  elsif ($k==47) { $s = pick("$V.dbl()", "$V.dbl().dbl()", "mk(3, 4).dbl()", "pass($V.dbl(), $V)"); }
63
63
  elsif ($k==48) { $s = pick("vping($V, ".r(4).")", "vping(mk(0, 0), ".r(4).")", "vpong($V, ".r(3).")"); }
64
64
  elsif ($k==49) { $s = pick("vcnt($V, ".r(4).")", "vcnt(vcnt($V, 2), 1)", "vcnt(bump($V), 2)"); }
65
- elsif ($k==50) { $s = "0.until(".r(3).").fold($V, |acc, i| ".pick("vup(acc)", "acc.dbl()", "vcnt(acc, i)").")"; }
65
+ elsif ($k==50) { $s = "Range.until(0, ".r(3).").fold($V, |acc, i| ".pick("vup(acc)", "acc.dbl()", "vcnt(acc, i)").")"; }
66
- elsif ($k==45) { $s = "0.until(".r(4).").fold($V, |acc, i| ".pick("step2(acc, i)", "step2(acc, $V2.a)").")"; }
66
+ elsif ($k==45) { $s = "Range.until(0, ".r(4).").fold($V, |acc, i| ".pick("step2(acc, i)", "step2(acc, $V2.a)").")"; }
67
67
  else { $isv = 0; }
68
68
  if ($isv) { push @stmts, "$nvn := $s"; push @vs, $nvn; $nv++; next; }
69
69
  if ($k==16) { $s = "Q(p: $V, n: ".r(4).")"; }
@@ -131,7 +131,7 @@ for my $n (1..(4+r(9))) {
131
131
  if ($k == 8) { $x = "lup(".consume(\@ls).")"; }
132
132
  elsif ($k == 9) { $x = consume(\@ls).".up()"; }
133
133
  elsif ($k == 10) { $x = "lthru(".consume(\@ls).")"; }
134
- elsif ($k == 11) { $x = "0.until(".r(4).").fold(".consume(\@ls).", |acc, i| lup(acc))"; }
134
+ elsif ($k == 11) { $x = "Range.until(0, ".r(4).").fold(".consume(\@ls).", |acc, i| lup(acc))"; }
135
135
  else { $x = "lmk(".r(9).")"; }
136
136
  push @lin, "l$nl := $x"; push @ls, "l$nl"; $nl++;
137
137
  }
@@ -188,7 +188,7 @@ for my $n (1..(5+r(12))) {
188
188
  elsif ($k == 7) { my $g = consume(\@gs); $x = "$g.with($g.gn).with(P(..$g.gv, b: 9))"; }
189
189
  elsif ($k == 8) { $x = "gspin(".consume(\@gs).", ".r(4).")"; }
190
190
  elsif ($k == 9) { my $g = consume(\@gs); my $g2 = pick(@gs, $g); $x = "if ".gint()." > 2 then $g.bump() else $g2"; }
191
- elsif ($k == 10) { $x = "0.until(".r(4).").fold(".consume(\@gs).", |acc, i| ".pick("acc.bump()", "G(..acc, gn: acc.gn + i)", "gbump(acc)", "acc.set(acc.gv.inc())").")"; }
191
+ elsif ($k == 10) { $x = "Range.until(0, ".r(4).").fold(".consume(\@gs).", |acc, i| ".pick("acc.bump()", "G(..acc, gn: acc.gn + i)", "gbump(acc)", "acc.set(acc.gv.inc())").")"; }
192
192
  elsif ($k == 11) { $x = "gapply(".consume(\@gs).", |y| ".pick("y.bump()", "gbump(y)", "G(..y, gn: 5)").")"; }
193
193
  elsif ($k == 12) { $x = "Some(".consume(\@gs).").unwrapOr(g0)"; }
194
194
  elsif ($k == 13) { $x = "gtk(".consume(\@gs).")"; }
tests/fbip/last_use_moves.plum CHANGED
@@ -37,9 +37,9 @@ primitive LastUseMoves =
37
37
  # a fold accumulator
38
38
  fun lmBumpF(c: Cnt) -> Cnt = Cnt(..c, n: c.n + 1)
39
39
 
40
- fun lmFold(k: Int) -> Cnt = 0.until(k).fold(Cnt(label: "a", n: 0), |acc, i| lmBumpF(acc))
40
+ fun lmFold(k: Int) -> Cnt = Range.until(0, k).fold(Cnt(label: "a", n: 0), |acc, i| lmBumpF(acc))
41
41
 
42
- fun lmFoldSpread(k: Int) -> Cnt = 0.until(k).fold(Cnt(label: "a", n: 0), |acc, i| Cnt(..acc, n: acc.n + i))
42
+ fun lmFoldSpread(k: Int) -> Cnt = Range.until(0, k).fold(Cnt(label: "a", n: 0), |acc, i| Cnt(..acc, n: acc.n + i))
43
43
 
44
44
  # ---- hostile: the old value is still there afterwards ----
45
45
  fun lmBumpS(c: Cnt) -> Cnt = Cnt(..c, n: c.n + 1)
tests/fbip/map_persistence/snapshot.plum CHANGED
@@ -23,7 +23,7 @@ primitive SnapshotTest[UnitTest] =
23
23
 
24
24
  # a kept set is unchanged by updates of the new version
25
25
  fun aKeptSetIsUnchangedByUpdatesOf() =
26
- a := 0.until(40).fold(Set<Int>(), |acc, i| acc.add(i))
26
+ a := Range.until(0, 40).fold(Set<Int>(), |acc, i| acc.add(i))
27
27
  b := a.add(100).remove(7).add(101)
28
28
  assert a.length() == 40 && a.contains(7) && !a.contains(100)
29
29
  assert b.length() == 41 && !b.contains(7) && b.contains(101)
tests/fbip/moves_into_fields.plum CHANGED
@@ -65,21 +65,21 @@ primitive MovesIntoFields =
65
65
  # A fold whose closure calls a named function: the literal left at the call never runs.
66
66
  fip fun foldStep(c: MoveIn, i: Int) -> MoveIn = MoveIn(..c, n: c.n + i)
67
67
 
68
- fun foldNamed() -> MoveIn = 0.until(4).fold(MoveIn(label: "f", n: 0), |acc, i| foldStep(acc, i))
68
+ fun foldNamed() -> MoveIn = Range.until(0, 4).fold(MoveIn(label: "f", n: 0), |acc, i| foldStep(acc, i))
69
69
 
70
70
  fun foldSeedShared() -> Int =
71
71
  seed := MoveIn(label: "s", n: 1)
72
- r := 0.until(4).fold(seed, |acc, i| MoveIn(..acc, n: acc.n + i))
72
+ r := Range.until(0, 4).fold(seed, |acc, i| MoveIn(..acc, n: acc.n + i))
73
73
  r.n * 10 + seed.n
74
74
 
75
75
  fun foldCapture() -> Int =
76
76
  c := MoveIn(label: "c", n: 5)
77
- r := 0.until(3).fold(MoveIn(label: "f", n: 0), |acc, i| MoveIn(..acc, n: acc.n + c.n))
77
+ r := Range.until(0, 3).fold(MoveIn(label: "f", n: 0), |acc, i| MoveIn(..acc, n: acc.n + c.n))
78
78
  r.n * 10 + c.n
79
79
 
80
80
  fun foldCaptureSpread() -> Int =
81
81
  c := MoveIn(label: "c", n: 5)
82
- r := 0.until(3).fold(0, |acc, i| acc + MoveIn(..c, n: c.n + 1).n)
82
+ r := Range.until(0, 3).fold(0, |acc, i| acc + MoveIn(..c, n: c.n + 1).n)
83
83
  r
84
84
 
85
85
  # A local moved into a field is not the field's only holder when it is used again.
tests/fbip/receiver_stamps.plum CHANGED
@@ -66,7 +66,7 @@ primitive ReceiverStampsTest[UnitTest] =
66
66
  a.n * 100 + h.v.n
67
67
 
68
68
  fun loopy(s: Ship, o: Orb) -> Int =
69
- 0.until(3).fold(0, |t, i|
69
+ Range.until(0, 3).fold(0, |t, i|
70
70
  q := s.inplace()
71
71
  r := o.inplace()
72
72
  t + q.n + r.n + s.n + o.n + i)
tests/fbip/slice_shapes.plum CHANGED
@@ -36,7 +36,7 @@ primitive SliceShapes[App] =
36
36
  v
37
37
 
38
38
  fun s4(n: Int) -> Int =
39
- v := 0.until(n).fold(Slice<Int>(), |cur, i| grow4(cur, i))
39
+ v := Range.until(0, n).fold(Slice<Int>(), |cur, i| grow4(cur, i))
40
40
  v.length() + v.at(n - 1)
41
41
 
42
42
  fun s5(n: Int) -> Int =
@@ -88,7 +88,7 @@ primitive SliceShapes[App] =
88
88
  State10(..s, tick: s.tick + 1)
89
89
 
90
90
  fun s10(n: Int) -> Int =
91
- s := 0.until(n).fold(State10(items: Slice<Int>(), tick: 0), |cur, i| step10(cur, i))
91
+ s := Range.until(0, n).fold(State10(items: Slice<Int>(), tick: 0), |cur, i| step10(cur, i))
92
92
  s.items.length() + s.items.at(n - 1) + s.tick
93
93
 
94
94
  fun frame11(w: World11, n: Int) -> World11 =
@@ -109,8 +109,8 @@ primitive SliceShapes[App] =
109
109
  # the persistent alternative to Slice: a List, rebuilt each frame by `map`
110
110
  fun s11list(n: Int, frames: Int) -> Int =
111
111
  empty: List<Int> := Nil
112
- zeros := 0.until(n).fold(empty, |l, i| Cons(head: 0, tail: l))
112
+ zeros := Range.until(0, n).fold(empty, |l, i| Cons(head: 0, tail: l))
113
- bumped := 0.until(frames).fold(zeros, |l, f| l.map(|x| x + 1))
113
+ bumped := Range.until(0, frames).fold(zeros, |l, f| l.map(|x| x + 1))
114
114
  bumped.at(0) + bumped.at(n - 1) + frames
115
115
 
116
116
  fun timed(io: Io, label: Str, work: fn() -> Int) -> Unit =
tests/fbip_probes/array_set.plum CHANGED
@@ -15,7 +15,7 @@ primitive ArraySet[App] =
15
15
  a := Array<Int>().resize(1000)
16
16
  for i := range n
17
17
  a.set(i % 1000, i)
18
- 0.until(1000).fold(0, |total, j| total + a.at(j))
18
+ Range.until(0, 1000).fold(0, |total, j| total + a.at(j))
19
19
 
20
20
  fun main(io: Io) =
21
21
  t0 := Time.now(io).toMillis()
tests/fbip_probes/map_set_get.plum CHANGED
@@ -16,8 +16,8 @@ primitive MapSetGet[App] =
16
16
 
17
17
  fun run(n: Int) -> Int =
18
18
  start: Map<Int, Int> := Map.empty()
19
- m := 0.until(n).fold(start, |acc, i| acc.with(i, i * 2))
19
+ m := Range.until(0, n).fold(start, |acc, i| acc.with(i, i * 2))
20
- 0.until(n).fold(0, |total, i| total + m.get(i).unwrapOr(0))
20
+ Range.until(0, n).fold(0, |total, i| total + m.get(i).unwrapOr(0))
21
21
 
22
22
  fun main(io: Io) =
23
23
  t0 := Time.now(io).toMillis()
tests/fbip_probes/struct_spread.plum CHANGED
@@ -13,7 +13,7 @@ primitive StructSpread[App] =
13
13
  fun size() -> Int = 1000000
14
14
 
15
15
  fun run(count: Int) -> Int =
16
- c := 0.until(count).fold(Cell(label: "cell", n: 0, m: 0), |cur, i| Cell(..cur, n: cur.n + 1))
16
+ c := Range.until(0, count).fold(Cell(label: "cell", n: 0, m: 0), |cur, i| Cell(..cur, n: cur.n + 1))
17
17
  c.n + c.m
18
18
 
19
19
  fun main(io: Io) =
tests/param_defaults.plum CHANGED
@@ -55,7 +55,7 @@ primitive ParamDefaults =
55
55
  # the parameter is rebuilt with a spread
56
56
  fun respread(d: Cell = Cell(n: 1, label: "a")) -> Int =
57
57
  first := Cell(..d, n: d.n + 1)
58
- 0.until(3).fold(first, |c, i| Cell(..c, n: c.n + 1)).n
58
+ Range.until(0, 3).fold(first, |c, i| Cell(..c, n: c.n + 1)).n
59
59
 
60
60
  # a default that calls a fn, a generic fn, and an expression
61
61
  fun made() -> Int = times3(2)
tests/port/game/determinism.plum CHANGED
@@ -95,7 +95,7 @@ primitive Determinism =
95
95
  0.0166 + Float(i % 3) * 0.004 - 0.004
96
96
 
97
97
  fun scriptedRun(io: Io, seed: Int, frames: Int) -> Run =
98
- 0.until(frames).fold(start(seed), |r, i| runFrame(io, r, scripted(i), jitter(i)))
98
+ Range.until(0, frames).fold(start(seed), |r, i| runFrame(io, r, scripted(i), jitter(i)))
99
99
 
100
100
  # The ticks one frame of `dt` runs from a fresh clock.
101
101
  fun ticksOf(io: Io, dt: Float) -> Int =
@@ -129,7 +129,7 @@ primitive DeterminismTest[UnitTest] =
129
129
  rates := [30, 60, 75, 144, 240]
130
130
  for k := range rates.length()
131
131
  rate := rates.at(k)
132
- r := 0.until(rate).fold(Determinism.start(1), |acc, _| Determinism.runFrame(io, acc, Determinism.still(), 1.0 / Float(rate)))
132
+ r := Range.until(0, rate).fold(Determinism.start(1), |acc, _| Determinism.runFrame(io, acc, Determinism.still(), 1.0 / Float(rate)))
133
133
  assert r.probe().minDt == Clock.Tick
134
134
  assert r.probe().maxDt == Clock.Tick
135
135
  assert r.probe().ticks >= 59 && r.probe().ticks <= 60
@@ -149,7 +149,7 @@ primitive DeterminismTest[UnitTest] =
149
149
  inputs := Slice<Input>()
150
150
  for i := range 120
151
151
  inputs.push(Determinism.scripted(i / 3))
152
- play := |seed: Int| 0.until(120).fold(Determinism.probeGame(seed), |g, i| g.step(io, inputs.at(i), 1.0 / 60.0, Determinism.View))
152
+ play := |seed: Int| Range.until(0, 120).fold(Determinism.probeGame(seed), |g, i| g.step(io, inputs.at(i), 1.0 / 60.0, Determinism.View))
153
153
  play2 := |seed: Int| Run(game: play(seed), clock: Clock.create()).probe()
154
154
  a := play2(5)
155
155
  b := play2(5)
tests/port/game/replay.plum CHANGED
@@ -270,8 +270,8 @@ primitive ReplayTest[UnitTest] =
270
270
 
271
271
  fun recorded(io: Io, seed: Int, frames: Int) -> Run =
272
272
  start := Run(game: probeGame(seed), clock: Clock.create(), log: Slice<Input>())
273
- 0.until(frames).fold(start, |r, i| recordFrame(io, r, scripted(i), jitter(i)))
273
+ Range.until(0, frames).fold(start, |r, i| recordFrame(io, r, scripted(i), jitter(i)))
274
274
 
275
275
  fun replayed(io: Io, r: Replay, frames: Int) -> Run =
276
276
  start := Run(game: probeGame(r.seed), clock: Clock.playing(r), log: Slice<Input>())
277
- 0.until(frames).fold(start, |run, i| replayFrame(io, run, jitter(i + 1)))
277
+ Range.until(0, frames).fold(start, |run, i| replayFrame(io, run, jitter(i + 1)))
tests/port/game/routing.plum CHANGED
@@ -132,7 +132,7 @@ primitive RoutingTest[UnitTest] =
132
132
  # The reference's answer for `p`: the last node in draw order hit there, -1 for none, -2
133
133
  # when the point is within 1e-6 of a candidate's edge (skipped).
134
134
  fun reference(specs: Slice<Spec>, p: Vec2) -> Int =
135
- 0.until(specs.length()).fold(-1, |best, i|
135
+ Range.until(0, specs.length()).fold(-1, |best, i|
136
136
  s := specs.at(i)
137
137
  if best == -2 || !s.touch.enabled() || s.touch.disabled() || !reachable(specs, i, true)
138
138
  best
tests/port/game/screens.plum CHANGED
@@ -334,7 +334,7 @@ primitive ScreensTest[UnitTest] =
334
334
 
335
335
  fun aRecordedRunReplaysToTheSameState() =
336
336
  a := Screens.probe(io).record(5)
337
- b := 0.until(60).fold(a, |r, i| if i % 7 == 3 then r.press(Key.Space).tick() else r.tick())
337
+ b := Range.until(0, 60).fold(a, |r, i| if i % 7 == 3 then r.press(Key.Space).tick() else r.tick())
338
338
  assert b.recorded().length() == 60
339
339
  back := Replay.decode(b.recorded().encode()).unwrap()
340
340
  c := Screens.probe(io).replay(back)
tests/std/Decimal.plum CHANGED
@@ -113,7 +113,7 @@ primitive DecimalTest[UnitTest] =
113
113
 
114
114
  # 6000 random bit patterns (and their negatives) round-trip through ofFloat, toStr, parse and exact
115
115
  fun t6000RandomBitPatternsAndTheirNegativesRound() =
116
- bad := 1.to(3000).fold(Pair(first: 88172645463325252, second: 0), |acc, i|
116
+ bad := Range.to(1, 3000).fold(Pair(first: 88172645463325252, second: 0), |acc, i|
117
117
  x0 := acc.first
118
118
  x1 := x0 ^ {x0 << 13}
119
119
  x2 := x1 ^ {x1 >> 7}
tests/std/Int.plum CHANGED
@@ -10,19 +10,19 @@ import std/Test
10
10
 
11
11
  primitive IntTest[UnitTest] =
12
12
  fun rangeFoldEachFind() =
13
- assert 1.to(10).fold(0, |a, x| a + x) == 55
13
+ assert Range.to(1, 10).fold(0, |a, x| a + x) == 55
14
- assert 5.until(5).fold(7, |a, x| a + x) == 7
14
+ assert Range.until(5, 5).fold(7, |a, x| a + x) == 7
15
- assert 3.downTo(1).fold(0, |a, x| a * 10 + x) == 321
15
+ assert Range.downTo(3, 1).fold(0, |a, x| a * 10 + x) == 321
16
- assert 1.to(10).find(|x| x * x > 20).unwrapOr(-1) == 5
16
+ assert Range.to(1, 10).find(|x| x * x > 20).unwrapOr(-1) == 5
17
- assert 1.to(3).find(|x| x > 9).isNone()
17
+ assert Range.to(1, 3).find(|x| x > 9).isNone()
18
18
 
19
19
  fun rangeAnyAndAll() =
20
- assert 1.to(10).any(|x| x == 7) && !1.to(10).any(|x| x > 10)
20
+ assert Range.to(1, 10).any(|x| x == 7) && !Range.to(1, 10).any(|x| x > 10)
21
- assert 1.to(10).all(|x| x > 0) && !1.to(10).all(|x| x < 10)
21
+ assert Range.to(1, 10).all(|x| x > 0) && !Range.to(1, 10).all(|x| x < 10)
22
- assert 5.until(5).all(|x| false) && !5.until(5).any(|x| true)
22
+ assert Range.until(5, 5).all(|x| false) && !Range.until(5, 5).any(|x| true)
23
- assert 3.downTo(1).all(|x| x >= 1) && 0.until(10).stepBy(3).any(|x| x == 9)
23
+ assert Range.downTo(3, 1).all(|x| x >= 1) && Range.until(0, 10).stepBy(3).any(|x| x == 9)
24
24
  calls := Array.filled(1, 0)
25
- assert 0.until(100).any(|x|
25
+ assert Range.until(0, 100).any(|x|
26
26
  calls.set(0, calls.at(0) + 1)
27
27
  x == 2
28
28
  )
@@ -30,10 +30,10 @@ primitive IntTest[UnitTest] =
30
30
 
31
31
  # range fold, each, find, repeatUntil run a million iterations
32
32
  fun rangeFoldEachFindRepeatUntilRunAMillion() =
33
- assert 0.until(1000000).fold(0, |a, x| a + 1) == 1000000
33
+ assert Range.until(0, 1000000).fold(0, |a, x| a + 1) == 1000000
34
- assert 0.until(1000000).find(|x| x == 999999).unwrapOr(-1) == 999999
34
+ assert Range.until(0, 1000000).find(|x| x == 999999).unwrapOr(-1) == 999999
35
35
  calls := Array.filled(1, 0)
36
- 0.until(1000000).each(|x|
36
+ Range.until(0, 1000000).each(|x|
37
37
  calls.set(0, calls.at(0) + 1)
38
38
  )
39
39
  assert calls.at(0) == 1000000
@@ -41,7 +41,7 @@ primitive IntTest[UnitTest] =
41
41
 
42
42
  fun rangeFindExitsEarly() =
43
43
  calls := Array.filled(1, 0)
44
- r := 0.until(1000000).find(|x|
44
+ r := Range.until(0, 1000000).find(|x|
45
45
  calls.set(0, calls.at(0) + 1)
46
46
  x == 3
47
47
  )
tests/std/Slice.plum CHANGED
@@ -255,7 +255,7 @@ primitive SliceTest[UnitTest] =
255
255
  assert v.drop(2).toStr() == "[3,7]"
256
256
  assert v.chunk(3).length() == 2
257
257
  assert v.join("-") == "1-5-3-7"
258
- total := 0.until(v.length()).fold(0, |sum, i| sum + v.at(i))
258
+ total := Range.until(0, v.length()).fold(0, |sum, i| sum + v.at(i))
259
259
  assert total == 16
260
260
  assert v.pop()! == 7
261
261
  assert v.length() == 3
tests/std/base64.plum CHANGED
@@ -10,7 +10,7 @@ import std/Test
10
10
  primitive Base64Test[UnitTest] =
11
11
  # every variant round-trips every length and byte, padding and line breaks included
12
12
  fun everyVariantRoundTripsEveryLengthAndByte() =
13
- bad := 0.until(300).fold(0, |acc, n|
13
+ bad := Range.until(0, 300).fold(0, |acc, n|
14
14
  data := base64TestBytes(n * 7919 + 1, n % 100)
15
15
  ok := Base64.decode(Base64.encode(data))! == data && Base64.decode(Base64.encode(data, "+", "/", ""))! == data && Base64.decodeUrl(Base64.encodeUrl(data))! == data && Base64.decodeUrl(Base64.encodeUrl(data, true))! == data && Base64.decode(Base64.encodePem(data))! == data && Base64.decode(Base64.encodeMime(data))! == data
16
16
  if ok then acc else acc + 1
@@ -30,7 +30,7 @@ primitive Base64Test[UnitTest] =
30
30
  # `n` pseudo-random bytes from the generator state `x`.
31
31
  fun base64TestBytes(x: Int, n: Int) -> Str =
32
32
  buf := Buffer()
33
- _ := 0.until(n).fold(x, |s, i|
33
+ _ := Range.until(0, n).fold(x, |s, i|
34
34
  next := {s * 6364136223846793005 + 1442695040888963407}
35
35
  buf.writeByte(Byte({next >> 33} & 0xFF))
36
36
  next
tests/std/collections.plum CHANGED
@@ -17,7 +17,7 @@ primitive CollectionsTest[UnitTest] =
17
17
  # List.toArray of 200000 elements is sized once and keeps the order
18
18
  fun listToArrayOf200000ElementsIsSizedOnce() =
19
19
  nil: List<Int> := Nil
20
- xs := 1.to(200000).fold(nil, |acc, i| Cons(head: i, tail: acc))
20
+ xs := Range.to(1, 200000).fold(nil, |acc, i| Cons(head: i, tail: acc))
21
21
  a := xs.toArray()
22
22
  assert a.length() == 200000
23
23
  assert a.at(0) == 200000 && a.at(199999) == 1
@@ -49,7 +49,7 @@ primitive CollectionsTest[UnitTest] =
49
49
  for i := range 1000
50
50
  xs.push(Rec(k: {i * 31} % 7, tag: i))
51
51
  s := xs.sort(|a, b| a.k < b.k)
52
- ok := 0.until(999).fold(true, |acc, i|
52
+ ok := Range.until(0, 999).fold(true, |acc, i|
53
53
  a := s.at(i)
54
54
  b := s.at(i + 1)
55
55
  acc && {a.k < b.k || a.k == b.k && a.tag < b.tag}
@@ -155,4 +155,4 @@ primitive CollectionsTest[UnitTest] =
155
155
  xs
156
156
 
157
157
  fun sortedOk(xs: Slice<Int>) -> Bool =
158
- 0.until(xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) <= xs.at(i + 1))
158
+ Range.until(0, xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) <= xs.at(i + 1))
tests/std/collections/BPlusTree.plum CHANGED
@@ -90,7 +90,7 @@ primitive BPlusTreeTest[UnitTest] =
90
90
  assert !v.contains(17)
91
91
  assert v.contains(16) && v.contains(18)
92
92
  assert v.isValid()
93
- w := 0.until(40).fold(v, |acc, i|
93
+ w := Range.until(0, 40).fold(v, |acc, i|
94
94
  next := acc.remove(i)
95
95
  assert next.isValid()
96
96
  next
@@ -188,7 +188,7 @@ primitive BPlusTreeTest[UnitTest] =
188
188
  assert t.get(2 * {n / 2})! == n / 2
189
189
  assert !t.contains(1)
190
190
  full: BPlusTree<Int, Int> := BPlusTree.fromSorted(BPlusTreeHelpers.sorted(200), |a, b| a < b, 4)
191
- drained := 0.until(200).fold(full, |acc, i|
191
+ drained := Range.until(0, 200).fold(full, |acc, i|
192
192
  next := acc.remove(i * 2)
193
193
  if i % 10 == 0
194
194
  assert next.isValid()
@@ -213,7 +213,7 @@ primitive BPlusTreeTest[UnitTest] =
213
213
  n := t.length()
214
214
  assert n > 19000
215
215
  ks := t.keys().toArray()
216
- for j := range 1.until(ks.length())
216
+ for j := range Range.until(1, ks.length())
217
217
  assert ks.at(j - 1) < ks.at(j)
218
218
  for j := range ks.length()
219
219
  if j % 2 == 0
@@ -247,8 +247,8 @@ primitive BPlusTreeTest[UnitTest] =
247
247
  # struct values (Vec2) insert, split, merge and remove
248
248
  fun structValuesVec2InsertSplitMergeAndRemove() =
249
249
  empty: BPlusTree<Int, Vec2> := BPlusTree.ints(3)
250
- old := 0.until(60).fold(empty, |acc, i| acc.insert(i, Vec2(x: Float(i), y: -1.0)))
250
+ old := Range.until(0, 60).fold(empty, |acc, i| acc.insert(i, Vec2(x: Float(i), y: -1.0)))
251
- t := 0.until(30).fold(old, |acc, j| acc.remove(2 * j))
251
+ t := Range.until(0, 30).fold(old, |acc, j| acc.remove(2 * j))
252
252
  assert t.isValid() && old.isValid()
253
253
  assert t.length() == 30 && old.length() == 60
254
254
  assert t.get(7)!.x == 7.0 && t.get(7)!.y == -1.0
@@ -304,7 +304,7 @@ primitive BPlusTreeHelpers =
304
304
 
305
305
  # The keys `0` to `n - 1` inserted in order, each with itself as value.
306
306
  fun upTo(order: Int, n: Int) -> BPlusTree<Int, Int> =
307
- 0.until(n).fold(ints(order), |acc, i| acc.insert(i, i))
307
+ Range.until(0, n).fold(ints(order), |acc, i| acc.insert(i, i))
308
308
 
309
309
  # Random inserts and removes over keys 0..span, checked against an array model
310
310
  # (-1 = absent) and the invariants every 50 steps.
tests/std/collections/BTree.plum CHANGED
@@ -159,7 +159,7 @@ primitive BTreeTest[UnitTest] =
159
159
  fun t10000AscendingKeysIterateInOrderThen() =
160
160
  empty: BTree<Int, Int> := BTree.ints(4)
161
161
  n := 10000
162
- tree := 0.until(n).fold(empty, |acc, i| acc.insert(i, i * 2))
162
+ tree := Range.until(0, n).fold(empty, |acc, i| acc.insert(i, i * 2))
163
163
  assert tree.length() == n
164
164
  assert tree.isValid()
165
165
  assert tree.height() <= 7
@@ -170,13 +170,13 @@ primitive BTreeTest[UnitTest] =
170
170
  assert seen == n
171
171
  assert tree.min()!.first == 0
172
172
  assert tree.max()!.first == n - 1
173
- half := 0.until(n / 2).fold(tree, |acc, j|
173
+ half := Range.until(0, n / 2).fold(tree, |acc, j|
174
174
  i := n - 1 - 2 * j
175
175
  acc.remove(i).remove(i)
176
176
  )
177
177
  assert half.length() == n / 2
178
178
  assert half.isValid()
179
- drained := 0.until(n).fold(half, |acc, i| acc.remove(i))
179
+ drained := Range.until(0, n).fold(half, |acc, i| acc.remove(i))
180
180
  assert drained.isEmpty()
181
181
  assert drained.height() == 0
182
182
  assert drained.isValid()
@@ -184,7 +184,7 @@ primitive BTreeTest[UnitTest] =
184
184
  fun theDefaultDegreeIs16() =
185
185
  empty: BTree<Int, Int> := BTree.ints()
186
186
  assert empty.t == 16
187
- tree := 0.until(31).fold(empty, |acc, i| acc.insert(i, i))
187
+ tree := Range.until(0, 31).fold(empty, |acc, i| acc.insert(i, i))
188
188
  assert tree.height() == 1
189
189
  assert tree.insert(31, 31).height() == 2
190
190
 
@@ -209,8 +209,8 @@ primitive BTreeTest[UnitTest] =
209
209
  # struct values (Vec2) insert, split, merge and remove
210
210
  fun structValuesVec2InsertSplitMergeAndRemove() =
211
211
  empty: BTree<Int, Vec2> := BTree.ints(2)
212
- old := 0.until(60).fold(empty, |acc, i| acc.insert(i, Vec2(x: Float(i), y: -1.0)))
212
+ old := Range.until(0, 60).fold(empty, |acc, i| acc.insert(i, Vec2(x: Float(i), y: -1.0)))
213
- tree := 0.until(30).fold(old, |acc, j| acc.remove(2 * j))
213
+ tree := Range.until(0, 30).fold(old, |acc, j| acc.remove(2 * j))
214
214
  assert tree.isValid() && old.isValid()
215
215
  assert tree.length() == 30 && old.length() == 60
216
216
  assert tree.get(7)!.x == 7.0 && tree.get(7)!.y == -1.0
@@ -231,7 +231,7 @@ primitive BTreeHelpers =
231
231
  # The keys `lo` to `hi - 1`, in order.
232
232
  fun span(lo: Int, hi: Int) -> List<Int> =
233
233
  nil: List<Int> := Nil
234
- {hi - 1}.downTo(lo).fold(nil, |acc, k| Cons(head: k, tail: acc))
234
+ Range.downTo(hi - 1, lo).fold(nil, |acc, k| Cons(head: k, tail: acc))
235
235
 
236
236
  # Inserts each key `k` with value `k * 10`, in order, into a tree of degree `t`.
237
237
  fun of(t: Int, ks: List<Int>) -> BTree<Int, Int> =
tests/std/collections/Bvh.plum CHANGED
@@ -162,7 +162,7 @@ primitive BvhTest[UnitTest] =
162
162
  pcount := t.pairs().length()
163
163
  brute := BvhTally(n: 0)
164
164
  for i := range n
165
- for j := range {i + 1}.until(n)
165
+ for j := range Range.until(i + 1, n)
166
166
  if items.at(i).first.overlaps(items.at(j).first)
167
167
  brute.n = brute.n + 1
168
168
  assert pcount == brute.n
@@ -291,7 +291,7 @@ primitive BvhHelpers =
291
291
  out
292
292
 
293
293
  fun sortedInts(xs: Slice<Int>) -> Slice<Int> =
294
- hi := 0.until(xs.length()).fold(0, |m, i| m.max(xs.at(i) + 1))
294
+ hi := Range.until(0, xs.length()).fold(0, |m, i| m.max(xs.at(i) + 1))
295
295
  marks := Slice<Bool>()
296
296
  for i := range hi
297
297
  marks.push(false)
@@ -313,11 +313,11 @@ primitive BvhHelpers =
313
313
  if sa.length() != a.length() || sb.length() != b.length()
314
314
  false
315
315
  else
316
- 0.until(sa.length()).fold(true, |ok, i| ok && sa.at(i) == sb.at(i))
316
+ Range.until(0, sa.length()).fold(true, |ok, i| ok && sa.at(i) == sb.at(i))
317
317
 
318
318
  # The nearest entry t over every box, or -1.0 when nothing is hit.
319
319
  fun bruteRay(items: Slice<Pair<Aabb, Int>>, o: Vec2, d: Vec2, maxT: Float) -> Float =
320
- 0.until(items.length()).fold(-1.0, |best, i|
320
+ Range.until(0, items.length()).fold(-1.0, |best, i|
321
321
  t := items.at(i).first.rayEntry(o, d, maxT)
322
322
  if t >= 0.0 && {best < 0.0 || t < best} then t else best
323
323
  )
@@ -335,7 +335,7 @@ primitive BvhHelpers =
335
335
  got := seen.s
336
336
  count := BvhTally(n: 0)
337
337
  for i := range n
338
- for j := range {i + 1}.until(n)
338
+ for j := range Range.until(i + 1, n)
339
339
  if items.at(i).first.overlaps(items.at(j).first)
340
340
  count.n = count.n + 1
341
341
  assert got.contains(i * n + j)
tests/std/collections/FenwickTree.plum CHANGED
@@ -107,11 +107,11 @@ primitive FenwickTreeTest[UnitTest] =
107
107
  x5 := FenwickTreeHelpers.lcg(x4)
108
108
  hi := x5 % {n + 1}
109
109
  st.x = x5
110
- want := lo.until(hi).fold(0, |w, k| w + brute.at(k))
110
+ want := Range.until(lo, hi).fold(0, |w, k| w + brute.at(k))
111
111
  assert st.f.rangeSum(lo, hi) == want
112
112
  if step % 100 == 0
113
113
  assert FenwickTreeHelpers.valid(st.f)
114
- for i := range 0.to(n)
114
+ for i := range Range.to(0, n)
115
115
  assert st.f.prefixSum(i) == st.pre
116
116
  if i < n
117
117
  st.pre = st.pre + brute.at(i)
@@ -131,7 +131,7 @@ primitive FenwickTreeTest[UnitTest] =
131
131
  st.f = st.f.add(i, xs.at(i))
132
132
  b := st.f
133
133
  assert FenwickTreeHelpers.valid(a) && FenwickTreeHelpers.valid(b)
134
- for i := range 0.to(n)
134
+ for i := range Range.to(0, n)
135
135
  assert a.prefixSum(i) == st.pre
136
136
  assert b.prefixSum(i) == st.pre
137
137
  assert zero.prefixSum(i) == 0
tests/std/collections/Hamt.plum CHANGED
@@ -143,7 +143,7 @@ primitive HamtTest[UnitTest] =
143
143
  # forced collisions: keys with a bad hash
144
144
  fun forcedCollisionsKeysWithABadHash() =
145
145
  m0: Hamt<HamtBadKey, Int> := Hamt.empty()
146
- m := 0.until(40).fold(m0, |acc, i| acc.set(HamtBadKey(id: i), i))
146
+ m := Range.until(0, 40).fold(m0, |acc, i| acc.set(HamtBadKey(id: i), i))
147
147
  assert m.length() == 40
148
148
  assert HamtHelpers.valid(m)
149
149
  for i := range 40
@@ -153,7 +153,7 @@ primitive HamtTest[UnitTest] =
153
153
  assert m2.get(HamtBadKey(id: 3))! == 333
154
154
  assert m2.length() == 40
155
155
  # Remove all but one key of each hash class: collisions shrink back to leaves.
156
- m3 := 4.until(40).fold(m2, |acc, i|
156
+ m3 := Range.until(4, 40).fold(m2, |acc, i|
157
157
  next := acc.remove(HamtBadKey(id: i))
158
158
  assert HamtHelpers.valid(next)
159
159
  next
@@ -259,14 +259,14 @@ primitive HamtTest[UnitTest] =
259
259
 
260
260
  fun t20000StrKeysThenRemoveThemAll() =
261
261
  h0: Hamt<Str, Int> := Hamt.empty()
262
- h := 0.until(20000).fold(h0, |acc, i| acc.set("key{i}", i))
262
+ h := Range.until(0, 20000).fold(h0, |acc, i| acc.set("key{i}", i))
263
263
  assert h.length() == 20000
264
264
  assert HamtHelpers.valid(h)
265
265
  assert h.entries().length() == 20000
266
- bad := 0.until(20000).fold(0, |n, i| if h.get("key{i}")! != i then n + 1 else n)
266
+ bad := Range.until(0, 20000).fold(0, |n, i| if h.get("key{i}")! != i then n + 1 else n)
267
267
  assert bad == 0
268
268
  assert h.contains("key20000") == false
269
- gone := 0.until(20000).fold(h, |acc, i| acc.remove("key{i}"))
269
+ gone := Range.until(0, 20000).fold(h, |acc, i| acc.remove("key{i}"))
270
270
  assert gone.isEmpty()
271
271
  assert HamtHelpers.valid(gone)
272
272
  assert gone.root.isBranch()
tests/std/collections/Heap.plum CHANGED
@@ -11,13 +11,13 @@ primitive HeapTest[UnitTest] =
11
11
  # heap_pop_order: 1000 pseudo-random keys pop in ascending order
12
12
  fun heapPopOrder1000PseudoRandomKeysPop() =
13
13
  h: Heap<Int> := Heap.by(|a, b| a < b)
14
- _ := 1.to(1000).fold(12345, |x, _|
14
+ _ := Range.to(1, 1000).fold(12345, |x, _|
15
15
  next := {x * 1103515245 + 12345} % 2147483648
16
16
  h.push(next % 100000)
17
17
  next
18
18
  )
19
19
  assert h.length() == 1000
20
- _ := 1.to(1000).fold(-1, |prev, _|
20
+ _ := Range.to(1, 1000).fold(-1, |prev, _|
21
21
  v := h.pop()!
22
22
  assert v >= prev
23
23
  v
@@ -48,7 +48,7 @@ primitive HeapTest[UnitTest] =
48
48
  for i := range 100
49
49
  g.push({i * 37} % 100)
50
50
  assert g.peek()! == 99
51
- assert 0.until(100).fold(true, |ok, i| ok && g.pop()! == 99 - i)
51
+ assert Range.until(0, 100).fold(true, |ok, i| ok && g.pop()! == 99 - i)
52
52
 
53
53
  # toSlice, fold and each go in pop order and leave the heap as it was
54
54
  fun toSliceFoldAndEachGoInPopOrder() =
tests/std/collections/IntervalTree.plum CHANGED
@@ -107,7 +107,7 @@ primitive IntervalTreeTest[UnitTest] =
107
107
  if {x / 100} % 4 == 0 && model.length() > 0
108
108
  pick := model.at({x / 17} % model.length())
109
109
  s.t = s.t.remove(pick.lo, pick.hi)
110
- j := 0.until(model.length()).find(|j| model.at(j).lo == pick.lo && model.at(j).hi == pick.hi)
110
+ j := Range.until(0, model.length()).find(|j| model.at(j).lo == pick.lo && model.at(j).hi == pick.hi)
111
111
  model.removeAt(j!)
112
112
  else
113
113
  s.t = s.t.insert(lo, hi, i)
@@ -119,7 +119,7 @@ primitive IntervalTreeTest[UnitTest] =
119
119
  assert IntervalTreeHelpers.spans(s.t.containing(q)) == IntervalTreeHelpers.spans(IntervalTreeHelpers.scan(model, q, q))
120
120
  assert IntervalTreeHelpers.valid(s.t)
121
121
  assert s.t.length() == model.length()
122
- for q := range 0.until(1100).stepBy(37)
122
+ for q := range Range.until(0, 1100).stepBy(37)
123
123
  assert IntervalTreeHelpers.spans(s.t.overlapping(q, q + 7)) == IntervalTreeHelpers.spans(IntervalTreeHelpers.scan(model, q, q + 7))
124
124
 
125
125
  fun t10000IntervalsStayBalancedAndAnswerQueries() =
tests/std/collections/KdTree.plum CHANGED
@@ -90,7 +90,7 @@ primitive KdTreeTest[UnitTest] =
90
90
 
91
91
  # built trees match brute force on pseudo-random points
92
92
  fun builtTreesMatchBruteForceOnPseudoRandom() =
93
- for n := range 0.until(70).stepBy(7)
93
+ for n := range Range.until(0, 70).stepBy(7)
94
94
  items := KdTreeHelpers.points(n, n + 3)
95
95
  t := KdTreeHelpers.of(items)
96
96
  assert t.length() == n
@@ -108,7 +108,7 @@ primitive KdTreeTest[UnitTest] =
108
108
  fun insertedTreesMatchBruteForceOnPseudoRandom() =
109
109
  items := KdTreeHelpers.points(400, 11)
110
110
  first := KdTreeHelpers.of(items.sublist(0, 100))
111
- t := 100.until(400).fold(first, |acc, i| acc.insert(items.at(i).first, i))
111
+ t := Range.until(100, 400).fold(first, |acc, i| acc.insert(items.at(i).first, i))
112
112
  assert t.length() == 400
113
113
  assert KdTreeHelpers.valid(t)
114
114
  assert KdTreeHelpers.crossCheck(t, items, 60, 9)
@@ -228,7 +228,7 @@ primitive KdTreeHelpers =
228
228
  seen := Slice<Bool>()
229
229
  for e := range items
230
230
  seen.push(false)
231
- 0.until(got.length()).fold(true, |ok, i|
231
+ Range.until(0, got.length()).fold(true, |ok, i|
232
232
  e := got.at(i)
233
233
  if !ok || seen.at(e.second) || items.at(e.second).first != e.first || KdTree.distSq(e.first, p) != want.at(i)
234
234
  false
@@ -261,7 +261,7 @@ primitive KdTreeHelpers =
261
261
  # Runs every query against brute force at `q` query points.
262
262
  fun crossCheck(t: KdTree<Int>, items: Slice<Pair<Vec2, Int>>, q: Int, seed: Int) -> Bool =
263
263
  rng := KdRng(x: seed)
264
- 0.until(q).fold(true, |ok, j| ok && checkOne(t, items, rng))
264
+ Range.until(0, q).fold(true, |ok, j| ok && checkOne(t, items, rng))
265
265
 
266
266
  # Entries `(i, i) => i` for `i` from `lo` to `hi - 1` inserted in order, as a tail call.
267
267
  fun line(t: KdTree<Int>, lo: Int, hi: Int) -> KdTree<Int> =
tests/std/collections/LeftistHeap.plum CHANGED
@@ -41,7 +41,7 @@ primitive LeftistHeapTest[UnitTest] =
41
41
 
42
42
  # heapsort of pseudo-random lists matches Slice.sort
43
43
  fun heapsortOfPseudoRandomListsMatchesSliceSort() =
44
- for seed := range 1.to(5)
44
+ for seed := range Range.to(1, 5)
45
45
  xs := LeftistHeapHelpers.randList(300, seed * 7919)
46
46
  h := LeftistHeapHelpers.pushAll(LeftistHeapHelpers.ints(), xs)
47
47
  assert LeftistHeapHelpers.valid(h)
@@ -218,4 +218,4 @@ primitive LeftistHeapHelpers =
218
218
 
219
219
  # The index of the smallest element of a non-empty `xs`.
220
220
  fun minAt(xs: Slice<Int>) -> Int =
221
- 0.until(xs.length()).fold(0, |best, i| if xs.at(i) < xs.at(best) then i else best)
221
+ Range.until(0, xs.length()).fold(0, |best, i| if xs.at(i) < xs.at(best) then i else best)
tests/std/collections/List.plum CHANGED
@@ -12,14 +12,14 @@ primitive ListTest[UnitTest] =
12
12
  # filter_million_constant_stack
13
13
  fun filterMillionConstantStack() =
14
14
  nil: List<Int> := Nil
15
- xs := 1.to(1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
15
+ xs := Range.to(1, 1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
16
16
  evens := xs.filter(|x| x % 2 == 0)
17
17
  assert evens.length() == 500000
18
18
 
19
19
  # list fold, each, find: a million elements, find exits early
20
20
  fun listFoldEachFindAMillionElementsFind() =
21
21
  nil: List<Int> := Nil
22
- xs := 1.to(1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
22
+ xs := Range.to(1, 1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
23
23
  assert xs.fold(0, |a, x| a + 1) == 1000000
24
24
  calls := Array.filled(1, 0)
25
25
  xs.each(|x|
@@ -49,7 +49,7 @@ primitive ListTest[UnitTest] =
49
49
 
50
50
  fun joinOf100000Pieces() =
51
51
  nil: List<Str> := Nil
52
- s := 99999.downTo(0).fold(nil, |acc, i| Cons(head: i.toStr(), tail: acc)).join(",")
52
+ s := Range.downTo(99999, 0).fold(nil, |acc, i| Cons(head: i.toStr(), tail: acc)).join(",")
53
53
  assert s.startsWith("0,1,2,")
54
54
  assert s.endsWith(",99998,99999")
55
55
  assert s.length() == 588889
@@ -57,6 +57,6 @@ primitive ListTest[UnitTest] =
57
57
  # any and all stop early, a million elements in constant stack
58
58
  fun anyAndAllStopEarlyAMillionElements() =
59
59
  nil: List<Int> := Nil
60
- xs := 1.to(1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
60
+ xs := Range.to(1, 1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
61
61
  assert xs.any(|x| x == 1) && !xs.any(|x| x < 0) && xs.all(|x| x > 0) && !xs.all(|x| x > 1)
62
62
  assert !nil.any(|x| true) && nil.all(|x| false)
tests/std/collections/Map.plum CHANGED
@@ -84,7 +84,7 @@ primitive MapTest[UnitTest] =
84
84
  assert n.get("x")!.get(1)! == "one" && n.get("y")!.isEmpty()
85
85
  big := ["0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10, "11" => 11, "12" => 12, "13" => 13, "14" => 14, "15" => 15, "16" => 16, "17" => 17, "18" => 18, "19" => 19]
86
86
  assert big.length() == 20
87
- assert 0.until(20).find(|i| big.get("{i}")! != i).isNone()
87
+ assert Range.until(0, 20).find(|i| big.get("{i}")! != i).isNone()
88
88
  assert big.keys().join(",") == "0,1,10,11,12,13,14,15,16,17,18,19,2,3,4,5,6,7,8,9"
89
89
  neg := [-5 => "a", -17 => "b", -5 => "c"]
90
90
  assert neg.toStr() == "[-17 => b, -5 => c]"
@@ -129,10 +129,10 @@ primitive MapTest[UnitTest] =
129
129
 
130
130
  # neighbours agree with a scan over pseudo-random maps
131
131
  fun neighboursAgreeWithAScanOverPseudoRandom() =
132
- for seed := range 1.to(8)
132
+ for seed := range Range.to(1, 8)
133
133
  m := MapHelpers.random(seed, 120, 300, 0)
134
134
  ks := m.keys()
135
- bad := -2.until(303).fold(0, |b, q|
135
+ bad := -Range.until(2, 303).fold(0, |b, q|
136
136
  lt := ks.filter(|k| k < q).last()
137
137
  le := ks.filter(|k| k <= q).last()
138
138
  gt := ks.filter(|k| k > q).first()
@@ -180,7 +180,7 @@ primitive MapTest[UnitTest] =
180
180
 
181
181
  # range and foldRange agree with a filter over pseudo-random maps
182
182
  fun rangeAndFoldRangeAgreeWithAFilterOver() =
183
- for seed := range 1.to(10)
183
+ for seed := range Range.to(1, 10)
184
184
  m := MapHelpers.random(seed, 200, 400, 0)
185
185
  x := MapHelpers.lcg(seed * 31)
186
186
  lo := x % 450 - 25
@@ -240,7 +240,7 @@ primitive MapTest[UnitTest] =
240
240
 
241
241
  # set operations agree with a filter over pseudo-random maps, and stay balanced
242
242
  fun setOperationsAgreeWithAFilterOverPseudo() =
243
- for seed := range 1.to(12)
243
+ for seed := range Range.to(1, 12)
244
244
  a := MapHelpers.random(seed, 300, 400, 1)
245
245
  b := MapHelpers.random(seed * 7919, 200, 400, 2)
246
246
  u := a.union(b)
@@ -291,7 +291,7 @@ primitive MapTest[UnitTest] =
291
291
 
292
292
  # fromSlice and fromList: sorted input is built directly, any input works
293
293
  fun fromSliceAndFromListSortedInputIsBuiltDirectly() =
294
- sorted := 0.until(1000).fold(Slice<Pair<Int, Int>>(), |xs, i|
294
+ sorted := Range.until(0, 1000).fold(Slice<Pair<Int, Int>>(), |xs, i|
295
295
  xs.push(Pair(first: i, second: i * 2))
296
296
  xs
297
297
  )
@@ -440,7 +440,7 @@ primitive MapHelpers =
440
440
 
441
441
  # True when the keys of `xs` strictly ascend.
442
442
  fun ascending(xs: Slice<Int>) -> Bool =
443
- 0.until(xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) < xs.at(i + 1))
443
+ Range.until(0, xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) < xs.at(i + 1))
444
444
 
445
445
  # The invariants: cached sizes right, every node balanced, keys strictly ascending.
446
446
  fun valid(m: Map<Int, Int>) -> Bool =
tests/std/collections/PairingHeap.plum CHANGED
@@ -41,7 +41,7 @@ primitive PairingHeapTest[UnitTest] =
41
41
 
42
42
  # heapsort of pseudo-random lists matches Slice.sort
43
43
  fun heapsortOfPseudoRandomListsMatchesSliceSort() =
44
- for seed := range 1.to(5)
44
+ for seed := range Range.to(1, 5)
45
45
  xs := PairingHeapHelpers.randList(300, seed * 7919)
46
46
  h := PairingHeapHelpers.pushAll(PairingHeapHelpers.ints(), xs)
47
47
  assert PairingHeapHelpers.valid(h)
@@ -243,4 +243,4 @@ primitive PairingHeapHelpers =
243
243
 
244
244
  # The index of the smallest element of a non-empty `xs`.
245
245
  fun minAt(xs: Slice<Int>) -> Int =
246
- 0.until(xs.length()).fold(0, |best, i| if xs.at(i) < xs.at(best) then i else best)
246
+ Range.until(0, xs.length()).fold(0, |best, i| if xs.at(i) < xs.at(best) then i else best)
tests/std/collections/Quadtree.plum CHANGED
@@ -125,8 +125,8 @@ primitive QuadtreeTest[UnitTest] =
125
125
  py := Float(rng.roll() % 21) * 5.0
126
126
  pts.push(Vec2(x: px, y: py))
127
127
  live.push(true)
128
- full := 0.until(600).fold(e, |acc, i| acc.insert(pts.at(i), i))
128
+ full := Range.until(0, 600).fold(e, |acc, i| acc.insert(pts.at(i), i))
129
- t := 0.until(600).fold(full, |acc, i|
129
+ t := Range.until(0, 600).fold(full, |acc, i|
130
130
  next := if rng.roll() % 3 == 0
131
131
  live.putAt(i, false)
132
132
  acc.remove(pts.at(i), i)
@@ -138,7 +138,7 @@ primitive QuadtreeTest[UnitTest] =
138
138
  )
139
139
  assert QuadtreeHelpers.valid(t)
140
140
  assert full.length() == 600 && QuadtreeHelpers.valid(full)
141
- n := 0.until(600).fold(0, |c, i| if live.at(i) then c + 1 else c)
141
+ n := Range.until(0, 600).fold(0, |c, i| if live.at(i) then c + 1 else c)
142
142
  for i := range 600
143
143
  assert t.contains(pts.at(i), i) == live.at(i)
144
144
  assert full.contains(pts.at(i), i)
@@ -156,7 +156,7 @@ primitive QuadtreeTest[UnitTest] =
156
156
  fun t10000Entries() =
157
157
  e: Quadtree<Int> := Quadtree.over(Aabb.of(0.0, 0.0, 1000.0, 1000.0))
158
158
  rng := QuadRng(x: 7)
159
- t := 0.until(10000).fold(e, |acc, i|
159
+ t := Range.until(0, 10000).fold(e, |acc, i|
160
160
  px := Float(rng.roll() % 100000) / 100.0
161
161
  py := Float(rng.roll() % 100000) / 100.0
162
162
  acc.insert(Vec2(x: px, y: py), i)
@@ -246,7 +246,7 @@ primitive QuadtreeHelpers =
246
246
  seen := Slice<Bool>()
247
247
  for i := range pts.length()
248
248
  seen.push(false)
249
- expected := 0.until(pts.length()).fold(0, |c, i| if live.at(i) && want(pts.at(i)) then c + 1 else c)
249
+ expected := Range.until(0, pts.length()).fold(0, |c, i| if live.at(i) && want(pts.at(i)) then c + 1 else c)
250
250
  ok := got.fold(true, |acc, e|
251
251
  if !acc || seen.at(e.second) || !live.at(e.second) || !want(e.first) || e.first != pts.at(e.second)
252
252
  false
tests/std/collections/RadixTree.plum CHANGED
@@ -267,7 +267,7 @@ primitive RadixTreeTest[UnitTest] =
267
267
  t := RadixTreeHelpers.addRange(RadixTree.empty(), 0, 10000)
268
268
  assert t.length() == 10000
269
269
  assert RadixTreeHelpers.valid(t)
270
- bad := 0.until(10000).fold(0, |n, i| if t.get("key/{i}")! != i then n + 1 else n)
270
+ bad := Range.until(0, 10000).fold(0, |n, i| if t.get("key/{i}")! != i then n + 1 else n)
271
271
  assert bad == 0
272
272
  assert t.withPrefix("key/999").length() == 11
273
273
  assert t.withPrefix("ke").length() == 10000
tests/std/collections/SegmentTree.plum CHANGED
@@ -123,7 +123,7 @@ primitive SegmentTreeTest[UnitTest] =
123
123
 
124
124
  # invariants_after_random_ops: sets and queries match brute force for sum, min, max and concat
125
125
  fun invariantsAfterRandomOpsSetsAndQueriesMatch() =
126
- for i := range 1.to(40)
126
+ for i := range Range.to(1, 40)
127
127
  n := i
128
128
  brute := SegmentTreeHelpers.zeros(n)
129
129
  zeros := List.fromSlice(SegmentTreeHelpers.zeros(n))
@@ -167,7 +167,7 @@ primitive SegmentTreeTest[UnitTest] =
167
167
  xs.push(seed.x % 2001 - 1000)
168
168
  first := SegmentTreeHelpers.sum(List.fromSlice(xs))
169
169
  assert SegmentTreeHelpers.valid(first)
170
- for k := range 0.to(n)
170
+ for k := range Range.to(0, n)
171
171
  assert first.query(0, k) == seed.pre
172
172
  if k < n
173
173
  seed.pre = seed.pre + xs.at(k)
@@ -267,7 +267,7 @@ primitive SegmentTreeHelpers =
267
267
  s
268
268
 
269
269
  fun brute(brute: Slice<Int>, lo: Int, hi: Int) -> SegWant =
270
- lo.until(hi).fold(SegWant(sum: 0, mn: 9223372036854775807, mx: -9223372036854775807, cat: ""), |w, k|
270
+ Range.until(lo, hi).fold(SegWant(sum: 0, mn: 9223372036854775807, mx: -9223372036854775807, cat: ""), |w, k|
271
271
  v := brute.at(k)
272
272
  SegWant(sum: w.sum + v, mn: w.mn.min(v), mx: w.mx.max(v), cat: "{w.cat}{v}")
273
273
  )
tests/std/collections/Set.plum CHANGED
@@ -44,7 +44,7 @@ primitive SetTest[UnitTest] =
44
44
  assert s.range(20, 50).toStr() == "[20, 30, 40]" && s.range(50, 20).isEmpty() && s.range(11, 20).isEmpty()
45
45
  assert s.foldRange(15, 45, 0, |acc, x| acc + x) == 90
46
46
  assert s.until(30).join(s.from(30)) == s && s.until(25).join(s.from(45)).toStr() == "[10, 20, 50]"
47
- for seed := range 1.to(6)
47
+ for seed := range Range.to(1, 6)
48
48
  a := SetHelpers.random(seed, 150, 300, Set.empty())
49
49
  lo := seed * 37
50
50
  hi := seed * 41 + 20
@@ -55,7 +55,7 @@ primitive SetTest[UnitTest] =
55
55
 
56
56
  # union, intersection, difference and isSubsetOf agree with a filter
57
57
  fun unionIntersectionDifferenceAndIsSubsetOfAgreeWithA() =
58
- for seed := range 1.to(10)
58
+ for seed := range Range.to(1, 10)
59
59
  a := SetHelpers.random(seed, 200, 300, Set.empty())
60
60
  b := SetHelpers.random(seed * 7919, 150, 300, Set.empty())
61
61
  assert a.union(b).toSlice().toStr() == SetHelpers.where(300, |x| a.contains(x) || b.contains(x))
tests/std/collections/Trie.plum CHANGED
@@ -218,7 +218,7 @@ primitive TrieTest[UnitTest] =
218
218
  t := TrieHelpers.addRange(Trie.empty(), 0, 10000)
219
219
  assert t.length() == 10000
220
220
  assert TrieHelpers.valid(t)
221
- bad := 0.until(10000).fold(0, |n, i| if t.get("k{i}")! != i then n + 1 else n)
221
+ bad := Range.until(0, 10000).fold(0, |n, i| if t.get("k{i}")! != i then n + 1 else n)
222
222
  assert bad == 0
223
223
  assert t.withPrefix("k999").length() == 11
224
224
  ks := t.keys()
tests/std/collections/UnionFind.plum CHANGED
@@ -65,7 +65,7 @@ primitive UnionFindTest[UnitTest] =
65
65
  # a chain of 10,000 unions stays shallow and fully joined
66
66
  fun aChainOf10000UnionsStaysShallow() =
67
67
  n := 10000
68
- uf := 1.until(n).fold(UnionFind.ofSize(n), |u, i|
68
+ uf := Range.until(1, n).fold(UnionFind.ofSize(n), |u, i|
69
69
  next := u.union(i - 1, i)
70
70
  assert next.componentCount() == u.componentCount() - 1
71
71
  next
@@ -107,9 +107,9 @@ primitive UnionFindTest[UnitTest] =
107
107
  k := run.x % n
108
108
  assert run.uf.connected(j, k) == {labels.at(j) == labels.at(k)}
109
109
  uf := run.uf
110
- distinct := 0.until(n).fold(0, |c, i| if labels.at(i) == i then c + 1 else c)
110
+ distinct := Range.until(0, n).fold(0, |c, i| if labels.at(i) == i then c + 1 else c)
111
111
  for i := range n
112
- count := 0.until(n).fold(0, |c, j| if labels.at(j) == labels.at(i) then c + 1 else c)
112
+ count := Range.until(0, n).fold(0, |c, j| if labels.at(j) == labels.at(i) then c + 1 else c)
113
113
  assert uf.sizeOf(i) == count
114
114
  assert uf.componentCount() == distinct
115
115
  assert UnionFindHelpers.valid(uf)
@@ -196,7 +196,7 @@ primitive UnionFindHelpers =
196
196
  false
197
197
  else
198
198
  limit := if uf.n > 1 then Int(Float(uf.n).log2()) + 1 else 1
199
- if 0.until(uf.n).find(|i| !linkOk(uf, i, limit)).isSome()
199
+ if Range.until(0, uf.n).find(|i| !linkOk(uf, i, limit)).isSome()
200
200
  false
201
201
  else
202
202
  members := Slice<Int>()
@@ -205,6 +205,6 @@ primitive UnionFindHelpers =
205
205
  for i := range uf.n
206
206
  r := uf.find(i)
207
207
  _ := members.set(r, members.at(r) + 1)
208
- roots := 0.until(uf.n).fold(0, |c, i| if uf.parent.get(i)! == i then c + 1 else c)
208
+ roots := Range.until(0, uf.n).fold(0, |c, i| if uf.parent.get(i)! == i then c + 1 else c)
209
- badSize := 0.until(uf.n).find(|i| uf.find(i) == i && uf.sizes.get(i)! != members.at(i))
209
+ badSize := Range.until(0, uf.n).find(|i| uf.find(i) == i && uf.sizes.get(i)! != members.at(i))
210
210
  badSize.isNone() && roots == uf.componentCount()
tests/std/encoding/Json.plum CHANGED
@@ -97,7 +97,7 @@ primitive JsonTest[UnitTest] =
97
97
  fun parsesA10000ElementArray() =
98
98
  buf := Buffer()
99
99
  buf.write("[0")
100
- for i := range 1.until(10000)
100
+ for i := range Range.until(1, 10000)
101
101
  buf.write(",{i}")
102
102
  buf.write("]")
103
103
  items := Json.parse(buf.toStr())!.asList()!
@@ -107,7 +107,7 @@ primitive JsonTest[UnitTest] =
107
107
  fun parsesAnObjectWith2000Keys() =
108
108
  buf := Buffer()
109
109
  buf.write("{{\"k0\":0")
110
- for i := range 1.until(2000)
110
+ for i := range Range.until(1, 2000)
111
111
  buf.write(",\"k{i}\":{i}")
112
112
  buf.write("}}")
113
113
  pairs := Json.parse(buf.toStr())!.asMap()!
tests/std/game/History.plum CHANGED
@@ -27,7 +27,7 @@ primitive HistoryTest[UnitTest] =
27
27
 
28
28
  # a full history lets its ticks go and counts on
29
29
  fun aFullHistoryLetsItsTicksGoAnd() =
30
- h := 0.until(4).fold(History.start(3, Vec2(x: 1.0, y: 1.0)), |acc, i| acc.push(HistoryHelpers.tick(false)))
30
+ h := Range.until(0, 4).fold(History.start(3, Vec2(x: 1.0, y: 1.0)), |acc, i| acc.push(HistoryHelpers.tick(false)))
31
31
  assert h.full && h.now() == 4
32
32
 
33
33
  primitive HistoryHelpers =
tests/std/game/Input.plum CHANGED
@@ -51,7 +51,7 @@ primitive InputTest[UnitTest] =
51
51
  assert Held.keysOnly(codes).isDown(Key.Up)
52
52
  assert Held.keysOnly(codes).isDown(Key.LeftControl)
53
53
  assert Held.keysOnly(codes).isDown(Key.RightSuper)
54
- assert 1.until(codes.length()).all(|i| codes.at(i - 1) < codes.at(i))
54
+ assert Range.until(1, codes.length()).all(|i| codes.at(i - 1) < codes.at(i))
55
55
 
56
56
  # pointer events have a position, keys don't
57
57
  fun pointerEventsHaveAPositionKeysDont() =
tests/std/game/Screen.plum CHANGED
@@ -34,7 +34,7 @@ primitive ScreenTest[UnitTest] =
34
34
  assert l.frame(false, pixels).y == 300.0
35
35
  assert Cut.secs() == 0.0
36
36
  assert Shift(from: 0, how: Cut, t: 0.0).progress() == 1.0
37
- half := 0.until(30).fold(Some(Shift(from: 0, how: Fade(secs: 0.5), t: 0.0)), |s, i| match s
37
+ half := Range.until(0, 30).fold(Some(Shift(from: 0, how: Fade(secs: 0.5), t: 0.0)), |s, i| match s
38
38
  Some(x) => x.after(1.0 / 60.0)
39
39
  None => None)
40
40
  assert half.isNone()
tests/std/game/Tween.plum CHANGED
@@ -25,7 +25,7 @@ primitive TweenTest[UnitTest] =
25
25
  assert !t.done()
26
26
  u := t.advance(0.25)
27
27
  assert u.value() == 10.0 + 20.0 * 0.75
28
- v := 0.until(15).fold(u, |x, i| x.advance(1.0 / 60.0))
28
+ v := Range.until(0, 15).fold(u, |x, i| x.advance(1.0 / 60.0))
29
29
  assert v.done()
30
30
  assert v.value() == 30.0
31
31
  assert v.advance(1.0).value() == 30.0
@@ -35,6 +35,6 @@ primitive TweenTest[UnitTest] =
35
35
 
36
36
  # half a second of ticks is done on the thirtieth
37
37
  fun halfASecondOfTicksIsDoneOn() =
38
- t := 0.until(29).fold(Tween.of(0.0, 1.0, 0.5), |x, i| x.advance(1.0 / 60.0))
38
+ t := Range.until(0, 29).fold(Tween.of(0.0, 1.0, 0.5), |x, i| x.advance(1.0 / 60.0))
39
39
  assert !t.done()
40
40
  assert t.advance(1.0 / 60.0).done()
tests/std/game/View.plum CHANGED
@@ -34,7 +34,7 @@ primitive ViewTest[UnitTest] =
34
34
  # 0.25) come after its parent's own.
35
35
  expect := [1001.0, 0.5, 1002.0, 0.5, 1014.0, 0.25, 1101.0, 0.25, 1102.0, 0.25, 1114.0, 0.125]
36
36
  assert log.length() == expect.length()
37
- assert 0.until(expect.length()).all(|i| log.at(i) == expect.at(i))
37
+ assert Range.until(0, expect.length()).all(|i| log.at(i) == expect.at(i))
38
38
  Views.paint(io, [v], Affine.Identity, 1.0)
39
39
  assert views.length() == 4
40
40
 
@@ -113,11 +113,11 @@ struct Viewed[View](x: Float, log: Slice<Float>, views: Slice<Int>, lit: Bool, i
113
113
 
114
114
  fun view(self) -> List<View> =
115
115
  self.views.push(1)
116
+ [
116
- first := [ViewHelpers.probeAt(1.0, self.log)]
117
+ ViewHelpers.probeAt(1.0, self.log),
117
- lit := if self.lit then [ViewHelpers.probeAt(2.0, self.log)] else Nil
118
+ if self.lit then ViewHelpers.probeAt(2.0, self.log),
118
- grouped := [Group.of(10.0, 0.0, [ViewProbe(x: 4.0, log: self.log, fade: 0.5)])]
119
+ Group.of(10.0, 0.0, [ViewProbe(x: 4.0, log: self.log, fade: 0.5)]),
119
- inner := if self.inner then [Viewed(x: 100.0, log: self.log, views: self.views, lit: true, inner: false)] else Nil
120
+ if self.inner then Viewed(x: 100.0, log: self.log, views: self.views, lit: true, inner: false)]
120
- first.append(lit).append(grouped).append(inner)
121
121
 
122
122
  # A view that paints itself (-1) and then has its view drawn, and is invisible unless
123
123
  # `shows`.
tests/std/map_model.plum CHANGED
@@ -125,7 +125,7 @@ primitive MapModelTest[UnitTest] =
125
125
 
126
126
  fun sortedModel(m: Map<Int, Int>, b: Int, keep: fn(Int) -> Bool) -> Str =
127
127
  out := Slice<Pair<Int, Int>>()
128
- for k := range {0 - 20}.until(b + 20)
128
+ for k := range Range.until(0 - 20, b + 20)
129
129
  if keep(k) && m.contains(k)
130
130
  out.push(Pair(first: k, second: m.get(k)!))
131
131
  modelStr(out)
@@ -178,7 +178,7 @@ primitive MapModelHelpers =
178
178
 
179
179
  # True when the keys of `xs` strictly ascend.
180
180
  fun ascending(xs: Slice<Int>) -> Bool =
181
- 0.until(xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) < xs.at(i + 1))
181
+ Range.until(0, xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) < xs.at(i + 1))
182
182
 
183
183
  # The invariants: cached sizes right, every node balanced, keys strictly ascending.
184
184
  fun valid(m: Map<Int, Int>) -> Bool =
tests/std/math/Random.plum CHANGED
@@ -8,7 +8,7 @@ primitive RandomTest[UnitTest] =
8
8
  fun sameSeedSameSequence() =
9
9
  a := Random.seeded(12345)
10
10
  b := Random.seeded(12345)
11
- _ := 1.to(100).fold(Rolled<Random>(value: a, rng: b), |pair, _|
11
+ _ := Range.to(1, 100).fold(Rolled<Random>(value: a, rng: b), |pair, _|
12
12
  da := pair.value.nextInt()
13
13
  db := pair.rng.nextInt()
14
14
  assert da.value == db.value
@@ -28,7 +28,7 @@ primitive RandomTest[UnitTest] =
28
28
  assert r.nextInt().value == r.nextInt().value
29
29
 
30
30
  fun nextIntBelowStaysInRangeAndCoversTheRange() =
31
- end := 1.to(1000).fold(Rolled<Int>(value: 0, rng: Random.seeded(99)), |state, _|
31
+ end := Range.to(1, 1000).fold(Rolled<Int>(value: 0, rng: Random.seeded(99)), |state, _|
32
32
  d := state.rng.nextIntBelow(10)
33
33
  assert d.value >= 0
34
34
  assert d.value < 10
@@ -39,7 +39,7 @@ primitive RandomTest[UnitTest] =
39
39
 
40
40
  # nextFloat is in [0, 1) with a sane mean
41
41
  fun nextFloatIsIn01WithASane() =
42
- end := 1.to(1000).fold(Rolled<Float>(value: 0.0, rng: Random.seeded(5)), |state, _|
42
+ end := Range.to(1, 1000).fold(Rolled<Float>(value: 0.0, rng: Random.seeded(5)), |state, _|
43
43
  d := state.rng.nextFloat()
44
44
  assert d.value >= 0.0
45
45
  assert d.value < 1.0
tests/std/slice_sort.plum CHANGED
@@ -36,7 +36,7 @@ primitive SliceSortTest[UnitTest] =
36
36
 
37
37
  # Sorted by key, equal keys in their original order, nothing lost or repeated.
38
38
  fun stableSorted(xs: Slice<Pair<Int, Int>>, n: Int) -> Bool =
39
- ordered := 0.until(xs.length() - 1).find(|i|
39
+ ordered := Range.until(0, xs.length() - 1).find(|i|
40
40
  a := xs.at(i)
41
41
  b := xs.at(i + 1)
42
42
  a.first > b.first || a.first == b.first && a.second > b.second
tests/syntax/block_closures.plum CHANGED
@@ -11,7 +11,7 @@ struct Tally(mut n: Int)
11
11
 
12
12
  primitive BlockClosures =
13
13
  fun sumDoubled(n: Int) -> Int =
14
- 1.to(n).fold(0, |acc, x|
14
+ Range.to(1, n).fold(0, |acc, x|
15
15
  y := x * 2
16
16
  acc + y
17
17
  )
@@ -20,7 +20,7 @@ primitive BlockClosures =
20
20
  fun shadow(n: Int) -> Int =
21
21
  y := 1000
22
22
  acc := 5
23
- r := 1.to(n).fold(0, |acc, x|
23
+ r := Range.to(1, n).fold(0, |acc, x|
24
24
  y := x + 1
25
25
  acc + y
26
26
  )
@@ -28,12 +28,12 @@ primitive BlockClosures =
28
28
 
29
29
  # Two closures in one function with the same local names.
30
30
  fun twoClosures(n: Int) -> Int =
31
- a := 1.to(n).fold(0, |acc, x|
31
+ a := Range.to(1, n).fold(0, |acc, x|
32
32
  t := x * 3
33
33
  u := t + 1
34
34
  acc + u
35
35
  )
36
- b := 1.to(n).fold(0, |acc, x|
36
+ b := Range.to(1, n).fold(0, |acc, x|
37
37
  t := x * 5
38
38
  u := t - 1
39
39
  acc + u
@@ -41,7 +41,7 @@ primitive BlockClosures =
41
41
  a * 1000 + b
42
42
 
43
43
  fun classify(n: Int) -> Int =
44
- 1.to(n).fold(0, |acc, x|
44
+ Range.to(1, n).fold(0, |acc, x|
45
45
  match x % 3
46
46
  0 => acc + 100
47
47
  1 => acc + 10
@@ -49,7 +49,7 @@ primitive BlockClosures =
49
49
  )
50
50
 
51
51
  fun branches(n: Int) -> Int =
52
- 1.to(n).fold(0, |acc, x|
52
+ Range.to(1, n).fold(0, |acc, x|
53
53
  d := x * x
54
54
  if d % 2 == 0
55
55
  acc + d
@@ -59,8 +59,8 @@ primitive BlockClosures =
59
59
 
60
60
  # Nested block closures.
61
61
  fun nested(n: Int) -> Int =
62
- 1.to(n).fold(0, |acc, x|
62
+ Range.to(1, n).fold(0, |acc, x|
63
- inner := 1.to(x).fold(0, |a, z|
63
+ inner := Range.to(1, x).fold(0, |a, z|
64
64
  w := z * x
65
65
  a + w
66
66
  )
@@ -74,7 +74,7 @@ primitive BlockClosures =
74
74
  f(1, 2) + f(3, 4)
75
75
 
76
76
  fun record(n: Int) -> Int =
77
- r := 1.to(n).fold(Acc(total: 0, count: 0), |acc, x|
77
+ r := Range.to(1, n).fold(Acc(total: 0, count: 0), |acc, x|
78
78
  t := acc.total + x
79
79
  Acc(total: t, count: acc.count + 1)
80
80
  )
@@ -82,14 +82,14 @@ primitive BlockClosures =
82
82
 
83
83
  fun eachSum(n: Int) -> Int =
84
84
  t := Tally(n: 0)
85
- 1.to(n).each(|x|
85
+ Range.to(1, n).each(|x|
86
86
  y := x * 2
87
87
  t.n = t.n + y
88
88
  )
89
89
  t.n
90
90
 
91
91
  fun big() -> Int =
92
- 0.until(1000000).fold(0, |acc, x|
92
+ Range.until(0, 1000000).fold(0, |acc, x|
93
93
  y := x % 7
94
94
  acc + y
95
95
  )
tests/syntax/list_items.plum ADDED
@@ -0,0 +1,151 @@
1
+ import std/Int
2
+ import std/Bool
3
+ import std/Str
4
+ import std/Test
5
+ import std/Option
6
+ import std/collections/List
7
+
8
+ # A list literal's items: a value, a spread `..xs` (a `List`, an `Option`, a `Range`), and a
9
+ # conditional item `if c then x` / `if c then ..xs`, added only when `c` holds. Items run left
10
+ # to right; the list is built once, from the back.
11
+
12
+ trait Shape =
13
+ fun area(self) -> Int
14
+
15
+ struct Sq[Shape](k: Int) =
16
+ fun area(self) -> Int = self.k * self.k
17
+
18
+ struct Dot[Shape](r: Int) =
19
+ fun area(self) -> Int = self.r
20
+
21
+ # Records the order items run in.
22
+ struct Log(mut seen: List<Int>) =
23
+ fun note(self, n: Int) -> Int =
24
+ self.seen = Cons(head: n, tail: self.seen)
25
+ n
26
+
27
+ fun notes(self, n: Int) -> List<Int> = [self.note(n)]
28
+
29
+ fun order(self) -> List<Int> = self.seen.reverse()
30
+
31
+ struct Counter(mut n: Int) =
32
+ fun bump(self) -> Int =
33
+ self.n = self.n + 1
34
+ self.n
35
+
36
+ primitive Items =
37
+ fun total(xs: List<Shape>) -> Int = xs.fold(0, |acc, x| acc + x.area())
38
+
39
+ fun scene(sqs: List<Sq>, over: Bool, dot: Option<Dot>) -> List<Shape> =
40
+ [Dot(r: 1), ..sqs, ..dot, if over then Sq(k: 10)]
41
+
42
+ # A spread followed by items of other types: the spread list widens to the literal's
43
+ # `List<Shape>`, which its result must be.
44
+ fun mixed(sqs: List<Sq>, n: Int, over: Bool) -> List<Shape> = [
45
+ ..sqs,
46
+ Dot(r: n),
47
+ ..Range.until(0, n).map(|i| Sq(k: i)),
48
+ if over then Dot(r: 100)]
49
+
50
+ primitive ListItemsTest[UnitTest] =
51
+ fun values() =
52
+ assert [1, 2, 3] == Cons(head: 1, tail: Cons(head: 2, tail: Cons(head: 3, tail: Nil)))
53
+
54
+ fun spreads() =
55
+ xs := [2, 3]
56
+ assert [1, ..xs, 4] == [1, 2, 3, 4]
57
+ assert [..xs, ..xs] == [2, 3, 2, 3]
58
+ assert [..xs] == xs
59
+ assert [0, ..xs] == [0, 2, 3]
60
+
61
+ fun emptySpreads() =
62
+ none: List<Int> := []
63
+ assert [..none] == none
64
+ assert [1, ..none, 2, ..none] == [1, 2]
65
+ n: Option<Int> := None
66
+ assert [1, ..n] == [1]
67
+ e: List<Int> := [..none, ..n]
68
+ assert e.isEmpty()
69
+
70
+ fun optionSpreads() =
71
+ o := Some(7)
72
+ assert [1, ..o, 2] == [1, 7, 2]
73
+ assert [..o] == [7]
74
+
75
+ fun rangeSpreads() =
76
+ assert [..Range.until(0, 3), 9] == [0, 1, 2, 9]
77
+ assert [..Range.until(3, 3)] == []
78
+ assert [..Range.until(0, 3).map(|i| i * 10)] == [0, 10, 20]
79
+
80
+ fun ifItems() =
81
+ yes := true
82
+ no := false
83
+ assert [1, if yes then 2, 3] == [1, 2, 3]
84
+ assert [1, if no then 2, 3] == [1, 3]
85
+ assert [1, if yes then 2] == [1, 2]
86
+ assert [1, if no then 2] == [1]
87
+ assert [if yes then 1 else 2, if no then 3 else 4] == [1, 4]
88
+ e: List<Int> := [if no then 1]
89
+ assert e.isEmpty()
90
+
91
+ fun ifSpreads() =
92
+ xs := [2, 3]
93
+ yes := true
94
+ no := false
95
+ assert [1, if yes then ..xs, 4] == [1, 2, 3, 4]
96
+ assert [1, if no then ..xs, 4] == [1, 4]
97
+ assert [if yes then ..xs] == xs
98
+
99
+ fun ifBinds() =
100
+ o := Some(5)
101
+ n: Option<Int> := None
102
+ assert [if Some(v) := o then v + 1, if Some(w) := n then w, 9] == [6, 9]
103
+
104
+ fun nested() =
105
+ xs := [2, 3]
106
+ yes := true
107
+ assert [[1, ..xs], [if yes then 4, ..[5, if yes then ..[6, 7]]]] == [[1, 2, 3], [4, 5, 6, 7]]
108
+
109
+ fun orderPlain() =
110
+ log := Log(seen: Nil)
111
+ xs := [log.note(1), ..log.notes(2), log.note(3)]
112
+ assert xs == [1, 2, 3]
113
+ assert log.order() == [1, 2, 3]
114
+
115
+ fun orderAroundIfItems() =
116
+ log := Log(seen: Nil)
117
+ yes := true
118
+ no := false
119
+ xs := [log.note(1), if log.note(2) > 0 then log.note(3), if no then log.note(99), log.note(4), if yes then ..log.notes(5), log.note(6)]
120
+ assert xs == [1, 3, 4, 5, 6]
121
+ assert log.order() == [1, 2, 3, 4, 5, 6]
122
+
123
+ fun orderWithPlainTail() =
124
+ log := Log(seen: Nil)
125
+ yes := true
126
+ k := 4
127
+ xs := [log.note(1), if yes then log.note(2), k, if yes then ..[k + 1]]
128
+ assert xs == [1, 2, 4, 5]
129
+ assert log.order() == [1, 2]
130
+
131
+ fun aPlainItemAfterAnEffect() =
132
+ c := Counter(n: 0)
133
+ assert [if c.bump() > 0 then 10, c.n] == [10, 1]
134
+ assert [if c.bump() > 5 then 10, c.n, c.bump(), c.n] == [2, 3, 3]
135
+
136
+ fun covariantSpreads() =
137
+ sqs := [Sq(k: 2), Sq(k: 3)]
138
+ assert Items.total(Items.scene(sqs, false, None)) == 14
139
+ assert Items.total(Items.scene(sqs, true, Some(Dot(r: 5)))) == 119
140
+ assert Items.total([..sqs, Dot(r: 1)]) == 14
141
+
142
+ fun spreadsWidenToTheLiteral() =
143
+ sqs := [Sq(k: 2)]
144
+ assert Items.total(Items.mixed(sqs, 3, false)) == 4 + 3 + 0 + 1 + 4
145
+ assert Items.total(Items.mixed(sqs, 0, true)) == 4 + 0 + 100
146
+
147
+ fun longSpread() =
148
+ big := Range.until(0, 100000).map(|i| i)
149
+ xs := [-1, ..big, 100000]
150
+ assert xs.length() == 100002
151
+ assert big.length() == 100000
tests/wasm_codegen/e2e_types/user_type_shadows_std_pair_imported_by_std.plum CHANGED
@@ -6,7 +6,7 @@ struct Pair(a: Int, b: Int) =
6
6
 
7
7
  primitive UserTypeShadowsStdPairImportedByStd =
8
8
  fun runMain() -> Int =
9
- p := 0.until(3).fold(Pair(a: 3, b: 4), |q, i| Pair(a: q.a + i, b: q.b))
9
+ p := Range.until(0, 3).fold(Pair(a: 3, b: 4), |q, i| Pair(a: q.a + i, b: q.b))
10
10
  p.a * 10 + p.sum()
11
11
 
12
12
  # moved from e2e_types::list_and_shadow::user_type_shadows_std_pair_imported_by_std