plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
471e488
— Peter John
2026-11-13T20:57:26+05:30
inference, so a view needs no annotations: `List` and `Option` are covariant over a trait (a `List<Ship>` is a `List<View>` wherever one is expected, an `Option<Ship>` an `Option<View>`, nested too); each instance is its own wasm-gc type, so the check records each site (`unifyArg` falls back to `tryUpcast`, by the value's node id) and `lowerUpcasts` (checker/upcasts.rs) wraps the value in a helper made once per pair of types, `fun __upcast0(xs: List<Ship>) -> List<View> = match xs Nil => Nil, Cons(h, t) => Cons(head: h, tail: __upcast0(t))`, which the second check types exactly (`checkSourceFullPre` lowers, then checks again; a check or a pass's re-check that leaves a site unlowered is an error, so a rewrite that makes one is dropped); a value already of the wider type costs nothing; `Slice`/`Array` stay invariant (written in place), nothing is covariant inside a fn type, a generic body's `List<T>` is not upcast; a receiver widens to its arguments (`back.append(views)` on a `List<Box>` retries the call at the join `List<View>` and upcasts the receiver); with nothing expected, a list literal of several types is built at their join and `if`/`match` branches join at their trait (`joinTrait` falls back to `joinAll`): the one most specific trait two types share, ties broken along each type's first listed trait (`Box[View, Sized, Touch]` and `Circle[..]` join at `View`); TRMC types the cell it builds as the result (a `Cons(head: ship, ..)` built for a `List<View>` failed its re-check, so a map into a wider list was never a loop: the backlog entry is gone); `Views.all`/`Views.one` are gone: orbitrunner's and balloonpop's views, the web-test fixture, std/game's tests and the screen_views benchmark have no `List<View>`/`View` annotations; cost on benchmarks/screen_views: orbit paint the same before and after (about 156 ms for 14,400 ticks, checksum 925878360), and a screen upcasting a `List<ViewDot>` of 10,000 each frame costs about 4 ns an item, the same as the hand map it replaces; `import std/App` is required like any module (no prelude): the loader no longer loads it for a file that lists `[App]` ("unknown trait App (import std/App)"; a library folder without std still takes the marker), and every program imports it: examples, games, tests, benchmarks, fixtures, run.py's generated programs, the docs' snippets and the Rust inline programs (in a shared prefix the import takes the blank line's place; positions asserted after an inserted line moved by one); tests: tests/traits/covariance.plum (each rule, a 100,000-item upcast, the source list untouched), checker tests for covariance, its soundness (fn types, a `mut` container, a generic body, `Slice`), the joins and an ambiguous one, and the import; the `$dyn` copy of a `List<Self>` result now upcasts (a `List<Self>` parameter is still the error); docs: language.md's Coercion (the covariance, its cost, the inference rules, a sample), game.md's view, std/App's comment
- README.md +1 -0
- benchmarks/dispatch/run.py +1 -1
- benchmarks/map_snapshots/snapshots.plum +1 -0
- benchmarks/master_vs_simpler/branch/array.plum +1 -0
- benchmarks/master_vs_simpler/branch/cons.plum +1 -0
- benchmarks/master_vs_simpler/branch/cons_rec.plum +1 -0
- benchmarks/master_vs_simpler/branch/fib.plum +1 -0
- benchmarks/master_vs_simpler/branch/loop.plum +1 -0
- benchmarks/master_vs_simpler/branch/map.plum +1 -0
- benchmarks/master_vs_simpler/branch/particles.plum +1 -0
- benchmarks/master_vs_simpler/branch/str.plum +1 -0
- benchmarks/master_vs_simpler/branch/trig.plum +1 -0
- benchmarks/master_vs_simpler/run.py +2 -0
- benchmarks/math_bits/check.plum +1 -0
- benchmarks/screen_views/orbit.plum +1 -0
- benchmarks/screen_views/scale.plum +2 -1
- benchmarks/static_calls/static_vs_free.plum +1 -0
- compiler/checker/src/infer.rs +19 -1
- compiler/checker/src/lib.rs +5 -0
- compiler/checker/src/program.rs +42 -1
- compiler/checker/src/state.rs +3 -0
- compiler/checker/src/traits.rs +3 -1
- compiler/checker/src/unification.rs +8 -1
- compiler/checker/src/upcasts.rs +376 -0
- compiler/checker/tests/checker/features/empty_list.rs +1 -1
- compiler/checker/tests/checker/features/primitive_generics.rs +2 -2
- compiler/checker/tests/checker/features/review_fixes.rs +4 -4
- compiler/checker/tests/checker/modules_tests.rs +21 -12
- compiler/checker/tests/checker/review_tests.rs +4 -4
- compiler/checker/tests/checker/traits_tests.rs +176 -8
- compiler/cli/src/program.rs +1 -1
- compiler/cli/tests/cli/args_clock_test.rs +1 -1
- compiler/cli/tests/cli/crash_test.rs +4 -4
- compiler/cli/tests/cli/explain_layout_test.rs +1 -1
- compiler/cli/tests/cli/fusion_agree_test.rs +1 -1
- compiler/cli/tests/cli/game_entry_test.rs +4 -4
- compiler/cli/tests/cli/game_web_test.rs +1 -1
- compiler/cli/tests/cli/inputs_test.rs +2 -2
- compiler/cli/tests/cli/main_result_test.rs +4 -4
- compiler/cli/tests/cli/no_fbip_test.rs +1 -1
- compiler/cli/tests/cli/old_forms_test.rs +13 -13
- compiler/cli/tests/cli/replay_test.rs +1 -1
- compiler/cli/tests/cli/run_folder_test.rs +1 -1
- compiler/cli/tests/cli/std_bounds_test.rs +1 -1
- compiler/cli/tests/cli/test_scope_test.rs +2 -2
- compiler/core/src/ast.rs +1 -1
- compiler/core/src/loader.rs +7 -10
- compiler/core/src/trmc.rs +3 -1
- compiler/core/tests/core/closure_escape_test.rs +1 -1
- compiler/core/tests/core/closure_spec_test.rs +22 -22
- compiler/core/tests/core/loader_test.rs +2 -2
- compiler/core/tests/core/trmc_test.rs +6 -6
- compiler/driver/src/lib.rs +2 -0
- compiler/driver/tests/driver_tests.rs +14 -14
- compiler/game/tests/fixtures/assets_fixture.plum +1 -0
- compiler/game/tests/fixtures/camera_fixture.plum +1 -0
- compiler/game/tests/fixtures/host_fixture.plum +1 -0
- compiler/game/tests/fixtures/main_cli_fixture.plum +1 -0
- compiler/game/tests/fixtures/main_game_fixture.plum +1 -0
- compiler/game/tests/fixtures/main_missing_fixture.plum +1 -0
- compiler/game/tests/fixtures/state_draw_keeps.plum +1 -0
- compiler/game/tests/fixtures/state_in_place.plum +1 -0
- compiler/game/tests/fixtures/state_main_alias.plum +1 -0
- compiler/game/tests/fixtures/state_reset.plum +1 -0
- compiler/game/tests/fixtures/target_fixture.plum +1 -0
- compiler/game/tests/fixtures/turn_fixture.plum +1 -0
- compiler/game/tests/host_test.rs +6 -6
- compiler/game/web-test/fixtures/interleave.plum +1 -0
- compiler/game/web-test/fixtures/main_game.plum +1 -0
- compiler/game/web-test/fixtures/rendertarget.plum +1 -0
- compiler/game/web-test/fixtures/stress.plum +1 -0
- compiler/game/web-test/fixtures/stress_state_view.plum +3 -3
- compiler/game/web-test/fixtures/text_sizes.plum +1 -0
- compiler/lsp/src/main.rs +10 -10
- compiler/lsp/tests/protocol.rs +4 -4
- compiler/test-support/src/lib.rs +1 -1
- compiler/wasm-codegen/src/lib.rs +2 -2
- compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +45 -35
- compiler/wasm-codegen/tests/wasm_codegen/dispatch_test.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_records/enum_init.rs +2 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_records/inline_variants.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_records/unboxed_variants.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_tail/closure_tail.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_types/io_entry.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_types/question.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_types/type_param_static.rs +3 -3
- compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/literals_test.rs +3 -3
- compiler/wasm-codegen/tests/wasm_codegen/names_test.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/native_test.rs +2 -2
- compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs +8 -8
- docs/backlog.md +1 -1
- docs/game.md +7 -10
- docs/language.md +43 -3
- docs/std.md +7 -0
- examples/basics.plum +1 -0
- examples/closures.plum +1 -0
- examples/games/balloonpop/BalloonPop.plum +1 -0
- examples/games/balloonpop/actors/Balloon.plum +1 -1
- examples/games/balloonpop/screens/PlaygroundScreen.plum +4 -4
- examples/games/clicks.plum +1 -0
- examples/games/orbitrunner/OrbitRunner.plum +1 -0
- examples/games/orbitrunner/screens/PlayingScreen.plum +5 -8
- examples/games/two_screens.plum +1 -0
- std/App.plum +2 -2
- std/game/Overlay.plum +1 -1
- std/game/View.plum +0 -6
- tests/fbip/slice_shapes.plum +1 -0
- tests/fbip_probes/array_set.plum +1 -0
- tests/fbip_probes/buffer_write.plum +1 -0
- tests/fbip_probes/map_set_get.plum +1 -0
- tests/fbip_probes/slice_push_field.plum +1 -0
- tests/fbip_probes/slice_push_helper.plum +1 -0
- tests/fbip_probes/slice_push_local.plum +1 -0
- tests/fbip_probes/struct_spread.plum +1 -0
- tests/port/game/screens.plum +2 -2
- tests/port/io/args.plum +1 -0
- tests/std/game/Overlay.plum +1 -1
- tests/std/game/View.plum +7 -7
- tests/traits/covariance.plum +105 -0
README.md
CHANGED
|
@@ -9,6 +9,7 @@ import std/Float
|
|
|
9
9
|
import std/Str
|
|
10
10
|
import std/collections/List
|
|
11
11
|
import std/Option
|
|
12
|
+
import std/App
|
|
12
13
|
|
|
13
14
|
enum Shape =
|
|
14
15
|
| Circle(r: Float)
|
benchmarks/dispatch/run.py
CHANGED
|
@@ -24,7 +24,7 @@ import subprocess
|
|
|
24
24
|
import sys
|
|
25
25
|
|
|
26
26
|
def program(n, calls):
|
|
27
|
-
out = ["import std/Int", "import std/Float", "import std/Str", "import std/Io", "import std/Slice", "import std/Option", "",
|
|
27
|
+
out = ["import std/Int", "import std/Float", "import std/Str", "import std/Io", "import std/Slice", "import std/Option", "import std/App", "",
|
|
28
28
|
"trait Act<M> =", " fun val(self, x: Int) -> Int", " fun kind(self) -> Int = 0", ""]
|
|
29
29
|
for i in range(n):
|
|
30
30
|
out.append(f"struct S{i}[Act<Int>](k: Int) =")
|
benchmarks/map_snapshots/snapshots.plum
CHANGED
|
@@ -11,6 +11,7 @@ import std/Option
|
|
|
11
11
|
import std/Io
|
|
12
12
|
import std/collections/List
|
|
13
13
|
import std/collections/Map
|
|
14
|
+
import std/App
|
|
14
15
|
|
|
15
16
|
primitive Snapshots[App] =
|
|
16
17
|
fun fill(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fill(m.with(i, i), i + 1, n)
|
benchmarks/master_vs_simpler/branch/array.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
primitive ArrayBench[App] =
|
|
13
14
|
fun sumFrom(xs: Slice<Int>, i: Int, acc: Int) -> Int = if i >= xs.length() then acc else sumFrom(xs, i + 1, acc + xs.at(i))
|
benchmarks/master_vs_simpler/branch/cons.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
primitive ConsBench[App] =
|
|
13
14
|
fun build(n: Int, acc: List<Int>) -> List<Int> = if n == 0 then acc else build(n - 1, Cons(head: n, tail: acc))
|
benchmarks/master_vs_simpler/branch/cons_rec.plum
CHANGED
|
@@ -3,6 +3,7 @@ import std/Float
|
|
|
3
3
|
import std/Str
|
|
4
4
|
import std/Io
|
|
5
5
|
import std/collections/List
|
|
6
|
+
import std/App
|
|
6
7
|
|
|
7
8
|
primitive ConsRecBench[App] =
|
|
8
9
|
fun build(n: Int, acc: List<Int>) -> List<Int> = if n == 0 then acc else build(n - 1, Cons(head: n, tail: acc))
|
benchmarks/master_vs_simpler/branch/fib.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
primitive FibBench[App] =
|
|
13
14
|
fun fib(n: Int) -> Int = if n < 2 then n else fib(n - 1) + fib(n - 2)
|
benchmarks/master_vs_simpler/branch/loop.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
primitive LoopBench[App] =
|
|
13
14
|
fun go(i: Int, n: Int, acc: Int) -> Int = if i >= n then acc else go(i + 1, n, {acc + i * i % 7} % 1000000007)
|
benchmarks/master_vs_simpler/branch/map.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
primitive MapBench[App] =
|
|
13
14
|
fun look(m: Map<Int, Int>, i: Int, n: Int, acc: Int) -> Int = if i >= n then acc else look(m, i + 1, n, acc + m.get(i * 7919 % 1000003).unwrapOr(0) % 13)
|
benchmarks/master_vs_simpler/branch/particles.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
struct P(x: Float, y: Float, vx: Float, vy: Float) =
|
|
13
14
|
fun moved(self) -> P =
|
benchmarks/master_vs_simpler/branch/str.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
primitive StrBench[App] =
|
|
13
14
|
fun go(i: Int, n: Int, acc: Int) -> Int = if i >= n then acc else go(i + 1, n, acc + "item-{i}-{i % 97}".length())
|
benchmarks/master_vs_simpler/branch/trig.plum
CHANGED
|
@@ -8,6 +8,7 @@ import std/collections/List
|
|
|
8
8
|
import std/Slice
|
|
9
9
|
import std/collections/Map
|
|
10
10
|
import std/math/Math
|
|
11
|
+
import std/App
|
|
11
12
|
|
|
12
13
|
primitive TrigBench[App] =
|
|
13
14
|
fun go(i: Int, n: Int, s: Float) -> Float =
|
benchmarks/master_vs_simpler/run.py
CHANGED
|
@@ -141,6 +141,7 @@ import std/math/Random
|
|
|
141
141
|
import std/game/Input
|
|
142
142
|
import std/game/Screen
|
|
143
143
|
import std/game/Game
|
|
144
|
+
import std/App
|
|
144
145
|
import examples/games/orbitrunner/OrbitRunner
|
|
145
146
|
import examples/games/orbitrunner/screens/PlayingScreen
|
|
146
147
|
|
|
@@ -233,6 +234,7 @@ import std/math/Vec2
|
|
|
233
234
|
import std/game/Input
|
|
234
235
|
import std/game/Screen
|
|
235
236
|
import std/game/Game
|
|
237
|
+
import std/App
|
|
236
238
|
import examples/games/balloonpop/BalloonPop
|
|
237
239
|
import examples/games/balloonpop/screens/PlaygroundScreen
|
|
238
240
|
|
benchmarks/math_bits/check.plum
CHANGED
|
@@ -30,6 +30,7 @@ import std/Slice
|
|
|
30
30
|
import std/collections/Map
|
|
31
31
|
import std/Pair
|
|
32
32
|
import std/math/Math
|
|
33
|
+
import std/App
|
|
33
34
|
|
|
34
35
|
primitive MathCheck[App] =
|
|
35
36
|
# --- the references ---
|
benchmarks/screen_views/orbit.plum
CHANGED
|
@@ -29,6 +29,7 @@ import std/game/Input
|
|
|
29
29
|
import std/math/Vec2
|
|
30
30
|
import std/game/Screen
|
|
31
31
|
import std/game/Game
|
|
32
|
+
import std/App
|
|
32
33
|
import benchmarks/screen_views/timing
|
|
33
34
|
import examples/games/orbitrunner/OrbitRunner
|
|
34
35
|
import examples/games/orbitrunner/screens/PlayingScreen
|
benchmarks/screen_views/scale.plum
CHANGED
|
@@ -42,6 +42,7 @@ import std/game/Screen
|
|
|
42
42
|
import std/game/ScreenSlice
|
|
43
43
|
import std/game/Game
|
|
44
44
|
import std/game/TestRig
|
|
45
|
+
import std/App
|
|
45
46
|
import benchmarks/screen_views/timing
|
|
46
47
|
|
|
47
48
|
primitive ScaleBench[App] =
|
|
@@ -51,7 +52,7 @@ primitive ScaleBench[App] =
|
|
|
51
52
|
if i >= n
|
|
52
53
|
Nil
|
|
53
54
|
else
|
|
54
|
-
d
|
|
55
|
+
d := if hand then HandDot.of(i) else ViewDot.of(i)
|
|
55
56
|
Cons(d, dotsFrom(hand, i + 1, n))
|
|
56
57
|
|
|
57
58
|
fun frameOf(d: View) -> Int = match d
|
benchmarks/static_calls/static_vs_free.plum
CHANGED
|
@@ -20,6 +20,7 @@ import std/Int
|
|
|
20
20
|
import std/Float
|
|
21
21
|
import std/Str
|
|
22
22
|
import std/Slice
|
|
23
|
+
import std/App
|
|
23
24
|
|
|
24
25
|
struct Acc(mut n: Int)
|
|
25
26
|
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -736,6 +736,12 @@ pub(crate) fn inferExprInner(
|
|
|
736
736
|
}
|
|
737
737
|
}
|
|
738
738
|
ast::Expr { kind: ast::ExprKind::ClassCall(call), .. } => {
|
|
739
|
+
// A list literal of several types, no element type expected: built at their join.
|
|
740
|
+
if expected.is_none_or(|e| hasInferVars(&resolveRecorded(e))) {
|
|
741
|
+
if let Some(j) = literalJoin(call, env, ctx) {
|
|
742
|
+
return inferClassCallRaw(call, env, ctx, Some(&j));
|
|
743
|
+
}
|
|
744
|
+
}
|
|
739
745
|
inferClassCallRaw(call, env, ctx, expected)
|
|
740
746
|
}
|
|
741
747
|
ast::Expr { kind: ast::ExprKind::Attribute(attr), .. } => {
|
|
@@ -816,7 +822,19 @@ pub(crate) fn inferExprInner(
|
|
|
816
822
|
withCheck(|s| s.open_receivers.borrow_mut().push((attr.object.id, e)));
|
|
817
823
|
}
|
|
818
824
|
checkStaticUse(&attr.object, &obj_ty, &call.name, ctx)?;
|
|
819
|
-
inferMethodCallWith(&obj_ty, call.name.as_str(), &call.args, &call.type_args, env, ctx, expected)
|
|
825
|
+
let r = inferMethodCallWith(&obj_ty, call.name.as_str(), &call.args, &call.type_args, env, ctx, expected);
|
|
826
|
+
if r.is_err() {
|
|
827
|
+
// `back.append(views)` on a `List<Box>`: the receiver widens to the
|
|
828
|
+
// join (`List<View>`) and is upcast there.
|
|
829
|
+
if let Some(wider) = widenReceiver(&obj_ty, call, env, 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
|
+
}
|
|
836
|
+
}
|
|
837
|
+
r
|
|
820
838
|
}
|
|
821
839
|
}
|
|
822
840
|
}
|
compiler/checker/src/lib.rs
CHANGED
|
@@ -25,6 +25,7 @@ mod tables;
|
|
|
25
25
|
pub mod traits;
|
|
26
26
|
mod typeconv;
|
|
27
27
|
mod unification;
|
|
28
|
+
mod upcasts;
|
|
28
29
|
pub mod types;
|
|
29
30
|
pub use types::{CheckErrorExt, DiagKind};
|
|
30
31
|
|
|
@@ -52,6 +53,7 @@ pub use tables::*;
|
|
|
52
53
|
pub use traits::*;
|
|
53
54
|
pub use typeconv::*;
|
|
54
55
|
pub use unification::*;
|
|
56
|
+
pub(crate) use upcasts::*;
|
|
55
57
|
|
|
56
58
|
/// Per-expression instantiated types of a checked source, for codegen.
|
|
57
59
|
///
|
|
@@ -89,6 +91,9 @@ pub struct TypedInfo {
|
|
|
89
91
|
/// The program's traits: what implements each `(trait, arguments)` (see
|
|
90
92
|
/// `Traits::implementerSets`), the trait methods' signatures and the bounds of generics.
|
|
91
93
|
pub traits: std::rc::Rc<traits::Traits>,
|
|
94
|
+
/// Covariant upcasts the check found, `(to, from)` by the value's node id; empty once
|
|
95
|
+
/// they are lowered (see `upcasts.rs`). A program checked with some left is not compiled.
|
|
96
|
+
pub upcasts: BTreeMap<ast::NodeId, (PlumType, PlumType)>,
|
|
92
97
|
}
|
|
93
98
|
|
|
94
99
|
/// One reached instantiation of a generic fn or method of a generic type.
|
compiler/checker/src/program.rs
CHANGED
|
@@ -82,7 +82,8 @@ pub(crate) fn checkSourceFullPre(source: &ast::Source, pre: &mut Option<ast::Sou
|
|
|
82
82
|
}
|
|
83
83
|
if !source.formLoops {
|
|
84
84
|
*pre = Some(source.clone());
|
|
85
|
-
|
|
85
|
+
let (result, info) = plum_core::timing::time("check once", || checkSourceOnce(source));
|
|
86
|
+
return lowerAndCheck(source, result, info, pre);
|
|
86
87
|
}
|
|
87
88
|
// `for` loops are lowered by the checker, because how a loop iterates depends
|
|
88
89
|
// on the type of its source. Pass 1 checks the program and lowers each loop as
|
|
@@ -95,6 +96,9 @@ pub(crate) fn checkSourceFullPre(source: &ast::Source, pre: &mut Option<ast::Sou
|
|
|
95
96
|
ast::numberIds(&mut lowered);
|
|
96
97
|
*pre = Some(lowered.clone());
|
|
97
98
|
let (result, mut info) = plum_core::timing::time("check once", || checkSourceOnce(&lowered));
|
|
99
|
+
if !info.upcasts.is_empty() {
|
|
100
|
+
return lowerAndCheck(&lowered, result, info, pre);
|
|
101
|
+
}
|
|
98
102
|
if info.lowered.is_none() {
|
|
99
103
|
// `lowered` itself was checked.
|
|
100
104
|
info.lowered = Some(std::rc::Rc::new(lowered));
|
|
@@ -102,6 +106,42 @@ pub(crate) fn checkSourceFullPre(source: &ast::Source, pre: &mut Option<ast::Sou
|
|
|
102
106
|
(result, info)
|
|
103
107
|
}
|
|
104
108
|
|
|
109
|
+
/// The check of `source` when it found no covariant upcast; else the check of the program
|
|
110
|
+
/// with each one made a call of its helper (`upcasts.rs`), which is what codegen compiles. A
|
|
111
|
+
/// site the lowering missed is an error: compiled as it is, its list would have the wrong
|
|
112
|
+
/// type.
|
|
113
|
+
fn lowerAndCheck(
|
|
114
|
+
source: &ast::Source,
|
|
115
|
+
result: CheckResult<()>,
|
|
116
|
+
mut info: TypedInfo,
|
|
117
|
+
pre: &mut Option<ast::Source>,
|
|
118
|
+
) -> (CheckResult<()>, TypedInfo) {
|
|
119
|
+
if info.upcasts.is_empty() || result.is_err() {
|
|
120
|
+
return (result, info);
|
|
121
|
+
}
|
|
122
|
+
let mut ups = std::mem::take(&mut info.upcasts);
|
|
123
|
+
let mut lowered = plum_core::timing::time("upcasts", || lowerUpcasts(source, &mut ups));
|
|
124
|
+
ast::numberIds(&mut lowered);
|
|
125
|
+
*pre = Some(lowered.clone());
|
|
126
|
+
let (result, mut info) = plum_core::timing::time("check once (upcasts)", || checkSourceOnce(&lowered));
|
|
127
|
+
let result = upcastsLeft(result, &info);
|
|
128
|
+
info.upcasts.clear();
|
|
129
|
+
if info.lowered.is_none() {
|
|
130
|
+
info.lowered = Some(std::rc::Rc::new(lowered));
|
|
131
|
+
}
|
|
132
|
+
(result, info)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// `result`, failed if the check left a covariant upcast that nothing lowered (a pass's
|
|
136
|
+
/// rewrite re-checked, or a site `lowerUpcasts` doesn't reach).
|
|
137
|
+
pub fn upcastsLeft(result: CheckResult<()>, info: &TypedInfo) -> CheckResult<()> {
|
|
138
|
+
if info.upcasts.is_empty() || result.is_err() {
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
let (to, from) = info.upcasts.values().next().expect("non-empty");
|
|
142
|
+
Err(vec![CheckError::at(0, 0, format!("internal checker error: the upcast of a {from} to a {to} was not lowered"))])
|
|
143
|
+
}
|
|
144
|
+
|
|
105
145
|
/// The `Io` capability rules: a module-level `extern fun` takes `io: Io` first, and the
|
|
106
146
|
/// primitive `Io` has no constructor.
|
|
107
147
|
pub(crate) fn ioCapabilityErrors(source: &ast::Source) -> Vec<CheckError> {
|
|
@@ -173,6 +213,7 @@ pub(crate) fn checkSourceOnce(source: &ast::Source) -> (CheckResult<()>, TypedIn
|
|
|
173
213
|
}
|
|
174
214
|
};
|
|
175
215
|
info.op_calls = withCheck(|s| { let r = &s.op_calls; std::mem::take(&mut *r.borrow_mut()) });
|
|
216
|
+
info.upcasts = withCheck(|s| std::mem::take(&mut *s.upcasts.borrow_mut()));
|
|
176
217
|
let mut recorded = withCheck(|s| { let r = &s.record; r.borrow_mut().take() }).unwrap_or_default();
|
|
177
218
|
let binds = withCheck(|s| { let r = &s.record_binds; r.borrow_mut().take() })
|
|
178
219
|
.unwrap_or_default();
|
compiler/checker/src/state.rs
CHANGED
|
@@ -105,6 +105,9 @@ pub(crate) struct CheckState {
|
|
|
105
105
|
/// typed (`xs := []` then `xs.map(|x| x.length())`), by the receiver's node id: an error
|
|
106
106
|
/// if nothing ever fixed that type (`checkSourceOnce`), as codegen would see `Unit`.
|
|
107
107
|
pub(crate) open_receivers: RefCell<Vec<(ast::NodeId, crate::types::CheckError)>>,
|
|
108
|
+
/// Covariant upcasts, by the node id of the value upcast: `(to, from)`, a `List<Ship>`
|
|
109
|
+
/// used as a `List<View>` (see `upcasts.rs`).
|
|
110
|
+
pub(crate) upcasts: RefCell<BTreeMap<ast::NodeId, (crate::types::PlumType, crate::types::PlumType)>>,
|
|
108
111
|
/// The working directory, read once per check (`callsites::displayFile` needs it for
|
|
109
112
|
/// every instantiation; asking the OS each time was a measurable part of a check).
|
|
110
113
|
pub(crate) cwd: std::cell::OnceCell<Option<std::path::PathBuf>>,
|
compiler/checker/src/traits.rs
CHANGED
|
@@ -861,7 +861,9 @@ pub(crate) fn joinTrait(expected: Option<&PlumType>, vals: &[PlumType], ctx: &Ch
|
|
|
861
861
|
return Some(c);
|
|
862
862
|
}
|
|
863
863
|
}
|
|
864
|
+
// No trait expected or given: the one trait the branches share (`Box` and `Circle` are
|
|
864
|
-
|
|
865
|
+
// `View`s).
|
|
866
|
+
joinAll(&vals).filter(isTraitObject)
|
|
865
867
|
}
|
|
866
868
|
|
|
867
869
|
/// Checks the parameter defaults of every trait method (`fun moved(self, dx: Int = 1)`) and
|
compiler/checker/src/unification.rs
CHANGED
|
@@ -348,7 +348,14 @@ pub(crate) fn unifyArg(
|
|
|
348
348
|
actual_expr: &ast::Expr,
|
|
349
349
|
ctx: &CheckCtx,
|
|
350
350
|
) -> Result<(), String> {
|
|
351
|
+
if let Err(e) = unify(expected, actual, ctx) {
|
|
352
|
+
// A `List<Ship>` where a `List<View>` is wanted: rebuilt there (`upcasts.rs`).
|
|
353
|
+
if tryUpcast(expected, actual, actual_expr) {
|
|
354
|
+
return Ok(());
|
|
355
|
+
}
|
|
351
|
-
|
|
356
|
+
return Err(format!("{}{}", e, wrapHint(expected, actual, ctx)));
|
|
357
|
+
}
|
|
358
|
+
forgetUpcast(actual_expr);
|
|
352
359
|
// The value is that type from here on: what one side leaves open, the other fixes
|
|
353
360
|
// (`x := None` then `a: Option<Int> := x`, or `cell.v = Some(1)`), instead of the open
|
|
354
361
|
// side being left to default to `Unit` while the other is compiled as written.
|
compiler/checker/src/upcasts.rs
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
//! Covariant upcasts of immutable containers.
|
|
2
|
+
//!
|
|
3
|
+
//! A `List<Ship>` is usable where a `List<View>` is expected when `Ship` implements the trait
|
|
4
|
+
//! `View`, and likewise an `Option<Ship>` (`List` and `Option` are values nothing updates in
|
|
5
|
+
//! place; a `Slice` or an `Array` is written through, so it stays invariant). Inside a
|
|
6
|
+
//! function type nothing is covariant: a `fn(List<View>)` takes no `fn(List<Ship>)`.
|
|
7
|
+
//!
|
|
8
|
+
//! A trait object is a reference to the value itself (`plum_wasm_codegen::traits`), but each
|
|
9
|
+
//! instance of a generic enum is its own wasm-gc type: a `List<Ship>`'s cells hold `Ship`s and
|
|
10
|
+
//! a `List<View>`'s hold trait objects. So an upcast builds the list again: the check records
|
|
11
|
+
//! each site (`tryUpcast`, by the node id of the value), and `lowerUpcasts` wraps the value
|
|
12
|
+
//! in a call of a helper made for the pair of types, an ordinary function the second check
|
|
13
|
+
//! types exactly:
|
|
14
|
+
//!
|
|
15
|
+
//! ```text
|
|
16
|
+
//! fun __upcast0(xs: List<Ship>) -> List<View> = match xs
|
|
17
|
+
//! Nil => Nil
|
|
18
|
+
//! Cons(h, t) => Cons(head: h, tail: __upcast0(t))
|
|
19
|
+
//! ```
|
|
20
|
+
//!
|
|
21
|
+
//! which TRMC makes a loop, the same work as `xs.map(|x| x)`. A value already of the wider
|
|
22
|
+
//! type is no site and costs nothing.
|
|
23
|
+
|
|
24
|
+
use crate::loops::astTypeOf;
|
|
25
|
+
use crate::*;
|
|
26
|
+
|
|
27
|
+
/// The containers whose arguments are covariant.
|
|
28
|
+
const COVARIANT: [&str; 2] = ["List", "Option"];
|
|
29
|
+
|
|
30
|
+
fn isCovariant(n: &str) -> bool {
|
|
31
|
+
COVARIANT.contains(&n)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/// No open variable and no generic parameter: an upcast is made for concrete types only (a
|
|
35
|
+
/// generic body's erased pass keeps the old rule).
|
|
36
|
+
fn closed(t: &PlumType) -> bool {
|
|
37
|
+
!hasFreeVars(t)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Whether a `from` is a `to` by covariance: the same covariant container, each argument the
|
|
41
|
+
/// same type, an implementer of the trait object expected there, or itself such an upcast;
|
|
42
|
+
/// at least one argument differs.
|
|
43
|
+
pub(crate) fn upcastable(to: &PlumType, from: &PlumType) -> bool {
|
|
44
|
+
let (PlumType::TApp(a, xs), PlumType::TApp(b, ys)) = (to, from) else { return false };
|
|
45
|
+
if a != b || !isCovariant(a) || xs.len() != ys.len() {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
let mut differs = false;
|
|
49
|
+
for (x, y) in xs.iter().zip(ys) {
|
|
50
|
+
if x == y {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if !elemUpcast(x, y) {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
differs = true;
|
|
57
|
+
}
|
|
58
|
+
differs
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// An argument of a covariant container: a nested upcast or an implementer of a trait object.
|
|
62
|
+
fn elemUpcast(to: &PlumType, from: &PlumType) -> bool {
|
|
63
|
+
upcastable(to, from) || (isTraitObject(to) && implementsTrait(from, to))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Records the value `expr` of type `actual` used where `expected` is wanted as an upcast,
|
|
67
|
+
/// when it is one. In an instantiation of a generic body only a site the erased pass recorded
|
|
68
|
+
/// passes (the body is one code for every instantiation).
|
|
69
|
+
pub(crate) fn tryUpcast(expected: &PlumType, actual: &PlumType, expr: &ast::Expr) -> bool {
|
|
70
|
+
let (to, from) = (resolveRecorded(expected), resolveRecorded(actual));
|
|
71
|
+
if expr.id == ast::NodeId(0) || !closed(&to) || !closed(&from) || !upcastable(&to, &from) {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
withCheck(|s| {
|
|
75
|
+
let mut ups = s.upcasts.borrow_mut();
|
|
76
|
+
if s.inst_mode.get() || s.tsubst.borrow().is_some() {
|
|
77
|
+
return ups.get(&expr.id) == Some(&(to.clone(), from.clone()));
|
|
78
|
+
}
|
|
79
|
+
ups.insert(expr.id, (to, from));
|
|
80
|
+
true
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// `expr` was checked again and fits as it is (a closure body typed again with its
|
|
85
|
+
/// parameters known): no upcast there.
|
|
86
|
+
pub(crate) fn forgetUpcast(expr: &ast::Expr) {
|
|
87
|
+
withCheck(|s| {
|
|
88
|
+
if !s.inst_mode.get() && s.tsubst.borrow().is_none() {
|
|
89
|
+
s.upcasts.borrow_mut().remove(&expr.id);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// `xs.append(ys)` where `xs` is a `List<Box>` and `ys` a `List<View>`: the receiver of a
|
|
95
|
+
/// method of a covariant container, widened to what its arguments need, so the call's
|
|
96
|
+
/// generic is their join (`List<View>`, `Box` implementing `View`). `None` when no argument
|
|
97
|
+
/// asks for a wider type.
|
|
98
|
+
pub(crate) fn widenReceiver(obj_ty: &PlumType, call: &ast::FnCall, env: &TypeEnv, ctx: &CheckCtx) -> Option<PlumType> {
|
|
99
|
+
let obj = resolveRecorded(obj_ty);
|
|
100
|
+
let PlumType::TApp(n, targs) = &obj else { return None };
|
|
101
|
+
if !isCovariant(n) || !closed(&obj) {
|
|
102
|
+
return None;
|
|
103
|
+
}
|
|
104
|
+
let sig = ctx.methods.get(&(n.clone(), call.name.clone()))?;
|
|
105
|
+
let gens = enumGenericsOf(n, ctx).to_vec();
|
|
106
|
+
if gens.len() != targs.len() {
|
|
107
|
+
return None;
|
|
108
|
+
}
|
|
109
|
+
let vars: Vec<PlumType> = gens.iter().map(|_| freshVar()).collect();
|
|
110
|
+
let owner: BTreeMap<String, PlumType> = gens.iter().cloned().zip(vars.iter().cloned()).collect();
|
|
111
|
+
let PlumType::TFun(params, _) = instSig(sig, &owner) else { return None };
|
|
112
|
+
let mut binds = Binds::new();
|
|
113
|
+
for (arg, param) in call.args.iter().zip(¶ms) {
|
|
114
|
+
let e = argExpr(arg);
|
|
115
|
+
if matches!(e.kind, ast::ExprKind::Closure(_)) || !vars.iter().any(|v| matches!(v, PlumType::TVar(x) if tvarOccurs(param, x))) {
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
let Ok(t) = inferExpr(e, env, ctx) else { continue };
|
|
119
|
+
bindMatch(param, &resolveRecorded(&t), &mut binds);
|
|
120
|
+
}
|
|
121
|
+
let mut widened = Vec::new();
|
|
122
|
+
let mut changed = false;
|
|
123
|
+
for (v, a) in vars.iter().zip(targs) {
|
|
124
|
+
let b = resolveRecorded(&substVars(v, &binds));
|
|
125
|
+
match join2(a, &b).filter(|j| j != a) {
|
|
126
|
+
Some(j) => {
|
|
127
|
+
changed = true;
|
|
128
|
+
widened.push(j);
|
|
129
|
+
}
|
|
130
|
+
None => widened.push(a.clone()),
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
changed.then(|| PlumType::TApp(n.clone(), widened))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/// The type a value of `a` and a value of `b` both are: the same type, a trait object one of
|
|
137
|
+
/// them is and the other implements, else the most specific trait they share (`Mine` and
|
|
138
|
+
/// `Orb`, both `Actor`s and so `View`s, join at `Actor`). When several are (`Box` and
|
|
139
|
+
/// `Circle` are each a `View`, a `Sized` and a `Touch`), the one along each type's first
|
|
140
|
+
/// listed trait, its kind (`struct Box[View, Sized, Touch]`). `None` when nothing joins them.
|
|
141
|
+
pub(crate) fn join2(a: &PlumType, b: &PlumType) -> Option<PlumType> {
|
|
142
|
+
if a == b {
|
|
143
|
+
return Some(a.clone());
|
|
144
|
+
}
|
|
145
|
+
if !closed(a) || !closed(b) {
|
|
146
|
+
return None;
|
|
147
|
+
}
|
|
148
|
+
if isTraitObject(a) && implementsTrait(b, a) {
|
|
149
|
+
return Some(a.clone());
|
|
150
|
+
}
|
|
151
|
+
if isTraitObject(b) && implementsTrait(a, b) {
|
|
152
|
+
return Some(b.clone());
|
|
153
|
+
}
|
|
154
|
+
let traits = currentTraits();
|
|
155
|
+
// The traits `t` is a value of, its own (or its first) with their supertraits.
|
|
156
|
+
let traitsOf = |t: &PlumType, firstOnly: bool| -> Vec<PlumType> {
|
|
157
|
+
let mut own: Vec<PlumType> = match traits.traitObject(t) {
|
|
158
|
+
Some(_) => vec![t.clone()],
|
|
159
|
+
None => traits.entriesOf(t).into_iter().map(|e| e.ty).collect(),
|
|
160
|
+
};
|
|
161
|
+
if firstOnly {
|
|
162
|
+
own.truncate(1);
|
|
163
|
+
}
|
|
164
|
+
let mut out: Vec<PlumType> = Vec::new();
|
|
165
|
+
for tr in own.iter().flat_map(|o| std::iter::once(o.clone()).chain(traits.supertraitsOf(o))) {
|
|
166
|
+
if !out.contains(&tr) && closed(&tr) {
|
|
167
|
+
out.push(tr);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
out
|
|
171
|
+
};
|
|
172
|
+
// The most specific of the traits both are: not a supertrait of another of them.
|
|
173
|
+
let least = |firstOnly: bool| -> Option<PlumType> {
|
|
174
|
+
let bs = traitsOf(b, firstOnly);
|
|
175
|
+
let common: Vec<PlumType> = traitsOf(a, firstOnly).into_iter().filter(|t| bs.contains(t)).collect();
|
|
176
|
+
let least: Vec<&PlumType> =
|
|
177
|
+
common.iter().filter(|t| !common.iter().any(|o| o != *t && traits.supertraitsOf(o).contains(t))).collect();
|
|
178
|
+
match least.as_slice() {
|
|
179
|
+
[one] => Some((*one).clone()),
|
|
180
|
+
_ => None,
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
least(false).or_else(|| least(true))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/// `join2` of all of `ts` (at least one).
|
|
187
|
+
pub(crate) fn joinAll(ts: &[PlumType]) -> Option<PlumType> {
|
|
188
|
+
let (first, rest) = ts.split_first()?;
|
|
189
|
+
rest.iter().try_fold(first.clone(), |acc, t| join2(&acc, t))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/// `[Box.of(..), Circle.of(..)]` with no element type expected: the literal's items as one
|
|
193
|
+
/// list, at the join of their types (`List<View>`). `None` when they are of one type
|
|
194
|
+
/// already, or don't join.
|
|
195
|
+
pub(crate) fn literalJoin(call: &ast::ClassCall, env: &TypeEnv, ctx: &CheckCtx) -> Option<PlumType> {
|
|
196
|
+
let mut heads: Vec<&ast::Expr> = Vec::new();
|
|
197
|
+
let mut at = call;
|
|
198
|
+
loop {
|
|
199
|
+
if at.type_name != "Cons" || at.spread.is_some() || at.fields.len() != 2 || at.fields[0].name != "head" {
|
|
200
|
+
return None;
|
|
201
|
+
}
|
|
202
|
+
heads.push(&at.fields[0].value);
|
|
203
|
+
match &at.fields[1].value.kind {
|
|
204
|
+
ast::ExprKind::ClassCall(next) => at = next,
|
|
205
|
+
_ => break,
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if heads.len() < 2 {
|
|
209
|
+
return None;
|
|
210
|
+
}
|
|
211
|
+
let mut ts: Vec<PlumType> = Vec::new();
|
|
212
|
+
for h in heads {
|
|
213
|
+
ts.push(resolveRecorded(&inferExpr(h, env, ctx).ok()?));
|
|
214
|
+
}
|
|
215
|
+
if ts.windows(2).all(|w| w[0] == w[1]) {
|
|
216
|
+
return None;
|
|
217
|
+
}
|
|
218
|
+
Some(PlumType::TApp("List".to_string(), vec![joinAll(&ts)?]))
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/// The program with every recorded upcast made a call of its helper (see the module doc).
|
|
222
|
+
/// A site this does not reach stays in `ups` (the check after it reports it).
|
|
223
|
+
pub(crate) fn lowerUpcasts(source: &ast::Source, ups: &mut BTreeMap<ast::NodeId, (PlumType, PlumType)>) -> ast::Source {
|
|
224
|
+
let mut out = source.clone();
|
|
225
|
+
let mut helpers = Helpers { made: HashMap::new(), items: Vec::new(), source };
|
|
226
|
+
let mut wrap = |e: &mut ast::Expr| {
|
|
227
|
+
let Some((to, from)) = ups.remove(&e.id) else { return };
|
|
228
|
+
let name = helpers.helper(&to, &from);
|
|
229
|
+
let inner = std::mem::replace(e, ast::Expr::TypeName(String::new()));
|
|
230
|
+
let span = inner.span;
|
|
231
|
+
*e = call(&name, inner);
|
|
232
|
+
e.span = span;
|
|
233
|
+
};
|
|
234
|
+
for item in &mut out.items {
|
|
235
|
+
match item {
|
|
236
|
+
ast::Item::Fn(f) => {
|
|
237
|
+
for p in &mut f.params {
|
|
238
|
+
if let Some(d) = &mut p.default {
|
|
239
|
+
plum_core::forms::mapExprsIn(d, &mut wrap);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
plum_core::forms::mapExprs(&mut f.body, &mut wrap);
|
|
243
|
+
}
|
|
244
|
+
ast::Item::Const(c) => plum_core::forms::mapExprsIn(&mut c.value, &mut wrap),
|
|
245
|
+
_ => {}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
out.items.extend(helpers.items);
|
|
249
|
+
out
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
fn call(name: &str, arg: ast::Expr) -> ast::Expr {
|
|
253
|
+
ast::Expr::FnCall(ast::FnCall {
|
|
254
|
+
name: name.to_string(),
|
|
255
|
+
args: vec![ast::Arg::Positional(arg)],
|
|
256
|
+
line: 0,
|
|
257
|
+
column: 0,
|
|
258
|
+
tail: ast::TailKind::NotTail,
|
|
259
|
+
recv: None,
|
|
260
|
+
type_args: Vec::new(),
|
|
261
|
+
})
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/// The helpers made so far, one per pair of types.
|
|
265
|
+
struct Helpers<'a> {
|
|
266
|
+
made: HashMap<(PlumType, PlumType), String>,
|
|
267
|
+
items: Vec<ast::Item>,
|
|
268
|
+
source: &'a ast::Source,
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
impl Helpers<'_> {
|
|
272
|
+
/// The helper that makes a `from` a `to`, made (with those of nested pairs) if new.
|
|
273
|
+
fn helper(&mut self, to: &PlumType, from: &PlumType) -> String {
|
|
274
|
+
if let Some(n) = self.made.get(&(to.clone(), from.clone())) {
|
|
275
|
+
return n.clone();
|
|
276
|
+
}
|
|
277
|
+
let name = format!("__upcast{}", self.made.len());
|
|
278
|
+
self.made.insert((to.clone(), from.clone()), name.clone());
|
|
279
|
+
let (PlumType::TApp(kind, tos), PlumType::TApp(_, froms)) = (to, from) else {
|
|
280
|
+
unreachable!("an upcast is between two instances of one container")
|
|
281
|
+
};
|
|
282
|
+
// Each argument as the value of the other: itself, or the nested helper's call.
|
|
283
|
+
let elem = |me: &mut Self, v: &str| -> ast::Expr {
|
|
284
|
+
let (t, f) = (&tos[0], &froms[0]);
|
|
285
|
+
let x = ast::Expr::Var(v.to_string());
|
|
286
|
+
if upcastable(t, f) { call(&me.helper(t, f), x) } else { x }
|
|
287
|
+
};
|
|
288
|
+
let (none, some) = self.variants(kind);
|
|
289
|
+
let x = ast::Expr::Var("__xs".to_string());
|
|
290
|
+
let cases = match kind.as_str() {
|
|
291
|
+
"List" => {
|
|
292
|
+
let head = elem(self, "__h");
|
|
293
|
+
let rest = call(&name, ast::Expr::Var("__t".to_string()));
|
|
294
|
+
vec![
|
|
295
|
+
case(&none.0, vec![], ast::Expr::TypeName(none.0.clone())),
|
|
296
|
+
case(&some.0, vec!["__h", "__t"], build(&some, vec![head, rest])),
|
|
297
|
+
]
|
|
298
|
+
}
|
|
299
|
+
_ => {
|
|
300
|
+
let value = elem(self, "__v");
|
|
301
|
+
vec![
|
|
302
|
+
case(&none.0, vec![], ast::Expr::TypeName(none.0.clone())),
|
|
303
|
+
case(&some.0, vec!["__v"], build(&some, vec![value])),
|
|
304
|
+
]
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
let body = ast::Block { stmts: vec![ast::Stmt::Match(ast::Match { subjects: vec![x], cases })] };
|
|
308
|
+
let mut generics = Vec::new();
|
|
309
|
+
self.items.push(ast::Item::Fn(ast::Fn {
|
|
310
|
+
name: name.clone(),
|
|
311
|
+
file: self.source.file.clone(),
|
|
312
|
+
line: 0,
|
|
313
|
+
column: 0,
|
|
314
|
+
type_param: None,
|
|
315
|
+
generics: vec![],
|
|
316
|
+
bounds: vec![],
|
|
317
|
+
is_extern: false,
|
|
318
|
+
is_export: false,
|
|
319
|
+
is_test: false,
|
|
320
|
+
is_fip: false,
|
|
321
|
+
has_self: false,
|
|
322
|
+
params: vec![ast::Param {
|
|
323
|
+
name: "__xs".to_string(),
|
|
324
|
+
ty: ast::ParamType::Type(astTypeOf(from, &mut generics).expect("an upcast's types are closed")),
|
|
325
|
+
default: None,
|
|
326
|
+
}],
|
|
327
|
+
returns: Some(astTypeOf(to, &mut generics).expect("an upcast's types are closed")),
|
|
328
|
+
body: ast::FnBody::Block(body),
|
|
329
|
+
}));
|
|
330
|
+
name
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/// The container's empty variant and its other one, with that one's field names
|
|
334
|
+
/// (`Nil`, `Cons(head, tail)`; `None`, `Some(value)`), as declared.
|
|
335
|
+
fn variants(&self, kind: &str) -> ((String, Vec<String>), (String, Vec<String>)) {
|
|
336
|
+
let e = self
|
|
337
|
+
.source
|
|
338
|
+
.items
|
|
339
|
+
.iter()
|
|
340
|
+
.find_map(|i| match i {
|
|
341
|
+
ast::Item::Enum(e) if e.name == kind => Some(e),
|
|
342
|
+
_ => None,
|
|
343
|
+
})
|
|
344
|
+
.expect("an upcast's container is declared");
|
|
345
|
+
let v = |empty: bool| {
|
|
346
|
+
let v = e.variants.iter().find(|v| v.fields.is_empty() == empty).expect("the container's two variants");
|
|
347
|
+
(v.name.clone(), v.field_names.clone())
|
|
348
|
+
};
|
|
349
|
+
(v(true), v(false))
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
fn case(variant: &str, binders: Vec<&str>, value: ast::Expr) -> ast::Case {
|
|
354
|
+
ast::Case {
|
|
355
|
+
patterns: vec![ast::CasePattern::Class {
|
|
356
|
+
name: variant.to_string(),
|
|
357
|
+
fields: binders.into_iter().map(|b| ast::CasePattern::Name(b.to_string())).collect(),
|
|
358
|
+
id: ast::NodeId(0),
|
|
359
|
+
}],
|
|
360
|
+
guard: None,
|
|
361
|
+
body: ast::Block { stmts: vec![ast::Stmt::Expr(value, 0, 0)] },
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/// `Cons(head: a, tail: b)`.
|
|
366
|
+
fn build(variant: &(String, Vec<String>), values: Vec<ast::Expr>) -> ast::Expr {
|
|
367
|
+
ast::Expr::ClassCall(ast::ClassCall {
|
|
368
|
+
type_name: variant.0.clone(),
|
|
369
|
+
fields: variant.1.iter().cloned().zip(values).map(|(name, value)| ast::FieldArg { name, value }).collect(),
|
|
370
|
+
generics: vec![],
|
|
371
|
+
spread: None,
|
|
372
|
+
unique: false,
|
|
373
|
+
reuse: None,
|
|
374
|
+
reboxed: vec![],
|
|
375
|
+
})
|
|
376
|
+
}
|
compiler/checker/tests/checker/features/empty_list.rs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
//! field, a sibling element or the rest of its statement. A later statement does not type it.
|
|
3
3
|
use plum_checker::checkSource;
|
|
4
4
|
|
|
5
|
-
const PRE: &str = "import std/Int\nimport std/Str\nimport std/Test\nimport std/Option\nimport std/collections/List\nimport std/encoding/Json\
|
|
5
|
+
const PRE: &str = "import std/Int\nimport std/Str\nimport std/Test\nimport std/Option\nimport std/collections/List\nimport std/encoding/Json\nimport std/App\nstruct Holder(xs: List<Int>, y: Int)\n\nstruct Box<T>(items: List<T>)\n\nprimitive Pre =\n fun count(xs: List<Int>) -> Int =\n xs.length()\n\n";
|
|
6
6
|
|
|
7
7
|
/// The errors of `PRE` + `body`, as (line, column, message).
|
|
8
8
|
fn errors(name: &str, body: &str) -> Vec<(u32, u32, String)> {
|
compiler/checker/tests/checker/features/primitive_generics.rs
CHANGED
|
@@ -8,7 +8,7 @@ fn load(name: &str, body: &str) -> plum_core::ast::Source {
|
|
|
8
8
|
fn primitiveGenericsAreNotPseudoVariants() {
|
|
9
9
|
let source = load(
|
|
10
10
|
"a",
|
|
11
|
-
"import std/Array\nimport std/Int\
|
|
11
|
+
"import std/Array\nimport std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n 1\n",
|
|
12
12
|
);
|
|
13
13
|
assert!(source.primitives.iter().any(|p| p.name == "Array"));
|
|
14
14
|
let (_, _, enum_variants) = buildGlobalTables(&source);
|
|
@@ -23,7 +23,7 @@ fn primitiveGenericsAreNotPseudoVariants() {
|
|
|
23
23
|
fn arrayElementTypeIsEnforced() {
|
|
24
24
|
let source = load(
|
|
25
25
|
"c",
|
|
26
|
-
"import std/Array\nimport std/Int\nimport std/Str\
|
|
26
|
+
"import std/Array\nimport std/Int\nimport std/Str\nimport std/App\nprimitive Main[App] =\n fun main() -> Str =\n a := Array<Int>().push(3)\n a.at(0)\n",
|
|
27
27
|
);
|
|
28
28
|
assert!(checkSource(&source).is_err());
|
|
29
29
|
}
|
compiler/checker/tests/checker/features/review_fixes.rs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
//! reported at the wrong place: each is now an error at the offending code.
|
|
3
3
|
use plum_core::Diagnostic;
|
|
4
4
|
|
|
5
|
-
const PRE: &str = "import std/Int\nimport std/Option\n";
|
|
5
|
+
const PRE: &str = "import std/Int\nimport std/Option\nimport std/App\n";
|
|
6
6
|
|
|
7
7
|
/// Loads `src` (after `PRE`) with std and checks it; the errors, or the load error.
|
|
8
8
|
fn diags(src: &str) -> Vec<Diagnostic> {
|
|
@@ -122,7 +122,7 @@ fn duplicateNamesAreErrors() {
|
|
|
122
122
|
("import std/Test\nstruct P(x: Int, y: Int)\n\nprimitive SampleTest[UnitTest] =\n fun x() =\n p := P(x: 1, y: 2)\n q := P(..p, x: 3, x: 4)\n assert q.x == 4\n", "field 'x' is given twice"),
|
|
123
123
|
("struct P(x: Int, y: Int)\n\nprimitive Main =\n fun f(p: P) -> Int = match p\n P(a, a) => a\n", "'a' is bound twice in one pattern"),
|
|
124
124
|
("import std/Test\nprimitive SampleTest[UnitTest] =\n fun x() =\n assert 1 == 1\n\n fun x() =\n assert 2 == 2\n", "duplicate test SampleTest.x"),
|
|
125
|
-
("primitive Main =\n fun f() -> Int = 1\n\n fun f() -> Int = 2\n", "duplicate declaration of method 'Main.f': already declared at line
|
|
125
|
+
("primitive Main =\n fun f() -> Int = 1\n\n fun f() -> Int = 2\n", "duplicate declaration of method 'Main.f': already declared at line 5"),
|
|
126
126
|
];
|
|
127
127
|
for (src, needle) in cases {
|
|
128
128
|
let es = diags(src);
|
|
@@ -178,7 +178,7 @@ fn callChainNamesTheFile() {
|
|
|
178
178
|
let src = "primitive Main[App] =\n fun nm<T>(x: T) -> Int = x.nope()\n\n fun main() -> Int = Main.nm(1)\n";
|
|
179
179
|
let es = diags(src);
|
|
180
180
|
let e = es.iter().find(|e| e.message.contains("Int has no method 'nope'")).expect("error");
|
|
181
|
-
assert!(e.message.contains("main.plum:
|
|
181
|
+
assert!(e.message.contains("main.plum:7:23)"), "{e:?}");
|
|
182
182
|
assert!(!e.message.contains("<source>"), "{e:?}");
|
|
183
183
|
}
|
|
184
184
|
|
|
@@ -206,7 +206,7 @@ fn failingCompareInATestIsAtTheAssert() {
|
|
|
206
206
|
let lowered = plum_core::tests_lower::lowerTests(&source).source;
|
|
207
207
|
let es = plum_driver::check(&lowered, &plum_driver::PassOptions::default()).expect_err("mismatch");
|
|
208
208
|
let e = es.iter().find(|e| e.message.contains("compare op")).expect("compare error");
|
|
209
|
-
assert_eq!((e.line, e.column), (
|
|
209
|
+
assert_eq!((e.line, e.column), (9, 5), "{es:?}");
|
|
210
210
|
}
|
|
211
211
|
|
|
212
212
|
#[test]
|
compiler/checker/tests/checker/modules_tests.rs
CHANGED
|
@@ -21,7 +21,7 @@ fn run(name: &str, src: &str) -> Result<(), String> {
|
|
|
21
21
|
checkProgram(&source).0.map_err(|ds| ds.iter().map(|d| d.message.clone()).collect::<Vec<_>>().join(" | "))
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
const BOTH: &str = "import std/Int\nimport tests/modules/mathx\nimport tests/modules/shapes\
|
|
24
|
+
const BOTH: &str = "import std/Int\nimport tests/modules/mathx\nimport tests/modules/shapes\nimport std/App\n";
|
|
25
25
|
|
|
26
26
|
#[test]
|
|
27
27
|
fn qualified_calls_and_constants_check() {
|
|
@@ -99,7 +99,7 @@ fn constants_declared_out_of_order_check() {
|
|
|
99
99
|
/// goes; `main` and an `export fun` go in the program's `[App]` primitive.
|
|
100
100
|
#[test]
|
|
101
101
|
fn a_top_level_fun_or_constant_is_an_error() {
|
|
102
|
-
let e = run("topfun", "import std/Int\
|
|
102
|
+
let e = run("topfun", "import std/Int\nimport std/App\nfun f() -> Int = 1\n\nprimitive Main[App] =\n fun main() -> Int = f()\n").unwrap_err();
|
|
103
103
|
assert!(
|
|
104
104
|
e.contains("`f` is a top-level function, and nothing is global: move `f` into a `primitive`, `struct`, `enum` or `trait`"),
|
|
105
105
|
"{e}"
|
|
@@ -107,14 +107,14 @@ fn a_top_level_fun_or_constant_is_an_error() {
|
|
|
107
107
|
assert!(e.contains("main.plum:3:1"), "{e}");
|
|
108
108
|
let e = run("topext", "import std/Io\nimport std/Float\n\nextern fun rawNowMillis(io: Io) -> Float\n").unwrap_err();
|
|
109
109
|
assert!(e.contains("`rawNowMillis` is a top-level function"), "{e}");
|
|
110
|
-
let e = run("topconst", "import std/Int\
|
|
110
|
+
let e = run("topconst", "import std/Int\nimport std/App\nconst Limit = 10\n\nprimitive Main[App] =\n fun main() -> Int = 1\n").unwrap_err();
|
|
111
111
|
assert!(e.contains("`Limit` is a top-level constant, and nothing is global: move `Limit` into a `primitive`"), "{e}");
|
|
112
|
-
let e = run("topbare", "import std/Int\
|
|
112
|
+
let e = run("topbare", "import std/Int\nimport std/App\nLimit = 10\n\nprimitive Main[App] =\n fun main() -> Int = 1\n").unwrap_err();
|
|
113
113
|
assert!(e.contains("`Limit` is a top-level constant"), "{e}");
|
|
114
114
|
// `main`, an `export fun` and every kind of type's statics and constants are allowed.
|
|
115
115
|
run(
|
|
116
116
|
"homes",
|
|
117
|
-
"import std/Int\
|
|
117
|
+
"import std/Int\nimport std/App\nstruct Pt(x: Int) =\n const Origin = Pt(x: 0)\n\n fun at(x: Int) -> Pt = Pt(x: x)\n\nenum Dir =\n | Up\n | Down\n\n fun flip(d: Dir) -> Dir = Up\n\ntrait Named =\n fun name(self) -> Int\n\nprimitive Main[App] =\n const Limit = 10\n\n fun f() -> Int = Main.Limit + Pt.Origin.x + Pt.at(1).x\n\n export fun twice(x: Int) -> Int = x * 2\n\n fun main() -> Int = Main.f()\n",
|
|
118
118
|
)
|
|
119
119
|
.unwrap();
|
|
120
120
|
}
|
|
@@ -132,7 +132,7 @@ fn a_top_level_main_or_export_is_an_error() {
|
|
|
132
132
|
let e = run("topexport", "import std/Int\n\nexport fun twice(x: Int) -> Int = x * 2\n").unwrap_err();
|
|
133
133
|
assert!(e.contains("`twice` is a top-level function, and nothing is global: a program's entry points live in"), "{e}");
|
|
134
134
|
// `App` needs no import, and a program may import nothing else.
|
|
135
|
-
run("noimport", "
|
|
135
|
+
run("noimport", "import std/App\nprimitive Hello[App] =\n fun main() = Unit\n").unwrap();
|
|
136
136
|
}
|
|
137
137
|
|
|
138
138
|
/// A program has one entry: a second `[App]` primitive in a file is an error naming the first.
|
|
@@ -140,17 +140,26 @@ fn a_top_level_main_or_export_is_an_error() {
|
|
|
140
140
|
fn two_app_primitives_are_an_error() {
|
|
141
141
|
let e = run(
|
|
142
142
|
"twoapps",
|
|
143
|
-
"import std/Int\
|
|
143
|
+
"import std/Int\nimport std/App\nprimitive One[App] =\n fun main() -> Int = 1\n\nprimitive Two[App] =\n fun helper() -> Int = 2\n",
|
|
144
144
|
)
|
|
145
145
|
.unwrap_err();
|
|
146
146
|
assert!(e.contains("`primitive Two[App]` is a second entry: a program has one `[App]` primitive, and this file's is `One` (line 3)"), "{e}");
|
|
147
147
|
assert!(e.contains("main.plum:6:1"), "{e}");
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
+
/// `App` is std/App's, imported like any module: there is no prelude.
|
|
151
|
+
#[test]
|
|
152
|
+
fn app_needs_its_import() {
|
|
153
|
+
let e = run("noappimport", "import std/Int\n\nprimitive Hello[App] =\n fun main() -> Int = 1\n").unwrap_err();
|
|
154
|
+
assert!(e.contains("primitive Hello: unknown trait App (import std/App)"), "{e}");
|
|
155
|
+
assert!(e.contains("main.plum:3:1"), "{e}");
|
|
156
|
+
run("appimport", "import std/Int\nimport std/App\n\nprimitive Hello[App] =\n fun main() -> Int = 1\n").unwrap();
|
|
157
|
+
}
|
|
158
|
+
|
|
150
159
|
/// A `main` outside an `[App]` primitive is an ordinary static, not the program's entry.
|
|
151
160
|
#[test]
|
|
152
161
|
fn a_main_in_another_primitive_is_a_static() {
|
|
153
|
-
let path = temp("plainmain", "import std/Int\
|
|
162
|
+
let path = temp("plainmain", "import std/Int\nimport std/App\nprimitive Tool =\n fun main() -> Int = 1\n\nprimitive Hello[App] =\n fun main() -> Int = Tool.main() + 1\n");
|
|
154
163
|
let loaded = plum_core::loadAndMergeDiag(&path, &plum_test_support::repoRoot()).unwrap();
|
|
155
164
|
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
|
156
165
|
let mains: Vec<Option<String>> = loaded
|
|
@@ -171,9 +180,9 @@ fn a_main_in_another_primitive_is_a_static() {
|
|
|
171
180
|
fn an_imported_apps_main_is_a_static() {
|
|
172
181
|
let dir = std::env::temp_dir().join(format!("plum_modules_imported_app_{}", std::process::id()));
|
|
173
182
|
std::fs::create_dir_all(&dir).unwrap();
|
|
174
|
-
std::fs::write(dir.join("game.plum"), "import std/Int\
|
|
183
|
+
std::fs::write(dir.join("game.plum"), "import std/Int\nimport std/App\nprimitive Game1[App] =\n fun main() -> Int = 40\n").unwrap();
|
|
175
184
|
let path = dir.join("main.plum");
|
|
176
|
-
std::fs::write(&path, "import std/Int\nimport game\
|
|
185
|
+
std::fs::write(&path, "import std/Int\nimport game\nimport std/App\nprimitive Driver[App] =\n fun main() -> Int = Game1.main() + 2\n").unwrap();
|
|
177
186
|
let loaded = plum_core::loadAndMergeDiag(&path, &plum_test_support::repoRoot());
|
|
178
187
|
let _ = std::fs::remove_dir_all(&dir);
|
|
179
188
|
let loaded = loaded.unwrap();
|
|
@@ -192,7 +201,7 @@ fn an_imported_apps_main_is_a_static() {
|
|
|
192
201
|
/// One way to write a constant: `const Name = value`; the bare form points at `const`.
|
|
193
202
|
#[test]
|
|
194
203
|
fn a_constant_without_const_is_an_error() {
|
|
195
|
-
let e = run("bare", "import std/Int\
|
|
204
|
+
let e = run("bare", "import std/Int\nimport std/App\nprimitive Main[App] =\n Limit = 10\n\n fun main() -> Int = Main.Limit\n").unwrap_err();
|
|
196
205
|
assert!(e.contains("a constant is declared with `const`: write `const Limit = ..`"), "{e}");
|
|
197
206
|
}
|
|
198
207
|
|
|
@@ -319,7 +328,7 @@ fn runIn(name: &str, folder: &str, src: &str) -> Result<(), String> {
|
|
|
319
328
|
checkProgram(&source).0.map_err(|ds| ds.iter().map(|d| d.message.clone()).collect::<Vec<_>>().join(" | "))
|
|
320
329
|
}
|
|
321
330
|
|
|
322
|
-
const UNIT: &str = "import std/Test\
|
|
331
|
+
const UNIT: &str = "import std/Test\nimport std/App\nprimitive MainTest[UnitTest] =\n fun works() =\n assert true\n";
|
|
323
332
|
|
|
324
333
|
#[test]
|
|
325
334
|
fn a_unit_test_primitive_outside_a_tests_folder_is_an_error() {
|
compiler/checker/tests/checker/review_tests.rs
CHANGED
|
@@ -138,7 +138,7 @@ fn a_parse_time_form_error_names_its_own_file() {
|
|
|
138
138
|
"import std/Int\n\nprimitive M =\n fun sign(n: Int) -> Int =\n match\n | n < 0 => 0\n | n > 0 => 1\n",
|
|
139
139
|
)
|
|
140
140
|
.unwrap();
|
|
141
|
-
std::fs::write(dir.join("main.plum"), "import std/Int\nimport sub/m\
|
|
141
|
+
std::fs::write(dir.join("main.plum"), "import std/Int\nimport sub/m\nimport std/App\nprimitive Main[App] =\n fun main() -> Int = M.sign(1)\n").unwrap();
|
|
142
142
|
let source = plum_core::loader::loadAndMergeDiag(&dir.join("main.plum"), dir.path()).expect("loads");
|
|
143
143
|
let es = plum_checker::checkProgram(&source).0.expect_err("the form error");
|
|
144
144
|
let e = es.iter().find(|e| e.message.contains("last `| _ =>` arm")).unwrap_or_else(|| panic!("{es:?}"));
|
|
@@ -150,7 +150,7 @@ fn a_parse_time_form_error_names_its_own_file() {
|
|
|
150
150
|
/// order on every compile (they were taken from a `HashSet`).
|
|
151
151
|
#[test]
|
|
152
152
|
fn open_dispatch_instantiations_come_out_in_a_fixed_order() {
|
|
153
|
-
let src = "import std/Int\n\
|
|
153
|
+
let src = "import std/Int\nimport std/App\n\
|
|
154
154
|
import std/Str\n\
|
|
155
155
|
import std/Float\n\
|
|
156
156
|
import std/Bool\n\n\
|
|
@@ -220,12 +220,12 @@ fn old_type_parameters_in_brackets_are_one_error() {
|
|
|
220
220
|
fn a_generic_fn_calling_itself_with_a_growing_type_is_an_error() {
|
|
221
221
|
let es = stdErrors(
|
|
222
222
|
"polyrec",
|
|
223
|
-
"
|
|
223
|
+
"import std/App\nstruct P<A, B>(a: A, b: B)\n\nprimitive Main[App] =\n fun nest<T>(x: T, n: Int) -> Int = if n == 0 then 0 else 1 + nest(P(a: x, b: x), n - 1)\n\n fun main() -> Int = Main.nest(1, 3)",
|
|
224
224
|
);
|
|
225
225
|
assert!(es.iter().any(|e| e.contains("nest calls itself with a bigger type each time")), "{es:?}");
|
|
226
226
|
let ok = stdErrors(
|
|
227
227
|
"fixedrec",
|
|
228
|
-
"
|
|
228
|
+
"import std/App\nprimitive Main[App] =\n fun sh<T>(x: T, n: Int) -> Int = if n == 0 then 0 else 1 + sh(Some(1), n - 1)\n\n fun main() -> Int = Main.sh(1, 3)",
|
|
229
229
|
);
|
|
230
230
|
assert!(ok.is_empty(), "{ok:?}");
|
|
231
231
|
}
|
compiler/checker/tests/checker/traits_tests.rs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
//! Traits: conformance, trait objects, `Self`, downcasts and bounds.
|
|
3
3
|
use plum_checker::types::PlumType;
|
|
4
4
|
|
|
5
|
-
const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/collections/List\nimport std/Option\
|
|
5
|
+
const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/collections/List\nimport std/Option\nimport std/App\nprimitive Pre =\n fun show(s: Str) = Unit\n\n";
|
|
6
6
|
|
|
7
7
|
const ACTOR: &str = "trait Actor =
|
|
8
8
|
fun key(self) -> Int
|
|
@@ -611,13 +611,173 @@ fn memoryBuiltins() {
|
|
|
611
611
|
", "type mismatch");
|
|
612
612
|
}
|
|
613
613
|
|
|
614
|
+
fn typeText(t: &plum_core::ast::Type) -> String {
|
|
615
|
+
if t.generics.is_empty() {
|
|
616
|
+
return t.name.clone();
|
|
617
|
+
}
|
|
618
|
+
let args: Vec<String> = t.generics.iter().map(typeText).collect();
|
|
619
|
+
format!("{}<{}>", t.name, args.join(", "))
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/// The upcast helpers of the checked program by the types they convert, `from -> to`, sorted.
|
|
623
|
+
fn upcastsOf(info: &plum_checker::TypedInfo) -> Vec<String> {
|
|
624
|
+
let mut v: Vec<String> = info
|
|
625
|
+
.lowered
|
|
626
|
+
.iter()
|
|
627
|
+
.flat_map(|l| l.items.iter())
|
|
628
|
+
.filter_map(|i| match i {
|
|
629
|
+
plum_core::ast::Item::Fn(f) if f.name.starts_with("__upcast") => {
|
|
630
|
+
let ty = typeText;
|
|
631
|
+
let from = match &f.params[0].ty {
|
|
632
|
+
plum_core::ast::ParamType::Type(t) => ty(t),
|
|
633
|
+
_ => String::new(),
|
|
634
|
+
};
|
|
635
|
+
Some(format!("{from} -> {}", f.returns.as_ref().map(ty).unwrap_or_default()))
|
|
636
|
+
}
|
|
637
|
+
_ => None,
|
|
638
|
+
})
|
|
639
|
+
.collect();
|
|
640
|
+
v.sort();
|
|
641
|
+
v
|
|
642
|
+
}
|
|
643
|
+
|
|
614
644
|
#[test]
|
|
615
|
-
fn
|
|
645
|
+
fn immutableContainersAreCovariant() {
|
|
616
|
-
// a `List<Orb>` is
|
|
646
|
+
// a `List<Orb>` is a `List<Actor>`, an `Option<Orb>` an `Option<Actor>`, nested too; each
|
|
647
|
+
// site is rebuilt by a helper made once per pair of types
|
|
648
|
+
let info = ok(&format!(
|
|
649
|
+
"{ACTOR}primitive Main =
|
|
650
|
+
fun f(xs: List<Orb>) -> List<Actor> = xs
|
|
651
|
+
|
|
652
|
+
fun g(o: Option<Orb>) -> Option<Actor> = o
|
|
653
|
+
|
|
654
|
+
fun h(xss: List<List<Orb>>) -> List<List<Actor>> = xss
|
|
655
|
+
|
|
656
|
+
fun k(xs: List<Orb>) -> Int = Main.f(xs).length() + Main.count(xs)
|
|
657
|
+
|
|
658
|
+
fun count(xs: List<Actor>) -> Int = xs.length()
|
|
659
|
+
"
|
|
660
|
+
));
|
|
661
|
+
assert_eq!(
|
|
662
|
+
upcastsOf(&info),
|
|
663
|
+
vec!["List<List<Orb>> -> List<List<Actor>>", "List<Orb> -> List<Actor>", "Option<Orb> -> Option<Actor>"]
|
|
664
|
+
);
|
|
665
|
+
// a value already of the wider type is no site
|
|
666
|
+
let info = ok(&format!("{ACTOR}primitive Main =\n fun f(xs: List<Actor>) -> List<Actor> = xs\n"));
|
|
667
|
+
assert!(upcastsOf(&info).is_empty());
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
#[test]
|
|
671
|
+
fn covarianceIsSound() {
|
|
672
|
+
// nothing is covariant inside a function type: a `fn(List<Orb>)` is no `fn(List<Actor>)`
|
|
673
|
+
// (it would get a `Label`), nor a `fn() -> List<Orb>` a `fn() -> List<Actor>`
|
|
617
674
|
fails(
|
|
675
|
+
&format!("{ACTOR}primitive Main =
|
|
618
|
-
|
|
676
|
+
fun app(f: fn(List<Actor>) -> Int, xs: List<Actor>) -> Int = f(xs)
|
|
677
|
+
|
|
678
|
+
fun orbs(xs: List<Orb>) -> Int = xs.length()
|
|
679
|
+
|
|
680
|
+
fun h(xs: List<Actor>) -> Int = Main.app(Main.orbs, xs)
|
|
681
|
+
"),
|
|
682
|
+
"type mismatch",
|
|
683
|
+
);
|
|
684
|
+
fails(
|
|
685
|
+
&format!("{ACTOR}primitive Main =
|
|
686
|
+
fun run(f: fn() -> List<Actor>) -> Int = f().length()
|
|
687
|
+
|
|
688
|
+
fun h() -> Int = Main.run(|| [Orb(id: 1, vx: 0.0)].filter(|o| o.id > 0))
|
|
689
|
+
"),
|
|
690
|
+
"type mismatch",
|
|
691
|
+
);
|
|
692
|
+
// a container written in place stays invariant: a `Cell<Orb>` taken as a `Cell<Actor>`
|
|
693
|
+
// could be given a `Label`
|
|
694
|
+
fails(
|
|
695
|
+
&format!("{ACTOR}struct Cell<T>(mut v: T)
|
|
696
|
+
|
|
697
|
+
primitive Main =
|
|
698
|
+
fun put(c: Cell<Actor>) =
|
|
699
|
+
c.v = Label(id: 1, text: \"x\")
|
|
700
|
+
|
|
701
|
+
fun h(c: Cell<Orb>) = Main.put(c)
|
|
702
|
+
"),
|
|
619
703
|
"inside another type a value must already be a Actor",
|
|
620
704
|
);
|
|
705
|
+
// a generic body is one code for every `T`: its list is not upcast
|
|
706
|
+
fails(
|
|
707
|
+
&format!("{ACTOR}primitive Main[App] =\n fun f<T: Actor>(xs: List<T>) -> List<Actor> = xs\n\n fun main() -> Int = Main.f([Orb(id: 1, vx: 0.0)]).length()\n"),
|
|
708
|
+
"in Main.f<Orb>",
|
|
709
|
+
);
|
|
710
|
+
// the element must implement the trait
|
|
711
|
+
fails(
|
|
712
|
+
&format!("{ACTOR}primitive Main =\n fun f(xs: List<Rock>) -> List<Actor> = xs\n"),
|
|
713
|
+
"type mismatch",
|
|
714
|
+
);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
#[test]
|
|
718
|
+
fn joinsWithNoExpectedType() {
|
|
719
|
+
// a literal of several implementers is a list of their trait, and so are branches of two;
|
|
720
|
+
// a `List<Orb>` receiver widens to its argument's `List<Actor>`, and to the join of two
|
|
721
|
+
// implementers' lists
|
|
722
|
+
let info = ok(&format!(
|
|
723
|
+
"{ACTOR}primitive Main =
|
|
724
|
+
fun keys(xs: List<Actor>) -> Int = xs.fold(0, |n, a| n + a.key())
|
|
725
|
+
|
|
726
|
+
fun lit() -> Int =
|
|
727
|
+
xs := [Orb(id: 1, vx: 0.0), Label(id: 2, text: \"a\")]
|
|
728
|
+
Main.keys(xs)
|
|
729
|
+
|
|
730
|
+
fun branch(c: Bool) -> Int =
|
|
731
|
+
a := if c then Orb(id: 1, vx: 0.0) else Label(id: 2, text: \"a\")
|
|
732
|
+
a.key()
|
|
733
|
+
|
|
734
|
+
fun widen(actors: List<Actor>) -> Int =
|
|
735
|
+
orbs := [Orb(id: 1, vx: 0.0)]
|
|
736
|
+
Main.keys(orbs.append(actors))
|
|
737
|
+
|
|
738
|
+
fun join() -> Int =
|
|
739
|
+
orbs := [Orb(id: 1, vx: 0.0)]
|
|
740
|
+
labels := [Label(id: 2, text: \"a\")]
|
|
741
|
+
Main.keys(orbs.append(labels))
|
|
742
|
+
"
|
|
743
|
+
));
|
|
744
|
+
assert_eq!(upcastsOf(&info), vec!["List<Label> -> List<Actor>", "List<Orb> -> List<Actor>"]);
|
|
745
|
+
// nothing joins a `Rock` with an `Orb`
|
|
746
|
+
fails(&format!("{ACTOR}primitive Main =\n fun f() -> Int =\n xs := [Orb(id: 1, vx: 0.0), Rock(id: 2)]\n xs.length()\n"), "type mismatch");
|
|
747
|
+
// two traits shared, each type's first different: no one join
|
|
748
|
+
fails(
|
|
749
|
+
&format!("{ACTOR}trait Tagged =\n fun tag(self) -> Int
|
|
750
|
+
|
|
751
|
+
struct A[Actor, Tagged](id: Int) =
|
|
752
|
+
fun key(self) -> Int = self.id
|
|
753
|
+
fun tag(self) -> Int = 1
|
|
754
|
+
|
|
755
|
+
struct B[Tagged, Actor](id: Int) =
|
|
756
|
+
fun key(self) -> Int = self.id
|
|
757
|
+
fun tag(self) -> Int = 2
|
|
758
|
+
|
|
759
|
+
primitive Main =
|
|
760
|
+
fun f() -> Int =
|
|
761
|
+
xs := [A(id: 1), B(id: 2)]
|
|
762
|
+
xs.length()
|
|
763
|
+
"),
|
|
764
|
+
"type mismatch",
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
#[test]
|
|
769
|
+
fn sliceIsInvariant() {
|
|
770
|
+
// `Slice.set` writes in place: a `Slice<Orb>` is no `Slice<Actor>`
|
|
771
|
+
let src = format!("import std/Slice\n{PRE}{ACTOR}primitive Main =\n fun f(xs: Slice<Orb>) -> Slice<Actor> = xs\n");
|
|
772
|
+
let source = plum_test_support::load("traits", &src).unwrap_or_else(|e| panic!("load failed: {e}"));
|
|
773
|
+
let (r, _) = plum_checker::checkProgram(&source);
|
|
774
|
+
let errs: Vec<String> = r.err().unwrap_or_default().into_iter().map(|e| e.message).collect();
|
|
775
|
+
assert!(errs.iter().any(|e| e.contains("inside another type a value must already be a Actor")), "{errs:?}");
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
#[test]
|
|
779
|
+
fn coercionIsOfWholeValuesOnly() {
|
|
780
|
+
// a `fn(Orb) -> Orb` is not a `fn(Actor) -> Actor`
|
|
621
781
|
fails(
|
|
622
782
|
&format!("{ACTOR}primitive Main =
|
|
623
783
|
fun app(f: fn(Actor) -> Actor, a: Actor) -> Actor = f(a)
|
|
@@ -891,16 +1051,24 @@ primitive Main[App] =
|
|
|
891
1051
|
s: Splits := C(id: 1)
|
|
892
1052
|
Pre.show(\"{{s.split().length()}}\")
|
|
893
1053
|
"));
|
|
894
|
-
|
|
1054
|
+
// the result's `List<C>` is upcast to the trait object's `List<Splits>`
|
|
895
|
-
|
|
1055
|
+
ok(&format!("{tr}struct C[Splits](id: Int) =
|
|
896
1056
|
fun split(self) -> List<C> =
|
|
897
1057
|
xs: List<C> := [C(id: 1)]
|
|
898
1058
|
xs
|
|
899
1059
|
|
|
900
1060
|
primitive Main[App] =
|
|
901
1061
|
fun main() = Unit
|
|
1062
|
+
"));
|
|
1063
|
+
// a `List<Self>` parameter is a `List<Joins>` there, whose items have no `id`
|
|
1064
|
+
fails(
|
|
1065
|
+
"trait Joins =\n fun join(self, xs: List<Self>) -> Int\n\nstruct C[Joins](id: Int) =
|
|
1066
|
+
fun join(self, xs: List<C>) -> Int = xs.fold(self.id, |n, c| n + c.id)
|
|
1067
|
+
|
|
1068
|
+
primitive Main[App] =
|
|
1069
|
+
fun main() = Unit
|
|
902
|
-
"
|
|
1070
|
+
",
|
|
903
|
-
"C.
|
|
1071
|
+
"C.join can't be called on a trait object",
|
|
904
1072
|
);
|
|
905
1073
|
}
|
|
906
1074
|
|
compiler/cli/src/program.rs
CHANGED
|
@@ -141,7 +141,7 @@ mod rebuildTests {
|
|
|
141
141
|
let dir = std::env::temp_dir().join(format!("plum_rebuild_{}", std::process::id()));
|
|
142
142
|
std::fs::create_dir_all(&dir).unwrap();
|
|
143
143
|
let src = dir.join("app.plum");
|
|
144
|
-
std::fs::write(&src, "module app\nimport std/Int\nimport std/Io\
|
|
144
|
+
std::fs::write(&src, "module app\nimport std/Int\nimport std/Io\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) -> Int =\n 1\n").unwrap();
|
|
145
145
|
let root = Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
146
146
|
let got = rebuildGame(&src, root, opts());
|
|
147
147
|
let _ = std::fs::remove_dir_all(&dir);
|
compiler/cli/tests/cli/args_clock_test.rs
CHANGED
|
@@ -65,7 +65,7 @@ fn args_built_exe() {
|
|
|
65
65
|
fn now_micros_monotonic() {
|
|
66
66
|
let dir = crate::common::Scratch::at(std::env::temp_dir().join(format!("plum_clock_{}", std::process::id())));
|
|
67
67
|
let file = dir.join("main.plum");
|
|
68
|
-
let src = "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\
|
|
68
|
+
let src = "import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) =\n t0 := io.nowMicros()\n t1 := io.nowMicros()\n io.printLn(\"{t1 >= t0} {t1 - t0 < 1000.0} {t0 > 1600000000000000.0}\")\n";
|
|
69
69
|
std::fs::write(&file, src).unwrap();
|
|
70
70
|
let out = Command::new(plumBin()).current_dir(root()).args(["run", file.to_str().unwrap()]).output().unwrap();
|
|
71
71
|
assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr));
|
compiler/cli/tests/cli/crash_test.rs
CHANGED
|
@@ -15,7 +15,7 @@ fn plumBin() -> std::path::PathBuf {
|
|
|
15
15
|
fn crash_prints_message() {
|
|
16
16
|
let dir = crate::common::Scratch::at(std::env::temp_dir().join("tests").join(format!("plum_crash_{}", std::process::id())));
|
|
17
17
|
let src = dir.join("crash.plum");
|
|
18
|
-
std::fs::write(&src, "import std/Str\
|
|
18
|
+
std::fs::write(&src, "import std/Str\nimport std/App\nprimitive Main[App] =\n fun main() =\n crash \"boom\"\n").unwrap();
|
|
19
19
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
|
20
20
|
.ancestors().nth(2)
|
|
21
21
|
.unwrap();
|
|
@@ -68,7 +68,7 @@ fn crash_in_a_loop_names_the_function_not_its_lifted_loop() {
|
|
|
68
68
|
let src = dir.join("crash_loop.plum");
|
|
69
69
|
std::fs::write(
|
|
70
70
|
&src,
|
|
71
|
-
"import std/Int\nimport std/Io\nimport std/Str\
|
|
71
|
+
"import std/Int\nimport std/Io\nimport std/Str\nimport std/App\nstruct T(mut n: Int)\n\nprimitive Main[App] =\n fun boom(t: T, k: Int) =\n for i := range k\n d := 2 - i\n t.n = t.n / d\n\n fun main(io: Io) =\n t := T(n: 5)\n Main.boom(t, 5)\n io.printLn(\"never\")\n",
|
|
72
72
|
)
|
|
73
73
|
.unwrap();
|
|
74
74
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
@@ -88,8 +88,8 @@ fn crash_in_a_loop_names_the_function_not_its_lifted_loop() {
|
|
|
88
88
|
#[test]
|
|
89
89
|
fn aTrapIsOneCleanLine() {
|
|
90
90
|
let dir = crate::common::Scratch::new("trap_line");
|
|
91
|
-
std::fs::write(dir.join("div.plum"), "import std/Int\
|
|
91
|
+
std::fs::write(dir.join("div.plum"), "import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n z := 0\n 1 / z\n").unwrap();
|
|
92
|
-
std::fs::write(dir.join("boom.plum"), "import std/Str\
|
|
92
|
+
std::fs::write(dir.join("boom.plum"), "import std/Str\nimport std/App\nprimitive Main[App] =\n fun main() =\n crash \"boom\"\n").unwrap();
|
|
93
93
|
let run = |f: &str| {
|
|
94
94
|
let out = Command::new(plumBin()).current_dir(crate::common::root()).arg("run").arg(dir.join(f)).output().unwrap();
|
|
95
95
|
assert!(!out.status.success());
|
compiler/cli/tests/cli/explain_layout_test.rs
CHANGED
|
@@ -18,7 +18,7 @@ fn explainPrintsStructLayouts() {
|
|
|
18
18
|
let src = dir.join("layouts.plum");
|
|
19
19
|
std::fs::write(
|
|
20
20
|
&src,
|
|
21
|
-
"import std/Int\nimport std/Str\
|
|
21
|
+
"import std/Int\nimport std/Str\nimport std/App\nstruct Vec2(x: Int, y: Int)\nstruct Named(label: Str, n: Int)\nstruct Cat(mut n: Int)\n\nprimitive Main[App] =\n fun main() -> Int =\n v := Vec2(x: 1, y: 2)\n v.x\n",
|
|
22
22
|
)
|
|
23
23
|
.unwrap();
|
|
24
24
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
compiler/cli/tests/cli/fusion_agree_test.rs
CHANGED
|
@@ -55,7 +55,7 @@ fn paramDefaultsAgree() {
|
|
|
55
55
|
/// `main`, an expression body, and a callee handed `[]` were the shapes that failed.
|
|
56
56
|
#[test]
|
|
57
57
|
fn closureCopiesInTailPositionAgree() {
|
|
58
|
-
const HEAD: &str = "import std/Int\nimport std/Str\nimport std/Io\nimport std/collections/List\nimport std/Option\
|
|
58
|
+
const HEAD: &str = "import std/Int\nimport std/Str\nimport std/Io\nimport std/collections/List\nimport std/Option\nimport std/App\n";
|
|
59
59
|
let cases: &[(&str, &str, &str)] = &[
|
|
60
60
|
("list_fold_tail", "primitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3]\n xs.fold(0, |a, x| a + x)\n", "6"),
|
|
61
61
|
("list_fold_body", "primitive Main[App] =\n fun sum(xs: List<Int>) -> Int = xs.fold(0, |a, x| a + x)\n\n fun main() -> Int = Main.sum([1, 2, 3])\n", "6"),
|
compiler/cli/tests/cli/game_entry_test.rs
CHANGED
|
@@ -20,7 +20,7 @@ fn aStructWithoutUpdateAndDrawIsNotAGame() {
|
|
|
20
20
|
let src = dir.join("app.plum");
|
|
21
21
|
std::fs::write(
|
|
22
22
|
&src,
|
|
23
|
-
"module app\nimport std/Int\nimport std/Io\
|
|
23
|
+
"module app\nimport std/Int\nimport std/Io\nimport std/App\nstruct Game(n: Int)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n Game(n: 1)\n",
|
|
24
24
|
)
|
|
25
25
|
.unwrap();
|
|
26
26
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
@@ -59,10 +59,10 @@ fn compileSource(name: &str, text: &str) -> (bool, String) {
|
|
|
59
59
|
(out.status.success() && exports, err)
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
const HEAD: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/Input\
|
|
62
|
+
const HEAD: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/Input\nimport std/App\nstruct Counter(n: Int) =\n";
|
|
63
63
|
|
|
64
64
|
/// A whole game: one screen that counts its ticks.
|
|
65
|
-
const GAME: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/game/Input\n\
|
|
65
|
+
const GAME: &str = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/game/Input\nimport std/App\n\
|
|
66
66
|
import std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
|
|
67
67
|
struct CountScreen[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"count\"\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n \
|
|
68
68
|
fun reduce(self, a: Int) -> CountScreen = CountScreen(n: self.n + a)\n\nprimitive Main[App] =\n \
|
|
@@ -128,7 +128,7 @@ fn screensGame(names: &[&str], to: &str) -> String {
|
|
|
128
128
|
let screens: Vec<String> = (0..names.len()).map(|i| format!("s{i}")).collect();
|
|
129
129
|
let made: Vec<String> = names.iter().enumerate().map(|(i, n)| format!(" s{i}: Screen := Named(n: \"{n}\")\n")).collect();
|
|
130
130
|
format!(
|
|
131
|
-
"module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/game/Input\n\
|
|
131
|
+
"module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/game/Input\nimport std/App\n\
|
|
132
132
|
import std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
|
|
133
133
|
struct Named[ScreenSlice<Int>](n: Str) =\n fun name(self) -> Str = self.n\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n \
|
|
134
134
|
fun reduce(self, a: Int) -> Named = self\n fun effect(self, io: Io, a: Int, game: Control) = game.goTo(\"{to}\")\n\nprimitive Main[App] =\n \
|
compiler/cli/tests/cli/game_web_test.rs
CHANGED
|
@@ -148,7 +148,7 @@ fn oldInitEntryIsRejectedWithAPointer() {
|
|
|
148
148
|
let file = scratch.join("old.plum");
|
|
149
149
|
std::fs::write(
|
|
150
150
|
&file,
|
|
151
|
-
"import std/Int\nimport std/Float\nimport std/Io\nstruct State(mut n: Int)\n\nprimitive Main[App] =\n export fun init() -> State =\n State(n: 0)\n export fun update(g: State, dt: Float) =\n g.n = 1\n export fun draw(io: Io, g: State) =\n g.n = 2\n",
|
|
151
|
+
"import std/Int\nimport std/Float\nimport std/Io\nimport std/App\nstruct State(mut n: Int)\n\nprimitive Main[App] =\n export fun init() -> State =\n State(n: 0)\n export fun update(g: State, dt: Float) =\n g.n = 1\n export fun draw(io: Io, g: State) =\n g.n = 2\n",
|
|
152
152
|
)
|
|
153
153
|
.unwrap();
|
|
154
154
|
for cmd in ["run", "build"] {
|
compiler/cli/tests/cli/inputs_test.rs
CHANGED
|
@@ -13,7 +13,7 @@ fn plum(dir: &Scratch, args: &[&str]) -> (bool, String) {
|
|
|
13
13
|
fn eachCommandRefusesAMissingPathAFolderAndNonUtf8() {
|
|
14
14
|
let dir = Scratch::new("inputs");
|
|
15
15
|
std::fs::create_dir(dir.join("folder")).unwrap();
|
|
16
|
-
std::fs::write(dir.join("bytes.plum"), b"import std/Int\
|
|
16
|
+
std::fs::write(dir.join("bytes.plum"), b"import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n \"\xff\xfe\"\n").unwrap();
|
|
17
17
|
for cmd in ["compile", "run", "build", "check", "test"] {
|
|
18
18
|
let (ok, err) = plum(&dir, &[cmd, "missing.plum"]);
|
|
19
19
|
assert!(!ok && err.contains("missing.plum") && (err.contains("no such file") || err.contains("No such file")), "{cmd}: {err}");
|
|
@@ -51,7 +51,7 @@ fn aProgramWithoutMainIsNotRunOrBuilt() {
|
|
|
51
51
|
fn aPathWithSpacesWorks() {
|
|
52
52
|
let dir = Scratch::new("inputs_spaces");
|
|
53
53
|
std::fs::create_dir(dir.join("a folder")).unwrap();
|
|
54
|
-
std::fs::write(dir.join("a folder/my prog.plum"), "import std/Int\
|
|
54
|
+
std::fs::write(dir.join("a folder/my prog.plum"), "import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n 41 + 1\n").unwrap();
|
|
55
55
|
let (ok, err) = plum(&dir, &["compile", "a folder/my prog.plum"]);
|
|
56
56
|
assert!(ok, "{err}");
|
|
57
57
|
assert!(dir.join("a folder/my prog.wasm").is_file());
|
compiler/cli/tests/cli/main_result_test.rs
CHANGED
|
@@ -16,7 +16,7 @@ fn runSource(name: &str, body: &str) -> Output {
|
|
|
16
16
|
let dir = crate::common::Scratch::at(std::env::temp_dir().join(format!("plum_result_{}_{name}", std::process::id())));
|
|
17
17
|
let src = dir.join("app.plum");
|
|
18
18
|
let text = format!(
|
|
19
|
-
"module app\nimport std/Result\nimport std/Int\nimport std/Str\nimport std/Io\
|
|
19
|
+
"module app\nimport std/Result\nimport std/Int\nimport std/Str\nimport std/Io\nimport std/App\nenum AppError =\n | Bad\n | Worse(code: Int)\n\n{body}"
|
|
20
20
|
);
|
|
21
21
|
std::fs::write(&src, text).unwrap();
|
|
22
22
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
@@ -110,7 +110,7 @@ fn errorInMainNamesMainNotTheRenamedFn() {
|
|
|
110
110
|
fn lowersOnTheAstNotTheText() {
|
|
111
111
|
use plum_core::ast::{duplicateId, hasUnnumbered, Item};
|
|
112
112
|
let mut source = plum_test_support::parse(
|
|
113
|
-
"import std/Result\nimport std/Int\nimport std/Str\
|
|
113
|
+
"import std/Result\nimport std/Int\nimport std/Str\nimport std/App\nenum AppError =\n | Bad\n\nprimitive Main[App] =\n fun main () -> Result<Unit, AppError> =\n Ok(Unit)\n",
|
|
114
114
|
);
|
|
115
115
|
assert!(plum_core::main_result::lowerResultMain(&mut source));
|
|
116
116
|
let names: Vec<&str> = source.items.iter().filter_map(|i| match i { Item::Fn(f) => Some(f.name.as_str()), _ => None }).collect();
|
|
@@ -130,9 +130,9 @@ fn lowersOnTheAstNotTheText() {
|
|
|
130
130
|
fn builtExecutablesReportACrashOnce() {
|
|
131
131
|
let dir = crate::common::Scratch::new("built_crash");
|
|
132
132
|
let err = dir.join("err.plum");
|
|
133
|
-
std::fs::write(&err, "module app\nimport std/Result\nimport std/Int\nimport std/Io\
|
|
133
|
+
std::fs::write(&err, "module app\nimport std/Result\nimport std/Int\nimport std/Io\nimport std/App\nenum AppError =\n | Bad\n\nprimitive Main[App] =\n fun main(io: Io) -> Result<Int, AppError> =\n Err(error: Bad)\n").unwrap();
|
|
134
134
|
let div = dir.join("div.plum");
|
|
135
|
-
std::fs::write(&div, "import std/Int\
|
|
135
|
+
std::fs::write(&div, "import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n z := 0\n 1 / z\n").unwrap();
|
|
136
136
|
for (src, want) in [(&err, "crash: Bad"), (&div, "crash: division by zero in main")] {
|
|
137
137
|
let exe = src.with_extension("");
|
|
138
138
|
let out = Command::new(plumBin()).current_dir(crate::common::root()).arg("build").arg(src).arg("-o").arg(&exe).output().unwrap();
|
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\
|
|
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";
|
|
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/cli/tests/cli/old_forms_test.rs
CHANGED
|
@@ -28,16 +28,16 @@ fn compileOutcome(name: &str, src: &str) -> (bool, String) {
|
|
|
28
28
|
|
|
29
29
|
#[test]
|
|
30
30
|
fn theOldModuleFormIsAnError() {
|
|
31
|
-
let (ok, text) = compileOutcome("palette", "import std/Int\nimport tests/modules/Palette\
|
|
31
|
+
let (ok, text) = compileOutcome("palette", "import std/Int\nimport tests/modules/Palette\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n palette.shade(50)\n");
|
|
32
32
|
assert!(!ok, "{text}");
|
|
33
33
|
assert!(text.contains("shade"), "{text}");
|
|
34
|
-
let (ok, text) = compileOutcome("modern", "import std/Int\nimport tests/modules/Palette\
|
|
34
|
+
let (ok, text) = compileOutcome("modern", "import std/Int\nimport tests/modules/Palette\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n Palette.shade(50)\n");
|
|
35
35
|
assert!(ok, "{text}");
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
#[test]
|
|
39
39
|
fn aBareCallOfAnotherFilesStaticIsAnError() {
|
|
40
|
-
let (ok, text) = compileOutcome("bare", "import std/Int\nimport tests/modules/Palette\
|
|
40
|
+
let (ok, text) = compileOutcome("bare", "import std/Int\nimport tests/modules/Palette\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n shade(50)\n");
|
|
41
41
|
assert!(!ok, "{text}");
|
|
42
42
|
assert!(text.contains("undefined function 'shade'"), "{text}");
|
|
43
43
|
}
|
|
@@ -46,13 +46,13 @@ fn aBareCallOfAnotherFilesStaticIsAnError() {
|
|
|
46
46
|
fn hostCallsAreNoLongerMethodsOfIo() {
|
|
47
47
|
let (ok, text) = compileOutcome(
|
|
48
48
|
"ioclear",
|
|
49
|
-
"import std/Io\nimport std/game/Color\nimport std/game/Gfx\
|
|
49
|
+
"import std/Io\nimport std/game/Color\nimport std/game/Gfx\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) =\n io.clear(Color.Black)\n",
|
|
50
50
|
);
|
|
51
51
|
assert!(!ok, "{text}");
|
|
52
52
|
assert!(text.contains("Io has no method 'clear'"), "{text}");
|
|
53
53
|
let (ok, text) = compileOutcome(
|
|
54
54
|
"gfxclear",
|
|
55
|
-
"import std/Io\nimport std/game/Color\nimport std/game/Gfx\
|
|
55
|
+
"import std/Io\nimport std/game/Color\nimport std/game/Gfx\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) =\n Gfx.clear(io, Color.Black)\n",
|
|
56
56
|
);
|
|
57
57
|
assert!(ok, "{text}");
|
|
58
58
|
}
|
|
@@ -62,19 +62,19 @@ fn hostCallsAreNoLongerMethodsOfIo() {
|
|
|
62
62
|
#[test]
|
|
63
63
|
fn squareBracketGenericsAreAnError() {
|
|
64
64
|
let hint = |new: &str, old: &str| format!("hint: type parameters and type arguments are written in `< >`: `{new}`, not `{old}`");
|
|
65
|
-
let (ok, text) = compileOutcome("sqfun", "import std/Int\
|
|
65
|
+
let (ok, text) = compileOutcome("sqfun", "import std/Int\nimport std/App\nprimitive Main[App] =\n fun id[T](x: T) -> T = x\n\n fun main() -> Int = Main.id(1)\n");
|
|
66
66
|
assert!(!ok && text.contains(&hint("id<T>", "id[T]")), "{text}");
|
|
67
|
-
let (ok, text) = compileOutcome("sqtype", "import std/Int\nimport std/Option\
|
|
67
|
+
let (ok, text) = compileOutcome("sqtype", "import std/Int\nimport std/Option\nimport std/App\nprimitive Main[App] =\n fun f(x: Option[Int]) -> Int = 1\n\n fun main() -> Int = 1\n");
|
|
68
68
|
assert!(!ok && text.contains(&hint("Option<Int>", "Option[Int]")), "{text}");
|
|
69
|
-
let (ok, text) = compileOutcome("sqctor", "import std/Int\nimport std/Slice\
|
|
69
|
+
let (ok, text) = compileOutcome("sqctor", "import std/Int\nimport std/Slice\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := Slice[Int]()\n xs.length()\n");
|
|
70
70
|
assert!(!ok && text.contains(&hint("Slice<Int>", "Slice[Int]")), "{text}");
|
|
71
|
-
let (ok, text) = compileOutcome("sqcall", "import std/Int\nimport std/Slice\
|
|
71
|
+
let (ok, text) = compileOutcome("sqcall", "import std/Int\nimport std/Slice\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1].toSlice()\n xs.map[Int](|x| x).length()\n");
|
|
72
72
|
assert!(!ok && text.contains(&hint("map<Int>", "map[Int]")), "{text}");
|
|
73
73
|
// On a struct or an enum the `[ ]` after the name is the trait list now.
|
|
74
|
-
let (ok, text) = compileOutcome("sqstruct", "import std/Int\
|
|
74
|
+
let (ok, text) = compileOutcome("sqstruct", "import std/Int\nimport std/App\nstruct S[T](x: T)\n\nprimitive Main[App] =\n fun main() -> Int = 1\n");
|
|
75
75
|
assert!(!ok, "{text}");
|
|
76
76
|
assert!(text.contains("S: `[T]`: T is not a trait (`[ ]` after the name lists traits; type parameters are written in `< >`: `S<T>`)"), "{text}");
|
|
77
|
-
let (ok, text) = compileOutcome("angle", "import std/Int\nimport std/Slice\
|
|
77
|
+
let (ok, text) = compileOutcome("angle", "import std/Int\nimport std/Slice\nimport std/App\nstruct S<T>(x: T)\n\nprimitive Main[App] =\n fun id<T>(x: T) -> T = x\n\n fun main() -> Int =\n xs := Slice<Int>()\n Main.id<Int>(xs.length()) + S<Int>(x: 1).x\n");
|
|
78
78
|
assert!(ok, "{text}");
|
|
79
79
|
}
|
|
80
80
|
|
|
@@ -82,7 +82,7 @@ fn squareBracketGenericsAreAnError() {
|
|
|
82
82
|
/// written now.
|
|
83
83
|
#[test]
|
|
84
84
|
fn theIsClauseIsAnError() {
|
|
85
|
-
let tr = "import std/Int\
|
|
85
|
+
let tr = "import std/Int\nimport std/App\ntrait Named<M> =\n fun name(self) -> Int\n\n";
|
|
86
86
|
let (ok, text) = compileOutcome("isstruct", &format!("{tr}struct Dog<M>(n: Int, m: M) is Named<M> =\n fun name(self) -> Int = self.n\n\nprimitive Main[App] =\n fun main() -> Int = 1\n"));
|
|
87
87
|
assert!(!ok, "{text}");
|
|
88
88
|
assert!(text.contains("6:29: parse error: the `is` clause is gone: the traits go in `[ ]` after the name, `struct Dog<M>[Named<M>](..)`"), "{text}");
|
|
@@ -97,7 +97,7 @@ fn theIsClauseIsAnError() {
|
|
|
97
97
|
/// `Box<Int>.make()`: a static call is written on the bare type.
|
|
98
98
|
#[test]
|
|
99
99
|
fn typeArgumentsOnAStaticCallsTypeAreAnError() {
|
|
100
|
-
let (ok, text) = compileOutcome("static", "import std/Int\
|
|
100
|
+
let (ok, text) = compileOutcome("static", "import std/Int\nimport std/App\nstruct Box<T>(v: T) =\n fun make(v: T) -> Box<T> = Box(v: v)\n\nprimitive Main[App] =\n fun main() -> Int =\n b := Box<Int>.make(1)\n b.v\n");
|
|
101
101
|
assert!(!ok, "{text}");
|
|
102
102
|
assert!(text.contains("8:10: parse error: `Box<Int>.`: a static call or constant is written on the bare type, `Box.`"), "{text}");
|
|
103
103
|
}
|
compiler/cli/tests/cli/replay_test.rs
CHANGED
|
@@ -91,7 +91,7 @@ fn replayFlagRefusesABadFileAndBrowserFlags() {
|
|
|
91
91
|
let (ok, _, stderr) = runReplay("examples/games/orbitrunner/OrbitRunner.plum", &file, &["--no-open"]);
|
|
92
92
|
assert!(!ok && stderr.contains("--replay runs the game headless"), "{stderr}");
|
|
93
93
|
let prog = dir.join("app.plum");
|
|
94
|
-
std::fs::write(&prog, "import std/Str\nimport std/Io\
|
|
94
|
+
std::fs::write(&prog, "import std/Str\nimport std/Io\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) =\n io.printLn(\"hi\")\n").unwrap();
|
|
95
95
|
let (ok, _, stderr) = runReplay(prog.to_str().unwrap(), &file, &[]);
|
|
96
96
|
let _ = std::fs::remove_dir_all(&dir);
|
|
97
97
|
assert!(!ok && stderr.contains("--replay is only for games"), "{stderr}");
|
compiler/cli/tests/cli/run_folder_test.rs
CHANGED
|
@@ -11,7 +11,7 @@ fn run(args: &[&str]) -> (bool, String, String) {
|
|
|
11
11
|
(out.status.success(), String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned())
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
const APP: &str = "import std/Str\nimport std/Io\
|
|
14
|
+
const APP: &str = "import std/Str\nimport std/Io\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) =\n io.printLn(\"hi from the folder\")\n";
|
|
15
15
|
|
|
16
16
|
#[test]
|
|
17
17
|
fn runFolderRunsItsOneMain() {
|
compiler/cli/tests/cli/std_bounds_test.rs
CHANGED
|
@@ -20,7 +20,7 @@ fn run(name: &str, body: &str) -> (bool, String) {
|
|
|
20
20
|
let dir = crate::common::Scratch::new(&format!("bounds_{name}"));
|
|
21
21
|
let src = dir.join(format!("{name}.plum"));
|
|
22
22
|
let text = format!(
|
|
23
|
-
"import std/Int\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/Slice\nimport std/collections/Deque\nimport std/collections/Grid\nimport std/collections/List\nimport std/collections/Map\nimport std/collections/Set\
|
|
23
|
+
"import std/Int\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/Slice\nimport std/collections/Deque\nimport std/collections/Grid\nimport std/collections/List\nimport std/collections/Map\nimport std/collections/Set\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) =\n{body}"
|
|
24
24
|
);
|
|
25
25
|
std::fs::write(&src, text).unwrap();
|
|
26
26
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
compiler/cli/tests/cli/test_scope_test.rs
CHANGED
|
@@ -32,7 +32,7 @@ fn scratch(name: &str) -> crate::common::Scratch {
|
|
|
32
32
|
dir
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
const TWO: &str = "import std/Test\nimport std/Str\nimport std/Int\
|
|
35
|
+
const TWO: &str = "import std/Test\nimport std/Str\nimport std/Int\nimport std/App\nprimitive SampleTest[UnitTest] =\n fun one() =\n assert 1 == 1\n\n fun two() =\n assert 2 == 2\n";
|
|
36
36
|
|
|
37
37
|
#[test]
|
|
38
38
|
fn directoryRunsSumOfOwnTests() {
|
|
@@ -114,7 +114,7 @@ fn aFilterThatMatchesNothingFails() {
|
|
|
114
114
|
fn checkReportsTypeErrorsWithoutRunning() {
|
|
115
115
|
let dir = scratch("check");
|
|
116
116
|
std::fs::write(dir.join("good.plum"), TWO).unwrap();
|
|
117
|
-
std::fs::write(dir.join("bad.plum"), "import std/Int\
|
|
117
|
+
std::fs::write(dir.join("bad.plum"), "import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n nope\n").unwrap();
|
|
118
118
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
119
119
|
let out = Command::new(plumBin()).current_dir(root).arg("check").arg(dir.path()).output().unwrap();
|
|
120
120
|
let err = String::from_utf8_lossy(&out.stderr);
|
compiler/core/src/ast.rs
CHANGED
|
@@ -334,7 +334,7 @@ pub struct PrimitiveDecl {
|
|
|
334
334
|
/// The marker trait (std/Test) of a primitive whose funs without parameters are tests.
|
|
335
335
|
pub const UNIT_TEST_TRAIT: &str = "UnitTest";
|
|
336
336
|
|
|
337
|
-
/// The marker trait (std/App,
|
|
337
|
+
/// The marker trait (std/App, imported by the file that lists it) of the primitive that holds a program's entry points: its
|
|
338
338
|
/// `fun main` (`primitive Hello[App] = fun main(io: Io) = ..`) and any `export fun` the host
|
|
339
339
|
/// calls. The parser lifts those out as top-level fns (see `parser::liftEntries`), so every
|
|
340
340
|
/// later pass and the wasm exports see `main` as they always did.
|
compiler/core/src/loader.rs
CHANGED
|
@@ -62,14 +62,10 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
62
62
|
for import in &imports {
|
|
63
63
|
collectImport(import, &entry_canon, lib_path, overrides, &mut parsed, &mut visited, &mut files)?;
|
|
64
64
|
}
|
|
65
|
-
// `App`, the marker of a program's entry,
|
|
65
|
+
// `App`, the marker of a program's entry, is std/App's: a file that lists it imports it,
|
|
66
|
-
//
|
|
66
|
+
// like any module. A library folder without it (a test's own) has nothing to import, and
|
|
67
|
-
//
|
|
67
|
+
// the marker needs no declaration there (see `primitiveTraits`).
|
|
68
|
-
let listsApp = files.iter().any(|f| f.source.primitives.iter().any(|p| p.implements.iter().any(|t| t == APP_TRAIT)));
|
|
69
|
-
let
|
|
68
|
+
let hasApp = resolveImport(&Import { path: "std/App".to_string() }, &entry_canon, lib_path).is_ok();
|
|
70
|
-
if listsApp && resolveImport(&app, &entry_canon, lib_path).is_ok() {
|
|
71
|
-
collectImport(&app, &entry_canon, lib_path, overrides, &mut parsed, &mut visited, &mut files)?;
|
|
72
|
-
}
|
|
73
69
|
shadowStdTypes(&mut files, lib_path)?;
|
|
74
70
|
nativeOnlyInStd(&files, lib_path)?;
|
|
75
71
|
testsOnlyInTests(&files, lib_path)?;
|
|
@@ -80,7 +76,7 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
80
76
|
for f in &files {
|
|
81
77
|
mergeItems(&f.path, &f.source, &mut items, &mut names, &mut prims)?;
|
|
82
78
|
}
|
|
83
|
-
primitiveTraits(&files, &items)?;
|
|
79
|
+
primitiveTraits(&files, &items, hasApp)?;
|
|
84
80
|
let entry_source = files.swap_remove(0).source;
|
|
85
81
|
|
|
86
82
|
dropExtensions(&items, &mut prims);
|
|
@@ -443,7 +439,7 @@ fn importedMainsAreStatics(files: &mut [Loaded]) {
|
|
|
443
439
|
|
|
444
440
|
/// A primitive has no values, so the traits it lists are markers: each must be a declared
|
|
445
441
|
/// trait without methods (`primitive MapTest[UnitTest]`, `UnitTest` from std/Test).
|
|
446
|
-
fn primitiveTraits(files: &[Loaded], items: &[Item]) -> Loaded_<()> {
|
|
442
|
+
fn primitiveTraits(files: &[Loaded], items: &[Item], hasApp: bool) -> Loaded_<()> {
|
|
447
443
|
for f in files {
|
|
448
444
|
for p in &f.source.primitives {
|
|
449
445
|
for t in &p.implements {
|
|
@@ -452,6 +448,7 @@ fn primitiveTraits(files: &[Loaded], items: &[Item]) -> Loaded_<()> {
|
|
|
452
448
|
_ => None,
|
|
453
449
|
}) {
|
|
454
450
|
None if t == UNIT_TEST_TRAIT => format!("primitive {}: unknown trait {t} (import std/Test)", p.name),
|
|
451
|
+
None if t == APP_TRAIT && hasApp => format!("primitive {}: unknown trait {t} (import std/App)", p.name),
|
|
455
452
|
// A library folder without std/App (a test's own): the marker needs no
|
|
456
453
|
// declaration, since a primitive has no values to be one.
|
|
457
454
|
None if t == APP_TRAIT => continue,
|
compiler/core/src/trmc.rs
CHANGED
|
@@ -450,9 +450,11 @@ impl<'a> Cx<'a> {
|
|
|
450
450
|
// Receiver and arguments of the recursive call.
|
|
451
451
|
let moves = self.recurseMoves(recv.as_ref(), &call, &mut stmts)?;
|
|
452
452
|
let cell = self.fresh("cell");
|
|
453
|
+
// Typed as the result: a `Cons(head: ship, ..)` built for a `List<View>` is one of
|
|
454
|
+
// those, not a `List<Ship>` (the fill below writes it into the result's cells).
|
|
453
455
|
stmts.push(declare(
|
|
454
456
|
&cell,
|
|
455
|
-
|
|
457
|
+
Some(self.ret.clone()),
|
|
456
458
|
Expr::ClassCall(ClassCall {
|
|
457
459
|
type_name: c.type_name.clone(),
|
|
458
460
|
fields,
|
compiler/core/tests/core/closure_escape_test.rs
CHANGED
|
@@ -70,7 +70,7 @@ fn std_list_combinators_non_escaping() {
|
|
|
70
70
|
let dir = std::env::temp_dir().join(format!("plum_escape_{}", std::process::id()));
|
|
71
71
|
std::fs::create_dir_all(&dir).unwrap();
|
|
72
72
|
let path = dir.join("main.plum");
|
|
73
|
-
std::fs::write(&path, "import std/Int\nimport std/collections/List\
|
|
73
|
+
std::fs::write(&path, "import std/Int\nimport std/collections/List\nimport std/App\nprimitive Main[App] =\n fun main() =\n [1]\n").unwrap();
|
|
74
74
|
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
|
75
75
|
let r = plum_core::loadAndMergeDiag(&path, &root);
|
|
76
76
|
let _ = std::fs::remove_dir_all(&dir);
|
compiler/core/tests/core/closure_spec_test.rs
CHANGED
|
@@ -63,7 +63,7 @@ fn copies(name: &str, src: &str) -> Vec<String> {
|
|
|
63
63
|
/// closure arguments (e.g. `Slice.shuffle`'s `downTo(1).fold(..)`), found by lowering the
|
|
64
64
|
/// same imports with an empty `main`.
|
|
65
65
|
fn userCopies(name: &str, src: &str) -> Vec<String> {
|
|
66
|
-
let mut std = copies("stdbase", &withHead("
|
|
66
|
+
let mut std = copies("stdbase", &withHead("import std/App\nprimitive Main[App] =\n fun main() -> Int = 0\n"));
|
|
67
67
|
let mut mine = Vec::new();
|
|
68
68
|
for n in copies(name, src) {
|
|
69
69
|
match std.iter().position(|s| *s == n) {
|
|
@@ -170,7 +170,7 @@ fn withHead(body: &str) -> String {
|
|
|
170
170
|
#[test]
|
|
171
171
|
fn map_literal_no_call_ref() {
|
|
172
172
|
let src = withHead(
|
|
173
|
-
"
|
|
173
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3, 4]\n xs.map(|x| x * 2).fold(0, |a, x| a + x)\n",
|
|
174
174
|
);
|
|
175
175
|
let names = copies("map_lit", &src);
|
|
176
176
|
assert!(names.contains(&"List.map$c0".to_string()), "{names:?}");
|
|
@@ -183,7 +183,7 @@ fn map_literal_no_call_ref() {
|
|
|
183
183
|
#[test]
|
|
184
184
|
fn capture_becomes_param() {
|
|
185
185
|
let src = withHead(
|
|
186
|
-
"
|
|
186
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n k := 10\n xs := [1, 2, 3]\n xs.map(|x| x + k).fold(0, |a, x| a + x)\n",
|
|
187
187
|
);
|
|
188
188
|
let names = copies("capture", &src);
|
|
189
189
|
assert!(names.contains(&"List.map$c0".to_string()), "{names:?}");
|
|
@@ -195,7 +195,7 @@ fn capture_becomes_param() {
|
|
|
195
195
|
#[test]
|
|
196
196
|
fn recursive_copy_calls_itself() {
|
|
197
197
|
let src = withHead(
|
|
198
|
-
"
|
|
198
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3, 4, 5]\n xs.fold(0, |a, x| a + x)\n",
|
|
199
199
|
);
|
|
200
200
|
let l = lowered("recursive", &src);
|
|
201
201
|
let f = l
|
|
@@ -214,7 +214,7 @@ fn recursive_copy_calls_itself() {
|
|
|
214
214
|
#[test]
|
|
215
215
|
fn fn_name_argument() {
|
|
216
216
|
let src = withHead(
|
|
217
|
-
"
|
|
217
|
+
"import std/App\nprimitive Main[App] =\n fun double(x: Int) -> Int = x * 2\n\n fun main() -> Int =\n xs := [1, 2, 3]\n xs.map(Main.double).fold(0, |a, x| a + x)\n",
|
|
218
218
|
);
|
|
219
219
|
let names = copies("fnname", &src);
|
|
220
220
|
assert!(names.contains(&"List.map$c0".to_string()), "{names:?}");
|
|
@@ -228,7 +228,7 @@ fn fn_name_argument() {
|
|
|
228
228
|
#[test]
|
|
229
229
|
fn copies_of_same_named_methods_have_different_names() {
|
|
230
230
|
let src = withHead(
|
|
231
|
-
"
|
|
231
|
+
"import std/App\nstruct A(n: Int) =\n fun twice(self, f: fn(Int) -> Int) -> Int = f(f(self.n))\n\nstruct B(n: Int) =\n fun twice(self, f: fn(Int) -> Int) -> Int = f(f(self.n))\n\nprimitive Main[App] =\n fun main() -> Int = A(n: 1).twice(|x| x + 1) + B(n: 2).twice(|x| x + 2)\n",
|
|
232
232
|
);
|
|
233
233
|
let names = userCopies("same_method", &src);
|
|
234
234
|
assert_eq!(names.len(), 2, "{names:?}");
|
|
@@ -240,7 +240,7 @@ fn copies_of_same_named_methods_have_different_names() {
|
|
|
240
240
|
#[test]
|
|
241
241
|
fn escaping_closure_untouched() {
|
|
242
242
|
let src = withHead(
|
|
243
|
-
"
|
|
243
|
+
"import std/App\nstruct Box(cb: fn(Int) -> Int)\n\nprimitive Main[App] =\n fun keep(f: fn(Int) -> Int) -> Box = Box(cb: f)\n\n fun main() -> Int =\n b := Main.keep(|x| x + 1)\n g := b.cb\n g(41)\n",
|
|
244
244
|
);
|
|
245
245
|
assert!(userCopies("escaping", &src).is_empty());
|
|
246
246
|
assert_eq!(runInt("escaping", &src), 42);
|
|
@@ -249,7 +249,7 @@ fn escaping_closure_untouched() {
|
|
|
249
249
|
#[test]
|
|
250
250
|
fn dedup_same_closure_twice() {
|
|
251
251
|
let src = withHead(
|
|
252
|
-
"
|
|
252
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3]\n a := xs.map(|x| x * 2).fold(0, |a, x| a + x)\n b := xs.map(|x| x * 2).fold(0, |a, x| a + x)\n a + b\n",
|
|
253
253
|
);
|
|
254
254
|
let names = copies("dedup", &src);
|
|
255
255
|
assert_eq!(names.iter().filter(|n| n.starts_with("List.map$")).count(), 1, "{names:?}");
|
|
@@ -258,7 +258,7 @@ fn dedup_same_closure_twice() {
|
|
|
258
258
|
|
|
259
259
|
#[test]
|
|
260
260
|
fn cap_eight_copies() {
|
|
261
|
-
let mut body = String::from("
|
|
261
|
+
let mut body = String::from("import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3]\n");
|
|
262
262
|
for i in 0..10 {
|
|
263
263
|
body.push_str(&format!(" r{0} := xs.map(|x| x + {0}).fold(0, |a, x| a + x)\n", i));
|
|
264
264
|
}
|
|
@@ -273,7 +273,7 @@ fn cap_eight_copies() {
|
|
|
273
273
|
#[test]
|
|
274
274
|
fn block_closure_is_inlined() {
|
|
275
275
|
let src = withHead(
|
|
276
|
-
"
|
|
276
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3, 4]\n k := 10\n y := 1000\n r := xs.fold(0, |a, x|\n y := x * k\n a + y\n )\n r + y\n",
|
|
277
277
|
);
|
|
278
278
|
let names = copies("block_closure", &src);
|
|
279
279
|
assert!(names.contains(&"List.fold$c0".to_string()), "{names:?}");
|
|
@@ -283,11 +283,11 @@ fn block_closure_is_inlined() {
|
|
|
283
283
|
#[test]
|
|
284
284
|
fn results_equal_original() {
|
|
285
285
|
let src = withHead(
|
|
286
|
-
"
|
|
286
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3, 4, 5, 6, 7, 8]\n k := 3\n a := xs.map(|x| x * k).filter(|x| x % 2 == 0).fold(0, |a, x| a + x)\n b := xs.filter(|x| x > k).map(|x| x - 1).fold(100, |a, x| a - x)\n c := xs.fold(1, |a, x| if x > 4 then a + x else a)\n a * 10000 + b * 100 + c\n",
|
|
287
287
|
);
|
|
288
288
|
// Same program through closures held in locals, which are not specialised.
|
|
289
289
|
let plain = withHead(
|
|
290
|
-
"
|
|
290
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3, 4, 5, 6, 7, 8]\n k := 3\n m1 := |x| x * k\n f1 := |x| x % 2 == 0\n s1 := |a, x| a + x\n a := xs.map(m1).filter(f1).fold(0, s1)\n f2 := |x| x > k\n m2 := |x| x - 1\n s2 := |a, x| a - x\n b := xs.filter(f2).map(m2).fold(100, s2)\n s3 := |a, x| if x > 4 then a + x else a\n c := xs.fold(1, s3)\n a * 10000 + b * 100 + c\n",
|
|
291
291
|
);
|
|
292
292
|
assert!(!copies("equal", &src).is_empty());
|
|
293
293
|
assert_eq!(runInt("equal", &src), runInt("equal_plain", &plain));
|
|
@@ -296,7 +296,7 @@ fn results_equal_original() {
|
|
|
296
296
|
#[test]
|
|
297
297
|
fn list_pipeline_million_timed() {
|
|
298
298
|
let src = withHead(
|
|
299
|
-
"
|
|
299
|
+
"import std/App\nprimitive Main[App] =\n fun buildDown(i: Int, out: List<Int>) -> List<Int> =\n if i > 0 then buildDown(i - 1, Cons(head: i, tail: out)) else out\n\n fun build(n: Int) -> List<Int> = buildDown(n, Nil)\n\n fun main() -> Int =\n xs := Main.build(1000000)\n xs.map(|x| x * 2).filter(|x| x % 4 == 0).fold(0, |a, x| a + x)\n",
|
|
300
300
|
);
|
|
301
301
|
let bytes = compile("million", &src);
|
|
302
302
|
let t = std::time::Instant::now();
|
|
@@ -309,10 +309,10 @@ fn list_pipeline_million_timed() {
|
|
|
309
309
|
assert_eq!(r, 500001000000);
|
|
310
310
|
// Reference: the same pipeline through closures held in locals (not specialised).
|
|
311
311
|
let plain = withHead(
|
|
312
|
-
"
|
|
312
|
+
"import std/App\nprimitive Main[App] =\n fun buildDown(i: Int, out: List<Int>) -> List<Int> =\n if i > 0 then buildDown(i - 1, Cons(head: i, tail: out)) else out\n\n fun build(n: Int) -> List<Int> = buildDown(n, Nil)\n\n fun main() -> Int =\n xs := Main.build(1000000)\n m := |x| x * 2\n f := |x| x % 4 == 0\n s := |a, x| a + x\n xs.map(m).filter(f).fold(0, s)\n",
|
|
313
313
|
);
|
|
314
314
|
let buildOnly = withHead(
|
|
315
|
-
"
|
|
315
|
+
"import std/App\nprimitive Main[App] =\n fun buildDown(i: Int, out: List<Int>) -> List<Int> =\n if i > 0 then buildDown(i - 1, Cons(head: i, tail: out)) else out\n\n fun build(n: Int) -> List<Int> = buildDown(n, Nil)\n\n fun main() -> Int =\n xs := Main.build(1000000)\n xs.length()\n",
|
|
316
316
|
);
|
|
317
317
|
let bb = compile("million_build", &buildOnly);
|
|
318
318
|
let t = std::time::Instant::now();
|
|
@@ -324,7 +324,7 @@ fn list_pipeline_million_timed() {
|
|
|
324
324
|
("fold only", "xs.fold(0, |a, x| a + x)"),
|
|
325
325
|
] {
|
|
326
326
|
let one = withHead(&format!(
|
|
327
|
-
"
|
|
327
|
+
"import std/App\nprimitive Main[App] =\n fun buildDown(i: Int, out: List<Int>) -> List<Int> =\n if i > 0 then buildDown(i - 1, Cons(head: i, tail: out)) else out\n\n fun build(n: Int) -> List<Int> = buildDown(n, Nil)\n\n fun main() -> Int =\n xs := Main.build(1000000)\n {expr}\n"
|
|
328
328
|
));
|
|
329
329
|
let b = compile("million_stage", &one);
|
|
330
330
|
let t = std::time::Instant::now();
|
|
@@ -340,7 +340,7 @@ fn list_pipeline_million_timed() {
|
|
|
340
340
|
#[test]
|
|
341
341
|
fn copies_get_trmc_and_tail_marks() {
|
|
342
342
|
let src = withHead(
|
|
343
|
-
"
|
|
343
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3]\n xs.map(|x| x * 2).fold(0, |a, x| a + x)\n",
|
|
344
344
|
);
|
|
345
345
|
let l = lowered("trmc_copy", &src);
|
|
346
346
|
let text = |n: &str| {
|
|
@@ -367,7 +367,7 @@ fn deep_recursive_closure_callee() {
|
|
|
367
367
|
// levels of non-escaping params (`outer` -> `mid` -> `loop`) and is also used by
|
|
368
368
|
// `mid` itself.
|
|
369
369
|
let src = withHead(
|
|
370
|
-
"
|
|
370
|
+
"import std/App\nprimitive Main[App] =\n fun loop(n: Int, acc: Int, f: fn(Int) -> Int) -> Int =\n if n == 0 then acc else loop(n - 1, f(acc), f)\n\n fun mid(n: Int, f: fn(Int) -> Int) -> Int = loop(n, f(0), f)\n\n fun outer(n: Int, g: fn(Int) -> Int) -> Int = mid(n, g)\n\n fun main() -> Int =\n k := 2\n Main.outer(100000, |x| x + 1) + Main.outer(50000, |x| x + k)\n",
|
|
371
371
|
);
|
|
372
372
|
let names = copies("deep", &src);
|
|
373
373
|
for callee in ["loop", "mid", "outer"] {
|
|
@@ -377,7 +377,7 @@ fn deep_recursive_closure_callee() {
|
|
|
377
377
|
let bytes = compile("deep", &src);
|
|
378
378
|
// Same program through closures held in locals (not specialised).
|
|
379
379
|
let plain = withHead(
|
|
380
|
-
"
|
|
380
|
+
"import std/App\nprimitive Main[App] =\n fun loop(n: Int, acc: Int, f: fn(Int) -> Int) -> Int =\n if n == 0 then acc else loop(n - 1, f(acc), f)\n\n fun mid(n: Int, f: fn(Int) -> Int) -> Int = loop(n, f(0), f)\n\n fun outer(n: Int, g: fn(Int) -> Int) -> Int = mid(n, g)\n\n fun main() -> Int =\n k := 2\n a := |x| x + 1\n b := |x| x + k\n Main.outer(100000, a) + Main.outer(50000, b)\n",
|
|
381
381
|
);
|
|
382
382
|
assert!(userCopies("deep_plain", &plain).is_empty());
|
|
383
383
|
let r = runIntBytes(&bytes);
|
|
@@ -389,7 +389,7 @@ fn deep_recursive_closure_callee() {
|
|
|
389
389
|
fn many_call_sites_capped() {
|
|
390
390
|
// 20 distinct closures to one callee: exactly MAX_COPIES (8) copies, the rest left as
|
|
391
391
|
// ordinary closure calls, every result right.
|
|
392
|
-
let mut body = String::from("
|
|
392
|
+
let mut body = String::from("import std/App\nprimitive Main[App] =\n fun apply(x: Int, f: fn(Int) -> Int) -> Int = f(x)\n\n fun main() -> Int =\n");
|
|
393
393
|
for i in 0..20 {
|
|
394
394
|
body.push_str(&format!(" r{1} := Main.apply(5, |x| x * {0} + {1})\n", i + 1, i));
|
|
395
395
|
}
|
|
@@ -409,7 +409,7 @@ fn pattern_decl() {
|
|
|
409
409
|
// (here it shadows the outer `n`). Block-bodied closures are not inlined today, so this
|
|
410
410
|
// pins the program's result through whichever path the pass takes.
|
|
411
411
|
let src = withHead(
|
|
412
|
-
"
|
|
412
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n k := 10\n n := 1000\n xs := [0, 1, 2]\n xs.fold(0, |a, x|\n r := a\n match x\n 0 => r + 100\n n => r + n + k\n )\n",
|
|
413
413
|
);
|
|
414
414
|
assert_eq!(runInt("patdecl", &src), 100 + 11 + 12);
|
|
415
415
|
}
|
|
@@ -418,7 +418,7 @@ fn pattern_decl() {
|
|
|
418
418
|
fn identical_closures_share_a_copy() {
|
|
419
419
|
// Same closure text at two positions: one copy (the dedup key ignores positions).
|
|
420
420
|
let src = withHead(
|
|
421
|
-
"
|
|
421
|
+
"import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3]\n a := xs.map(|x| x + 1).fold(0, |a, x| a + x)\n b := xs.map(|x| x + 1).fold(0, |a, x| a + x)\n a + b\n",
|
|
422
422
|
);
|
|
423
423
|
let names = copies("dedup", &src);
|
|
424
424
|
assert!(names.contains(&"List.map$c0".to_string()), "{names:?}");
|
compiler/core/tests/core/loader_test.rs
CHANGED
|
@@ -521,7 +521,7 @@ fn single_file_equals_loader() {
|
|
|
521
521
|
/// file importing `std/Pair` itself and declaring `Pair` is still a duplicate.
|
|
522
522
|
#[test]
|
|
523
523
|
fn userTypeShadowsStdTypeOnlyWhenNotImportedDirectly() {
|
|
524
|
-
let shadow = "import std/Int\
|
|
524
|
+
let shadow = "import std/Int\nimport std/App\nstruct Pair(a: Int, b: Int)\n\nprimitive Main[App] =\n fun main() -> Int =\n Pair(a: 1, b: 2).a\n";
|
|
525
525
|
let merged = plum_test_support::load("shadow_pair", shadow).expect("user Pair shadows std's");
|
|
526
526
|
let types: Vec<&str> = merged
|
|
527
527
|
.items
|
|
@@ -567,7 +567,7 @@ fn userFunctionMaySharePlainNameWithStdFunction() {
|
|
|
567
567
|
("user_shares_std_name", "primitive Main[App] =\n fun missingAsset(n: Int) -> Int =\n n\n\n fun main() -> Int =\n Main.missingAsset(1)\n", Some("Main".to_string())),
|
|
568
568
|
("export_shares_std_name", "primitive Main[App] =\n export fun missingAsset(n: Int) -> Int =\n n\n\n fun main() -> Int =\n missingAsset(1)\n", None),
|
|
569
569
|
] {
|
|
570
|
-
let src = format!("import std/Int\nimport std/game/Gfx\
|
|
570
|
+
let src = format!("import std/Int\nimport std/game/Gfx\nimport std/App\n{decl}");
|
|
571
571
|
let merged = plum_test_support::load(label, &src).expect("user fn shares a std name");
|
|
572
572
|
let names = owners(&merged);
|
|
573
573
|
assert!(names.contains(&(owner, "missingAsset".to_string())), "{names:?}");
|
compiler/core/tests/core/trmc_test.rs
CHANGED
|
@@ -87,7 +87,7 @@ fn rewrittenNames(name: &str, src: &str) -> Vec<String> {
|
|
|
87
87
|
|
|
88
88
|
const HEAD: &str = "import std/Str\n\
|
|
89
89
|
import std/Int\n\
|
|
90
|
-
import std/Bool\
|
|
90
|
+
import std/Bool\nimport std/App\n\
|
|
91
91
|
enum Link<T> = Nil | Cons(head: T, tail: Link<T>)\n\n\
|
|
92
92
|
primitive Head =\n fun fromTo(a: Int, b: Int) -> Link<Int> =\n if a >= b then Nil else Cons(head: a, tail: fromTo(a + 1, b))\n\n fun map<A, B>(xs: Link<A>, f: fn(A) -> B) -> Link<B> = match xs\n Nil => Nil\n Cons(h, t) => Cons(head: f(h), tail: map(t, f))\n\n fun append<T>(xs: Link<T>, ys: Link<T>) -> Link<T> = match xs\n Nil => ys\n Cons(h, t) => Cons(head: h, tail: append(t, ys))\n\n fun filter<T>(xs: Link<T>, keep: fn(T) -> Bool) -> Link<T> = match xs\n Nil => Nil\n Cons(h, t) =>\n rest := filter(t, keep)\n if keep(h) then Cons(head: h, tail: rest) else rest\n\n fun sumFrom(cur: Link<Int>, total: Int) -> Int = match cur\n Nil => total\n Cons(h, t) => sumFrom(t, total + h)\n\n fun sum(xs: Link<Int>) -> Int = sumFrom(xs, 0)\n\n fun countFrom<T>(cur: Link<T>, n: Int) -> Int = match cur\n Nil => n\n Cons(_, t) => countFrom(t, n + 1)\n\n fun count<T>(xs: Link<T>) -> Int = countFrom(xs, 0)\n\n fun toIntFrom(cur: Link<Int>, r: Int) -> Int = match cur\n Nil => r\n Cons(h, t) => toIntFrom(t, r * 10 + h)\n\n fun toInt(xs: Link<Int>) -> Int = toIntFrom(xs, 0)\n\n";
|
|
93
93
|
|
|
@@ -176,7 +176,7 @@ primitive Main[App] =
|
|
|
176
176
|
fn two_recursive_fields_not_rewritten() {
|
|
177
177
|
let p = "import std/Str\n\
|
|
178
178
|
import std/Int\n\
|
|
179
|
-
import std/Bool\
|
|
179
|
+
import std/Bool\nimport std/App\n\
|
|
180
180
|
enum Tree = Empty | Node(left: Tree, value: Int, right: Tree)\n\n\
|
|
181
181
|
primitive Main[App] =\n fun mapTree(t: Tree, f: fn(Int) -> Int) -> Tree = match t\n Empty => Empty\n Node(l, v, r) => Node(left: mapTree(l, f), value: f(v), right: mapTree(r, f))\n\n fun total(t: Tree) -> Int = match t\n Empty => 0\n Node(l, v, r) => total(l) + v + total(r)\n\n \
|
|
182
182
|
fun main() -> Int =\n t := Node(left: Node(left: Empty, value: 1, right: Empty), value: 2, right: Node(left: Empty, value: 3, right: Empty))\n Main.total(Main.mapTree(t, |x| x * 10))\n";
|
|
@@ -330,7 +330,7 @@ fun main() -> Int =\n none: Link<Int> := Nil\n big := Main.keepEven(Head.f
|
|
|
330
330
|
|
|
331
331
|
// Method (std List.filter): the receiver of the self call becomes the next `self`.
|
|
332
332
|
let m = "import std/collections/List\n\
|
|
333
|
-
import std/Int\
|
|
333
|
+
import std/Int\nimport std/App\n\
|
|
334
334
|
primitive Main[App] =\n fun buildDown(i: Int, out: List<Int>) -> List<Int> =\n if i > 0 then buildDown(i - 1, Cons(head: i, tail: out)) else out\n\n \
|
|
335
335
|
fun main() -> Int =\n xs := Main.buildDown(1000000, Nil)\n evens := xs.filter(|x| x % 2 == 0)\n small := [1, 2, 3, 4, 5, 6].filter(|x| x > 3)\n none: List<Int> := Nil\n if evens.length() == 500000 && small.length() == 3 && small.at(0) == 4 && none.filter(|x| x > 0).length() == 0 && evens.at(499999) == 1000000 then 1 else 0\n";
|
|
336
336
|
assert!(isRewritten("ifm1", m, "filter"));
|
|
@@ -392,7 +392,7 @@ fn hasOp(wasm: &[u8], name: &str, pred: fn(&wasmparser::Operator) -> bool) -> bo
|
|
|
392
392
|
/// The GC heap is pre-sized so no collection runs.
|
|
393
393
|
#[test]
|
|
394
394
|
fn std_map_1m_within_3x_of_build() {
|
|
395
|
-
let head = "import std/Int\nimport std/collections/List\
|
|
395
|
+
let head = "import std/Int\nimport std/collections/List\nimport std/App\nprimitive Main =\n fun build(n: Int, acc: List<Int>) -> List<Int> = if n == 0 then acc else build(n - 1, Cons(head: n, tail: acc))\n\n";
|
|
396
396
|
let buildSrc = format!("{head}primitive Main[App] =\n fun main() -> Int =\n nil: List<Int> := Nil\n xs := Main.build(1000000, nil)\n xs.length()\n");
|
|
397
397
|
let mapSrc = format!("{head}primitive Main[App] =\n fun main() -> Int =\n nil: List<Int> := Nil\n xs := Main.build(1000000, nil)\n ys := xs.map(|x| x * 2)\n xs.length() + ys.length()\n");
|
|
398
398
|
// Unfused: with fusion, `ys.length()` consumes `mapCells` and the fused fn replaces it
|
|
@@ -444,7 +444,7 @@ fn method_reading_self_fields_is_rewritten() {
|
|
|
444
444
|
// A method that only READS `self.limit` is still a TRMC loop; a string literal
|
|
445
445
|
// spelling the old Debug-text marker must not block it either.
|
|
446
446
|
let m = "import std/Int\n\
|
|
447
|
-
import std/Str\
|
|
447
|
+
import std/Str\nimport std/App\n\
|
|
448
448
|
struct Cfg(limit: Int) =\n\n fun below(self, xs: Link<Int>) -> Link<Int> = match xs\n Nil => Nil\n Cons(h, t) =>\n note := \"Field(Self_\"\n if h < self.limit then Cons(head: h, tail: self.below(t)) else self.below(t)\n\n\
|
|
449
449
|
enum Link<T> = Nil | Cons(head: T, tail: Link<T>)\n\n\
|
|
450
450
|
primitive Main[App] =\n fun fromTo(a: Int, b: Int) -> Link<Int> =\n if a >= b then Nil else Cons(head: a, tail: fromTo(a + 1, b))\n\n fun count(xs: Link<Int>) -> Int = match xs\n Nil => 0\n Cons(_, t) => 1 + count(t)\n\n \
|
|
@@ -457,7 +457,7 @@ fun main() -> Int =\n c := Cfg(limit: 3)\n if Main.count(c.below(Main.from
|
|
|
457
457
|
fn method_assigning_self_field_is_not_rewritten() {
|
|
458
458
|
let m = "\
|
|
459
459
|
import std/Int
|
|
460
|
-
|
|
460
|
+
import std/App
|
|
461
461
|
struct Counter(mut n: Int) =
|
|
462
462
|
|
|
463
463
|
fun bump(self, xs: Link<Int>) -> Link<Int> = match xs
|
compiler/driver/src/lib.rs
CHANGED
|
@@ -328,6 +328,8 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
|
|
|
328
328
|
fn recheck(copy: Source) -> (Result<(), Vec<Diagnostic>>, TypedInfo, Rc<Source>) {
|
|
329
329
|
let kept = Rc::new(copy);
|
|
330
330
|
let (r, i) = checkOnce(&kept);
|
|
331
|
+
// A rewrite that made a new covariant upcast is not compiled: nothing lowers it now.
|
|
332
|
+
let r = plum_checker::upcastsLeft(r, &i);
|
|
331
333
|
(r, i, kept)
|
|
332
334
|
}
|
|
333
335
|
|
compiler/driver/tests/driver_tests.rs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
use plum_core::ast::{Item, Source};
|
|
3
3
|
use plum_driver::{check, check_with, Env, Pass, PassOptions, Target, PASSES};
|
|
4
4
|
|
|
5
|
-
const SRC: &str = "import std/Int\n\
|
|
5
|
+
const SRC: &str = "import std/Int\nimport std/App\n\
|
|
6
6
|
import std/collections/List\n\n\
|
|
7
7
|
primitive Src =\n fun total(xs: List<Int>) -> Int = xs.map(|x| x + 1).fold(0, |a, x| a + x)\n\nprimitive Main[App] =\n \
|
|
8
8
|
fun main() -> Int = Src.total([1, 2, 3])\n";
|
|
@@ -98,7 +98,7 @@ fn aQuestionMarkInALoopBodyIsRejected() {
|
|
|
98
98
|
|
|
99
99
|
#[test]
|
|
100
100
|
fn aLoopOverALocalWithNoTypeYetIsAnError() {
|
|
101
|
-
let src = load("drv_loop_unresolved", "import std/Int\nimport std/collections/List\
|
|
101
|
+
let src = load("drv_loop_unresolved", "import std/Int\nimport std/collections/List\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := []\n for i := range 3\n _ := xs.length()\n ys := xs.push(1)\n ys.length()\n");
|
|
102
102
|
let opts = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
|
|
103
103
|
let errs = check(&src, &opts).err().expect("rejected");
|
|
104
104
|
assert!(errs.iter().any(|e| e.message.contains("cannot turn this loop into a function") && e.message.contains("fn 'main'")), "{errs:?}");
|
|
@@ -106,7 +106,7 @@ fn aLoopOverALocalWithNoTypeYetIsAnError() {
|
|
|
106
106
|
|
|
107
107
|
#[test]
|
|
108
108
|
fn aTypeErrorInAForSourceIsReportedNotAHiddenLoop() {
|
|
109
|
-
let src = load("drv_loop_source_error", "import std/Int\
|
|
109
|
+
let src = load("drv_loop_source_error", "import std/Int\nimport std/App\nstruct T(mut n: Int)\n\nprimitive Main[App] =\n fun main() -> Int =\n t := T(n: 0)\n for i := range undefinedThing\n t.n = i\n t.n\n");
|
|
110
110
|
let opts = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
|
|
111
111
|
let errs = check(&src, &opts).err().expect("rejected");
|
|
112
112
|
assert!(errs.iter().any(|e| e.message.contains("undefined name 'undefinedThing'")), "{errs:?}");
|
|
@@ -141,14 +141,14 @@ fn spreadInPlace(info: &plum_checker::TypedInfo, ty: &str, method: &str) -> bool
|
|
|
141
141
|
found
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
const TWO_TYPES: &str = "import std/Int\n\
|
|
144
|
+
const TWO_TYPES: &str = "import std/Int\nimport std/App\n\
|
|
145
145
|
import std/Str\n\n\
|
|
146
146
|
struct Ship(label: Str, n: Int) =\n fun update(self) -> Ship = Ship(..self, n: self.n + 1)\n\n\
|
|
147
147
|
struct Orb(label: Str, n: Int) =\n fun update(self) -> Orb = Orb(..self, n: self.n + 2)\n\n\
|
|
148
148
|
primitive TwoTypes =\n fun both(o: Orb) -> Int =\n p := o.update()\n o.n + p.n\n\n fun run() -> Int =\n t := Ship(label: \"s\", n: 0).update()\n o := Orb(label: \"o\", n: 0)\n t.n + both(o)\n\nprimitive Main[App] =\n \
|
|
149
149
|
fun main() -> Int = TwoTypes.run()\n";
|
|
150
150
|
|
|
151
|
-
const GENERIC_TYPES: &str = "import std/Int\n\
|
|
151
|
+
const GENERIC_TYPES: &str = "import std/Int\nimport std/App\n\
|
|
152
152
|
import std/Str\n\n\
|
|
153
153
|
struct Ship<T>(cargo: T, n: Int) =\n fun update(self) -> Ship<T> = Ship(..self, n: self.n + 1)\n\n\
|
|
154
154
|
struct Orb<T>(cargo: T, n: Int) =\n fun update(self) -> Orb<T> = Orb(..self, n: self.n + 2)\n\n\
|
|
@@ -190,7 +190,7 @@ fn noFusionMarksNothing() {
|
|
|
190
190
|
fn aSharedReceiverOfAnotherTypeDoesNotProveItsOwnMethod() {
|
|
191
191
|
let src = load(
|
|
192
192
|
"drv_hostile_names",
|
|
193
|
-
"import std/Int\n\
|
|
193
|
+
"import std/Int\nimport std/App\n\
|
|
194
194
|
import std/Str\n\
|
|
195
195
|
struct Ship(label: Str, n: Int) =\n fun update(self) -> Ship = Ship(..self, n: self.n + 1)\n\
|
|
196
196
|
struct Orb(label: Str, n: Int) =\n fun update(self) -> Orb = Orb(..self, n: self.n + 2)\n\
|
|
@@ -209,7 +209,7 @@ fn aSharedReceiverOfAnotherTypeDoesNotProveItsOwnMethod() {
|
|
|
209
209
|
/// `draw` and `main` are the bodies of its reducer, its draw and the screen the game starts with.
|
|
210
210
|
fn gameSource(name: &str, main: &str, step: &str, draw: &str) -> Source {
|
|
211
211
|
let text = format!(
|
|
212
|
-
"module {name}\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Input\n\
|
|
212
|
+
"module {name}\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Input\nimport std/App\n\
|
|
213
213
|
import std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\
|
|
214
214
|
struct Stress[ScreenSlice<Float>](label: Str, t: Int, n: Int) =\n \
|
|
215
215
|
const Start = Stress(label: \"s\", t: 0, n: 0)\n \
|
|
@@ -262,7 +262,7 @@ fn gameDrawNeverWritesTheScreenInPlace() {
|
|
|
262
262
|
fn purityResolvesAMethodByItsReceiverType() {
|
|
263
263
|
let src = load(
|
|
264
264
|
"drv_purity_types",
|
|
265
|
-
"import std/Int\n\
|
|
265
|
+
"import std/Int\nimport std/App\n\
|
|
266
266
|
struct Ship(x: Int) =\n fun bump(self, k: Int) -> Int = self.x + k\n\
|
|
267
267
|
struct Orb(mut x: Int) =\n fun bump(self, k: Int) -> Int =\n self.x = self.x + k\n self.x\n\
|
|
268
268
|
primitive Main[App] =\n fun viaShip(k: Int) -> Int = Ship(x: k).bump(1)\n\n fun viaOrb(k: Int) -> Int = Orb(x: k).bump(1)\n \
|
|
@@ -280,7 +280,7 @@ fn purityResolvesAMethodByItsReceiverType() {
|
|
|
280
280
|
assert!(!pure.contains("Main.viaOrb"), "{pure:?}");
|
|
281
281
|
}
|
|
282
282
|
|
|
283
|
-
const PRUNE: &str = "import std/Int\n\
|
|
283
|
+
const PRUNE: &str = "import std/Int\nimport std/App\n\
|
|
284
284
|
import std/Str\n\n\
|
|
285
285
|
primitive Prune =\n fun unused(s: Str) -> Str = s.trim()\n\nprimitive Main[App] =\n \
|
|
286
286
|
fun main() -> Int = \"abc\".length()\n";
|
|
@@ -303,7 +303,7 @@ fn upcastsSource() -> String {
|
|
|
303
303
|
let body = std::fs::read_to_string(plum_test_support::repoRoot().join("tests/core/passes_upcasts.plum")).expect("reads");
|
|
304
304
|
let at = body.find("\nprimitive PassesUpcastsTest[UnitTest]").expect("has tests");
|
|
305
305
|
let main = "\nprimitive Main[App] =\n fun main() -> Int = PassesUpcastsTest.grp(3, Nil).v.area() + PassesUpcastsTest.holders([Sq(s: 2)]).length() + PassesUpcastsTest.outer<Str, Int>(Box(v: 3)) + PassesUpcastsTest.caller<Str, Int>(Box(v: 3), 4)\n";
|
|
306
|
-
format!("{}{main}{}", &body[..at], &body[at..])
|
|
306
|
+
format!("import std/App\n{}{main}{}", &body[..at], &body[at..])
|
|
307
307
|
}
|
|
308
308
|
|
|
309
309
|
/// Wrappers and closures that upcast to a trait, a closure naming its fn's generics and a
|
|
@@ -319,7 +319,7 @@ fn upcastsAndGenericClosuresDropNoPass() {
|
|
|
319
319
|
assert!(names.iter().any(|n| n.starts_with("apply$c")), "{names:?}");
|
|
320
320
|
}
|
|
321
321
|
|
|
322
|
-
const PARTIAL: &str = "import std/Int\
|
|
322
|
+
const PARTIAL: &str = "import std/Int\nimport std/App\n\
|
|
323
323
|
primitive Partial =\n fun good(n: Int) -> Int = n + 1\n\n fun bad(n: Int) -> Int = n * 2\n\nprimitive Main[App] =\n \
|
|
324
324
|
fun main() -> Int = Partial.good(1) + Partial.bad(2)\n";
|
|
325
325
|
|
|
@@ -359,7 +359,7 @@ fn aFailingFnRevertsAloneInAPerFnPass() {
|
|
|
359
359
|
}
|
|
360
360
|
}
|
|
361
361
|
|
|
362
|
-
const PARTIAL_GENERIC: &str = "import std/Int\
|
|
362
|
+
const PARTIAL_GENERIC: &str = "import std/Int\nimport std/App\n\
|
|
363
363
|
struct Cell(n: Int) =\n fun good(self) -> Int = self.n + 1\n\n fun bad(self) -> Int = self.n * 2\n\n\
|
|
364
364
|
primitive PartialGeneric =\n fun same<T>(x: T) -> T = x\n\nprimitive Main[App] =\n \
|
|
365
365
|
fun main() -> Int = Cell(n: 1).good() + Cell(n: 2).bad() + PartialGeneric.same(3)\n";
|
|
@@ -389,7 +389,7 @@ fn aFailingMethodAndGenericCopyRevertAlone() {
|
|
|
389
389
|
assert_eq!(dropped[0].reverted, vec!["Cell.bad".to_string(), "PartialGeneric.same".to_string()], "{dropped:?}");
|
|
390
390
|
}
|
|
391
391
|
|
|
392
|
-
const PARTIAL_CALLERS: &str = "import std/Int\
|
|
392
|
+
const PARTIAL_CALLERS: &str = "import std/Int\nimport std/App\n\
|
|
393
393
|
primitive PartialCallers =\n fun good(n: Int) -> Int = n + 1\n\n fun bad(n: Int) -> Int = n * 2\n\n fun twice(n: Int) -> Int = good(n) + good(n)\n\n fun keep(n: Int) -> Int = n - 1\n\nprimitive Main[App] =\n \
|
|
394
394
|
fun main() -> Int = PartialCallers.good(1) + PartialCallers.bad(2) + PartialCallers.twice(3) + PartialCallers.keep(4)\n";
|
|
395
395
|
|
|
@@ -581,7 +581,7 @@ fn tailsTo(lowered: &Source, owner: &str, callee: &str) -> Vec<plum_core::ast::T
|
|
|
581
581
|
fn tailCallsAreMarkedWhateverPassRanLast() {
|
|
582
582
|
let src = load(
|
|
583
583
|
"drv_tail",
|
|
584
|
-
"import std/Int\nimport std/collections/List\
|
|
584
|
+
"import std/Int\nimport std/collections/List\nimport std/App\nprimitive Main[App] =\n fun count(n: Int, acc: Int) -> Int = if n == 0 then acc else count(n - 1, acc + 1)\n\n fun main() -> Int = Main.count(10, 0)\n",
|
|
585
585
|
);
|
|
586
586
|
for passes in [&PASSES[..1], &PASSES[..2], &PASSES[..]] {
|
|
587
587
|
let info = check_with(&src, &PassOptions::default(), passes).expect("checks");
|
compiler/game/tests/fixtures/assets_fixture.plum
CHANGED
|
@@ -18,6 +18,7 @@ import std/game/ScreenSlice
|
|
|
18
18
|
import std/game/Game
|
|
19
19
|
import std/game/View
|
|
20
20
|
import std/game/Place
|
|
21
|
+
import std/App
|
|
21
22
|
|
|
22
23
|
# Loads through the raw `io` (a missing file answers -1 or empty, where `Texture.load`
|
|
23
24
|
# would crash) and draws through it.
|
compiler/game/tests/fixtures/camera_fixture.plum
CHANGED
|
@@ -16,6 +16,7 @@ import std/game/Control
|
|
|
16
16
|
import std/game/Screen
|
|
17
17
|
import std/game/ScreenSlice
|
|
18
18
|
import std/game/Game
|
|
19
|
+
import std/App
|
|
19
20
|
|
|
20
21
|
# F, I, E and S set the first screen's scaling to Fit, Fill, Extend and Stretch; G goes to
|
|
21
22
|
# the second screen, which slides in from the right over one second.
|
compiler/game/tests/fixtures/host_fixture.plum
CHANGED
|
@@ -18,6 +18,7 @@ import std/game/ScreenSlice
|
|
|
18
18
|
import std/game/Game
|
|
19
19
|
import std/game/View
|
|
20
20
|
import std/game/Place
|
|
21
|
+
import std/App
|
|
21
22
|
|
|
22
23
|
# One raw host read in `draw` (`mousePos`), so the recorded call order is fixed. The game
|
|
23
24
|
# clears the frame (`Screen.background`, black) before the screen draws. The
|
compiler/game/tests/fixtures/main_cli_fixture.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/Int
|
|
|
4
4
|
import std/Str
|
|
5
5
|
import std/game/Input
|
|
6
6
|
import std/Io
|
|
7
|
+
import std/App
|
|
7
8
|
|
|
8
9
|
# Imports std/game/Gfx but `main` does not return a Game: a CLI program, no update/draw.
|
|
9
10
|
primitive MainCliFixture[App] =
|
compiler/game/tests/fixtures/main_game_fixture.plum
CHANGED
|
@@ -19,6 +19,7 @@ import std/game/Game
|
|
|
19
19
|
import std/Io
|
|
20
20
|
import std/game/View
|
|
21
21
|
import std/game/Place
|
|
22
|
+
import std/App
|
|
22
23
|
|
|
23
24
|
# A game whose entry is `main`, declared to return a `Game`: one screen, `Orbs`, that keeps
|
|
24
25
|
# the input of its last tick and moves while Right is held.
|
compiler/game/tests/fixtures/main_missing_fixture.plum
CHANGED
|
@@ -16,6 +16,7 @@ import std/game/ScreenSlice
|
|
|
16
16
|
import std/game/Game
|
|
17
17
|
import std/game/View
|
|
18
18
|
import std/game/Place
|
|
19
|
+
import std/App
|
|
19
20
|
|
|
20
21
|
# Its texture is missing: `main` crashes naming it.
|
|
21
22
|
struct Broken[ScreenSlice<Float>](tex: Texture) =
|
compiler/game/tests/fixtures/state_draw_keeps.plum
CHANGED
|
@@ -16,6 +16,7 @@ import std/game/ScreenSlice
|
|
|
16
16
|
import std/game/Game
|
|
17
17
|
import std/game/View
|
|
18
18
|
import std/game/Place
|
|
19
|
+
import std/App
|
|
19
20
|
|
|
20
21
|
# `draw` keeps the screen it is given: the next `reduce` must not write that object in place.
|
|
21
22
|
struct Log(mut last: Option<Run>)
|
compiler/game/tests/fixtures/state_in_place.plum
CHANGED
|
@@ -16,6 +16,7 @@ import std/game/ScreenSlice
|
|
|
16
16
|
import std/game/Game
|
|
17
17
|
import std/game/View
|
|
18
18
|
import std/game/Place
|
|
19
|
+
import std/App
|
|
19
20
|
|
|
20
21
|
struct Part(label: Str, x: Int) =
|
|
21
22
|
fun step(self) -> Part = Part(..self, x: self.x + 1)
|
compiler/game/tests/fixtures/state_main_alias.plum
CHANGED
|
@@ -16,6 +16,7 @@ import std/game/ScreenSlice
|
|
|
16
16
|
import std/game/Game
|
|
17
17
|
import std/game/View
|
|
18
18
|
import std/game/Place
|
|
19
|
+
import std/App
|
|
19
20
|
|
|
20
21
|
struct Run[ScreenSlice<Float>](label: Str, t: Int) =
|
|
21
22
|
# `main` starts the game with a local, but the local is a constant: `reduce` must not write
|
compiler/game/tests/fixtures/state_reset.plum
CHANGED
|
@@ -16,6 +16,7 @@ import std/game/ScreenSlice
|
|
|
16
16
|
import std/game/Game
|
|
17
17
|
import std/game/View
|
|
18
18
|
import std/game/Place
|
|
19
|
+
import std/App
|
|
19
20
|
|
|
20
21
|
struct Run[ScreenSlice<Float>](label: Str, t: Int) =
|
|
21
22
|
# The screen goes back to a constant: writing it in place would overwrite the constant.
|
compiler/game/tests/fixtures/target_fixture.plum
CHANGED
|
@@ -17,6 +17,7 @@ import std/game/ScreenSlice
|
|
|
17
17
|
import std/game/Game
|
|
18
18
|
import std/game/View
|
|
19
19
|
import std/game/Place
|
|
20
|
+
import std/App
|
|
20
21
|
|
|
21
22
|
# `bad` is a raw `io.textureCreate` of an impossible size: it answers -1 where
|
|
22
23
|
# `Texture.create` would crash.
|
compiler/game/tests/fixtures/turn_fixture.plum
CHANGED
|
@@ -13,6 +13,7 @@ import std/game/Box
|
|
|
13
13
|
import std/game/Label
|
|
14
14
|
import std/game/Screen
|
|
15
15
|
import std/game/Game
|
|
16
|
+
import std/App
|
|
16
17
|
|
|
17
18
|
# A group at (100, 100) turned a quarter, holding a red 40 by 20 box and a label, and a
|
|
18
19
|
# label in the hud at (5, 5).
|
compiler/game/tests/host_test.rs
CHANGED
|
@@ -116,7 +116,7 @@ fn missingExportErrors() {
|
|
|
116
116
|
let path = dir.join("m.plum");
|
|
117
117
|
std::fs::write(
|
|
118
118
|
&path,
|
|
119
|
-
"import std/Int\nimport std/Float\nimport std/Io\nstruct State(mut n: Int)\n\nprimitive Main[App] =\n export fun main(io: Io) -> State =\n State(n: 0)\n export fun update(g: State, dt: Float) =\n g.n = 1\n",
|
|
119
|
+
"import std/Int\nimport std/Float\nimport std/Io\nimport std/App\nstruct State(mut n: Int)\n\nprimitive Main[App] =\n export fun main(io: Io) -> State =\n State(n: 0)\n export fun update(g: State, dt: Float) =\n g.n = 1\n",
|
|
120
120
|
)
|
|
121
121
|
.unwrap();
|
|
122
122
|
let wasm = compile(&path);
|
|
@@ -133,7 +133,7 @@ fn oldInitEntryIsRejected() {
|
|
|
133
133
|
let path = dir.join("m.plum");
|
|
134
134
|
std::fs::write(
|
|
135
135
|
&path,
|
|
136
|
-
"import std/Int\nimport std/Float\nimport std/Io\nstruct State(mut n: Int)\n\nprimitive Main[App] =\n export fun init() -> State =\n State(n: 0)\n export fun update(g: State, dt: Float) =\n g.n = 1\n export fun draw(io: Io, g: State) =\n g.n = 2\n",
|
|
136
|
+
"import std/Int\nimport std/Float\nimport std/Io\nimport std/App\nstruct State(mut n: Int)\n\nprimitive Main[App] =\n export fun init() -> State =\n State(n: 0)\n export fun update(g: State, dt: Float) =\n g.n = 1\n export fun draw(io: Io, g: State) =\n g.n = 2\n",
|
|
137
137
|
)
|
|
138
138
|
.unwrap();
|
|
139
139
|
let source = plum_core::loadAndMergeDiag(&path, &root()).expect("load");
|
|
@@ -151,7 +151,7 @@ fn unknownImportTraps() {
|
|
|
151
151
|
let path = dir.join("m.plum");
|
|
152
152
|
std::fs::write(
|
|
153
153
|
&path,
|
|
154
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nstruct State[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n x := io.rawExists(\"a\")\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(n: 0)\n Game(screens: [only])\n",
|
|
154
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct State[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n x := io.rawExists(\"a\")\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(n: 0)\n Game(screens: [only])\n",
|
|
155
155
|
)
|
|
156
156
|
.unwrap();
|
|
157
157
|
let wasm = compile(&path);
|
|
@@ -364,7 +364,7 @@ fn randomSeedProvidedByHost() {
|
|
|
364
364
|
let path = dir.join("m.plum");
|
|
365
365
|
std::fs::write(
|
|
366
366
|
&path,
|
|
367
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nstruct State[ScreenSlice<Int>](seed: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed())\n Game(screens: [only])\n",
|
|
367
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct State[ScreenSlice<Int>](seed: Int) =\n fun name(self) -> Str = \"page\"\n fun reduce(self, a: Int) -> State = self\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed())\n Game(screens: [only])\n",
|
|
368
368
|
)
|
|
369
369
|
.unwrap();
|
|
370
370
|
let wasm = compile(&path);
|
|
@@ -388,7 +388,7 @@ fn seedGame(name: &str) -> Vec<u8> {
|
|
|
388
388
|
let path = dir.join("m.plum");
|
|
389
389
|
std::fs::write(
|
|
390
390
|
&path,
|
|
391
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nenum Saw = Held(keys: Int, x: Float) | Ticked\nstruct State[ScreenSlice<Saw>](seed: Int, ticks: Int, keys: Int, x: Float) =\n fun name(self) -> Str = \"page\"\n fun hud(self, window: Vec2) -> List<View> = [StateDrawing(s: self, w: window.x)]\n fun held(self, i: Input) -> Option<Saw> = Some(Held(keys: i.held.keys.length(), x: i.pos.x))\n fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked)\n fun reduce(self, a: Saw) -> State = match a\n Held(k, x) => State(..self, keys: self.keys + k, x: x)\n Ticked => State(..self, ticks: self.ticks + 1)\n\n# What the screen draws each frame, with `Gfx` by hand, and the window's width.\nstruct StateDrawing[View](s: State, w: Float) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed} ticks {self.s.ticks} keys {self.s.keys} x {self.s.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0)\n Game(screens: [only])\n",
|
|
391
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nenum Saw = Held(keys: Int, x: Float) | Ticked\nstruct State[ScreenSlice<Saw>](seed: Int, ticks: Int, keys: Int, x: Float) =\n fun name(self) -> Str = \"page\"\n fun hud(self, window: Vec2) -> List<View> = [StateDrawing(s: self, w: window.x)]\n fun held(self, i: Input) -> Option<Saw> = Some(Held(keys: i.held.keys.length(), x: i.pos.x))\n fun tick(self, dt: Float) -> Option<Saw> = Some(Ticked)\n fun reduce(self, a: Saw) -> State = match a\n Held(k, x) => State(..self, keys: self.keys + k, x: x)\n Ticked => State(..self, ticks: self.ticks + 1)\n\n# What the screen draws each frame, with `Gfx` by hand, and the window's width.\nstruct StateDrawing[View](s: State, w: Float) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"seed {self.s.seed} ticks {self.s.ticks} keys {self.s.keys} x {self.s.x} w {self.w}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := State(seed: io.randomSeed(), ticks: 0, keys: 0, x: 0.0)\n Game(screens: [only])\n",
|
|
392
392
|
)
|
|
393
393
|
.unwrap();
|
|
394
394
|
let wasm = compile(&path);
|
|
@@ -463,7 +463,7 @@ fn everySeedOfARecordedRunReplays() {
|
|
|
463
463
|
let path = dir.join("m.plum");
|
|
464
464
|
std::fs::write(
|
|
465
465
|
&path,
|
|
466
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nstruct Seeds(mut c: Int)\nstruct State[ScreenSlice<Int>](a: Int, b: Int, seeds: Seeds) =\n fun name(self) -> Str = \"page\"\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n fun reduce(self, n: Int) -> State = self\n fun effect(self, io: Io, n: Int, game: Control) =\n self.seeds.c = self.seeds.c ^ io.randomSeed()\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"{self.s.a} {self.s.b} {self.s.seeds.c}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n a := io.randomSeed()\n seeds := Seeds(c: 0)\n only: Screen := State(a: a, b: io.randomSeed(), seeds: seeds)\n Game(screens: [only])\n",
|
|
466
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Slice\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/math/Affine\nimport std/math/Aabb\nimport std/game/Color\nimport std/game/Gfx\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Place\nimport std/App\nstruct Seeds(mut c: Int)\nstruct State[ScreenSlice<Int>](a: Int, b: Int, seeds: Seeds) =\n fun name(self) -> Str = \"page\"\n fun tick(self, dt: Float) -> Option<Int> = Some(1)\n fun reduce(self, n: Int) -> State = self\n fun effect(self, io: Io, n: Int, game: Control) =\n self.seeds.c = self.seeds.c ^ io.randomSeed()\n fun view(self) -> List<View> = [StateDrawing(s: self)]\n\n# What the screen draws each frame, with `Gfx` by hand.\nstruct StateDrawing[View](s: State) =\n fun place(self) -> Place = Place.at(0.0, 0.0)\n fun paintSelf(self, io: Io, m: Affine, alpha: Float) =\n Gfx.drawText(io, \"{self.s.a} {self.s.b} {self.s.seeds.c}\", 0.0, 0.0, 8.0, Color.White)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n a := io.randomSeed()\n seeds := Seeds(c: 0)\n only: Screen := State(a: a, b: io.randomSeed(), seeds: seeds)\n Game(screens: [only])\n",
|
|
467
467
|
)
|
|
468
468
|
.unwrap();
|
|
469
469
|
let wasm = compile(&path);
|
compiler/game/web-test/fixtures/interleave.plum
CHANGED
|
@@ -20,6 +20,7 @@ import std/game/ScreenSlice
|
|
|
20
20
|
import std/game/Game
|
|
21
21
|
import std/game/View
|
|
22
22
|
import std/game/Place
|
|
23
|
+
import std/App
|
|
23
24
|
|
|
24
25
|
# All the sprites, one tick on each tick.
|
|
25
26
|
struct Interleave[ScreenSlice<Float>](tex: Array<Texture>, t: Int) =
|
compiler/game/web-test/fixtures/main_game.plum
CHANGED
|
@@ -17,6 +17,7 @@ import std/game/ScreenSlice
|
|
|
17
17
|
import std/game/Game
|
|
18
18
|
import std/game/View
|
|
19
19
|
import std/game/Place
|
|
20
|
+
import std/App
|
|
20
21
|
|
|
21
22
|
# A game whose `main` returns a `Game`: one screen, a square that moves
|
|
22
23
|
# with the tick count. It ticks and draws the count.
|
compiler/game/web-test/fixtures/rendertarget.plum
CHANGED
|
@@ -31,6 +31,7 @@ import std/game/ScreenSlice
|
|
|
31
31
|
import std/game/Game
|
|
32
32
|
import std/game/View
|
|
33
33
|
import std/game/Place
|
|
34
|
+
import std/App
|
|
34
35
|
|
|
35
36
|
# The targets and the tick count.
|
|
36
37
|
struct Targets[ScreenSlice<Float>](big: Texture, small: Texture, glass: Texture, t: Int) =
|
compiler/game/web-test/fixtures/stress.plum
CHANGED
|
@@ -20,6 +20,7 @@ import std/game/ScreenSlice
|
|
|
20
20
|
import std/game/Game
|
|
21
21
|
import std/game/View
|
|
22
22
|
import std/game/Place
|
|
23
|
+
import std/App
|
|
23
24
|
|
|
24
25
|
# The whole scene, drawn from the tick count.
|
|
25
26
|
struct Stress[ScreenSlice<Float>](sheet: Texture, t: Int) =
|
compiler/game/web-test/fixtures/stress_state_view.plum
CHANGED
|
@@ -31,6 +31,7 @@ import std/game/ScreenSlice
|
|
|
31
31
|
import std/game/Game
|
|
32
32
|
import std/game/TestRig
|
|
33
33
|
import std/Io
|
|
34
|
+
import std/App
|
|
34
35
|
|
|
35
36
|
primitive StressStateView[App] =
|
|
36
37
|
const Sprites = 5000
|
|
@@ -102,10 +103,9 @@ struct ViewScreen[ScreenSlice<StressAction>](clock: Float, frames: Int, clicks:
|
|
|
102
103
|
fun background(self) -> Color = Color.rgb(0.05, 0.06, 0.1)
|
|
103
104
|
|
|
104
105
|
fun view(self) -> List<View> =
|
|
105
|
-
world
|
|
106
|
-
buttons := Views.all(self.buttons)
|
|
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
107
|
labels := StressStateView.rangeLink(0, StressStateView.Buttons, |i| self.buttonLabel(i))
|
|
108
|
-
Cons(world, buttons.append(labels))
|
|
108
|
+
Cons(world, self.buttons.append(labels))
|
|
109
109
|
|
|
110
110
|
fun onPress(self, target: View, at: Vec2) -> Option<StressAction> =
|
|
111
111
|
0.until(StressStateView.Buttons).find(|i| @sameRef(target, self.buttons.at(i))).map(|i| Clicked(i: i))
|
compiler/game/web-test/fixtures/text_sizes.plum
CHANGED
|
@@ -19,6 +19,7 @@ import std/game/ScreenSlice
|
|
|
19
19
|
import std/game/Game
|
|
20
20
|
import std/game/View
|
|
21
21
|
import std/game/Place
|
|
22
|
+
import std/App
|
|
22
23
|
|
|
23
24
|
# The text, one tick older each tick.
|
|
24
25
|
struct Sizes[ScreenSlice<Float>](t: Int) =
|
compiler/lsp/src/main.rs
CHANGED
|
@@ -618,7 +618,7 @@ mod tests {
|
|
|
618
618
|
let dir = std::env::temp_dir().join(format!("plum-lsp-test-{}", std::process::id()));
|
|
619
619
|
std::fs::create_dir_all(&dir).unwrap();
|
|
620
620
|
let path = dir.join("t.plum");
|
|
621
|
-
let text = "module t\nimport std/Int\nimport std/Float\nimport std/Slice\
|
|
621
|
+
let text = "module t\nimport std/Int\nimport std/Float\nimport std/Slice\nimport std/App\nprimitive Main[App] =\n fun main() =\n xs := Slice<Int>()\n xs.zzzzzz\n";
|
|
622
622
|
std::fs::write(&path, text).unwrap();
|
|
623
623
|
let items = memberCompletionFor(&path, &repoRoot(), text, 8, "xs");
|
|
624
624
|
let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
|
|
@@ -636,7 +636,7 @@ mod tests {
|
|
|
636
636
|
let dir = std::env::temp_dir().join(format!("plum-lsp-int-{}", std::process::id()));
|
|
637
637
|
std::fs::create_dir_all(&dir).unwrap();
|
|
638
638
|
let path = dir.join("t.plum");
|
|
639
|
-
let text = "module t\nimport std/Int\nimport std/Float\
|
|
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
640
|
std::fs::write(&path, text).unwrap();
|
|
641
641
|
for (line, recv) in [(6, "n"), (7, "10")] {
|
|
642
642
|
let items = memberCompletionFor(&path, &repoRoot(), text, line, recv);
|
|
@@ -658,7 +658,7 @@ mod tests {
|
|
|
658
658
|
let dir = std::env::temp_dir().join(format!("plum-lsp-fsm-{}", std::process::id()));
|
|
659
659
|
std::fs::create_dir_all(&dir).unwrap();
|
|
660
660
|
let path = dir.join("t.plum");
|
|
661
|
-
let text = "module t\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Slice\nimport std/collections/Map\
|
|
661
|
+
let text = "module t\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Slice\nimport std/collections/Map\nimport std/App\nprimitive Main[App] =\n fun main() =\n f := 1.5\n f.zzzzzz\n s := \"x\"\n s.zzzzzz\n m: Map<Str, Int> := Map.empty()\n m.zzzzzz\n";
|
|
662
662
|
std::fs::write(&path, text).unwrap();
|
|
663
663
|
let cases: [(usize, &str, &[&str]); 3] = [
|
|
664
664
|
(9, "f", &["sqrt", "toStr"]),
|
|
@@ -691,7 +691,7 @@ mod tests {
|
|
|
691
691
|
let dir = std::env::temp_dir().join(format!("plum-lsp-statics-{}", std::process::id()));
|
|
692
692
|
std::fs::create_dir_all(&dir).unwrap();
|
|
693
693
|
let path = dir.join("t.plum");
|
|
694
|
-
let text = "module t\nimport std/Int\nimport std/Float\
|
|
694
|
+
let text = "module t\nimport std/Int\nimport std/Float\nimport std/App\nprimitive Main[App] =\n fun main() =\n x := Float.zzzzzz\n";
|
|
695
695
|
std::fs::write(&path, text).unwrap();
|
|
696
696
|
let labels = |recv: &str| -> Vec<String> {
|
|
697
697
|
memberCompletionFor(&path, &repoRoot(), text, 6, recv)
|
|
@@ -752,7 +752,7 @@ mod tests {
|
|
|
752
752
|
let dir = std::env::temp_dir().join(format!("plum-lsp-ns-{}", std::process::id()));
|
|
753
753
|
std::fs::create_dir_all(&dir).unwrap();
|
|
754
754
|
let path = dir.join("t.plum");
|
|
755
|
-
let text = "module t\nimport std/Int\nimport std/Str\nimport std/Os\nimport std/encoding/Base64\
|
|
755
|
+
let text = "module t\nimport std/Int\nimport std/Str\nimport std/Os\nimport std/encoding/Base64\nimport std/App\nprimitive Main[App] =\n fun main() =\n x := Os.zzzzzz\n";
|
|
756
756
|
std::fs::write(&path, text).unwrap();
|
|
757
757
|
let labels = |recv: &str| -> Vec<String> {
|
|
758
758
|
memberCompletionFor(&path, &repoRoot(), text, 7, recv)
|
|
@@ -781,7 +781,7 @@ mod tests {
|
|
|
781
781
|
let dir = std::env::temp_dir().join(format!("plum-lsp-module-{}", std::process::id()));
|
|
782
782
|
std::fs::create_dir_all(&dir).unwrap();
|
|
783
783
|
let path = dir.join("t.plum");
|
|
784
|
-
let text = "import std/Int\nimport tests/modules/mathx\nimport tests/modules/shapes\
|
|
784
|
+
let text = "import std/Int\nimport tests/modules/mathx\nimport tests/modules/shapes\nimport std/App\nprimitive Main[App] =\n fun main() =\n x := Mathx.zzzzzz\n";
|
|
785
785
|
std::fs::write(&path, text).unwrap();
|
|
786
786
|
let labels: Vec<String> = memberCompletionFor(&path, &repoRoot(), text, 6, "Mathx")
|
|
787
787
|
.into_iter()
|
|
@@ -791,14 +791,14 @@ mod tests {
|
|
|
791
791
|
assert!(labels.iter().any(|l| l == want), "missing {want} in {labels:?}");
|
|
792
792
|
}
|
|
793
793
|
assert!(!labels.iter().any(|l| l.contains('@')), "{labels:?}");
|
|
794
|
-
let ok = "import std/Int\nimport tests/modules/mathx\nimport tests/modules/shapes\
|
|
794
|
+
let ok = "import std/Int\nimport tests/modules/mathx\nimport tests/modules/shapes\nimport std/App\nprimitive Main[App] =\n fun clamp(x: Int) -> Int = x\n\n fun main() =\n _ := Mathx.clamp(1) + Main.clamp(1)\n";
|
|
795
795
|
std::fs::write(&path, ok).unwrap();
|
|
796
796
|
let merged = plum_core::loadAndMergeDiag(&path, &repoRoot()).expect("loads");
|
|
797
797
|
let top: Vec<String> = completion::topLevelItems(&merged).into_iter().map(|i| i.label).collect();
|
|
798
798
|
// A namespace is offered at the top level, its statics after `Main.`.
|
|
799
799
|
assert!(top.iter().any(|l| l == "Main") && top.iter().any(|l| l == "Mathx") && !top.iter().any(|l| l.contains('@')), "{top:?}");
|
|
800
800
|
// A built-in's declaration (the compiler's own `@sameRef`) is not offered either.
|
|
801
|
-
let builtin = "import std/Int\nimport std/Str\
|
|
801
|
+
let builtin = "import std/Int\nimport std/Str\nimport std/App\nprimitive Main[App] =\n fun same(a: Str) -> Bool = @sameRef(a, a)\n\n fun main() =\n _ := Main.same(\"x\")\n";
|
|
802
802
|
std::fs::write(&path, builtin).unwrap();
|
|
803
803
|
let merged = plum_core::loadAndMergeDiag(&path, &repoRoot()).expect("loads");
|
|
804
804
|
assert!(merged.items.iter().any(|i| matches!(i, plum_core::ast::Item::Fn(f) if f.name == "@sameRef")));
|
|
@@ -985,7 +985,7 @@ mod tests {
|
|
|
985
985
|
let dir = std::env::temp_dir().join(format!("plum_lsp_pos_{}", std::process::id()));
|
|
986
986
|
std::fs::create_dir_all(&dir).unwrap();
|
|
987
987
|
let path = dir.join("main.plum");
|
|
988
|
-
let text = "import std/Int\
|
|
988
|
+
let text = "import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n nope\n";
|
|
989
989
|
std::fs::write(&path, text).unwrap();
|
|
990
990
|
let diags = typeDiagnosticsFor(&path, &repoRoot(), text);
|
|
991
991
|
let _ = std::fs::remove_dir_all(&dir);
|
|
@@ -1118,7 +1118,7 @@ mod tests {
|
|
|
1118
1118
|
|
|
1119
1119
|
#[test]
|
|
1120
1120
|
fn syntaxDiagnosticUnderlinesTheTokenNotTheFunction() {
|
|
1121
|
-
let src = "import std/Float\
|
|
1121
|
+
let src = "import std/Float\nimport std/App\nprimitive Program[App] =\n export fun update(w: Float, dt: Float) =\n ()\n\nprimitive Main =\n fun ok() =\n _ := 1.0\n";
|
|
1122
1122
|
let d = Backend::syntaxDiagnostics(&Backend::parseTree(src), src);
|
|
1123
1123
|
assert_eq!(d.len(), 1, "{d:?}");
|
|
1124
1124
|
assert_eq!(d[0].range.start, Position::new(4, 4));
|
compiler/lsp/tests/protocol.rs
CHANGED
|
@@ -99,7 +99,7 @@ fn diagnosticsAreVersionedDebouncedAndDefinitionsFound() {
|
|
|
99
99
|
let dir = std::env::temp_dir().join(format!("plum_lsp_protocol_{}", std::process::id()));
|
|
100
100
|
std::fs::create_dir_all(&dir).unwrap();
|
|
101
101
|
let path = dir.join("main.plum");
|
|
102
|
-
let good = "import std/Int\
|
|
102
|
+
let good = "import std/Int\nimport std/App\nprimitive Main[App] =\n fun helper() -> Int = 1\n\n fun main() -> Int =\n Main.helper()\n";
|
|
103
103
|
std::fs::write(&path, good).unwrap();
|
|
104
104
|
let uri = format!("file://{}", path.display());
|
|
105
105
|
|
|
@@ -194,7 +194,7 @@ fn positionsGenericsAndParseErrorsOverStdio() {
|
|
|
194
194
|
let path = dir.join("généric.plum");
|
|
195
195
|
let call = " Main.pick(\"😀é\", nope)";
|
|
196
196
|
let text = format!(
|
|
197
|
-
"import std/Int\nimport std/Str\
|
|
197
|
+
"import std/Int\nimport std/Str\nimport std/App\nstruct Box<T>(value: T)\n\nprimitive Main[App] =\n fun first<T>(b: Box<T>) -> T =\n b.value\n\n fun pick(s: Str, n: Int) -> Int =\n n\n\n fun other() -> Int =\n first(Box(value: 2))\n\n fun main() -> Int =\n{call}\n"
|
|
198
198
|
);
|
|
199
199
|
// `call` is line 16.
|
|
200
200
|
std::fs::write(&path, &text).unwrap();
|
|
@@ -235,7 +235,7 @@ fn positionsGenericsAndParseErrorsOverStdio() {
|
|
|
235
235
|
assert!(done.contains(&format!(r#""start":{{"character":{},"line":16}}"#, end - 3)), "{done}");
|
|
236
236
|
|
|
237
237
|
// A parse error: one syntax diagnostic, on the broken line.
|
|
238
|
-
let broken = "import std/Int\
|
|
238
|
+
let broken = "import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n (1 +\n";
|
|
239
239
|
s.send(&format!(
|
|
240
240
|
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":3}},"contentChanges":[{{"text":"{}"}}]}}}}"#,
|
|
241
241
|
escape(broken)
|
|
@@ -263,7 +263,7 @@ fn aLongDocumentIsCheckedQuickly() {
|
|
|
263
263
|
let dir = std::env::temp_dir().join(format!("plum_lsp_long_{}", std::process::id()));
|
|
264
264
|
std::fs::create_dir_all(&dir).unwrap();
|
|
265
265
|
let path = dir.join("long.plum");
|
|
266
|
-
let mut text = String::from("import std/Int\
|
|
266
|
+
let mut text = String::from("import std/Int\nimport std/App\nprimitive Main =\n");
|
|
267
267
|
for i in 0..666 {
|
|
268
268
|
text.push_str(&format!(" fun f{i}(n: Int) -> Int =\n n + {i}\n\n"));
|
|
269
269
|
}
|
compiler/test-support/src/lib.rs
CHANGED
|
@@ -5,7 +5,7 @@ use plum_core::ast::Source;
|
|
|
5
5
|
use std::path::PathBuf;
|
|
6
6
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
7
7
|
|
|
8
|
-
pub const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/Slice\
|
|
8
|
+
pub const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/Slice\nimport std/App\n";
|
|
9
9
|
|
|
10
10
|
pub fn repoRoot() -> PathBuf {
|
|
11
11
|
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
|
compiler/wasm-codegen/src/lib.rs
CHANGED
|
@@ -173,7 +173,7 @@ pub use plum_core::tests_lower::{TestProgram, ASSERT_REPORT_MARK};
|
|
|
173
173
|
#[cfg(test)]
|
|
174
174
|
mod compileEntryTests {
|
|
175
175
|
use super::*;
|
|
176
|
-
const SRC: &str = "import std/Test\nimport std/Str\nimport std/Int\
|
|
176
|
+
const SRC: &str = "import std/Test\nimport std/Str\nimport std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int = 1 + 2\n\nprimitive SampleTest[UnitTest] =\n fun a() =\n assert 1 == 1\n";
|
|
177
177
|
|
|
178
178
|
fn load() -> ast::Source {
|
|
179
179
|
loadSrc(SRC)
|
|
@@ -220,7 +220,7 @@ mod compileEntryTests {
|
|
|
220
220
|
/// missing type became, which is missing from the GC registry; still an error.
|
|
221
221
|
#[test]
|
|
222
222
|
fn missingTypesOfAMatchAreAnErrorNotAPanic() {
|
|
223
|
-
let src = loadSrc("import std/Int\nimport std/Option\
|
|
223
|
+
let src = loadSrc("import std/Int\nimport std/Option\nimport std/App\nprimitive Main[App] =\n fun pick(o: Option<Int>) -> Int =\n match o\n Some(n) => n + 1\n None => 0\n\n fun main() -> Int = Main.pick(Some(2)) + Main.pick(None)\n");
|
|
224
224
|
let mut typed = plum_driver::check(&src, &CompileOptions::default().passes).expect("checks");
|
|
225
225
|
typed.expr_types.clear();
|
|
226
226
|
typed.inst_expr_types.clear();
|
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs
CHANGED
|
@@ -203,6 +203,7 @@ primitive FbTest[UnitTest] =
|
|
|
203
203
|
#[test]
|
|
204
204
|
fn unitTestsAreStrippedFromNormalCompile() {
|
|
205
205
|
let src = "\
|
|
206
|
+
import std/App
|
|
206
207
|
primitive Main[App] =
|
|
207
208
|
fun main() -> Int =
|
|
208
209
|
0
|
|
@@ -235,7 +236,7 @@ fn stringInterpolationOfAFloatIsAClearError() {
|
|
|
235
236
|
// Float-to-decimal-string formatting is a substantial separate undertaking
|
|
236
237
|
// (correct rounding needs something like Grisu/Ryu); scoped out for now with
|
|
237
238
|
// an explicit error rather than emitting an incorrect conversion.
|
|
238
|
-
let src = "
|
|
239
|
+
let src = "import std/App\nprimitive Main[App] =\n fun main() -> Str =\n x := 1.5\n \"{x}\"\n";
|
|
239
240
|
let source = parse(src);
|
|
240
241
|
let err = compileSource(&source).expect_err("float interpolation should not silently compile");
|
|
241
242
|
assert!(err.contains("Float"), "got: {}", err);
|
|
@@ -244,7 +245,7 @@ fn stringInterpolationOfAFloatIsAClearError() {
|
|
|
244
245
|
/// The last case of a match proven exhaustive is not tested: two variants, one `ref.test`.
|
|
245
246
|
#[test]
|
|
246
247
|
fn lastCaseOfAnExhaustiveMatchIsNotTested() {
|
|
247
|
-
let src = "import std/Int\
|
|
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";
|
|
248
249
|
let bytes = plum_test_support::compile("lastcase", src);
|
|
249
250
|
let ops = namedBodies(&bytes).into_iter().find(|(n, _)| n == "Main.areaOf").expect("areaOf").1;
|
|
250
251
|
assert_eq!(ops.iter().filter(|o| o.starts_with("RefTest")).count(), 1, "{ops:?}");
|
|
@@ -254,19 +255,19 @@ fn lastCaseOfAnExhaustiveMatchIsNotTested() {
|
|
|
254
255
|
/// A codegen error points at the node it came out of: here the interpolation on line 3.
|
|
255
256
|
#[test]
|
|
256
257
|
fn codegenErrorCarriesThePosition() {
|
|
257
|
-
let src = "
|
|
258
|
+
let src = "import std/App\nprimitive Main[App] =\n fun main() -> Str =\n x := 1.5\n \"{x}\"\n";
|
|
258
259
|
let source = parse(src);
|
|
259
260
|
let ds = compile(&source, &CompileOptions::default()).err().expect("an error");
|
|
260
261
|
assert_eq!(ds.len(), 1);
|
|
261
262
|
assert!(ds[0].message.contains("Float"), "{:?}", ds[0]);
|
|
262
|
-
assert_eq!((ds[0].line, ds[0].column), (
|
|
263
|
+
assert_eq!((ds[0].line, ds[0].column), (5, 5), "{:?}", ds[0]);
|
|
263
264
|
assert!(ds[0].end_line >= 4, "{:?}", ds[0]);
|
|
264
265
|
}
|
|
265
266
|
|
|
266
267
|
/// String and float literal patterns compile (`tests/core/literal_patterns.plum` runs them).
|
|
267
268
|
#[test]
|
|
268
269
|
fn matchStringAndFloatPatternsCompile() {
|
|
269
|
-
let src = "import std/Int\nimport std/Str\nimport std/Float\
|
|
270
|
+
let src = "import std/Int\nimport std/Str\nimport std/Float\nimport std/App\nprimitive Main[App] =\n fun pick(a: Str, x: Float) -> Int =\n match a\n \"x\" => 1\n _ =>\n match x\n 0.5 => 2\n _ => 0\n\n fun main() -> Int =\n Main.pick(\"x\", 0.0) + Main.pick(\"y\", 0.5) * 10\n";
|
|
270
271
|
assert_eq!(plum_test_support::runInt("strfloatpat", src), 21);
|
|
271
272
|
}
|
|
272
273
|
|
|
@@ -277,7 +278,7 @@ fn matchStringAndFloatPatternsCompile() {
|
|
|
277
278
|
// this half stays here.
|
|
278
279
|
#[test]
|
|
279
280
|
fn assertTrapsOnFalse() {
|
|
280
|
-
let src_trap = "
|
|
281
|
+
let src_trap = "import std/App\nprimitive Main[App] =\n fun check(n: Int) -> Int =\n assert n > 0\n n\n\n \
|
|
281
282
|
fun main() -> Int =\n Main.check(-1)\n";
|
|
282
283
|
let source = parse(src_trap);
|
|
283
284
|
let bytes = compileSource(&source).expect("compile failed");
|
|
@@ -303,11 +304,12 @@ fun main() -> Int =\n Main.check(-1)\n";
|
|
|
303
304
|
/// program defines it, so a body left as `todo` no longer compiles (it used to trap).
|
|
304
305
|
#[test]
|
|
305
306
|
fn todoIsAnOrdinaryName() {
|
|
306
|
-
let undefined = "
|
|
307
|
+
let undefined = "import std/App\nprimitive Main[App] =\n fun notDoneYet() -> Int =\n todo\n\n \
|
|
307
308
|
fun main() -> Int =\n Main.notDoneYet()\n";
|
|
308
309
|
let text = compileSource(&parse(undefined)).expect_err("`todo` is undefined");
|
|
309
310
|
assert!(text.contains("undefined name 'todo'"), "{text}");
|
|
310
311
|
let defined = "\
|
|
312
|
+
import std/App
|
|
311
313
|
primitive Main[App] =
|
|
312
314
|
fun main() -> Int =
|
|
313
315
|
todo := 41
|
|
@@ -965,7 +967,7 @@ fn wasmtimeGcConfigSupportsWideningConcreteStructRefToAnyrefAndCastingBack() {
|
|
|
965
967
|
|
|
966
968
|
#[test]
|
|
967
969
|
fn crash_traps_and_calls_import() {
|
|
968
|
-
let bytes = assertValid("
|
|
970
|
+
let bytes = assertValid("import std/App\nprimitive Main[App] =\n fun main() -> Int =\n crash \"boom\"\n");
|
|
969
971
|
let engine = gcEngine();
|
|
970
972
|
let module = wasmtime::Module::new(&engine, &bytes).unwrap();
|
|
971
973
|
assert!(
|
|
@@ -974,7 +976,7 @@ fn crash_traps_and_calls_import() {
|
|
|
974
976
|
.any(|i| i.module() == "plum" && i.name() == "crash"),
|
|
975
977
|
"crash import must be emitted when crash is used"
|
|
976
978
|
);
|
|
977
|
-
let plain = assertValid("
|
|
979
|
+
let plain = assertValid("import std/App\nprimitive Main[App] =\n fun main() -> Int =\n 1\n");
|
|
978
980
|
let plain_module = wasmtime::Module::new(&engine, &plain).unwrap();
|
|
979
981
|
assert!(
|
|
980
982
|
plain_module.imports().all(|i| i.name() != "crash"),
|
|
@@ -984,7 +986,7 @@ fn crash_traps_and_calls_import() {
|
|
|
984
986
|
|
|
985
987
|
#[test]
|
|
986
988
|
fn crash_import_not_triggered_by_string_literal() {
|
|
987
|
-
let src = "
|
|
989
|
+
let src = "import std/App\nprimitive Main[App] =\n fun main() -> Int =\n s := \"x Crash(y) [Crash(\"\n 1\n";
|
|
988
990
|
let bytes = assertValid(src);
|
|
989
991
|
let engine = gcEngine();
|
|
990
992
|
let module = wasmtime::Module::new(&engine, &bytes).unwrap();
|
|
@@ -995,7 +997,7 @@ fn crash_import_not_triggered_by_string_literal() {
|
|
|
995
997
|
/// interpolations, so a postfix `?` inside `"{...}"` hit a missing scratch slot.
|
|
996
998
|
#[test]
|
|
997
999
|
fn question_inside_string_interpolation_compiles() {
|
|
998
|
-
let src = "import std/Str\n\
|
|
1000
|
+
let src = "import std/Str\nimport std/App\n\
|
|
999
1001
|
import std/Int\n\
|
|
1000
1002
|
import std/Float\n\
|
|
1001
1003
|
import std/Result\n\n\
|
|
@@ -1012,7 +1014,7 @@ fn valid_method_chain_inside_string_interpolation_runs() {
|
|
|
1012
1014
|
let src = "\
|
|
1013
1015
|
import std/Str
|
|
1014
1016
|
import std/Int
|
|
1015
|
-
|
|
1017
|
+
import std/App
|
|
1016
1018
|
struct A(n: Int) =
|
|
1017
1019
|
fun c(self) -> B = B(m: self.n + 1)
|
|
1018
1020
|
|
|
@@ -1086,6 +1088,7 @@ import std/Int
|
|
|
1086
1088
|
import std/Float
|
|
1087
1089
|
import std/Slice
|
|
1088
1090
|
import std/collections/List
|
|
1091
|
+
import std/App
|
|
1089
1092
|
";
|
|
1090
1093
|
|
|
1091
1094
|
#[test]
|
|
@@ -1331,7 +1334,7 @@ import std/Int
|
|
|
1331
1334
|
import std/Float
|
|
1332
1335
|
import std/Slice
|
|
1333
1336
|
import std/Option
|
|
1334
|
-
|
|
1337
|
+
import std/App
|
|
1335
1338
|
primitive Main[App] =
|
|
1336
1339
|
fun main() -> Int =
|
|
1337
1340
|
l := Slice<Bool>()
|
|
@@ -1351,7 +1354,7 @@ primitive Main[App] =
|
|
|
1351
1354
|
|
|
1352
1355
|
#[test]
|
|
1353
1356
|
fn boxed_bool_to_str_and_eq() {
|
|
1354
|
-
let src = "import std/Str\n\
|
|
1357
|
+
let src = "import std/Str\nimport std/App\n\
|
|
1355
1358
|
import std/Bool\n\
|
|
1356
1359
|
import std/Int\n\
|
|
1357
1360
|
import std/Float\n\n\
|
|
@@ -1362,7 +1365,7 @@ fun main() -> Int =\n if Main.show(true) == \"true\" && Main.show(false) == \
|
|
|
1362
1365
|
|
|
1363
1366
|
#[test]
|
|
1364
1367
|
fn builtin_bool_in_result_with_question_and_unwrap_or() {
|
|
1365
|
-
let src = "import std/Str\n\
|
|
1368
|
+
let src = "import std/Str\nimport std/App\n\
|
|
1366
1369
|
import std/Bool\n\
|
|
1367
1370
|
import std/Int\n\
|
|
1368
1371
|
import std/Float\n\
|
|
@@ -1382,7 +1385,7 @@ fun main() -> Int =\n a := Main.chain(true).unwrapOr(true)\n b := Main.cha
|
|
|
1382
1385
|
/// import that is `(i32) -> i32`; returns the module plus `main`'s outcome.
|
|
1383
1386
|
fn externEcho(arg: &str) -> (wasmtime::Module, Result<i64, String>) {
|
|
1384
1387
|
let src = format!(
|
|
1385
|
-
"
|
|
1388
|
+
"import std/App\nprimitive Io =\n extern fun echo(self, x: Int) -> Int\n\nprimitive Main[App] =\n fun main(io: Io) -> Int =\n io.echo({})\n",
|
|
1386
1389
|
arg
|
|
1387
1390
|
);
|
|
1388
1391
|
let source = parse(&src);
|
|
@@ -1454,7 +1457,7 @@ fn bool_tostr_without_import_is_rejected() {
|
|
|
1454
1457
|
import std/Int
|
|
1455
1458
|
import std/Float
|
|
1456
1459
|
import std/Str
|
|
1457
|
-
|
|
1460
|
+
import std/App
|
|
1458
1461
|
primitive Main[App] =
|
|
1459
1462
|
fun main() -> Int =
|
|
1460
1463
|
t := true
|
|
@@ -1479,6 +1482,7 @@ fn int_tostr_without_import_is_rejected() {
|
|
|
1479
1482
|
// Unmerged source: nothing from std is loaded, so `Int` has no `toStr`.
|
|
1480
1483
|
// (The loader itself also refuses a file that uses Int without importing it.)
|
|
1481
1484
|
let src = "\
|
|
1485
|
+
import std/App
|
|
1482
1486
|
primitive Main[App] =
|
|
1483
1487
|
fun main() -> Str =
|
|
1484
1488
|
n := 5
|
|
@@ -1557,7 +1561,7 @@ fun main() -> Int =\n intNum := Num(add: |a, b| a + b, zero: 0)\n floatNum
|
|
|
1557
1561
|
const VEC2: &str = "\
|
|
1558
1562
|
import std/Int
|
|
1559
1563
|
import std/Float
|
|
1560
|
-
|
|
1564
|
+
import std/App
|
|
1561
1565
|
struct Vec2(x: Float, y: Float) =
|
|
1562
1566
|
|
|
1563
1567
|
fun add(self, o: Vec2) -> Vec2 =
|
|
@@ -1941,7 +1945,7 @@ fn runWithCrash(name: &str, src: &str) -> (Result<i64, String>, Vec<String>) {
|
|
|
1941
1945
|
|
|
1942
1946
|
#[test]
|
|
1943
1947
|
fn result_in_struct_field() {
|
|
1944
|
-
let src = "import std/Int\n\
|
|
1948
|
+
let src = "import std/Int\nimport std/App\n\
|
|
1945
1949
|
import std/Result\n\n\
|
|
1946
1950
|
enum NegError = Neg | Other\n\n\
|
|
1947
1951
|
struct Box(v: Result<Int, NegError>)\n\n\
|
|
@@ -1953,7 +1957,7 @@ fun main() -> Int =\n a := Box(v: Main.f(6))\n b := Box(v: Main.f(-6))\n
|
|
|
1953
1957
|
#[test]
|
|
1954
1958
|
fn bang_on_none_crashes_with_unwrap_message() {
|
|
1955
1959
|
// `!` on an Option unwraps it and crashes with the std unwrap message.
|
|
1956
|
-
let src = "import std/Str\n\
|
|
1960
|
+
let src = "import std/Str\nimport std/App\n\
|
|
1957
1961
|
import std/Int\n\
|
|
1958
1962
|
import std/Float\n\
|
|
1959
1963
|
import std/Slice\n\n\
|
|
@@ -1967,13 +1971,13 @@ fun main() -> Int =\n Main.first(Slice<Int>())\n";
|
|
|
1967
1971
|
"{}",
|
|
1968
1972
|
msgs[0]
|
|
1969
1973
|
);
|
|
1970
|
-
assert!(msgs[0].contains("main.plum:
|
|
1974
|
+
assert!(msgs[0].contains("main.plum:9:"), "{}", msgs[0]);
|
|
1971
1975
|
}
|
|
1972
1976
|
|
|
1973
1977
|
/// Master 9b8580b (F-final 26): `crash "msg"` names its file, line and column, as `!` does.
|
|
1974
1978
|
#[test]
|
|
1975
1979
|
fn crash_names_its_location() {
|
|
1976
|
-
let src = "import std/Str\n\
|
|
1980
|
+
let src = "import std/Str\nimport std/App\n\
|
|
1977
1981
|
import std/Int\n\n\
|
|
1978
1982
|
primitive Main[App] =\n fun g(n: Int) -> Int =\n if n > 2\n crash \"too big {n}\"\n else\n n\n\n \
|
|
1979
1983
|
fun main() -> Int =\n Main.g(5)\n";
|
|
@@ -1981,7 +1985,7 @@ fun main() -> Int =\n Main.g(5)\n";
|
|
|
1981
1985
|
assert!(r.is_err());
|
|
1982
1986
|
assert_eq!(msgs.len(), 1, "{msgs:?}");
|
|
1983
1987
|
assert!(msgs[0].starts_with("too big 5 at "), "{}", msgs[0]);
|
|
1984
|
-
assert!(msgs[0].ends_with("main.plum:
|
|
1988
|
+
assert!(msgs[0].ends_with("main.plum:8:7"), "{}", msgs[0]);
|
|
1985
1989
|
}
|
|
1986
1990
|
|
|
1987
1991
|
/// `crash "msg"` as a branch of an inline `if` (once a parse error): the other branch gives
|
|
@@ -1990,7 +1994,7 @@ fun main() -> Int =\n Main.g(5)\n";
|
|
|
1990
1994
|
fn inline_if_crash_branch() {
|
|
1991
1995
|
let src = |arg: i64| {
|
|
1992
1996
|
format!(
|
|
1993
|
-
"import std/Str\n\
|
|
1997
|
+
"import std/Str\nimport std/App\n\
|
|
1994
1998
|
import std/Int\n\n\
|
|
1995
1999
|
primitive Main[App] =\n fun pos(n: Int) -> Int =\n if n > 0 then n else crash \"not positive: {{n}}\"\n\n \
|
|
1996
2000
|
fun main() -> Int =\n Main.pos({arg}) + 1\n"
|
|
@@ -2003,7 +2007,7 @@ fun main() -> Int =\n Main.pos({arg}) + 1\n"
|
|
|
2003
2007
|
assert!(r.is_err());
|
|
2004
2008
|
assert_eq!(msgs.len(), 1, "{msgs:?}");
|
|
2005
2009
|
assert!(msgs[0].starts_with("not positive: -3 at "), "{}", msgs[0]);
|
|
2006
|
-
assert!(msgs[0].ends_with("main.plum:
|
|
2010
|
+
assert!(msgs[0].ends_with("main.plum:7:26"), "{}", msgs[0]);
|
|
2007
2011
|
}
|
|
2008
2012
|
|
|
2009
2013
|
/// Master 9b8580b: wasmtime demangled a one-letter name (`g` became `__float128`), so a
|
|
@@ -2012,7 +2016,7 @@ fun main() -> Int =\n Main.pos({arg}) + 1\n"
|
|
|
2012
2016
|
#[test]
|
|
2013
2017
|
fn short_function_names_get_a_prefix() {
|
|
2014
2018
|
// Recursive, so the passes keep the call and `g` is in the module.
|
|
2015
|
-
let src = "import std/Int\
|
|
2019
|
+
let src = "import std/Int\nimport std/App\nprimitive Main[App] =\n fun g(n: Int) -> Int =\n if n == 0 then 1 else g(n - 1) + 1\n\n fun main() -> Int =\n Main.g(5)\n";
|
|
2016
2020
|
let (r, _) = runWithCrash("shortname", src);
|
|
2017
2021
|
assert_eq!(r, Ok(6));
|
|
2018
2022
|
let dir = plum_test_support::Scratch::at(std::env::temp_dir().join(format!("plum_shortname_{}", std::process::id())));
|
|
@@ -2040,7 +2044,7 @@ fn short_function_names_get_a_prefix() {
|
|
|
2040
2044
|
|
|
2041
2045
|
#[test]
|
|
2042
2046
|
fn bang_on_err_names_the_variant_and_location() {
|
|
2043
|
-
let src = "import std/Str\n\
|
|
2047
|
+
let src = "import std/Str\nimport std/App\n\
|
|
2044
2048
|
import std/Int\n\
|
|
2045
2049
|
import std/Result\n\n\
|
|
2046
2050
|
enum Oops =\n | ListWasEmpty\n | Other(code: Int)\n\n\
|
|
@@ -2050,7 +2054,7 @@ fun main() -> Int =\n Main.get(0)!\n";
|
|
|
2050
2054
|
assert!(r.is_err());
|
|
2051
2055
|
assert_eq!(msgs.len(), 1, "{msgs:?}");
|
|
2052
2056
|
assert!(msgs[0].starts_with("unwrap on Err(ListWasEmpty) at "), "{}", msgs[0]);
|
|
2053
|
-
assert!(msgs[0].contains("main.plum:
|
|
2057
|
+
assert!(msgs[0].contains("main.plum:18:"), "{}", msgs[0]);
|
|
2054
2058
|
let (r, msgs) = runWithCrash("bangerr2", &src.replace("Main.get(0)!", "Main.get(3)!"));
|
|
2055
2059
|
assert!(r.is_err());
|
|
2056
2060
|
assert!(msgs[0].starts_with("unwrap on Err(Other) at "), "{}", msgs[0]);
|
|
@@ -2058,7 +2062,7 @@ fun main() -> Int =\n Main.get(0)!\n";
|
|
|
2058
2062
|
|
|
2059
2063
|
#[test]
|
|
2060
2064
|
fn list_of_results_valid_wasm() {
|
|
2061
|
-
let src = "import std/Str\n\
|
|
2065
|
+
let src = "import std/Str\nimport std/App\n\
|
|
2062
2066
|
import std/Int\n\
|
|
2063
2067
|
import std/Float\n\
|
|
2064
2068
|
import std/Slice\n\
|
|
@@ -2127,7 +2131,7 @@ primitive Main[App] =
|
|
|
2127
2131
|
/// array-first struct is `Buffer` itself, when the program uses it.
|
|
2128
2132
|
#[test]
|
|
2129
2133
|
fn strIsAViewOfAPackedByteArray() {
|
|
2130
|
-
let src = "import std/Str\nimport std/Int\nimport std/Float\
|
|
2134
|
+
let src = "import std/Str\nimport std/Int\nimport std/Float\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n \"hello\".length()\n";
|
|
2131
2135
|
let dir = plum_test_support::Scratch::at(std::env::temp_dir().join(format!("plum_strshape_{}", std::process::id())));
|
|
2132
2136
|
let path = dir.join("main.plum");
|
|
2133
2137
|
std::fs::write(&path, src).unwrap();
|
|
@@ -2194,7 +2198,7 @@ import std/Str
|
|
|
2194
2198
|
import std/Int
|
|
2195
2199
|
import std/Float
|
|
2196
2200
|
import std/Array
|
|
2197
|
-
|
|
2201
|
+
import std/App
|
|
2198
2202
|
struct Vec2(x: Float, y: Float)
|
|
2199
2203
|
|
|
2200
2204
|
primitive Main[App] =
|
|
@@ -2322,6 +2326,7 @@ fn exportFuncType(bytes: &[u8], name: &str) -> (Vec<String>, Vec<String>) {
|
|
|
2322
2326
|
#[test]
|
|
2323
2327
|
fn exportFlattensStructsAndNarrowsInt() {
|
|
2324
2328
|
let src = "\
|
|
2329
|
+
import std/App
|
|
2325
2330
|
struct Vc(x: Float, y: Float)
|
|
2326
2331
|
|
|
2327
2332
|
struct Inner(a: Float, b: Int)
|
|
@@ -2440,6 +2445,7 @@ primitive Main[App] =
|
|
|
2440
2445
|
#[test]
|
|
2441
2446
|
fn exportRecordRefRoundTrip() {
|
|
2442
2447
|
let src = "\
|
|
2448
|
+
import std/App
|
|
2443
2449
|
struct Game(mut n: Int)
|
|
2444
2450
|
|
|
2445
2451
|
primitive Main[App] =
|
|
@@ -2519,6 +2525,7 @@ fn strToHost(
|
|
|
2519
2525
|
#[test]
|
|
2520
2526
|
fn strBridgeRoundTrip() {
|
|
2521
2527
|
let src = "\
|
|
2528
|
+
import std/App
|
|
2522
2529
|
primitive Main[App] =
|
|
2523
2530
|
export fun echo(s: Str) -> Str =
|
|
2524
2531
|
s
|
|
@@ -2539,6 +2546,7 @@ primitive Main[App] =
|
|
|
2539
2546
|
#[test]
|
|
2540
2547
|
fn strBridgeOnView() {
|
|
2541
2548
|
let src = "\
|
|
2549
|
+
import std/App
|
|
2542
2550
|
primitive Main[App] =
|
|
2543
2551
|
export fun view() -> Str =
|
|
2544
2552
|
\"hello\".sub(1, 4)
|
|
@@ -2553,6 +2561,7 @@ primitive Main[App] =
|
|
|
2553
2561
|
#[test]
|
|
2554
2562
|
fn exportStillCallableAndMainUnchanged() {
|
|
2555
2563
|
let src = "\
|
|
2564
|
+
import std/App
|
|
2556
2565
|
primitive Main[App] =
|
|
2557
2566
|
export fun twice(n: Int) -> Int =
|
|
2558
2567
|
n * 2
|
|
@@ -2569,6 +2578,7 @@ primitive Main[App] =
|
|
|
2569
2578
|
#[test]
|
|
2570
2579
|
fn underscoreDiscardStillRunsTheCall() {
|
|
2571
2580
|
let src = "\
|
|
2581
|
+
import std/App
|
|
2572
2582
|
struct Counter(mut n: Int) =
|
|
2573
2583
|
fun next(self) -> Int =
|
|
2574
2584
|
self.n = self.n + 1
|
|
@@ -2592,7 +2602,7 @@ fn memRoundTripsAndGrows() {
|
|
|
2592
2602
|
let src = "\
|
|
2593
2603
|
import std/Int
|
|
2594
2604
|
import std/Float
|
|
2595
|
-
|
|
2605
|
+
import std/App
|
|
2596
2606
|
primitive Main[App] =
|
|
2597
2607
|
fun main() -> Int =
|
|
2598
2608
|
@memStoreI32(8, -7)
|
|
@@ -2613,7 +2623,7 @@ primitive Main[App] =
|
|
|
2613
2623
|
fn memOutOfBoundsTraps() {
|
|
2614
2624
|
let src = "\
|
|
2615
2625
|
import std/Int
|
|
2616
|
-
|
|
2626
|
+
import std/App
|
|
2617
2627
|
primitive Main[App] =
|
|
2618
2628
|
fun main() -> Int =
|
|
2619
2629
|
@memLoadI32(16 * 65536)
|
|
@@ -2640,12 +2650,12 @@ primitive Main[App] =
|
|
|
2640
2650
|
fn memoryExportedOnlyWhenMemUsed() {
|
|
2641
2651
|
let with = "\
|
|
2642
2652
|
import std/Int
|
|
2643
|
-
|
|
2653
|
+
import std/App
|
|
2644
2654
|
primitive Main[App] =
|
|
2645
2655
|
fun main() -> Int =
|
|
2646
2656
|
@memSize()
|
|
2647
2657
|
";
|
|
2648
|
-
let without = "import std/Int\
|
|
2658
|
+
let without = "import std/Int\nimport std/App\nprimitive Main[App] =\n fun main() -> Int =\n 1\n";
|
|
2649
2659
|
let exportsMemory = |name: &str, src: &str| {
|
|
2650
2660
|
let (bytes, _) = compiledKeys(name, src);
|
|
2651
2661
|
let mut mem = false;
|
compiler/wasm-codegen/tests/wasm_codegen/dispatch_test.rs
CHANGED
|
@@ -72,7 +72,7 @@ fn runInt(wasm: &[u8]) -> i64 {
|
|
|
72
72
|
main.call(&mut store, ()).unwrap()
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
const PRE: &str = "import std/Str\nimport std/Int\nimport std/collections/List\nimport std/Slice\nimport std/Option\
|
|
75
|
+
const PRE: &str = "import std/Str\nimport std/Int\nimport std/collections/List\nimport std/Slice\nimport std/Option\nimport std/App\n";
|
|
76
76
|
|
|
77
77
|
/// A trait with `n` struct implementers `S0..`, each `val` adding `i + 1`, and a generic one.
|
|
78
78
|
fn many(n: usize) -> String {
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_records/enum_init.rs
CHANGED
|
@@ -5,7 +5,8 @@ fn prog(body: &str) -> String {
|
|
|
5
5
|
|
|
6
6
|
#[test]
|
|
7
7
|
fn no_init_error_message() {
|
|
8
|
-
let src = prog("
|
|
8
|
+
let src = prog("import std/App
|
|
9
|
+
enum Shape =
|
|
9
10
|
| Dot
|
|
10
11
|
| Sq(side: Int)
|
|
11
12
|
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_records/inline_variants.rs
CHANGED
|
@@ -6,7 +6,7 @@ fn union_enum_is_an_error() {
|
|
|
6
6
|
let src = "\
|
|
7
7
|
import std/Str
|
|
8
8
|
import std/Int
|
|
9
|
-
|
|
9
|
+
import std/App
|
|
10
10
|
struct Circle(r: Int)
|
|
11
11
|
enum Shape = Circle | Dot
|
|
12
12
|
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_records/unboxed_variants.rs
CHANGED
|
@@ -44,7 +44,7 @@ const HEAD: &str = "\
|
|
|
44
44
|
import std/Str
|
|
45
45
|
import std/Int
|
|
46
46
|
import std/Float
|
|
47
|
-
|
|
47
|
+
import std/App
|
|
48
48
|
";
|
|
49
49
|
|
|
50
50
|
#[test]
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_tail/closure_tail.rs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
use plum_test_support::{compile};
|
|
2
2
|
|
|
3
|
-
const HEAD: &str = "import std/Int\
|
|
3
|
+
const HEAD: &str = "import std/Int\nimport std/App\n";
|
|
4
4
|
|
|
5
5
|
#[test]
|
|
6
6
|
fn wasm_closure_has_return_call() {
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_types/io_entry.rs
CHANGED
|
@@ -15,7 +15,7 @@ fn instantiate(engine: &wasmtime::Engine, module: &wasmtime::Module) -> (wasmtim
|
|
|
15
15
|
(store, instance)
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
const PRE_IO: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/Io\nimport std/game/Gfx\
|
|
18
|
+
const PRE_IO: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/Io\nimport std/game/Gfx\nimport std/App\n";
|
|
19
19
|
|
|
20
20
|
#[test]
|
|
21
21
|
fn entry_point_receives_io() {
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_types/question.rs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//! Postfix `?` and `!` on the std Option / Result enums, end to end.
|
|
2
2
|
use plum_test_support::*;
|
|
3
3
|
|
|
4
|
-
const HEAD: &str = "import std/Int\nimport std/Option\nimport std/Result\
|
|
4
|
+
const HEAD: &str = "import std/Int\nimport std/Option\nimport std/Result\nimport std/App\nstruct Pt(first: Int, second: Int)\n\n";
|
|
5
5
|
|
|
6
6
|
fn prog(body: &str) -> String {
|
|
7
7
|
format!("{HEAD}{body}")
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_types/type_param_static.rs
CHANGED
|
@@ -2,7 +2,7 @@ use plum_test_support::*;
|
|
|
2
2
|
|
|
3
3
|
#[test]
|
|
4
4
|
fn static_missing_reports() {
|
|
5
|
-
let src = "import std/Int\
|
|
5
|
+
let src = "import std/Int\nimport std/App\n\
|
|
6
6
|
struct Pt(x: Int) =\n fun other(n: Int) -> Pt = Pt(x: n)\n\n\
|
|
7
7
|
primitive Main[App] =\n fun build<T>(n: Int) -> T = T.make(n)\n\n \
|
|
8
8
|
fun main() -> Int =\n p: Pt := Main.build(3)\n p.x\n";
|
|
@@ -18,7 +18,7 @@ fn extension_outside_std_is_rejected() {
|
|
|
18
18
|
let src = "\
|
|
19
19
|
import std/Slice
|
|
20
20
|
import std/Int
|
|
21
|
-
|
|
21
|
+
import std/App
|
|
22
22
|
primitive Slice<T> =
|
|
23
23
|
fun extra(self) -> Int = 1
|
|
24
24
|
|
|
@@ -41,7 +41,7 @@ fn json_extension_needs_the_import() {
|
|
|
41
41
|
let src = "\
|
|
42
42
|
import std/Int
|
|
43
43
|
import std/Str
|
|
44
|
-
|
|
44
|
+
import std/App
|
|
45
45
|
primitive Main[App] =
|
|
46
46
|
fun main() -> Int =
|
|
47
47
|
j := 4.toJson()
|
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs
CHANGED
|
@@ -110,7 +110,7 @@ fn say(line: String) {
|
|
|
110
110
|
eprintln!("{line}");
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
-
const PRE: &str = "import std/Str\nimport std/Int\nimport std/collections/List\nimport std/Slice\
|
|
113
|
+
const PRE: &str = "import std/Str\nimport std/Int\nimport std/collections/List\nimport std/Slice\nimport std/App\n";
|
|
114
114
|
|
|
115
115
|
/// The fusion notes for `source` (what `--explain-fusion` prints): the stage is run
|
|
116
116
|
/// by hand on the checker's lowered program, built without fusion.
|
compiler/wasm-codegen/tests/wasm_codegen/literals_test.rs
CHANGED
|
@@ -15,7 +15,7 @@ fn segments(bytes: &[u8]) -> Vec<Vec<u8>> {
|
|
|
15
15
|
out
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
const REPEATED: &str = "import std/Int\n\
|
|
18
|
+
const REPEATED: &str = "import std/Int\nimport std/App\n\
|
|
19
19
|
import std/Str\n\n\
|
|
20
20
|
primitive Repeated =\n fun tag(n: Int) -> Str =\n if n == 0 then \"same text\" else if n == 1 then \"same text\" else \"other\"\n\nprimitive Main[App] =\n \
|
|
21
21
|
fun main() -> Str =\n \"{Repeated.tag(0)}{Repeated.tag(1)}same text{Repeated.tag(2)}\"\n";
|
|
@@ -52,10 +52,10 @@ fn names(bytes: &[u8]) -> Vec<String> {
|
|
|
52
52
|
/// Three or more parts build one buffer with `strJoin`; two parts call `Str.concat`.
|
|
53
53
|
#[test]
|
|
54
54
|
fn longInterpolationJoinsOnce() {
|
|
55
|
-
let long = "import std/Int\nimport std/Str\
|
|
55
|
+
let long = "import std/Int\nimport std/Str\nimport std/App\nprimitive Main[App] =\n fun show(a: Str, n: Int) -> Str =\n \"<{a}:{n}>\"\n\n fun main() -> Str =\n Main.show(\"k\", 42)\n";
|
|
56
56
|
assert!(names(&compile("join3", long)).iter().any(|n| n == "strJoin"));
|
|
57
57
|
assert_eq!(runStr("join3", long), "<k:42>");
|
|
58
|
-
let short = "import std/Int\nimport std/Str\
|
|
58
|
+
let short = "import std/Int\nimport std/Str\nimport std/App\nprimitive Main[App] =\n fun show(a: Str) -> Str =\n \"<{a}\"\n\n fun main() -> Str =\n Main.show(\"k\")\n";
|
|
59
59
|
assert!(!names(&compile("join2", short)).iter().any(|n| n == "strJoin"));
|
|
60
60
|
assert_eq!(runStr("join2", short), "<k");
|
|
61
61
|
}
|
compiler/wasm-codegen/tests/wasm_codegen/names_test.rs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
use plum_test_support::compile;
|
|
4
4
|
|
|
5
|
-
const POINT: &str = "import std/Int\n\
|
|
5
|
+
const POINT: &str = "import std/Int\nimport std/App\n\
|
|
6
6
|
import std/Str\n\n\
|
|
7
7
|
struct Point(x: Int, y: Int, label: Str)\n\n\
|
|
8
8
|
primitive PointFns =\n fun total(p: Point, n: Int) -> Int =\n if n == 0 then p.x + p.y else total(p, n - 1)\n\nprimitive Main[App] =\n \
|
compiler/wasm-codegen/tests/wasm_codegen/native_test.rs
CHANGED
|
@@ -78,7 +78,7 @@ fn runInt(wasm: &[u8]) -> i64 {
|
|
|
78
78
|
const SRC: &str = "import std/Int
|
|
79
79
|
import std/Float
|
|
80
80
|
import std/math/Math
|
|
81
|
-
|
|
81
|
+
import std/App
|
|
82
82
|
primitive Src =
|
|
83
83
|
fun calc(x: Float, y: Float) -> Float =
|
|
84
84
|
Math.sqrt(x) + y.sqrt() + {-x}.abs() + x.floor() + y.ceil() + {-y}.trunc()
|
|
@@ -124,7 +124,7 @@ fn native_ops_compile_in_line() {
|
|
|
124
124
|
const BITS_SRC: &str = "import std/Int
|
|
125
125
|
import std/Float
|
|
126
126
|
import std/math/Math
|
|
127
|
-
|
|
127
|
+
import std/App
|
|
128
128
|
primitive BitsSrc =
|
|
129
129
|
fun bitsOf(x: Float) -> Int =
|
|
130
130
|
x.toBits()
|
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs
CHANGED
|
@@ -41,7 +41,7 @@ fn body<'a>(all: &'a [(String, Vec<String>)], name: &str) -> &'a [String] {
|
|
|
41
41
|
&all.iter().find(|(n, _)| n == name).unwrap_or_else(|| panic!("no function {name}: {:?}", all.iter().map(|b| &b.0).collect::<Vec<_>>())).1
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
const POINT: &str = "import std/Int\n\
|
|
44
|
+
const POINT: &str = "import std/Int\nimport std/App\n\
|
|
45
45
|
import std/Str\n\n\
|
|
46
46
|
struct Point(x: Int, y: Int, label: Str)\n\n\
|
|
47
47
|
primitive PointFns =\n fun total(p: Point, n: Int) -> Int =\n if n == 0 then p.x + p.y else total(p, n - 1)\n\nprimitive Main[App] =\n \
|
|
@@ -61,7 +61,7 @@ fn fieldOfAStructParameterIsNotCast() {
|
|
|
61
61
|
/// A downcast to an enum variant is a real check and stays.
|
|
62
62
|
#[test]
|
|
63
63
|
fn variantDowncastStays() {
|
|
64
|
-
let src = "import std/Int\
|
|
64
|
+
let src = "import std/Int\nimport std/App\n\
|
|
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";
|
|
@@ -75,7 +75,7 @@ fun main() -> Int =\n Main.areaOf(Rect(w: 2, h: 5)) + Main.areaOf(Circle(r: 1
|
|
|
75
75
|
/// a call reaches are, renumbered, and still run.
|
|
76
76
|
#[test]
|
|
77
77
|
fn unreachableFunctionsAreDropped() {
|
|
78
|
-
let src = "import std/Int\
|
|
78
|
+
let src = "import std/Int\nimport std/App\n\
|
|
79
79
|
primitive Main[App] =\n fun neverCalled(n: Int) -> Int =\n n * 1000\n\n fun twice(f: fn(Int) -> Int, n: Int) -> Int =\n f(f(n))\n\n fun bump(n: Int) -> Int =\n n + 1\n\n \
|
|
80
80
|
fun main() -> Int =\n k := 10\n Main.twice(|n| n + k, 1) + Main.twice(Main.bump, 0)\n";
|
|
81
81
|
let all = bodies(&compile("deadfns", src));
|
|
@@ -110,7 +110,7 @@ fn functionTypesAreDeclaredOnce() {
|
|
|
110
110
|
/// is copied into its callers, and with no call left it is not in the module.
|
|
111
111
|
#[test]
|
|
112
112
|
fn tinyAccessorIsInlined() {
|
|
113
|
-
let src = "import std/Int\n\
|
|
113
|
+
let src = "import std/Int\nimport std/App\n\
|
|
114
114
|
import std/Str\n\n\
|
|
115
115
|
primitive Main[App] =\n fun count(s: Str, n: Int) -> Int =\n if n == 0 then s.length() else count(s, n - 1) + s.length()\n\n \
|
|
116
116
|
fun main() -> Int =\n Main.count(\"hello\", 2)\n";
|
|
@@ -126,7 +126,7 @@ fun main() -> Int =\n Main.count(\"hello\", 2)\n";
|
|
|
126
126
|
/// small enough to be copied into `main` too; the second round copies the comparisons it held.
|
|
127
127
|
#[test]
|
|
128
128
|
fn compareIsCopiedIntoItsCallers() {
|
|
129
|
-
let src = "import std/Int\
|
|
129
|
+
let src = "import std/Int\nimport std/App\n\
|
|
130
130
|
primitive Main[App] =\n fun rank(a: Int, b: Int) -> Int = a.compare(b) * 10 + b.compare(a)\n\n \
|
|
131
131
|
fun main() -> Int =\n Main.rank(1, 2) * 100 + Main.rank(3, 3) * 10 + Main.rank(9, -9)\n";
|
|
132
132
|
let all = bodies(&compile("cmp", src));
|
|
@@ -145,7 +145,7 @@ fun main() -> Int =\n Main.rank(1, 2) * 100 + Main.rank(3, 3) * 10 + Main.ran
|
|
|
145
145
|
/// either.
|
|
146
146
|
#[test]
|
|
147
147
|
fn staticCompilesLikeAFreeFn() {
|
|
148
|
-
let src = "import std/Int\n\
|
|
148
|
+
let src = "import std/Int\nimport std/App\n\
|
|
149
149
|
import std/Str\n\n\
|
|
150
150
|
struct Tool(x: Int) =\n fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =\n if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + digit(ds, i))\n\n fun digit(ds: Str, i: Int) -> Int = ds.byteAtUnchecked(i) - 48\n\n\
|
|
151
151
|
struct Pair2(a: Int, b: Int, c: Str) =\n fun twice(n: Int) -> Int = if n > 100 then n else Pair2.twice(n * 2)\n\n\
|
|
@@ -169,7 +169,7 @@ fn aStaticIsAFunctionValue() {
|
|
|
169
169
|
let src = "\
|
|
170
170
|
import std/Int
|
|
171
171
|
import std/collections/List
|
|
172
|
-
|
|
172
|
+
import std/App
|
|
173
173
|
primitive Rec =
|
|
174
174
|
fun call(f: fn(Int) -> Int, n: Int) -> Int = f(n)
|
|
175
175
|
|
|
@@ -189,7 +189,7 @@ primitive Main[App] =
|
|
|
189
189
|
/// A fn's closures get distinct names: `f.closure`, `f.closure2`.
|
|
190
190
|
#[test]
|
|
191
191
|
fn closuresOfOneFnHaveDistinctNames() {
|
|
192
|
-
let src = "import std/Int\
|
|
192
|
+
let src = "import std/Int\nimport std/App\n\
|
|
193
193
|
struct Ops(f: fn(Int) -> Int, g: fn(Int) -> Int)\n\n\
|
|
194
194
|
primitive Main[App] =\n fun run(o: Ops, n: Int) -> Int =\n if n > 1000 then n else o.f(o.g(n))\n\n \
|
|
195
195
|
fun main() -> Int =\n a := 3\n b := 5\n Main.run(Ops(f: |n| n + a, g: |n| n * b), 1)\n";
|
docs/backlog.md
CHANGED
|
@@ -7,7 +7,7 @@ Open work on `simpler-language`, rewritten 2026-11-11. Only what is still open i
|
|
|
7
7
|
The retained scene tree was replaced by master's screen view in functional form: a `Game(screens: ..)` of `Screen`s, a `ScreenSlice<A>` per screen with rules (master's `Slice<A>`), a `view` each frame that the game draws and hit-tests itself, `Control` for effects, undo and time travel by re-simulation, and the headless kit (`docs/game.md`, "Beside master", has the table of differences). `SceneTree`, `Ctx`, `Clickable`, `Store` and `ui` are gone, with the examples that used them (`orb_run`, `kids/balloon_pop`, now `examples/games/orbitrunner` and `balloonpop`), `benchmarks/scene_trees` and two web-test stress fixtures (their results stay in `docs/benchmarks` and `compiler/game/web-test/BENCHMARK.md`). Orbit Runner's state checksum over four seeds of 3,600 ticks is master's (925878360). On 2026-11-13 it was brought up to master at e91c40ce (stages 24 and 25 and the review after 24): `View` and `Actor[View]`, actors stepped by the game through the screen's `stepped(dt)`, `Screen.hud`, `steps` and `camera`, one walk over `view`, turned boxes and text, the other mouse buttons and keys, the per-screen backgrounds and dropped pointer events of a transition (the "Beside master" table has what still differs). Open:
|
|
8
8
|
|
|
9
9
|
- **A `match` on a nullary variant inside a closure in a function body matches every value.** `xs.fold(0, |s, e| match e` with an arm `B => s + 1` counts every element; the same match in a named function, or in a closure in a test, is right, and a variant with fields (`A(n) =>`) is right. std/game works around it (the matches are in methods: `Game.travelled`, `Game.redone`). Repro: `fun count(xs: List<E>) -> Int = xs.fold(0, |s, e| match e` / `B => s + 1` / `_ => s)` with `enum E = A(n: Int) | B | C`, `count([C])` gives 1.
|
|
10
|
-
- **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead);
|
|
10
|
+
- **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); dead-code removal is reverted when it removes every type a downcast to a trait could match (it met `Container as c`, which master has since folded into `view` too).
|
|
11
11
|
- **Frames on demand in the hosts**: `Game.idle()` works, but no host is told (master's `frameIdle` extern, and the browser skipping the draw and waiting for input).
|
|
12
12
|
- **Development keys** (`plum run --dev`, master's `remakeGame` host call): a game offers undo only through its own effects.
|
|
13
13
|
- **Master's other games** (`clockwork`, `menu`) are not ported.
|
docs/game.md
CHANGED
|
@@ -88,24 +88,21 @@ A screen's `view(self) -> List<View>` is what the frame shows: a list of views,
|
|
|
88
88
|
|
|
89
89
|
```plum
|
|
90
90
|
fun view(self) -> List<View> =
|
|
91
|
-
back
|
|
91
|
+
back := [Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16))]
|
|
92
|
-
mines := Views.all(self.mines)
|
|
93
|
-
orbs := Views.all(self.orbs)
|
|
94
|
-
ship
|
|
92
|
+
ship := if self.over then Nil else [self.ship]
|
|
95
|
-
rings := Views.all(self.rings)
|
|
96
|
-
hud
|
|
93
|
+
hud := [
|
|
97
94
|
Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
|
|
98
95
|
Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow)]
|
|
99
|
-
over
|
|
96
|
+
over := if self.over
|
|
100
97
|
[Overlay.of(Arena.W, Arena.H, [
|
|
101
98
|
Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
|
|
102
99
|
Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
|
|
103
100
|
else
|
|
104
101
|
Nil
|
|
105
|
-
back.append(starsFrom(0, self.clock)).append(mines).append(orbs).append(ship).append(rings).append(hud).append(lifeIcons(0, self.lives, self.assets.sheet)).append(over)
|
|
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)
|
|
106
103
|
```
|
|
107
104
|
|
|
108
|
-
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,
|
|
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.)
|
|
109
106
|
|
|
110
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.
|
|
111
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.
|
|
@@ -467,7 +464,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
|
|
|
467
464
|
| `timeTravel(make: fn(Io) -> Game, cap)` | `timeTravel(cap) -> Game` | the game keeps the screens it was made with |
|
|
468
465
|
| `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
|
|
469
466
|
| the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
|
|
470
|
-
| a view literal's `if`, `for`, `..` elements | `append`, `map`, functions
|
|
467
|
+
| a view literal's `if`, `for`, `..` elements | `append`, `map`, functions | not in this dialect's list literals |
|
|
471
468
|
| std's test helper types private (`_ViewProbe`, `_KitScreen`, ..) | public names (`ViewProbe`, `Stepper`, ..) | a type's name here is the module's: a game's own `Stepper` beside std's compiles, so there is no clash to avoid (checked with a probe) |
|
|
472
469
|
| `std/game` without `Anim` | `std/game/Anim` kept (pure animations of time) | a web-test fixture uses it; no example game does |
|
|
473
470
|
|
docs/language.md
CHANGED
|
@@ -29,6 +29,7 @@ A Plum function is a tree of expressions. There is no `return`, `break` or `cont
|
|
|
29
29
|
```plum
|
|
30
30
|
import std/Io
|
|
31
31
|
import std/Str
|
|
32
|
+
import std/App
|
|
32
33
|
|
|
33
34
|
primitive Hello[App] =
|
|
34
35
|
fun main(io: Io) =
|
|
@@ -39,7 +40,7 @@ primitive Hello[App] =
|
|
|
39
40
|
plum run hello.plum
|
|
40
41
|
```
|
|
41
42
|
|
|
42
|
-
A program starts at the `main` of the `primitive` named after it that lists `App` (std/App,
|
|
43
|
+
A program starts at the `main` of the `primitive` named after it that lists `App` (std/App's marker trait, imported like any module: `import std/App`): `primitive Hello[App]`. A program has one; its other funs are ordinary statics, and nothing else is global.
|
|
43
44
|
|
|
44
45
|
## Basics
|
|
45
46
|
|
|
@@ -373,6 +374,7 @@ A good habit is one error enum per module. Use `?` and `mapErr` for failures you
|
|
|
373
374
|
import std/Int
|
|
374
375
|
import std/collections/List
|
|
375
376
|
import std/Slice
|
|
377
|
+
import std/App
|
|
376
378
|
|
|
377
379
|
primitive Demo[App] =
|
|
378
380
|
fun main() =
|
|
@@ -400,6 +402,7 @@ import std/Str
|
|
|
400
402
|
import std/collections/List
|
|
401
403
|
import std/collections/Map
|
|
402
404
|
import std/Slice
|
|
405
|
+
import std/App
|
|
403
406
|
|
|
404
407
|
struct Tally(mut n: Int)
|
|
405
408
|
|
|
@@ -747,7 +750,42 @@ Each use is checked to meet the bound. Generics are compiled per type, so a call
|
|
|
747
750
|
|
|
748
751
|
### Coercion
|
|
749
752
|
|
|
750
|
-
A value of an implementing type becomes a trait object, with no cast, where one is expected
|
|
753
|
+
A value of an implementing type becomes a trait object, with no cast, where one is expected: an argument, an annotated local, a field, a list element, a returned value.
|
|
754
|
+
|
|
755
|
+
`List` and `Option` are covariant: a `List<Rect>` is a `List<Shape>` wherever one is expected, and an `Option<Rect>` an `Option<Shape>`, nested too (`List<List<Rect>>`). Each instance is stored as its own type, so the value is rebuilt there: a loop over the list, the work `rects.map(|r| r)` does. A list that is already a `List<Shape>` costs nothing. Nothing else is covariant: a `Slice` or an `Array` is written in place (a `Slice<Rect>` taken as a `Slice<Shape>` could be given a `Circle`), a `fn(List<Rect>) -> Int` is not a `fn(List<Shape>) -> Int`, and a generic body's `List<T>` is not a `List<Shape>`, since its one code serves every `T`.
|
|
756
|
+
|
|
757
|
+
So a value needs no annotation where its type is known:
|
|
758
|
+
|
|
759
|
+
```plum
|
|
760
|
+
import std/Int
|
|
761
|
+
import std/Bool
|
|
762
|
+
import std/collections/List
|
|
763
|
+
import std/App
|
|
764
|
+
|
|
765
|
+
trait Shape =
|
|
766
|
+
fun area(self) -> Int
|
|
767
|
+
|
|
768
|
+
struct Rect[Shape](w: Int, h: Int) =
|
|
769
|
+
fun area(self) -> Int = self.w * self.h
|
|
770
|
+
|
|
771
|
+
struct Dot[Shape](r: Int) =
|
|
772
|
+
fun area(self) -> Int = self.r
|
|
773
|
+
|
|
774
|
+
primitive Demo[App] =
|
|
775
|
+
fun total(xs: List<Shape>) -> Int = xs.fold(0, |n, x| n + x.area())
|
|
776
|
+
|
|
777
|
+
fun all(rects: List<Rect>, big: Bool) -> List<Shape> =
|
|
778
|
+
mixed := [Rect(w: 1, h: 2), Dot(r: 3)]
|
|
779
|
+
dot := if big then Nil else [Dot(r: 1)]
|
|
780
|
+
rects.append(mixed).append(dot)
|
|
781
|
+
|
|
782
|
+
fun main() -> Int = Demo.total(Demo.all([Rect(w: 2, h: 2)], false))
|
|
783
|
+
```
|
|
784
|
+
|
|
785
|
+
- **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
|
+
- **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>`.
|
|
788
|
+
- **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.
|
|
751
789
|
|
|
752
790
|
### Errors
|
|
753
791
|
|
|
@@ -758,7 +796,7 @@ A value of an implementing type becomes a trait object, with no cast, where one
|
|
|
758
796
|
- a value used as a trait it doesn't implement, or a downcast to a type that doesn't implement it, or to a trait no type shares with it;
|
|
759
797
|
- a supertrait that isn't a trait or has the wrong number of arguments, a trait that extends itself, or a subtrait that declares its supertrait's method again other than as a default with the same signature;
|
|
760
798
|
- a bound not met at a use, naming the missing trait;
|
|
761
|
-
- a method whose `Self` inside a parameter
|
|
799
|
+
- a method whose `Self` inside a parameter can't be checked with the trait object there (a `List<Self>` parameter is a `List<Shape>` there, whose items are no `Rect`s).
|
|
762
800
|
|
|
763
801
|
## Built-ins
|
|
764
802
|
|
|
@@ -838,6 +876,7 @@ primitive Shapes =
|
|
|
838
876
|
# main.plum
|
|
839
877
|
import std/Int
|
|
840
878
|
import geo/shapes
|
|
879
|
+
import std/App
|
|
841
880
|
|
|
842
881
|
primitive Demo[App] =
|
|
843
882
|
fun main() -> Int =
|
|
@@ -892,6 +931,7 @@ Everything that leaves your program goes through an `Io` value: printing, files,
|
|
|
892
931
|
import std/Io
|
|
893
932
|
import std/Str
|
|
894
933
|
import std/Os
|
|
934
|
+
import std/App
|
|
895
935
|
|
|
896
936
|
primitive Demo[App] =
|
|
897
937
|
fun main(io: Io) =
|
docs/std.md
CHANGED
|
@@ -27,6 +27,7 @@ import std/Int
|
|
|
27
27
|
import std/Float
|
|
28
28
|
import std/Str
|
|
29
29
|
import std/math/Math
|
|
30
|
+
import std/App
|
|
30
31
|
|
|
31
32
|
primitive Demo[App] =
|
|
32
33
|
fun main() =
|
|
@@ -56,6 +57,7 @@ A `Str` can't be changed. Taking part of one shares the original's memory rather
|
|
|
56
57
|
```plum
|
|
57
58
|
import std/Int
|
|
58
59
|
import std/Str
|
|
60
|
+
import std/App
|
|
59
61
|
|
|
60
62
|
primitive Demo[App] =
|
|
61
63
|
fun main() =
|
|
@@ -87,6 +89,7 @@ Across std, positional access follows one rule: `at` gives the element and crash
|
|
|
87
89
|
import std/Int
|
|
88
90
|
import std/collections/List
|
|
89
91
|
import std/Slice
|
|
92
|
+
import std/App
|
|
90
93
|
|
|
91
94
|
primitive Demo[App] =
|
|
92
95
|
fun main() =
|
|
@@ -111,6 +114,7 @@ Renamed or removed: `Slice.head` (use `first`), `Set.toList` is now `toSlice`, `
|
|
|
111
114
|
import std/Int
|
|
112
115
|
import std/Str
|
|
113
116
|
import std/collections/Map
|
|
117
|
+
import std/App
|
|
114
118
|
|
|
115
119
|
primitive Demo[App] =
|
|
116
120
|
fun main() =
|
|
@@ -177,6 +181,7 @@ import std/Int
|
|
|
177
181
|
import std/Str
|
|
178
182
|
import std/collections/Map
|
|
179
183
|
import std/encoding/Json
|
|
184
|
+
import std/App
|
|
180
185
|
|
|
181
186
|
struct Point(x: Int, y: Int) =
|
|
182
187
|
fun toJson(self) -> Json =
|
|
@@ -209,6 +214,7 @@ import std/Float
|
|
|
209
214
|
import std/Str
|
|
210
215
|
import std/Option
|
|
211
216
|
import std/Decimal
|
|
217
|
+
import std/App
|
|
212
218
|
|
|
213
219
|
primitive Demo[App] =
|
|
214
220
|
fun main() =
|
|
@@ -234,6 +240,7 @@ import std/Io
|
|
|
234
240
|
import std/Str
|
|
235
241
|
import std/Os
|
|
236
242
|
import std/Http
|
|
243
|
+
import std/App
|
|
237
244
|
|
|
238
245
|
primitive Demo[App] =
|
|
239
246
|
fun main(io: Io) =
|
examples/basics.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/collections/List
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/Io
|
|
7
|
+
import std/App
|
|
7
8
|
|
|
8
9
|
primitive Basics[App] =
|
|
9
10
|
# ==== basics ====
|
examples/closures.plum
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import std/Str
|
|
4
4
|
import std/Int
|
|
5
5
|
import std/Float
|
|
6
|
+
import std/App
|
|
6
7
|
|
|
7
8
|
primitive Closures[App] =
|
|
8
9
|
fun each(cb: fn(Int) -> Int) -> Int =
|
examples/games/balloonpop/BalloonPop.plum
CHANGED
|
@@ -10,6 +10,7 @@ import std/game/Audio
|
|
|
10
10
|
import std/game/Screen
|
|
11
11
|
import std/game/History
|
|
12
12
|
import std/game/Game
|
|
13
|
+
import std/App
|
|
13
14
|
import screens/PlaygroundScreen
|
|
14
15
|
|
|
15
16
|
struct Arena =
|
examples/games/balloonpop/actors/Balloon.plum
CHANGED
|
@@ -78,7 +78,7 @@ struct Balloon[Actor, Sized, Touch](id: Int, x: Float, y: Float, speed: Float, h
|
|
|
78
78
|
t := {{self.clock - self.poppedAt} / Balloon.PopTime}.min(1.0)
|
|
79
79
|
fade := 1.0 - t
|
|
80
80
|
reach := 20.0 + 70.0 * t
|
|
81
|
-
title
|
|
81
|
+
title := Label.of(0.0, 0.0 - 20.0 - 60.0 * t, "{hue.name}!", 40.0, Color.rgb(0.15, 0.15, 0.3).withAlpha(fade), Centre)
|
|
82
82
|
Cons(title, burst(0, reach, hue.color.withAlpha(fade)))
|
|
83
83
|
|
|
84
84
|
fun paintSelf(self, io: Io, m: Affine, alpha: Float) =
|
examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -57,7 +57,7 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
|
|
|
57
57
|
|
|
58
58
|
fun background(self) -> Color = Color.rgb(0.55, 0.8, 1.0)
|
|
59
59
|
|
|
60
|
-
fun view(self) -> List<View> = sky(self.clock).append(
|
|
60
|
+
fun view(self) -> List<View> = sky(self.clock).append(self.balloons).append(self.party())
|
|
61
61
|
|
|
62
62
|
fun hud(self, window: Vec2) -> List<View> = [
|
|
63
63
|
Box.of(16.0, 14.0, 170.0, 56.0, Color.White.withAlpha(0.7)),
|
|
@@ -122,7 +122,7 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
|
|
|
122
122
|
age := self.clock - self.partyAt
|
|
123
123
|
k := partyScale(age)
|
|
124
124
|
cx := Arena.W / 2.0
|
|
125
|
-
titles
|
|
125
|
+
titles := [
|
|
126
126
|
Label.of(cx, 250.0 - 40.0 * k, "Hooray!", 72.0 * k, Color.rgb(0.95, 0.3, 0.5), Centre),
|
|
127
127
|
Label.of(cx, 250.0 + 40.0 * k, "{self.pops} balloons!", 40.0 * k, Color.rgb(0.15, 0.15, 0.3), Centre)]
|
|
128
128
|
confettiFrom(0, age).append(titles)
|
|
@@ -145,11 +145,11 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
|
|
|
145
145
|
Cons(Box.of(x + wob, y, 12.0, 12.0, Hue.of(i).color), confettiFrom(i + 1, age))
|
|
146
146
|
|
|
147
147
|
fun sky(clock: Float) -> List<View> =
|
|
148
|
-
back
|
|
148
|
+
back := [
|
|
149
149
|
Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.55, 0.8, 1.0)),
|
|
150
150
|
Box.of(0.0, 0.0, Arena.W, 200.0, Color.rgb(0.45, 0.72, 0.98)),
|
|
151
151
|
Circle.of(690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35))]
|
|
152
|
-
grass
|
|
152
|
+
grass := [Box.of(0.0, Arena.H - 50.0, Arena.W, 50.0, Color.rgb(0.4, 0.78, 0.35))]
|
|
153
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
154
|
|
|
155
155
|
fun wrapX(x: Float) -> Float =
|
examples/games/clicks.plum
CHANGED
|
@@ -19,6 +19,7 @@ import std/game/Screen
|
|
|
19
19
|
import std/game/ScreenSlice
|
|
20
20
|
import std/game/Game
|
|
21
21
|
import std/game/TestRig
|
|
22
|
+
import std/App
|
|
22
23
|
|
|
23
24
|
enum TapAction = Tapped | Push(dx: Float) | Quit
|
|
24
25
|
|
examples/games/orbitrunner/OrbitRunner.plum
CHANGED
|
@@ -12,6 +12,7 @@ import std/game/Gfx
|
|
|
12
12
|
import std/game/Audio
|
|
13
13
|
import std/game/Screen
|
|
14
14
|
import std/game/Game
|
|
15
|
+
import std/App
|
|
15
16
|
import screens/PlayingScreen
|
|
16
17
|
|
|
17
18
|
struct Arena =
|
examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -71,21 +71,18 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
|
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
73
|
fun view(self) -> List<View> =
|
|
74
|
-
back
|
|
74
|
+
back := [Box.of(0.0, 0.0, Arena.W, Arena.H, Color.rgb(0.07, 0.08, 0.16))]
|
|
75
|
-
mines := Views.all(self.mines)
|
|
76
|
-
orbs := Views.all(self.orbs)
|
|
77
|
-
ship
|
|
75
|
+
ship := if self.over then Nil else [self.ship]
|
|
78
|
-
rings := Views.all(self.rings)
|
|
79
|
-
hud
|
|
76
|
+
hud := [
|
|
80
77
|
Label.of(16.0, 12.0, "Score {self.score}", 28.0, Color.White),
|
|
81
78
|
Label.of(16.0, 44.0, "Best {self.best.max(self.score)}", 20.0, Color.Yellow)]
|
|
82
|
-
over
|
|
79
|
+
over := if self.over
|
|
83
80
|
[Overlay.of(Arena.W, Arena.H, [
|
|
84
81
|
Label.of(300.0, 258.0, "Game over", 48.0, Color.Red),
|
|
85
82
|
Label.of(270.0, 316.0, "Press Enter to play again", 24.0, Color.White)])]
|
|
86
83
|
else
|
|
87
84
|
Nil
|
|
88
|
-
back.append(starsFrom(0, self.clock)).append(mines).append(orbs).append(ship).append(rings).append(hud).append(lifeIcons(0, self.lives, self.assets.sheet)).append(over)
|
|
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)
|
|
89
86
|
|
|
90
87
|
fun deal(self) -> PlayingScreen =
|
|
91
88
|
fresh := PlayingScreen(..self, clock: 0.0, ship: Ship.create(self.assets.sheet), orbs: Nil, mines: Nil, rings: Nil)
|
examples/games/two_screens.plum
CHANGED
|
@@ -15,6 +15,7 @@ import std/game/Screen
|
|
|
15
15
|
import std/game/ScreenSlice
|
|
16
16
|
import std/game/Game
|
|
17
17
|
import std/game/TestRig
|
|
18
|
+
import std/App
|
|
18
19
|
|
|
19
20
|
enum TitleAction = Start
|
|
20
21
|
|
std/App.plum
CHANGED
|
@@ -11,6 +11,6 @@ module std
|
|
|
11
11
|
# A program has one `[App]` primitive (`plum run` and `plum build` of a folder run the
|
|
12
12
|
# file that holds it). Its other funs are ordinary statics (`Hello.greeting()`), and
|
|
13
13
|
# nothing else is global. A file imported by another (a test importing a game's main
|
|
14
|
-
# file) keeps its `main` as a static: `Hello.main(io)`. A file that lists `App`
|
|
14
|
+
# file) keeps its `main` as a static: `Hello.main(io)`. A file that lists `App` imports this
|
|
15
|
-
#
|
|
15
|
+
# file (`import std/App`), like any other module.
|
|
16
16
|
trait App
|
std/game/Overlay.plum
CHANGED
|
@@ -23,7 +23,7 @@ import std/game/Label
|
|
|
23
23
|
# is an item of the view of the screen it sits on, after (so drawn above) what it covers,
|
|
24
24
|
# there while the state says so, with its own children on it (a label, buttons):
|
|
25
25
|
#
|
|
26
|
-
# over
|
|
26
|
+
# over := if self.over then [Overlay.of(Arena.W, Arena.H, [
|
|
27
27
|
# Label.of(300.0, 258.0, "Game over", 48.0, Color.Red)])] else Nil
|
|
28
28
|
#
|
|
29
29
|
# It paints a `w` by `h` box in its `color` (black at 0.6 alpha with `Overlay.of`) over
|
std/game/View.plum
CHANGED
|
@@ -115,12 +115,6 @@ primitive Views =
|
|
|
115
115
|
Actor as a => a.step(dt)
|
|
116
116
|
_ => x
|
|
117
117
|
|
|
118
|
-
# Each of `xs` as a `View`: a screen's `List<Mine>` in its view (a `List<Mine>` is not a
|
|
119
|
-
# `List<View>`).
|
|
120
|
-
fun all<T: View>(xs: List<T>) -> List<View> = xs.map(|x| Views.one(x))
|
|
121
|
-
|
|
122
|
-
fun one<T: View>(x: T) -> View = x
|
|
123
|
-
|
|
124
118
|
# Draws the visible `items`, `m` and `alpha` being those of what holds them (the screen's
|
|
125
119
|
# camera, or the view whose view they are): each through its own place under `m`, at
|
|
126
120
|
# `alpha` times its place's alpha, its `paintSelf` and then its view.
|
tests/fbip/slice_shapes.plum
CHANGED
|
@@ -7,6 +7,7 @@ import std/Slice
|
|
|
7
7
|
import std/collections/List
|
|
8
8
|
import std/math/Vec2
|
|
9
9
|
import std/Test
|
|
10
|
+
import std/App
|
|
10
11
|
|
|
11
12
|
# Twelve shapes on `Slice`, which mutates in place today (`push`, `putAt`), and the per-frame update
|
|
12
13
|
# on a persistent `List` (`List.map`).
|
tests/fbip_probes/array_set.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/Array
|
|
|
4
4
|
import std/Time
|
|
5
5
|
import std/Io
|
|
6
6
|
import std/Test
|
|
7
|
+
import std/App
|
|
7
8
|
|
|
8
9
|
# FBIP probe: Array.set over a 1000-slot array, n times; the sum of the array is the result.
|
|
9
10
|
|
tests/fbip_probes/buffer_write.plum
CHANGED
|
@@ -5,6 +5,7 @@ import std/Byte
|
|
|
5
5
|
import std/Time
|
|
6
6
|
import std/Io
|
|
7
7
|
import std/Test
|
|
8
|
+
import std/App
|
|
8
9
|
|
|
9
10
|
# FBIP probe: n Buffer.writeByte calls; the buffer's byte count is the result.
|
|
10
11
|
|
tests/fbip_probes/map_set_get.plum
CHANGED
|
@@ -5,6 +5,7 @@ import std/Option
|
|
|
5
5
|
import std/Time
|
|
6
6
|
import std/Io
|
|
7
7
|
import std/Test
|
|
8
|
+
import std/App
|
|
8
9
|
|
|
9
10
|
# FBIP probe: n Map.with calls threaded through a fold (each map is unique, though cell reuse
|
|
10
11
|
# doesn't reach Map's generic methods yet), then n Map.get calls; the sum of the values read
|
tests/fbip_probes/slice_push_field.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/Slice
|
|
|
4
4
|
import std/Time
|
|
5
5
|
import std/Io
|
|
6
6
|
import std/Test
|
|
7
|
+
import std/App
|
|
7
8
|
|
|
8
9
|
# FBIP probe: Slice.push on a `mut` struct field, n times.
|
|
9
10
|
|
tests/fbip_probes/slice_push_helper.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/Slice
|
|
|
4
4
|
import std/Time
|
|
5
5
|
import std/Io
|
|
6
6
|
import std/Test
|
|
7
|
+
import std/App
|
|
7
8
|
|
|
8
9
|
# FBIP probe: Slice.push through a helper function that takes the slice.
|
|
9
10
|
|
tests/fbip_probes/slice_push_local.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/Slice
|
|
|
4
4
|
import std/Time
|
|
5
5
|
import std/Io
|
|
6
6
|
import std/Test
|
|
7
|
+
import std/App
|
|
7
8
|
|
|
8
9
|
# FBIP probe: Slice.push on a local, n times. Result: the length plus the last element.
|
|
9
10
|
|
tests/fbip_probes/struct_spread.plum
CHANGED
|
@@ -3,6 +3,7 @@ import std/Str
|
|
|
3
3
|
import std/Time
|
|
4
4
|
import std/Io
|
|
5
5
|
import std/Test
|
|
6
|
+
import std/App
|
|
6
7
|
|
|
7
8
|
# FBIP probe: a struct spread in a loop on a boxed struct (the Str field keeps it boxed).
|
|
8
9
|
|
tests/port/game/screens.plum
CHANGED
|
@@ -78,8 +78,8 @@ struct ProbeScreen[ScreenSlice<ProbeAct>](
|
|
|
78
78
|
fun busy(self) -> Bool = self.left > 0
|
|
79
79
|
|
|
80
80
|
fun view(self) -> List<View> =
|
|
81
|
-
turned
|
|
81
|
+
turned := Group(x: 200.0, y: 100.0, touch: ChildrenOnly, children: [Group.of(50.0, 0.0, [self.inner])])
|
|
82
|
-
base
|
|
82
|
+
base := [
|
|
83
83
|
self.box,
|
|
84
84
|
Screens.turnedBy(turned),
|
|
85
85
|
self.under,
|
tests/port/io/args.plum
CHANGED
|
@@ -3,6 +3,7 @@ import std/Str
|
|
|
3
3
|
import std/Io
|
|
4
4
|
import std/Slice
|
|
5
5
|
import std/Test
|
|
6
|
+
import std/App
|
|
6
7
|
|
|
7
8
|
# `io.args()`: the arguments after `--` in `plum run args.plum -- a "b c"`, or a built
|
|
8
9
|
# executable's own arguments. The cli test `args_clock_test.rs` runs this file's `main`
|
tests/std/game/Overlay.plum
CHANGED
|
@@ -25,7 +25,7 @@ primitive OverlayTest[UnitTest] =
|
|
|
25
25
|
under := Box(x: 0.0, y: 0.0, w: 100.0, h: 100.0, color: Color.White, touch: Enabled)
|
|
26
26
|
button := Box(x: 40.0, y: 40.0, w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
|
|
27
27
|
over := Overlay.of(100.0, 100.0, [button, Label.of(0.0, 0.0, "Paused", 24.0, Color.White)])
|
|
28
|
-
items
|
|
28
|
+
items := [under, over]
|
|
29
29
|
assert @sameRef(Views.hitIn(items, Vec2(x: 5.0, y: 5.0)).unwrap(), over)
|
|
30
30
|
assert Views.hitIn(items, Vec2(x: 5000.0, y: -20.0)).isNone()
|
|
31
31
|
assert @sameRef(Views.hitIn(items, Vec2(x: 45.0, y: 45.0)).unwrap(), button)
|
tests/std/game/View.plum
CHANGED
|
@@ -58,7 +58,7 @@ primitive ViewTest[UnitTest] =
|
|
|
58
58
|
fun steppingAListOfActorsStepsEachIn() =
|
|
59
59
|
steppers := Views.stepAll([Stepper(time: 0.0), Stepper(time: 1.0)], 0.5)
|
|
60
60
|
assert steppers.at(0).time == 0.5 && steppers.at(1).time == 1.5
|
|
61
|
-
items
|
|
61
|
+
items := [Stepper(time: 0.0), Box.of(0.0, 0.0, 1.0, 1.0, Color.White), Stepper(time: 2.0)]
|
|
62
62
|
stepped := Views.stepIn(Views.stepIn(items, 0.5), 0.25)
|
|
63
63
|
times := stepped.map(|v| match v
|
|
64
64
|
Stepper as s => s.time
|
|
@@ -72,7 +72,7 @@ primitive ViewTest[UnitTest] =
|
|
|
72
72
|
inner := Box(x: 0.0, y: 0.0, w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
|
|
73
73
|
turned := TurnedGroup(x: 200.0, y: 100.0, children: [Group.of(50.0, 0.0, [inner])])
|
|
74
74
|
hidden := Group(x: 0.0, y: 0.0, touch: Disabled, children: [Box(x: 400.0, y: 400.0, w: 50.0, h: 50.0, color: Color.White, touch: Enabled)])
|
|
75
|
-
items
|
|
75
|
+
items := [under, top, turned, hidden, Label.of(0.0, 0.0, "deco", 24.0, Color.White)]
|
|
76
76
|
assert @sameRef(Views.hitIn(items, Vec2(x: 15.0, y: 15.0)).unwrap(), top)
|
|
77
77
|
# The inner box is 50 along the group's x, which is turned a quarter: 50 down from it.
|
|
78
78
|
assert @sameRef(Views.hitIn(items, Vec2(x: 195.0, y: 155.0)).unwrap(), inner)
|
|
@@ -84,7 +84,7 @@ primitive ViewTest[UnitTest] =
|
|
|
84
84
|
|
|
85
85
|
# the draw list holds every item and what is under it, and culling leaves out what misses the area
|
|
86
86
|
fun theDrawListHoldsEveryItemAndWhat() =
|
|
87
|
-
items
|
|
87
|
+
items := [Box.of(0.0, 0.0, 10.0, 10.0, Color.White), Group.of(5000.0, 0.0, [Circle.of(0.0, 0.0, 2.0, Color.White), Label.of(0.0, 0.0, "far", 24.0, Color.White)]), Box.of(5000.0, 0.0, 10.0, 10.0, Color.White)]
|
|
88
88
|
all := Slice<Drawn>()
|
|
89
89
|
Views.drawnIn(items, Affine.Identity, 1.0, all, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
|
|
90
90
|
assert all.length() == 5
|
|
@@ -113,10 +113,10 @@ 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
|
-
first
|
|
116
|
+
first := [ViewHelpers.probeAt(1.0, self.log)]
|
|
117
|
-
lit
|
|
117
|
+
lit := if self.lit then [ViewHelpers.probeAt(2.0, self.log)] else Nil
|
|
118
|
-
grouped
|
|
118
|
+
grouped := [Group.of(10.0, 0.0, [ViewProbe(x: 4.0, log: self.log, fade: 0.5)])]
|
|
119
|
-
inner
|
|
119
|
+
inner := if self.inner then [Viewed(x: 100.0, log: self.log, views: self.views, lit: true, inner: false)] else Nil
|
|
120
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
|
tests/traits/covariance.plum
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Bool
|
|
3
|
+
import std/Test
|
|
4
|
+
import std/Option
|
|
5
|
+
import std/collections/List
|
|
6
|
+
|
|
7
|
+
# Immutable containers are covariant over a trait (a `List<Sq>` is a `List<Shape>`, an
|
|
8
|
+
# `Option<Sq>` an `Option<Shape>`), and the expected type flows into literals, branches
|
|
9
|
+
# and calls, so none of these values is annotated.
|
|
10
|
+
|
|
11
|
+
trait Shape =
|
|
12
|
+
fun area(self) -> Int
|
|
13
|
+
|
|
14
|
+
trait Solid[Shape] =
|
|
15
|
+
fun depth(self) -> Int
|
|
16
|
+
|
|
17
|
+
trait Marked =
|
|
18
|
+
fun mark(self) -> Int
|
|
19
|
+
|
|
20
|
+
struct Sq[Solid, Marked](k: Int) =
|
|
21
|
+
fun area(self) -> Int = self.k * self.k
|
|
22
|
+
fun depth(self) -> Int = 1
|
|
23
|
+
fun mark(self) -> Int = 7
|
|
24
|
+
|
|
25
|
+
struct Rect[Solid, Marked](w: Int, h: Int) =
|
|
26
|
+
fun area(self) -> Int = self.w * self.h
|
|
27
|
+
fun depth(self) -> Int = 2
|
|
28
|
+
fun mark(self) -> Int = 8
|
|
29
|
+
|
|
30
|
+
struct Dot[Shape](r: Int) =
|
|
31
|
+
fun area(self) -> Int = self.r
|
|
32
|
+
|
|
33
|
+
primitive Shapes =
|
|
34
|
+
fun total(xs: List<Shape>) -> Int = xs.fold(0, |acc, x| acc + x.area())
|
|
35
|
+
|
|
36
|
+
fun totals(xss: List<List<Shape>>) -> Int = xss.fold(0, |acc, xs| acc + Shapes.total(xs))
|
|
37
|
+
|
|
38
|
+
fun areaOf(o: Option<Shape>) -> Int = match o
|
|
39
|
+
Some(s) => s.area()
|
|
40
|
+
None => 0
|
|
41
|
+
|
|
42
|
+
fun squares(k: Int) -> List<Shape> = [Sq(k: k)]
|
|
43
|
+
|
|
44
|
+
fun squaresHeld(k: Int) -> List<Shape> =
|
|
45
|
+
xs := [Sq(k: k), Sq(k: 1)]
|
|
46
|
+
xs
|
|
47
|
+
|
|
48
|
+
fun rects(w: Int) -> List<Shape> = [Rect(w: w, h: 5)]
|
|
49
|
+
|
|
50
|
+
fun many(n: Int, acc: List<Sq>) -> List<Sq> = if n == 0 then acc else Shapes.many(n - 1, Cons(Sq(k: 1), acc))
|
|
51
|
+
|
|
52
|
+
fun pick(c: Bool) -> Shape =
|
|
53
|
+
s := if c then Sq(k: 2) else Dot(r: 3)
|
|
54
|
+
s
|
|
55
|
+
|
|
56
|
+
primitive CovarianceTest[UnitTest] =
|
|
57
|
+
fun anArgumentIsUpcast() =
|
|
58
|
+
sqs := [Sq(k: 2), Sq(k: 3)]
|
|
59
|
+
assert Shapes.total(sqs) == 13
|
|
60
|
+
|
|
61
|
+
fun aBranchOfNilAndAListIsTheList() =
|
|
62
|
+
over := false
|
|
63
|
+
ship := if over then Nil else [Sq(k: 2)]
|
|
64
|
+
assert Shapes.total(ship) == 4
|
|
65
|
+
|
|
66
|
+
fun aResultIsUpcast() =
|
|
67
|
+
assert Shapes.total(Shapes.squares(3)) == 9
|
|
68
|
+
assert Shapes.total(Shapes.squaresHeld(3)) == 10
|
|
69
|
+
|
|
70
|
+
fun anOptionIsUpcast() =
|
|
71
|
+
assert Shapes.areaOf(Some(Sq(k: 3))) == 9
|
|
72
|
+
o := Some(Sq(k: 2))
|
|
73
|
+
assert Shapes.areaOf(o) == 4
|
|
74
|
+
|
|
75
|
+
fun aNestedListIsUpcast() =
|
|
76
|
+
xss := [[Sq(k: 1)], [Sq(k: 2)]]
|
|
77
|
+
assert Shapes.totals(xss) == 5
|
|
78
|
+
|
|
79
|
+
fun theReceiverWidensToItsArgument() =
|
|
80
|
+
back := [Sq(k: 1)]
|
|
81
|
+
all := back.append(Shapes.rects(1))
|
|
82
|
+
assert Shapes.total(all) == 6
|
|
83
|
+
|
|
84
|
+
fun twoImplementersJoinAtTheirMostSpecificTrait() =
|
|
85
|
+
a := [Sq(k: 1)]
|
|
86
|
+
b := [Rect(w: 2, h: 3)]
|
|
87
|
+
both := a.append(b)
|
|
88
|
+
assert both.fold(0, |acc, x| acc + x.depth()) == 3
|
|
89
|
+
|
|
90
|
+
fun aLiteralOfSeveralTypesIsTheirJoin() =
|
|
91
|
+
xs := [Sq(k: 1), Rect(w: 2, h: 3), Sq(k: 2)]
|
|
92
|
+
assert xs.fold(0, |acc, x| acc + x.depth()) == 4
|
|
93
|
+
ys := [Sq(k: 2), Dot(r: 5)]
|
|
94
|
+
assert Shapes.total(ys) == 9
|
|
95
|
+
|
|
96
|
+
fun branchesOfTwoImplementersAreTheirTrait() =
|
|
97
|
+
assert Shapes.pick(true).area() + Shapes.pick(false).area() == 7
|
|
98
|
+
|
|
99
|
+
fun theUpcastListIsANewList() =
|
|
100
|
+
sqs := [Sq(k: 2), Sq(k: 3)]
|
|
101
|
+
assert Shapes.total(sqs) == 13
|
|
102
|
+
assert sqs.fold(0, |acc, s| acc + s.k) == 5
|
|
103
|
+
|
|
104
|
+
fun aLongListIsUpcastInALoop() =
|
|
105
|
+
assert Shapes.total(Shapes.many(100000, Nil)) == 100000
|