plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
474d832
— Peter John
2026-11-06T17:45:46+05:30
Simpler language: std namespaces become modules
- compiler/checker/tests/checker/modules_tests.rs +66 -6
- compiler/cli/tests/cli/compile_tests.rs +1 -1
- compiler/cli/tests/cli/host_stub_test.rs +3 -3
- compiler/cli/tests/cli/main.rs +1 -0
- compiler/cli/tests/cli/old_forms_test.rs +57 -0
- compiler/cli/tests/cli/test_scope_test.rs +1 -1
- compiler/core/src/loader.rs +19 -56
- compiler/core/src/modules.rs +202 -54
- compiler/core/src/purity.rs +3 -2
- compiler/core/tests/core/loader_test.rs +26 -17
- compiler/game/src/api.rs +1 -1
- compiler/game/tests/fixtures/assets_fixture.plum +11 -11
- compiler/game/tests/fixtures/host_fixture.plum +9 -8
- compiler/game/tests/fixtures/main_cli_fixture.plum +2 -2
- compiler/game/tests/fixtures/main_game_fixture.plum +4 -4
- compiler/game/tests/fixtures/main_missing_fixture.plum +3 -3
- compiler/game/tests/fixtures/target_fixture.plum +8 -8
- compiler/game/tests/host_test.rs +2 -2
- compiler/game/web-test/fixtures/interleave.plum +13 -14
- compiler/game/web-test/fixtures/main_game.plum +4 -4
- compiler/game/web-test/fixtures/rendertarget.plum +22 -22
- compiler/game/web-test/fixtures/stress.plum +25 -26
- compiler/game/web-test/fixtures/stress_state_view.plum +38 -39
- compiler/game/web-test/fixtures/stress_state_view_deep.plum +24 -25
- compiler/game/web-test/fixtures/stress_world.plum +17 -18
- compiler/game/web-test/fixtures/text_sizes.plum +13 -13
- compiler/host/src/lib.rs +1 -1
- compiler/lsp/src/completion.rs +15 -5
- compiler/lsp/src/main.rs +19 -29
- compiler/wasm-codegen/src/driver.rs +1 -1
- compiler/wasm-codegen/src/emit.rs +1 -1
- compiler/wasm-codegen/src/intrinsics.rs +19 -14
- compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +20 -45
- compiler/wasm-codegen/tests/wasm_codegen/e2e_types/io_entry.rs +3 -3
- compiler/wasm-codegen/tests/wasm_codegen/examples_test.rs +7 -7
- docs/backlog.md +1 -1
- docs/game.md +22 -18
- docs/language.md +9 -8
- docs/std.md +15 -15
- examples/basics.plum +4 -6
- examples/control_flow.plum +1 -1
- examples/games/kids/balloon_pop.plum +54 -55
- examples/games/orb_run.plum +108 -109
- examples/numbers.plum +29 -31
- examples/sequences.plum +1 -1
- std/Base64.plum +0 -139
- std/Float.plum +12 -12
- std/Http.plum +0 -156
- std/Int.plum +6 -6
- std/Io.plum +7 -63
- std/Math.plum +0 -205
- std/Mem.plum +0 -49
- std/Os.plum +0 -322
- std/base64.plum +138 -0
- std/game/Affine.plum +4 -4
- std/game/Game.plum +0 -162
- std/game/Ui.plum +0 -225
- std/game/Vec2.plum +2 -2
- std/game/audio.plum +44 -0
- std/game/gfx.plum +120 -0
- std/game/{Input.plum → input.plum} +85 -8
- std/game/{Scene.plum → scene.plum} +20 -20
- std/game/ui.plum +224 -0
- std/http.plum +155 -0
- std/math.plum +204 -0
- std/mem.plum +48 -0
- std/os.plum +321 -0
- std/{Testing.plum → testing.plum} +44 -45
- tests/modules/Palette.plum +8 -0
compiler/checker/tests/checker/modules_tests.rs
CHANGED
|
@@ -28,16 +28,16 @@ fn qualified_calls_and_constants_check() {
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
#[test]
|
|
31
|
-
fn
|
|
31
|
+
fn an_unqualified_use_of_a_name_only_other_modules_define_is_an_error() {
|
|
32
32
|
let e = run("ambig", &format!("{BOTH}fun f() -> Int =\n clamp(5)\n")).unwrap_err();
|
|
33
|
-
assert!(e.contains("'clamp' is defined in
|
|
33
|
+
assert!(e.contains("'clamp' is defined in module mathx: write mathx.clamp"), "{e}");
|
|
34
34
|
assert!(!e.contains('@'), "{e}");
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
#[test]
|
|
38
|
-
fn
|
|
38
|
+
fn an_unqualified_constant_only_other_modules_define_is_an_error() {
|
|
39
39
|
let e = run("ambigc", &format!("{BOTH}fun f() -> Int =\n Limit\n")).unwrap_err();
|
|
40
|
-
assert!(e.contains("'Limit' is defined in
|
|
40
|
+
assert!(e.contains("'Limit' is defined in module mathx: write mathx.Limit"), "{e}");
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
#[test]
|
|
@@ -46,8 +46,9 @@ fn a_file_prefers_its_own_definition_of_a_shared_name() {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
#[test]
|
|
49
|
-
fn
|
|
49
|
+
fn an_unqualified_use_of_the_one_imported_module_is_an_error() {
|
|
50
|
-
run("direct", "import std/Int\nimport tests/modules/mathx\n\nfun f() -> Int =\n clamp(500)\n").
|
|
50
|
+
let e = run("direct", "import std/Int\nimport tests/modules/mathx\n\nfun f() -> Int =\n clamp(500)\n").unwrap_err();
|
|
51
|
+
assert!(e.contains("'clamp' is defined in module mathx: write mathx.clamp"), "{e}");
|
|
51
52
|
}
|
|
52
53
|
|
|
53
54
|
#[test]
|
|
@@ -112,3 +113,62 @@ fn primitive_outside_std_is_rejected_for_a_built_in_and_for_an_extension() {
|
|
|
112
113
|
let e = run("primext", "import std/Int\n\nstruct Pt(x: Int)\n\nprimitive Pt =\n fun g(self) -> Int = 1\n").unwrap_err();
|
|
113
114
|
assert!(e.contains("only allowed in std"), "{e}");
|
|
114
115
|
}
|
|
116
|
+
|
|
117
|
+
#[test]
|
|
118
|
+
fn a_local_in_one_branch_does_not_capture_the_module_in_another() {
|
|
119
|
+
// `mathx` is a local only inside the `if` branch; the `else` branch and the lines before
|
|
120
|
+
// it mean the module.
|
|
121
|
+
run(
|
|
122
|
+
"branch",
|
|
123
|
+
&format!(
|
|
124
|
+
"{BOTH}fun f(c: Bool) -> Int =\n before := mathx.clamp(500)\n if c\n mathx := 2\n return mathx + before\n else\n return mathx.clamp(500) + mathx.Limit\n"
|
|
125
|
+
),
|
|
126
|
+
)
|
|
127
|
+
.unwrap();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
#[test]
|
|
131
|
+
fn a_local_does_not_capture_the_module_before_its_declaration() {
|
|
132
|
+
run(
|
|
133
|
+
"before",
|
|
134
|
+
&format!("{BOTH}fun f() -> Int =\n a := mathx.clamp(500)\n mathx := 3\n a + mathx\n"),
|
|
135
|
+
)
|
|
136
|
+
.unwrap();
|
|
137
|
+
// After the declaration the local wins: `3.clamp(..)` is a method call, not the module's.
|
|
138
|
+
let e = run("after", &format!("{BOTH}fun f() -> Int =\n mathx := 3\n mathx.clamp(500)\n")).unwrap_err();
|
|
139
|
+
assert!(!e.contains("module 'mathx'"), "{e}");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
#[test]
|
|
143
|
+
fn a_closure_parameter_and_a_loop_binder_scope_to_their_bodies() {
|
|
144
|
+
run(
|
|
145
|
+
"closure",
|
|
146
|
+
&format!(
|
|
147
|
+
"{BOTH}import std/List\n\nfun f() -> Int =\n g := |mathx: Int| mathx + 1\n mathx.clamp(500) + g(1)\n"
|
|
148
|
+
),
|
|
149
|
+
)
|
|
150
|
+
.unwrap();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
#[test]
|
|
154
|
+
fn a_module_name_is_the_lowercased_last_path_segment() {
|
|
155
|
+
run("palette", "import std/Int\nimport tests/modules/Palette\n\nfun f() -> Int =\n palette.shade(50) + palette.Dark\n").unwrap();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
#[test]
|
|
159
|
+
fn the_old_namespace_form_is_an_error() {
|
|
160
|
+
let e = run("oldns", "import std/Float\nimport std/math\n\nfun f() -> Float =\n Math.sqrt(2.0)\n").unwrap_err();
|
|
161
|
+
assert!(e.contains("'Math' is not a type: modules are lowercase, write math.<name>"), "{e}");
|
|
162
|
+
run("newns", "import std/Float\nimport std/math\n\nfun f() -> Float =\n math.sqrt(2.0)\n").unwrap();
|
|
163
|
+
let e = run("barens", "import std/Float\nimport std/math\n\nfun f() -> Float =\n sqrt(2.0)\n").unwrap_err();
|
|
164
|
+
assert!(e.contains("'sqrt' is defined in module math: write math.sqrt"), "{e}");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
#[test]
|
|
168
|
+
fn a_game_calls_the_host_through_module_functions() {
|
|
169
|
+
run(
|
|
170
|
+
"gamemods",
|
|
171
|
+
"import std/Float\nimport std/Io\nimport std/game/Color\nimport std/game/gfx\nimport std/game/input\n\nfun f(io: Io) -> Float =\n gfx.clear(io, Color.Black)\n input.axis(io, Key.Left, Key.Right)\n",
|
|
172
|
+
)
|
|
173
|
+
.unwrap();
|
|
174
|
+
}
|
compiler/cli/tests/cli/compile_tests.rs
CHANGED
|
@@ -55,7 +55,7 @@ fn compileWithImportResolvesViaLibPath() {
|
|
|
55
55
|
let src_path = dir.join("main.plum");
|
|
56
56
|
std::fs::write(
|
|
57
57
|
&src_path,
|
|
58
|
-
"module fixtures\n\nimport helper\n\nfun main(u: Unit) -> Unit =\n helperValue(u)\n",
|
|
58
|
+
"module fixtures\n\nimport helper\n\nfun main(u: Unit) -> Unit =\n helper.helperValue(u)\n",
|
|
59
59
|
)
|
|
60
60
|
.unwrap();
|
|
61
61
|
let out_path = dir.join("main.wasm");
|
compiler/cli/tests/cli/host_stub_test.rs
CHANGED
|
@@ -36,7 +36,7 @@ fn runPlumTest(name: &str, source: &str) -> (bool, String) {
|
|
|
36
36
|
fn stubbed_host_import_unused_test_passes() {
|
|
37
37
|
let (ok, all) = runPlumTest(
|
|
38
38
|
"pass",
|
|
39
|
-
"import std/Int\nimport std/game/
|
|
39
|
+
"import std/Int\nimport std/game/gfx\n\ntest \"pure\"\n assert 1 + 1 == 2\n",
|
|
40
40
|
);
|
|
41
41
|
assert!(ok, "output: {all}");
|
|
42
42
|
assert!(all.contains("1 passed, 0 failed"), "output: {all}");
|
|
@@ -46,7 +46,7 @@ fn stubbed_host_import_unused_test_passes() {
|
|
|
46
46
|
fn stubbed_host_import_traps_when_called() {
|
|
47
47
|
let (ok, all) = runPlumTest(
|
|
48
48
|
"trap",
|
|
49
|
-
"import std/Int\nimport std/Float\nimport std/Io\nimport std/game/
|
|
49
|
+
"import std/Int\nimport std/Float\nimport std/Io\nimport std/game/gfx\n\ntest \"calls host\"\n assert gfx.screenWidth(io) > 0.0\n",
|
|
50
50
|
);
|
|
51
51
|
assert!(!ok, "output: {all}");
|
|
52
52
|
assert!(
|
|
@@ -59,7 +59,7 @@ fn stubbed_host_import_traps_when_called() {
|
|
|
59
59
|
fn real_host_functions_still_work_next_to_stubs() {
|
|
60
60
|
let (ok, all) = runPlumTest(
|
|
61
61
|
"real",
|
|
62
|
-
"import std/Int\nimport std/Str\nimport std/Io\nimport std/game/
|
|
62
|
+
"import std/Int\nimport std/Str\nimport std/Io\nimport std/game/gfx\n\ntest \"real\"\n io.printLn(\"hello\")\n assert 1 == 1\n",
|
|
63
63
|
);
|
|
64
64
|
assert!(ok, "output: {all}");
|
|
65
65
|
assert!(all.contains("hello"), "output: {all}");
|
compiler/cli/tests/cli/main.rs
CHANGED
|
@@ -10,4 +10,5 @@ mod game_web_test;
|
|
|
10
10
|
mod host_stub_test;
|
|
11
11
|
mod main_result_test;
|
|
12
12
|
mod no_fbip_test;
|
|
13
|
+
mod old_forms_test;
|
|
13
14
|
mod test_scope_test;
|
compiler/cli/tests/cli/old_forms_test.rs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#![allow(non_snake_case)]
|
|
2
|
+
//! The forms std no longer has are errors: `Math.sqrt` (a module is lowercase) and
|
|
3
|
+
//! `io.clear(..)` (the game host calls are `gfx` functions).
|
|
4
|
+
use std::process::Command;
|
|
5
|
+
|
|
6
|
+
fn compileOutcome(name: &str, src: &str) -> (bool, String) {
|
|
7
|
+
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
|
|
8
|
+
let mut bin = std::env::current_exe().unwrap();
|
|
9
|
+
bin.pop();
|
|
10
|
+
if bin.ends_with("deps") {
|
|
11
|
+
bin.pop();
|
|
12
|
+
}
|
|
13
|
+
bin.push("plum");
|
|
14
|
+
let dir = std::env::temp_dir().join(format!("plum_oldform_{}_{}", name, std::process::id()));
|
|
15
|
+
std::fs::create_dir_all(&dir).unwrap();
|
|
16
|
+
let file = dir.join("main.plum");
|
|
17
|
+
std::fs::write(&file, src).unwrap();
|
|
18
|
+
let out = Command::new(bin)
|
|
19
|
+
.current_dir(root)
|
|
20
|
+
.args(["compile", file.to_str().unwrap(), "-o", dir.join("main.wasm").to_str().unwrap()])
|
|
21
|
+
.output()
|
|
22
|
+
.expect("failed to run plum");
|
|
23
|
+
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
|
24
|
+
let _ = std::fs::remove_dir_all(&dir);
|
|
25
|
+
(out.status.success(), text)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
#[test]
|
|
29
|
+
fn theOldNamespaceFormIsAnError() {
|
|
30
|
+
let (ok, text) = compileOutcome("math", "import std/Float\nimport std/math\n\nfun main() -> Float =\n Math.sqrt(2.0)\n");
|
|
31
|
+
assert!(!ok, "{text}");
|
|
32
|
+
assert!(text.contains("'Math' is not a type: modules are lowercase, write math.<name>"), "{text}");
|
|
33
|
+
let (ok, text) = compileOutcome("modern", "import std/Float\nimport std/math\n\nfun main() -> Float =\n math.sqrt(2.0)\n");
|
|
34
|
+
assert!(ok, "{text}");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
#[test]
|
|
38
|
+
fn aBareModuleFunctionIsAnError() {
|
|
39
|
+
let (ok, text) = compileOutcome("bare", "import std/Float\nimport std/math\n\nfun main() -> Float =\n sqrt(2.0)\n");
|
|
40
|
+
assert!(!ok, "{text}");
|
|
41
|
+
assert!(text.contains("'sqrt' is defined in module math: write math.sqrt"), "{text}");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
#[test]
|
|
45
|
+
fn hostCallsAreNoLongerMethodsOfIo() {
|
|
46
|
+
let (ok, text) = compileOutcome(
|
|
47
|
+
"ioclear",
|
|
48
|
+
"import std/Io\nimport std/game/Color\nimport std/game/gfx\n\nfun main(io: Io) =\n io.clear(Color.Black)\n",
|
|
49
|
+
);
|
|
50
|
+
assert!(!ok, "{text}");
|
|
51
|
+
assert!(text.contains("Io.clear"), "{text}");
|
|
52
|
+
let (ok, text) = compileOutcome(
|
|
53
|
+
"gfxclear",
|
|
54
|
+
"import std/Io\nimport std/game/Color\nimport std/game/gfx\n\nfun main(io: Io) =\n gfx.clear(io, Color.Black)\n",
|
|
55
|
+
);
|
|
56
|
+
assert!(ok, "{text}");
|
|
57
|
+
}
|
compiler/cli/tests/cli/test_scope_test.rs
CHANGED
|
@@ -64,7 +64,7 @@ fn failingImportedTestDoesNotFailImporter() {
|
|
|
64
64
|
let f = dir.join("main.plum");
|
|
65
65
|
std::fs::write(
|
|
66
66
|
&f,
|
|
67
|
-
format!("import std/Int\nimport {rel}\n\ntest \"good\"\n assert one() == 1\n"),
|
|
67
|
+
format!("import std/Int\nimport {rel}\n\ntest \"good\"\n assert lib.one() == 1\n"),
|
|
68
68
|
)
|
|
69
69
|
.unwrap();
|
|
70
70
|
let (out, ok) = runPlum(&[f.to_str().unwrap()]);
|
compiler/core/src/loader.rs
CHANGED
|
@@ -59,7 +59,6 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
59
59
|
let mut prims: Vec<PrimitiveDecl> = Vec::new();
|
|
60
60
|
|
|
61
61
|
MERGED_LIT_ERRORS.with(|e| e.borrow_mut().clear());
|
|
62
|
-
USER_PRIMS.with(|u| u.borrow_mut().clear());
|
|
63
62
|
visited.insert(entry_canon.clone());
|
|
64
63
|
let imports = entry_source.imports.clone();
|
|
65
64
|
let mut files = vec![Loaded { path: entry_canon, text: entry_text, source: entry_source }];
|
|
@@ -69,11 +68,11 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
69
68
|
shadowStdTypes(&mut files, lib_path)?;
|
|
70
69
|
resolveFileModules(&mut files, lib_path)?;
|
|
71
70
|
for f in &files {
|
|
72
|
-
mergeItems(&f.path, &f.source, &mut items, &mut names, &mut prims
|
|
71
|
+
mergeItems(&f.path, &f.source, &mut items, &mut names, &mut prims)?;
|
|
73
72
|
}
|
|
74
73
|
let entry_source = files.swap_remove(0).source;
|
|
75
74
|
|
|
76
|
-
dropExtensions(&items, &mut prims)
|
|
75
|
+
dropExtensions(&items, &mut prims);
|
|
77
76
|
crate::modules::orderConsts(&mut items)?;
|
|
78
77
|
let mut merged = Source {
|
|
79
78
|
file: entry_source.file,
|
|
@@ -91,29 +90,12 @@ pub fn loadAndMergeWithOverridesDiag(
|
|
|
91
90
|
|
|
92
91
|
/// A std `primitive Slice[T] =` (any non-built-in name that is also a declared
|
|
93
92
|
/// enum/struct) is an EXTENSION: its `fun`s are methods of that type (a
|
|
94
|
-
/// duplicate method name is already a collision error)
|
|
93
|
+
/// duplicate method name is already a collision error), so it leaves the list of
|
|
95
|
-
/// stateless namespace, so it leaves the namespace list. Outside std this
|
|
96
|
-
///
|
|
94
|
+
/// constant groups. A built-in's `primitive` block is extended the same way
|
|
97
95
|
/// with no extra rule: its methods are flat items.
|
|
98
|
-
fn dropExtensions(items: &[Item], prims: &mut Vec<PrimitiveDecl>)
|
|
96
|
+
fn dropExtensions(items: &[Item], prims: &mut Vec<PrimitiveDecl>) {
|
|
99
97
|
let declared = |n: &str| items.iter().any(|i| matches!(i, Item::Enum(e) if e.name == n));
|
|
100
|
-
let bad = USER_PRIMS.with(|u| {
|
|
101
|
-
u.borrow()
|
|
102
|
-
.iter()
|
|
103
|
-
.find(|(n, _)| declared(n))
|
|
104
|
-
.map(|(n, f)| (n.clone(), f.clone()))
|
|
105
|
-
});
|
|
106
|
-
if let Some((n, f)) = bad {
|
|
107
|
-
return Err(vec![Diagnostic::new(
|
|
108
|
-
DiagKind::Resolution,
|
|
109
|
-
f.display().to_string(),
|
|
110
|
-
0,
|
|
111
|
-
0,
|
|
112
|
-
format!("primitive {} extends a declared type and is only allowed in std", n),
|
|
113
|
-
)]);
|
|
114
|
-
}
|
|
115
98
|
prims.retain(|p| !declared(&p.name));
|
|
116
|
-
Ok(())
|
|
117
99
|
}
|
|
118
100
|
|
|
119
101
|
fn canonicalizeMaybeMissing(path: &Path) -> Loaded_<PathBuf> {
|
|
@@ -209,7 +191,7 @@ fn resolveFileModules(files: &mut [Loaded], lib_path: &Path) -> Loaded_<()> {
|
|
|
209
191
|
.iter()
|
|
210
192
|
.filter_map(|imp| {
|
|
211
193
|
let target = resolveImport(imp, lib_path).ok()?;
|
|
212
|
-
let alias =
|
|
194
|
+
let alias = crate::modules::moduleAlias(&imp.path);
|
|
213
195
|
Some((alias, *index.get(&target)?))
|
|
214
196
|
})
|
|
215
197
|
.collect(),
|
|
@@ -668,10 +650,6 @@ fn lastLeaf(node: tree_sitter::Node) -> Option<tree_sitter::Node> {
|
|
|
668
650
|
}
|
|
669
651
|
|
|
670
652
|
thread_local! {
|
|
671
|
-
/// `(primitive name, file)` of every non-std `primitive` merged so far: such a
|
|
672
|
-
/// block may not extend a declared type (see `dropExtensions`).
|
|
673
|
-
static USER_PRIMS: std::cell::RefCell<Vec<(String, PathBuf)>> =
|
|
674
|
-
std::cell::RefCell::new(Vec::new());
|
|
675
653
|
static MERGED_LIT_ERRORS: std::cell::RefCell<Vec<(usize, usize, String)>> =
|
|
676
654
|
std::cell::RefCell::new(Vec::new());
|
|
677
655
|
}
|
|
@@ -679,7 +657,6 @@ thread_local! {
|
|
|
679
657
|
/// Clears the per-compile loader state (see `session::begin`).
|
|
680
658
|
pub fn resetSession() {
|
|
681
659
|
MERGED_LIT_ERRORS.with(|e| e.borrow_mut().clear());
|
|
682
|
-
USER_PRIMS.with(|u| u.borrow_mut().clear());
|
|
683
660
|
}
|
|
684
661
|
|
|
685
662
|
fn mergeItems(
|
|
@@ -688,7 +665,6 @@ fn mergeItems(
|
|
|
688
665
|
items: &mut Vec<Item>,
|
|
689
666
|
names: &mut HashMap<String, PathBuf>,
|
|
690
667
|
prims: &mut Vec<PrimitiveDecl>,
|
|
691
|
-
lib_path: &Path,
|
|
692
668
|
) -> Loaded_<()> {
|
|
693
669
|
// Removed forms, then inline variants as hidden records (per-file lowering).
|
|
694
670
|
let mut hoisted = source.clone();
|
|
@@ -696,19 +672,6 @@ fn mergeItems(
|
|
|
696
672
|
let source = &hoisted;
|
|
697
673
|
// Parse-time literal errors (out-of-range integers) of every merged file.
|
|
698
674
|
MERGED_LIT_ERRORS.with(|e| e.borrow_mut().extend(source.formErrors.iter().cloned()));
|
|
699
|
-
// Namespaces (a `primitive` whose name is no built-in) travel with the
|
|
700
|
-
// merged program so the checker can enforce their rules.
|
|
701
|
-
if !isStdFile(file, lib_path) {
|
|
702
|
-
USER_PRIMS.with(|u| {
|
|
703
|
-
u.borrow_mut().extend(
|
|
704
|
-
source
|
|
705
|
-
.primitives
|
|
706
|
-
.iter()
|
|
707
|
-
.filter(|p| !BUILTIN_PRIMITIVES.contains(&p.name.as_str()))
|
|
708
|
-
.map(|p| (p.name.clone(), file.to_path_buf())),
|
|
709
|
-
)
|
|
710
|
-
});
|
|
711
|
-
}
|
|
712
675
|
prims.extend(
|
|
713
676
|
source
|
|
714
677
|
.primitives
|
|
@@ -775,20 +738,20 @@ fn itemNameKey(item: &Item) -> String {
|
|
|
775
738
|
}
|
|
776
739
|
}
|
|
777
740
|
|
|
778
|
-
///
|
|
741
|
+
/// `primitive` declares the built-in types and the constant groups of std (`Int`, `Array`,
|
|
779
|
-
/// it is
|
|
742
|
+
/// `Key`); it is for std only.
|
|
780
743
|
fn checkExtends(path: &Path, source: &Source, lib_path: &Path) -> Loaded_<()> {
|
|
781
|
-
|
|
744
|
+
if isStdFile(path, lib_path) {
|
|
745
|
+
return Ok(());
|
|
746
|
+
}
|
|
782
|
-
|
|
747
|
+
if let Some(p) = source.primitives.first() {
|
|
783
|
-
if !inStd && BUILTIN_PRIMITIVES.contains(&p.name.as_str()) {
|
|
784
|
-
|
|
748
|
+
return Err(vec![Diagnostic::new(
|
|
785
|
-
|
|
749
|
+
DiagKind::Resolution,
|
|
786
|
-
|
|
750
|
+
path.display().to_string(),
|
|
787
|
-
|
|
751
|
+
p.line,
|
|
788
|
-
|
|
752
|
+
p.column,
|
|
789
|
-
|
|
753
|
+
format!("primitive {} is only allowed in std: write module-level functions and constants instead", p.name),
|
|
790
|
-
|
|
754
|
+
)]);
|
|
791
|
-
}
|
|
792
755
|
}
|
|
793
756
|
Ok(())
|
|
794
757
|
}
|
compiler/core/src/modules.rs
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
|
-
//! Modules. `import a/b` makes `b`
|
|
1
|
+
//! Modules. `import a/b` makes `b` (lowercased: `import std/math` is `math`) a name for that
|
|
2
|
-
//! constants: `b.f()`, `b.Const`. Types and enum variants stay
|
|
2
|
+
//! file's top-level functions and constants: `b.f()`, `b.Const`. Types and enum variants stay
|
|
3
|
+
//! unqualified.
|
|
3
4
|
//!
|
|
4
5
|
//! Two files may define the same function or constant name. Such a name is renamed per
|
|
5
6
|
//! module while the files are merged (`clamp` in `mathx` becomes `clamp@mathx`), so every
|
|
6
7
|
//! later pass keeps seeing plain global names and needs no change; diagnostics print the
|
|
7
|
-
//! source name (see `diag::sourceName`). A name only one file defines keeps its name
|
|
8
|
+
//! source name (see `diag::sourceName`). A name only one file defines keeps its name.
|
|
8
|
-
//! stays callable unqualified (the fallback T5 removes).
|
|
9
9
|
//!
|
|
10
|
-
//! Resolution of a use in file F
|
|
10
|
+
//! Resolution of a use in file F:
|
|
11
|
-
//! - `m.f()` / `m.C` with `m` an import of F (and not a local
|
|
11
|
+
//! - `m.f()` / `m.C` with `m` an import of F (and not a local in scope there): that module's;
|
|
12
|
-
//! - an unqualified use: F's own definition
|
|
12
|
+
//! - an unqualified use of a function or constant: F's own definition. A name another
|
|
13
|
+
//! module defines (and F does not) is an error: write `m.f()`.
|
|
13
14
|
//!
|
|
14
|
-
//! A local named like an import wins over the module
|
|
15
|
+
//! A local named like an import wins over the module, scope by scope: a local `m` declared
|
|
15
|
-
//!
|
|
16
|
+
//! in one branch does not capture `m.f()` in another branch or before its declaration.
|
|
16
17
|
use crate::ast::*;
|
|
17
18
|
use crate::diag::{DiagKind, Diagnostic};
|
|
18
19
|
use crate::rename::{renameStmts, Name};
|
|
19
|
-
use crate::visit::{
|
|
20
|
+
use crate::visit::{childExprs, patternBinders, stmtBlocks, stmtExprs, visitExpr};
|
|
20
21
|
use std::collections::{HashMap, HashSet};
|
|
21
22
|
|
|
22
23
|
/// Separates a source name from the module of a renamed definition: `clamp@mathx`.
|
|
@@ -32,9 +33,20 @@ pub struct ModuleInfo {
|
|
|
32
33
|
pub imports: Vec<(String, usize)>,
|
|
33
34
|
}
|
|
34
35
|
|
|
36
|
+
/// The name an import gives its module: the last path segment, lowercased.
|
|
37
|
+
pub fn moduleAlias(importPath: &str) -> String {
|
|
38
|
+
importPath.rsplit('/').next().unwrap_or(importPath).to_lowercase()
|
|
39
|
+
}
|
|
40
|
+
|
|
35
|
-
/// A top-level function a module may rename: not a method,
|
|
41
|
+
/// A top-level function a module may rename: not a method, export or `main`. (A host
|
|
42
|
+
/// import keeps its host name: see `sourceFnName`.)
|
|
36
43
|
fn renamable(f: &Fn) -> bool {
|
|
37
|
-
f.type_param.is_none() && !f.
|
|
44
|
+
f.type_param.is_none() && !f.is_export && !f.is_test && f.name != "main"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// The name a function was written with: `clear@gfx` is `clear`.
|
|
48
|
+
pub fn sourceFnName(name: &str) -> &str {
|
|
49
|
+
name.split(MODULE_MARK).next().unwrap_or(name)
|
|
38
50
|
}
|
|
39
51
|
|
|
40
52
|
fn isModuleConst(c: &Const) -> bool {
|
|
@@ -49,6 +61,8 @@ struct World {
|
|
|
49
61
|
/// Names defined in two or more files (renamable fns / consts only).
|
|
50
62
|
fnCollide: HashSet<String>,
|
|
51
63
|
constCollide: HashSet<String>,
|
|
64
|
+
/// Every type name: enums and structs, `primitive`s and the built-ins.
|
|
65
|
+
types: HashSet<String>,
|
|
52
66
|
}
|
|
53
67
|
|
|
54
68
|
fn mangle(name: &str, module: &str) -> String {
|
|
@@ -95,9 +109,17 @@ pub fn resolveModules(infos: Vec<ModuleInfo>, sources: &mut [&mut Source]) -> Re
|
|
|
95
109
|
let collide = |m: &HashMap<String, usize>| -> HashSet<String> {
|
|
96
110
|
m.iter().filter(|(_, &c)| c > 1).map(|(k, _)| k.clone()).collect()
|
|
97
111
|
};
|
|
112
|
+
let mut types: HashSet<String> = BUILTIN_PRIMITIVES.iter().map(|s| s.to_string()).collect();
|
|
113
|
+
for s in sources.iter() {
|
|
114
|
+
types.extend(s.primitives.iter().map(|p| p.name.clone()));
|
|
115
|
+
types.extend(s.items.iter().filter_map(|i| match i {
|
|
116
|
+
Item::Enum(e) => Some(e.name.clone()),
|
|
117
|
+
_ => None,
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
98
|
-
let world = World { fnCollide: collide(&fnCount), constCollide: collide(&constCount), infos, fns, consts };
|
|
120
|
+
let world = World { fnCollide: collide(&fnCount), constCollide: collide(&constCount), infos, fns, consts, types };
|
|
99
|
-
//
|
|
121
|
+
// One file has no other module to resolve against.
|
|
100
|
-
if
|
|
122
|
+
if n < 2 {
|
|
101
123
|
return Ok(());
|
|
102
124
|
}
|
|
103
125
|
let mut errors = Vec::new();
|
|
@@ -121,7 +143,8 @@ struct Cx<'a> {
|
|
|
121
143
|
world: &'a World,
|
|
122
144
|
file: usize,
|
|
123
145
|
aliases: HashMap<String, usize>,
|
|
146
|
+
/// The locals in scope, innermost last.
|
|
124
|
-
|
|
147
|
+
scopes: Vec<HashSet<String>>,
|
|
125
148
|
errors: &'a mut Vec<Diagnostic>,
|
|
126
149
|
}
|
|
127
150
|
|
|
@@ -131,44 +154,167 @@ impl Cx<'_> {
|
|
|
131
154
|
self.errors.push(Diagnostic::new(DiagKind::Resolution, path, line, column, message));
|
|
132
155
|
}
|
|
133
156
|
|
|
157
|
+
fn isLocal(&self, name: &str) -> bool {
|
|
158
|
+
self.scopes.iter().any(|s| s.contains(name))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
fn declare(&mut self, name: &str) {
|
|
162
|
+
if let Some(s) = self.scopes.last_mut() {
|
|
163
|
+
s.insert(name.to_string());
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
fn declarePattern(&mut self, p: &CasePattern) {
|
|
168
|
+
let mut names = Vec::new();
|
|
169
|
+
patternBinders(p, &mut names);
|
|
170
|
+
for n in names {
|
|
171
|
+
self.declare(&n);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
134
|
-
///
|
|
175
|
+
/// The global name of an unqualified use of `name`: the file's own definition. A name
|
|
176
|
+
/// only another module defines is an error (`None`); a name no module defines is left
|
|
177
|
+
/// to the checker.
|
|
135
|
-
fn
|
|
178
|
+
fn own(&mut self, name: &str, kind: Kind, line: usize, column: usize) -> Option<String> {
|
|
136
179
|
let world = self.world;
|
|
137
180
|
let defines = |f: usize| match kind {
|
|
138
181
|
Kind::Fn => world.fns[f].contains(name),
|
|
139
182
|
Kind::Const => world.consts[f].contains(name),
|
|
140
183
|
};
|
|
184
|
+
let collide = match kind {
|
|
185
|
+
Kind::Fn => &world.fnCollide,
|
|
186
|
+
Kind::Const => &world.constCollide,
|
|
187
|
+
};
|
|
141
188
|
if defines(self.file) {
|
|
142
|
-
return Some(self.file);
|
|
189
|
+
return Some(world.global(self.file, name, collide));
|
|
143
|
-
}
|
|
144
|
-
let direct: Vec<usize> = world.infos[self.file]
|
|
145
|
-
.imports
|
|
146
|
-
.iter()
|
|
147
|
-
.map(|(_, t)| *t)
|
|
148
|
-
.filter(|t| *t != self.file && defines(*t))
|
|
149
|
-
.collect();
|
|
150
|
-
if direct.len() == 1 {
|
|
151
|
-
return Some(direct[0]);
|
|
152
190
|
}
|
|
153
191
|
let mut owners: Vec<String> =
|
|
154
|
-
(0..world.infos.len()).filter(|f| defines(*f)).map(|f| world.infos[f].name.
|
|
192
|
+
(0..world.infos.len()).filter(|f| defines(*f)).map(|f| world.infos[f].name.to_lowercase()).collect();
|
|
193
|
+
if owners.is_empty() {
|
|
194
|
+
return Some(name.to_string());
|
|
195
|
+
}
|
|
155
196
|
owners.sort();
|
|
156
|
-
let hint = owners.first().cloned().unwrap_or_default();
|
|
157
|
-
|
|
197
|
+
let hint = owners
|
|
158
|
-
|
|
198
|
+
.iter()
|
|
199
|
+
.find(|o| self.aliases.contains_key(o.as_str()))
|
|
200
|
+
.unwrap_or(&owners[0])
|
|
159
|
-
|
|
201
|
+
.clone();
|
|
160
|
-
|
|
202
|
+
self.error(line, column, format!("'{name}' is defined in module {hint}: write {hint}.{name}"));
|
|
161
|
-
);
|
|
162
203
|
None
|
|
163
204
|
}
|
|
164
205
|
|
|
206
|
+
fn block(&mut self, b: &mut Block) {
|
|
207
|
+
self.scopes.push(HashSet::new());
|
|
208
|
+
for s in &mut b.stmts {
|
|
209
|
+
self.stmt(s);
|
|
210
|
+
}
|
|
211
|
+
self.scopes.pop();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
fn stmt(&mut self, s: &mut Stmt) {
|
|
215
|
+
let handled = match &mut s.kind {
|
|
216
|
+
StmtKind::Assign(a) => {
|
|
217
|
+
for t in &mut a.targets {
|
|
218
|
+
if let AssignTarget::Field(obj, _) = t {
|
|
219
|
+
self.expr(obj);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
for v in &mut a.values {
|
|
223
|
+
self.expr(v);
|
|
224
|
+
}
|
|
225
|
+
if a.declare {
|
|
226
|
+
for t in &a.targets {
|
|
227
|
+
if let AssignTarget::Var(n) = t {
|
|
228
|
+
self.declare(n);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
true
|
|
233
|
+
}
|
|
234
|
+
StmtKind::ForLoop(f) => {
|
|
235
|
+
self.expr(&mut f.source);
|
|
236
|
+
self.scopes.push(f.binders.iter().cloned().collect());
|
|
237
|
+
self.block(&mut f.body);
|
|
238
|
+
self.scopes.pop();
|
|
239
|
+
true
|
|
240
|
+
}
|
|
241
|
+
StmtKind::If(i) => {
|
|
242
|
+
// The scope of the whole statement holds what the conditions bind (`x is Some(v)`).
|
|
243
|
+
self.scopes.push(HashSet::new());
|
|
244
|
+
self.expr(&mut i.condition);
|
|
245
|
+
self.block(&mut i.body);
|
|
246
|
+
for e in &mut i.else_ifs {
|
|
247
|
+
self.expr(&mut e.condition);
|
|
248
|
+
self.block(&mut e.body);
|
|
249
|
+
}
|
|
250
|
+
if let Some(b) = &mut i.else_ {
|
|
251
|
+
self.block(b);
|
|
252
|
+
}
|
|
253
|
+
self.scopes.pop();
|
|
254
|
+
true
|
|
255
|
+
}
|
|
256
|
+
StmtKind::Match(m) => {
|
|
257
|
+
for e in &mut m.subjects {
|
|
258
|
+
self.expr(e);
|
|
259
|
+
}
|
|
260
|
+
for c in &mut m.cases {
|
|
261
|
+
self.scopes.push(HashSet::new());
|
|
262
|
+
for p in &c.patterns {
|
|
263
|
+
self.declarePattern(p);
|
|
264
|
+
}
|
|
265
|
+
if let Some(g) = &mut c.guard {
|
|
266
|
+
self.expr(g);
|
|
267
|
+
}
|
|
268
|
+
self.block(&mut c.body);
|
|
269
|
+
self.scopes.pop();
|
|
270
|
+
}
|
|
271
|
+
true
|
|
272
|
+
}
|
|
273
|
+
_ => false,
|
|
274
|
+
};
|
|
275
|
+
if !handled {
|
|
276
|
+
for e in stmtExprs(s) {
|
|
277
|
+
self.expr(e);
|
|
278
|
+
}
|
|
279
|
+
for b in stmtBlocks(s) {
|
|
280
|
+
self.block(b);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
fn expr(&mut self, e: &mut Expr) {
|
|
286
|
+
if let ExprKind::Closure(c) = &mut e.kind {
|
|
287
|
+
self.scopes.push(c.params.iter().cloned().collect());
|
|
288
|
+
self.block(&mut c.body);
|
|
289
|
+
self.scopes.pop();
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
for c in childExprs(e) {
|
|
293
|
+
self.expr(c);
|
|
294
|
+
}
|
|
295
|
+
if let ExprKind::Bind(b) = &e.kind {
|
|
296
|
+
let p = b.case.patterns[0].clone();
|
|
297
|
+
self.declarePattern(&p);
|
|
298
|
+
}
|
|
299
|
+
self.visit(e);
|
|
300
|
+
}
|
|
301
|
+
|
|
165
302
|
fn visit(&mut self, e: &mut Expr) {
|
|
166
303
|
let (line, column) = (e.span.startLine, e.span.startColumn);
|
|
167
304
|
let world = self.world;
|
|
168
305
|
match &mut e.kind {
|
|
169
306
|
ExprKind::Attribute(a) => {
|
|
307
|
+
// `Math.sqrt(..)`: the old namespace form; modules are lowercase.
|
|
308
|
+
if let ExprKind::TypeName(t) = &a.object.kind {
|
|
309
|
+
let lower = t.to_lowercase();
|
|
310
|
+
if !world.types.contains(t) && self.aliases.contains_key(&lower) {
|
|
311
|
+
let (line, column) = (a.object.span.startLine, a.object.span.startColumn);
|
|
312
|
+
self.error(line, column, format!("'{t}' is not a type: modules are lowercase, write {lower}.<name>"));
|
|
313
|
+
}
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
170
316
|
let ExprKind::Var(m) = &a.object.kind else { return };
|
|
171
|
-
if self.
|
|
317
|
+
if self.isLocal(m) {
|
|
172
318
|
return;
|
|
173
319
|
}
|
|
174
320
|
let Some(&target) = self.aliases.get(m) else { return };
|
|
@@ -193,24 +339,24 @@ impl Cx<'_> {
|
|
|
193
339
|
};
|
|
194
340
|
*e = replacement.at(e);
|
|
195
341
|
}
|
|
196
|
-
ExprKind::FnCall(c) if
|
|
342
|
+
ExprKind::FnCall(c) if !self.isLocal(&c.name) => {
|
|
197
343
|
let (name, l, col) = (c.name.clone(), c.line, c.column);
|
|
198
|
-
if let Some(
|
|
344
|
+
if let Some(new) = self.own(&name, Kind::Fn, l, col) {
|
|
199
345
|
if let ExprKind::FnCall(c) = &mut e.kind {
|
|
200
|
-
c.name =
|
|
346
|
+
c.name = new;
|
|
201
347
|
}
|
|
202
348
|
}
|
|
203
349
|
}
|
|
204
|
-
ExprKind::Var(n) if
|
|
350
|
+
ExprKind::Var(n) if !self.isLocal(n) => {
|
|
205
351
|
let name = n.clone();
|
|
206
|
-
if let Some(
|
|
352
|
+
if let Some(new) = self.own(&name, Kind::Fn, line, column) {
|
|
207
|
-
e.kind = ExprKind::Var(
|
|
353
|
+
e.kind = ExprKind::Var(new);
|
|
208
354
|
}
|
|
209
355
|
}
|
|
210
|
-
ExprKind::TypeName(n) if world.
|
|
356
|
+
ExprKind::TypeName(n) if world.consts.iter().any(|c| c.contains(n.as_str())) => {
|
|
211
357
|
let name = n.clone();
|
|
212
|
-
if let Some(
|
|
358
|
+
if let Some(new) = self.own(&name, Kind::Const, line, column) {
|
|
213
|
-
e.kind = ExprKind::TypeName(
|
|
359
|
+
e.kind = ExprKind::TypeName(new);
|
|
214
360
|
}
|
|
215
361
|
}
|
|
216
362
|
_ => {}
|
|
@@ -259,29 +405,31 @@ fn rewriteFile(world: &World, file: usize, source: &mut Source, errors: &mut Vec
|
|
|
259
405
|
.filter(|(_, t)| *t != file)
|
|
260
406
|
.map(|(a, t)| (a.clone(), *t))
|
|
261
407
|
.collect();
|
|
262
|
-
let mut cx = Cx { world, file, aliases,
|
|
408
|
+
let mut cx = Cx { world, file, aliases, scopes: Vec::new(), errors };
|
|
263
409
|
for item in &mut source.items {
|
|
264
410
|
match item {
|
|
265
411
|
Item::Fn(f) => {
|
|
266
|
-
cx.
|
|
412
|
+
cx.scopes = vec![HashSet::new()];
|
|
267
413
|
for p in &mut f.params {
|
|
268
414
|
if let Some(d) = &mut p.default {
|
|
269
|
-
|
|
415
|
+
cx.expr(d);
|
|
270
416
|
}
|
|
271
417
|
}
|
|
418
|
+
cx.scopes = vec![f.params.iter().map(|p| p.name.clone()).collect()];
|
|
272
419
|
match &mut f.body {
|
|
273
|
-
FnBody::Block(b) =>
|
|
420
|
+
FnBody::Block(b) => cx.block(b),
|
|
274
|
-
FnBody::Expr(e) =>
|
|
421
|
+
FnBody::Expr(e) => cx.expr(e),
|
|
275
422
|
FnBody::Extern => {}
|
|
276
423
|
}
|
|
277
424
|
}
|
|
278
425
|
Item::Test(t) => {
|
|
426
|
+
// The test wrapper passes the capability as `io`.
|
|
427
|
+
cx.scopes = vec![HashSet::from(["io".to_string()])];
|
|
279
|
-
cx.
|
|
428
|
+
cx.block(&mut t.body);
|
|
280
|
-
visitBlock(&mut t.body, &mut |e| cx.visit(e));
|
|
281
429
|
}
|
|
282
430
|
Item::Const(c) => {
|
|
283
|
-
cx.
|
|
431
|
+
cx.scopes = vec![HashSet::new()];
|
|
284
|
-
|
|
432
|
+
cx.expr(&mut c.value);
|
|
285
433
|
}
|
|
286
434
|
Item::Enum(_) => {}
|
|
287
435
|
}
|
compiler/core/src/purity.rs
CHANGED
|
@@ -166,9 +166,10 @@ pub fn readOnlyFns(src: &Source) -> HashSet<String> {
|
|
|
166
166
|
}
|
|
167
167
|
let mut info = analyse(f, &ctors, &receivers);
|
|
168
168
|
info.impure = if f.is_extern || matches!(f.body, FnBody::Extern) {
|
|
169
|
-
// `self` of a primitive `Io` extern method
|
|
169
|
+
// `self` of a primitive `Io` extern method, and the `io: Io` of a module-level extern, is
|
|
170
|
+
// the unit-like capability, not an object
|
|
170
171
|
(f.has_self && f.type_param.as_deref() != Some(crate::ast::IO_TYPE))
|
|
171
|
-
|| !f.params.iter().all(|p| match &p.ty {
|
|
172
|
+
|| !f.params.iter().skip(usize::from(takesIoFirst(f))).all(|p| match &p.ty {
|
|
172
173
|
ParamType::Type(t) => t.generics.is_empty() && values.contains(t.name.as_str()),
|
|
173
174
|
_ => false,
|
|
174
175
|
})
|
compiler/core/tests/core/loader_test.rs
CHANGED
|
@@ -32,7 +32,7 @@ fn importSeesImportedDeclarations() {
|
|
|
32
32
|
let entry = writeLibFile(
|
|
33
33
|
&lib_path,
|
|
34
34
|
"main",
|
|
35
|
-
"module fixtures\n\nimport helper\n\nfun main(u: Unit) -> Unit =\n helperFn(u)\n",
|
|
35
|
+
"module fixtures\n\nimport helper\n\nfun main(u: Unit) -> Unit =\n helper.helperFn(u)\n",
|
|
36
36
|
);
|
|
37
37
|
|
|
38
38
|
let merged = loadAndMergeDiag(&entry, &lib_path).expect("loadAndMerge failed");
|
|
@@ -68,12 +68,12 @@ fn transitiveImportSurfacesGrandchildDeclarations() {
|
|
|
68
68
|
writeLibFile(
|
|
69
69
|
&lib_path,
|
|
70
70
|
"b",
|
|
71
|
-
"module fixtures\n\nimport c\n\nfun bFn(u: Unit) -> Unit =\n cFn(u)\n",
|
|
71
|
+
"module fixtures\n\nimport c\n\nfun bFn(u: Unit) -> Unit =\n c.cFn(u)\n",
|
|
72
72
|
);
|
|
73
73
|
let entry = writeLibFile(
|
|
74
74
|
&lib_path,
|
|
75
75
|
"a",
|
|
76
|
-
"module fixtures\n\nimport b\n\nfun main(u: Unit) -> Unit =\n bFn(u)\n",
|
|
76
|
+
"module fixtures\n\nimport b\n\nfun main(u: Unit) -> Unit =\n b.bFn(u)\n",
|
|
77
77
|
);
|
|
78
78
|
|
|
79
79
|
let merged = loadAndMergeDiag(&entry, &lib_path).expect("loadAndMerge failed");
|
|
@@ -104,17 +104,17 @@ fn diamondImportIncludesSharedDependencyOnce() {
|
|
|
104
104
|
writeLibFile(
|
|
105
105
|
&lib_path,
|
|
106
106
|
"b",
|
|
107
|
-
"module fixtures\n\nimport d\n\nfun bFn(u: Unit) -> Unit =\n dFn(u)\n",
|
|
107
|
+
"module fixtures\n\nimport d\n\nfun bFn(u: Unit) -> Unit =\n d.dFn(u)\n",
|
|
108
108
|
);
|
|
109
109
|
writeLibFile(
|
|
110
110
|
&lib_path,
|
|
111
111
|
"c",
|
|
112
|
-
"module fixtures\n\nimport d\n\nfun cFn(u: Unit) -> Unit =\n dFn(u)\n",
|
|
112
|
+
"module fixtures\n\nimport d\n\nfun cFn(u: Unit) -> Unit =\n d.dFn(u)\n",
|
|
113
113
|
);
|
|
114
114
|
let entry = writeLibFile(
|
|
115
115
|
&lib_path,
|
|
116
116
|
"a",
|
|
117
|
-
"module fixtures\n\nimport b\nimport c\n\nfun main(u: Unit) -> Unit =\n bFn(cFn(u))\n",
|
|
117
|
+
"module fixtures\n\nimport b\nimport c\n\nfun main(u: Unit) -> Unit =\n b.bFn(c.cFn(u))\n",
|
|
118
118
|
);
|
|
119
119
|
|
|
120
120
|
let merged = loadAndMergeDiag(&entry, &lib_path).expect("loadAndMerge failed");
|
|
@@ -142,7 +142,7 @@ fn importCycleResolvesWithoutHangingOrErroring() {
|
|
|
142
142
|
let entry = writeLibFile(
|
|
143
143
|
&lib_path,
|
|
144
144
|
"a",
|
|
145
|
-
"module fixtures\n\nimport b\n\nfun main(u: Unit) -> Unit =\n bFn(u)\n",
|
|
145
|
+
"module fixtures\n\nimport b\n\nfun main(u: Unit) -> Unit =\n b.bFn(u)\n",
|
|
146
146
|
);
|
|
147
147
|
|
|
148
148
|
let merged = loadAndMergeDiag(&entry, &lib_path).expect("import cycle should resolve, not error");
|
|
@@ -371,10 +371,10 @@ fn duplicate_const_in_one_body() {
|
|
|
371
371
|
let entry = writeLibFile(
|
|
372
372
|
&lib_path,
|
|
373
373
|
"main",
|
|
374
|
-
"module fixtures\n\
|
|
374
|
+
"module fixtures\n\nPi = true\nPi = false\n",
|
|
375
375
|
);
|
|
376
376
|
let msg = errText(loadAndMergeDiag(&entry, &lib_path).unwrap_err());
|
|
377
|
-
assert!(msg.contains("duplicate constant '
|
|
377
|
+
assert!(msg.contains("duplicate constant 'Pi'"), "{}", msg);
|
|
378
378
|
}
|
|
379
379
|
|
|
380
380
|
#[test]
|
|
@@ -384,12 +384,12 @@ fn assoc_const_names_are_per_type_across_modules() {
|
|
|
384
384
|
writeLibFile(
|
|
385
385
|
&lib_path,
|
|
386
386
|
"helper",
|
|
387
|
-
"module fixtures\n\
|
|
387
|
+
"module fixtures\n\nstruct Alpha(x: Bool) =\n Flag = true\n",
|
|
388
388
|
);
|
|
389
389
|
let entry = writeLibFile(
|
|
390
390
|
&lib_path,
|
|
391
391
|
"main",
|
|
392
|
-
"module fixtures\n\nimport helper\n\
|
|
392
|
+
"module fixtures\n\nimport helper\n\nstruct Beta(x: Bool) =\n Flag = false\n",
|
|
393
393
|
);
|
|
394
394
|
let merged = loadAndMergeDiag(&entry, &lib_path).unwrap();
|
|
395
395
|
let names: Vec<String> = merged
|
|
@@ -418,14 +418,23 @@ fn primitive_builtin_std_only() {
|
|
|
418
418
|
.unwrap();
|
|
419
419
|
let err = errText(loadAndMergeDiag(&entry, dir.path()).unwrap_err());
|
|
420
420
|
assert!(err.contains("only allowed in std"), "{err}");
|
|
421
|
+
// Any other `primitive` (a namespace of constants and functions) is std's too: user
|
|
421
|
-
//
|
|
422
|
+
// code writes module-level functions and constants.
|
|
422
|
-
let
|
|
423
|
+
let ns = dir.path().join("ns.plum");
|
|
423
424
|
fs::write(
|
|
424
|
-
&
|
|
425
|
+
&ns,
|
|
425
426
|
"primitive Util =\n Enabled = true\n fun f() -> Unit =\n todo\n",
|
|
426
427
|
)
|
|
427
428
|
.unwrap();
|
|
429
|
+
let err = errText(loadAndMergeDiag(&ns, dir.path()).unwrap_err());
|
|
430
|
+
assert!(err.contains("primitive Util is only allowed in std"), "{err}");
|
|
431
|
+
let consts = dir.path().join("consts.plum");
|
|
432
|
+
fs::write(&consts, "primitive Config =\n Retries = 3\n").unwrap();
|
|
433
|
+
let err = errText(loadAndMergeDiag(&consts, dir.path()).unwrap_err());
|
|
434
|
+
assert!(err.contains("primitive Config is only allowed in std"), "{err}");
|
|
435
|
+
let plain = dir.path().join("plain.plum");
|
|
436
|
+
fs::write(&plain, "Retries = true\n\nfun f() -> Unit =\n todo\n").unwrap();
|
|
428
|
-
assert!(loadAndMergeDiag(&
|
|
437
|
+
assert!(loadAndMergeDiag(&plain, dir.path()).is_ok());
|
|
429
438
|
// Inside std, a built-in: fine.
|
|
430
439
|
let std = dir.path().join("std");
|
|
431
440
|
fs::create_dir_all(&std).unwrap();
|
|
@@ -489,7 +498,7 @@ fn outOfRangeLiteralInEntryOrImportSurvivesTheMerge() {
|
|
|
489
498
|
let entry = writeLibFile(
|
|
490
499
|
&lib_path,
|
|
491
500
|
"main",
|
|
492
|
-
"module fixtures\n\nimport helper\n\nfun main(u: Unit) -> Unit =\n big(u)\n",
|
|
501
|
+
"module fixtures\n\nimport helper\n\nfun main(u: Unit) -> Unit =\n helper.big(u)\n",
|
|
493
502
|
);
|
|
494
503
|
let merged = loadAndMergeDiag(&entry, &lib_path).expect("loadAndMerge failed");
|
|
495
504
|
assert!(
|
|
@@ -546,7 +555,7 @@ fn nestedStdImportResolvesToASubdirectory() {
|
|
|
546
555
|
let entry = writeLibFile(
|
|
547
556
|
&lib_path,
|
|
548
557
|
"main",
|
|
549
|
-
"module fixtures\n\nimport std/game/Util\n\nfun mainFn(b: Bool) -> Bool =\n helperFn(b)\n",
|
|
558
|
+
"module fixtures\n\nimport std/game/Util\n\nfun mainFn(b: Bool) -> Bool =\n util.helperFn(b)\n",
|
|
550
559
|
);
|
|
551
560
|
let source = loadAndMergeDiag(&entry, &lib_path).expect("nested std import loads");
|
|
552
561
|
assert!(source.items.iter().any(
|
compiler/game/src/api.rs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
//! The host API a Plum game programs against: one `Backend` method per
|
|
2
|
-
//! extern in `std/game/
|
|
2
|
+
//! extern in `std/game/gfx.plum`, in Rust types (`Float` is `f32`, `Int` is
|
|
3
3
|
//! `i32`, `Str` is `&str`, a `Color` is `[f32; 4]`, a `Vec2` is `(f32, f32)`).
|
|
4
4
|
//! `Int` handles are indexes into host vectors, `-1` on failure. The browser
|
|
5
5
|
//! bridge (`web/plum_bridge.js`) implements the same API; this crate's
|
compiler/game/tests/fixtures/assets_fixture.plum
CHANGED
|
@@ -3,10 +3,10 @@ module assets_fixture
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
|
-
import std/
|
|
6
|
+
import std/os
|
|
7
7
|
import std/game/Vec2
|
|
8
8
|
import std/game/Color
|
|
9
|
-
import std/game/
|
|
9
|
+
import std/game/gfx
|
|
10
10
|
import std/Io
|
|
11
11
|
|
|
12
12
|
# Loads through the raw `io` (a missing file answers -1 or empty, where `Texture.load`
|
|
@@ -17,17 +17,17 @@ struct State(frames: Int) =
|
|
|
17
17
|
|
|
18
18
|
# Loads a texture and files from the asset root and reports what came back as text.
|
|
19
19
|
fun draw(self, io: Io) =
|
|
20
|
-
t := Texture(id:
|
|
20
|
+
t := Texture(id: gfx.textureLoad(io, "sprites.png"))
|
|
21
|
-
|
|
21
|
+
gfx.drawText(io, "size {gfx.textureWidth(io, t.id)}x{gfx.textureHeight(io, t.id)}", 0.0, 0.0, 8.0, Color.White)
|
|
22
22
|
t.setSmooth(io, true)
|
|
23
23
|
t.draw(io, 1.0, 2.0, Color.White)
|
|
24
|
-
|
|
24
|
+
gfx.drawTextureEx(io, t.id, 16.0, 0.0, 16.0, 16.0, 10.0, 20.0, 32.0, 48.0, 0.5, true, Color.Blue)
|
|
25
|
-
|
|
25
|
+
gfx.drawText(io, "bad {gfx.textureWidth(io, 99)} {gfx.textureLoad(io, "missing.png")}", 0.0, 0.0, 8.0, Color.White)
|
|
26
|
-
if
|
|
26
|
+
if gfx.fileExists(io, "hello.txt")
|
|
27
|
-
|
|
27
|
+
gfx.drawText(io, "file [{gfx.fileLoad(io, "hello.txt")}]", 0.0, 0.0, 8.0, Color.White)
|
|
28
|
-
|
|
28
|
+
gfx.drawText(io, "missing [{gfx.fileLoad(io, "nope.txt")}] {gfx.fileExists(io, "nope.txt")}", 0.0, 0.0, 8.0, Color.White)
|
|
29
|
-
|
|
29
|
+
gfx.drawText(io, "escape {gfx.textureLoad(io, "../sprites.png")} {gfx.fileExists(io, "../hello.txt")} [{gfx.fileLoad(io, "../hello.txt")}]", 0.0, 0.0, 8.0, Color.White)
|
|
30
|
-
|
|
30
|
+
gfx.drawText(io, "abs {gfx.textureLoad(io, "/etc/hosts")} {gfx.fileExists(io, "/etc/hosts")}", 0.0, 0.0, 8.0, Color.White)
|
|
31
31
|
|
|
32
32
|
fun main(io: Io) -> State =
|
|
33
33
|
State(frames: 0)
|
compiler/game/tests/fixtures/host_fixture.plum
CHANGED
|
@@ -3,11 +3,12 @@ module host_fixture
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
|
-
import std/
|
|
6
|
+
import std/os
|
|
7
7
|
import std/game/Vec2
|
|
8
8
|
import std/game/Color
|
|
9
|
-
import std/game/
|
|
9
|
+
import std/game/gfx
|
|
10
10
|
import std/Io
|
|
11
|
+
import std/game/input
|
|
11
12
|
|
|
12
13
|
# One raw host read in `draw` (`mousePos`), so the recorded call order is fixed.
|
|
13
14
|
struct State(frames: Int) =
|
|
@@ -15,13 +16,13 @@ struct State(frames: Int) =
|
|
|
15
16
|
State(frames: self.frames + 1)
|
|
16
17
|
|
|
17
18
|
fun draw(self, io: Io) =
|
|
18
|
-
|
|
19
|
+
gfx.clear(io, Color.Black)
|
|
19
|
-
|
|
20
|
+
gfx.drawRect(io, 1.0, 2.0, 3.0, 4.0, Color.Red)
|
|
20
|
-
|
|
21
|
+
gfx.drawCircle(io, 5.0, 6.0, 7.0, Color.Green)
|
|
21
|
-
p :=
|
|
22
|
+
p := input.mousePos(io)
|
|
22
|
-
|
|
23
|
+
gfx.drawText(io, "hi", p.x, p.y, 16.0, Color.White)
|
|
23
24
|
if self.frames > 0
|
|
24
|
-
|
|
25
|
+
gfx.drawText(io, "frames {self.frames}", 0.0, 0.0, 8.0, Color.White)
|
|
25
26
|
|
|
26
27
|
fun main(io: Io) -> State =
|
|
27
28
|
State(frames: 0)
|
compiler/game/tests/fixtures/main_cli_fixture.plum
CHANGED
|
@@ -2,9 +2,9 @@ module main_cli_fixture
|
|
|
2
2
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Str
|
|
5
|
-
import std/game/
|
|
5
|
+
import std/game/input
|
|
6
6
|
import std/Io
|
|
7
7
|
|
|
8
|
-
# Imports std/game/
|
|
8
|
+
# Imports std/game/gfx but `main` does not return a Game: a CLI program, no update/draw.
|
|
9
9
|
fun main(io: Io) =
|
|
10
10
|
io.printLn("{Key.Space}")
|
compiler/game/tests/fixtures/main_game_fixture.plum
CHANGED
|
@@ -7,8 +7,8 @@ import std/Bool
|
|
|
7
7
|
import std/Slice
|
|
8
8
|
import std/game/Vec2
|
|
9
9
|
import std/game/Color
|
|
10
|
-
import std/game/
|
|
10
|
+
import std/game/gfx
|
|
11
|
-
import std/game/
|
|
11
|
+
import std/game/input
|
|
12
12
|
import std/Io
|
|
13
13
|
|
|
14
14
|
# A game whose entry is `main`, declared to return `Orbs`, which has `update` and `draw`.
|
|
@@ -21,7 +21,7 @@ struct Orbs(x: Float, ship: Texture, input: Input, frame: Int) =
|
|
|
21
21
|
fun draw(self, io: Io) =
|
|
22
22
|
first := self.input.events.length()
|
|
23
23
|
second := self.input.events.length()
|
|
24
|
-
|
|
24
|
+
gfx.drawText(io, "frame {self.frame} ev {first} {second} x {self.x} tex {self.ship.id} w {gfx.screenWidth(io)}", 0.0, 0.0, 8.0, Color.White)
|
|
25
25
|
|
|
26
26
|
fun main(io: Io) -> Orbs =
|
|
27
|
-
Orbs(x: 0.0, ship:
|
|
27
|
+
Orbs(x: 0.0, ship: gfx.loadTexture(io, "sprites.png"), input: Input.create(), frame: 0)
|
compiler/game/tests/fixtures/main_missing_fixture.plum
CHANGED
|
@@ -4,7 +4,7 @@ import std/Int
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/game/Color
|
|
7
|
-
import std/game/
|
|
7
|
+
import std/game/gfx
|
|
8
8
|
import std/Io
|
|
9
9
|
|
|
10
10
|
struct Broken(tex: Texture) =
|
|
@@ -12,7 +12,7 @@ struct Broken(tex: Texture) =
|
|
|
12
12
|
self
|
|
13
13
|
|
|
14
14
|
fun draw(self, io: Io) =
|
|
15
|
-
|
|
15
|
+
gfx.clear(io, Color.Black)
|
|
16
16
|
|
|
17
17
|
fun main(io: Io) -> Broken =
|
|
18
|
-
Broken(tex:
|
|
18
|
+
Broken(tex: gfx.loadTexture(io, "nope.png"))
|
compiler/game/tests/fixtures/target_fixture.plum
CHANGED
|
@@ -5,7 +5,7 @@ import std/Float
|
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/game/Vec2
|
|
7
7
|
import std/game/Color
|
|
8
|
-
import std/game/
|
|
8
|
+
import std/game/gfx
|
|
9
9
|
import std/Io
|
|
10
10
|
|
|
11
11
|
# `bad` is a raw `io.textureCreate` of an impossible size: it answers -1 where
|
|
@@ -16,13 +16,13 @@ struct State(target: Texture, bad: Int) =
|
|
|
16
16
|
|
|
17
17
|
fun draw(self, io: Io) =
|
|
18
18
|
self.target.renderTarget(io)
|
|
19
|
-
|
|
19
|
+
gfx.clear(io, Color.Transparent)
|
|
20
|
-
|
|
20
|
+
gfx.drawRect(io, 0.0, 0.0, 10.0, 10.0, Color.Red)
|
|
21
|
-
|
|
21
|
+
gfx.renderToScreen(io)
|
|
22
|
-
|
|
22
|
+
gfx.blendMode(io, Blend.Add)
|
|
23
23
|
self.target.draw(io, 20.0, 20.0, Color.White)
|
|
24
|
-
|
|
24
|
+
gfx.blendMode(io, Blend.Normal)
|
|
25
|
-
|
|
25
|
+
gfx.drawText(io, "size {self.target.width(io)}x{self.target.height(io)} bad {self.bad}", 0.0, 0.0, 8.0, Color.White)
|
|
26
26
|
|
|
27
27
|
fun main(io: Io) -> State =
|
|
28
|
-
State(target:
|
|
28
|
+
State(target: gfx.createTexture(io, 64, 32), bad: gfx.textureCreate(io, 0, 5))
|
compiler/game/tests/host_test.rs
CHANGED
|
@@ -106,7 +106,7 @@ fn unknownImportTraps() {
|
|
|
106
106
|
let path = dir.join("m.plum");
|
|
107
107
|
std::fs::write(
|
|
108
108
|
&path,
|
|
109
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/
|
|
109
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/gfx\nstruct State(n: Int) =\n fun update(self, io: Io, dt: Float) -> State =\n self\n fun draw(self, io: Io) =\n x := io.rawExists(\"a\")\n\nfun main(io: Io) -> State =\n State(n: 0)\n",
|
|
110
110
|
)
|
|
111
111
|
.unwrap();
|
|
112
112
|
let wasm = compile(&path);
|
|
@@ -314,7 +314,7 @@ fn randomSeedProvidedByHost() {
|
|
|
314
314
|
let path = dir.join("m.plum");
|
|
315
315
|
std::fs::write(
|
|
316
316
|
&path,
|
|
317
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/Color\nimport std/game/
|
|
317
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/Color\nimport std/game/gfx\nstruct State(seed: Int) =\n fun update(self, io: Io, dt: Float) -> State =\n self\n fun draw(self, io: Io) =\n gfx.drawText(io, \"seed {self.seed}\", 0.0, 0.0, 8.0, Color.White)\n\nfun main(io: Io) -> State =\n State(seed: io.randomSeed())\n",
|
|
318
318
|
)
|
|
319
319
|
.unwrap();
|
|
320
320
|
let wasm = compile(&path);
|
compiler/game/web-test/fixtures/interleave.plum
CHANGED
|
@@ -8,14 +8,13 @@ import std/Float
|
|
|
8
8
|
import std/Array
|
|
9
9
|
import std/game/Vec2
|
|
10
10
|
import std/game/Color
|
|
11
|
-
import std/game/
|
|
11
|
+
import std/game/gfx
|
|
12
12
|
import std/Io
|
|
13
13
|
|
|
14
|
-
primitive Scene =
|
|
15
|
-
|
|
14
|
+
Sprites = 4000
|
|
16
|
-
|
|
15
|
+
Textures = 8
|
|
17
|
-
|
|
16
|
+
WorldW = 1264
|
|
18
|
-
|
|
17
|
+
WorldH = 704
|
|
19
18
|
|
|
20
19
|
struct Interleave(tex: Array[Texture], t: Int) =
|
|
21
20
|
fun update(self, io: Io, dt: Float) -> Interleave =
|
|
@@ -25,14 +24,14 @@ struct Interleave(tex: Array[Texture], t: Int) =
|
|
|
25
24
|
drawSprites(io, self.tex, self.t)
|
|
26
25
|
|
|
27
26
|
fun main(io: Io) -> Interleave =
|
|
28
|
-
tex := Array.filled(
|
|
27
|
+
tex := Array.filled(Textures, Texture(id: -1))
|
|
29
|
-
for i := range
|
|
28
|
+
for i := range Textures
|
|
30
|
-
tex.set(i,
|
|
29
|
+
tex.set(i, gfx.loadTexture(io, "tex{i}.png"))
|
|
31
30
|
Interleave(tex: tex, t: 0)
|
|
32
31
|
|
|
33
32
|
fun drawSprites(io: Io, tex: Array[Texture], t: Int) =
|
|
34
|
-
|
|
33
|
+
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
35
|
-
for i := range
|
|
34
|
+
for i := range Sprites
|
|
36
|
-
x := {i * 37 + t * {1 + i % 5}} %
|
|
35
|
+
x := {i * 37 + t * {1 + i % 5}} % WorldW
|
|
37
|
-
y := {i * 53 + t * {1 + i % 3}} %
|
|
36
|
+
y := {i * 53 + t * {1 + i % 3}} % WorldH
|
|
38
|
-
tex.get(i %
|
|
37
|
+
tex.get(i % Textures).draw(io, Float(x), Float(y), Color.White)
|
compiler/game/web-test/fixtures/main_game.plum
CHANGED
|
@@ -5,7 +5,7 @@ import std/Float
|
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/game/Vec2
|
|
7
7
|
import std/game/Color
|
|
8
|
-
import std/game/
|
|
8
|
+
import std/game/gfx
|
|
9
9
|
import std/Io
|
|
10
10
|
|
|
11
11
|
# A game whose entry is `main` returning a type with `update` and `draw`; draws a square that moves with the frame count.
|
|
@@ -14,9 +14,9 @@ struct Mover(frame: Int) =
|
|
|
14
14
|
Mover(frame: self.frame + 1)
|
|
15
15
|
|
|
16
16
|
fun draw(self, io: Io) =
|
|
17
|
-
|
|
17
|
+
gfx.clear(io, Color.rgb(0.2, 0.2, 0.2))
|
|
18
|
-
|
|
18
|
+
gfx.drawRect(io, Float(self.frame % 600), 100.0, 40.0, 40.0, Color.Yellow)
|
|
19
|
-
|
|
19
|
+
gfx.drawText(io, "frame {self.frame}", 20.0, 20.0, 16.0, Color.White)
|
|
20
20
|
|
|
21
21
|
fun main(io: Io) -> Mover =
|
|
22
22
|
Mover(frame: 0)
|
compiler/game/web-test/fixtures/rendertarget.plum
CHANGED
|
@@ -16,7 +16,7 @@ import std/Int
|
|
|
16
16
|
import std/Float
|
|
17
17
|
import std/game/Vec2
|
|
18
18
|
import std/game/Color
|
|
19
|
-
import std/game/
|
|
19
|
+
import std/game/gfx
|
|
20
20
|
import std/Io
|
|
21
21
|
|
|
22
22
|
struct Targets(big: Texture, small: Texture, glass: Texture, t: Int) =
|
|
@@ -27,32 +27,32 @@ struct Targets(big: Texture, small: Texture, glass: Texture, t: Int) =
|
|
|
27
27
|
drawTargets(io, self)
|
|
28
28
|
|
|
29
29
|
fun main(io: Io) -> Targets =
|
|
30
|
-
Targets(big:
|
|
30
|
+
Targets(big: gfx.createTexture(io, 64, 64), small: gfx.createTexture(io, 16, 16), glass: gfx.createTexture(io, 16, 16), t: 0)
|
|
31
31
|
|
|
32
32
|
fun drawTargets(io: Io, g: Targets) =
|
|
33
|
-
|
|
33
|
+
gfx.setCamera(io, 10.0, 0.0, 2.0)
|
|
34
34
|
g.big.renderTarget(io)
|
|
35
|
-
|
|
35
|
+
gfx.clear(io, Color.Transparent)
|
|
36
|
-
|
|
36
|
+
gfx.drawRect(io, 0.0, 0.0, 32.0, 32.0, Color.rgb(1.0, 0.0, 0.0))
|
|
37
|
-
|
|
37
|
+
gfx.drawRect(io, 32.0, 32.0, 32.0, 32.0, Color.rgb(0.0, 1.0, 0.0))
|
|
38
38
|
g.small.renderTarget(io)
|
|
39
|
-
|
|
39
|
+
gfx.clear(io, Color.rgb(0.0, 0.0, 1.0))
|
|
40
40
|
g.glass.renderTarget(io)
|
|
41
|
-
|
|
41
|
+
gfx.clear(io, Color.Transparent)
|
|
42
|
-
|
|
42
|
+
gfx.drawRect(io, 0.0, 0.0, 16.0, 16.0, Color(r: 1.0, g: 0.0, b: 0.0, a: 0.5))
|
|
43
|
-
|
|
43
|
+
gfx.renderToScreen(io)
|
|
44
|
-
|
|
44
|
+
gfx.clear(io, Color.rgb(0.2, 0.2, 0.2))
|
|
45
45
|
g.big.draw(io, 60.0, 50.0, Color.White)
|
|
46
|
-
|
|
46
|
+
gfx.resetCamera(io)
|
|
47
|
-
|
|
47
|
+
gfx.blendMode(io, Blend.Add)
|
|
48
|
-
|
|
48
|
+
gfx.drawRect(io, 400.0, 100.0, 100.0, 100.0, Color.rgb(0.2, 0.4, 0.6))
|
|
49
|
-
|
|
49
|
+
gfx.blendMode(io, Blend.Multiply)
|
|
50
|
-
|
|
50
|
+
gfx.drawRect(io, 550.0, 100.0, 100.0, 100.0, Color.rgb(0.5, 1.0, 0.5))
|
|
51
|
-
|
|
51
|
+
gfx.blendMode(io, Blend.Screen)
|
|
52
|
-
|
|
52
|
+
gfx.drawRect(io, 700.0, 100.0, 100.0, 100.0, Color.rgb(0.5, 0.5, 0.5))
|
|
53
|
-
|
|
53
|
+
gfx.blendMode(io, Blend.Normal)
|
|
54
|
-
|
|
54
|
+
gfx.drawRect(io, 850.0, 100.0, 100.0, 100.0, Color(r: 1.0, g: 0.0, b: 0.0, a: 0.5))
|
|
55
55
|
g.small.draw(io, 400.0, 300.0, Color.White)
|
|
56
56
|
g.glass.draw(io, 400.0, 400.0, Color.White)
|
|
57
|
-
|
|
57
|
+
gfx.drawText(io, "frame {g.t}", 20.0, 500.0, 16.0, Color.White)
|
|
58
|
-
|
|
58
|
+
gfx.drawRect(io, Float(g.t % 600), 600.0, 40.0, 6.0, Color.Yellow)
|
compiler/game/web-test/fixtures/stress.plum
CHANGED
|
@@ -8,16 +8,15 @@ import std/Int
|
|
|
8
8
|
import std/Float
|
|
9
9
|
import std/game/Vec2
|
|
10
10
|
import std/game/Color
|
|
11
|
-
import std/game/
|
|
11
|
+
import std/game/gfx
|
|
12
12
|
import std/Io
|
|
13
13
|
|
|
14
|
-
primitive Scene =
|
|
15
|
-
|
|
14
|
+
Sprites = 5000
|
|
16
|
-
|
|
15
|
+
Rects = 500
|
|
17
|
-
|
|
16
|
+
Circles = 200
|
|
18
|
-
|
|
17
|
+
Texts = 50
|
|
19
|
-
|
|
18
|
+
WorldW = 1600
|
|
20
|
-
|
|
19
|
+
WorldH = 900
|
|
21
20
|
|
|
22
21
|
struct Stress(sheet: Texture, t: Int) =
|
|
23
22
|
fun update(self, io: Io, dt: Float) -> Stress =
|
|
@@ -27,27 +26,27 @@ struct Stress(sheet: Texture, t: Int) =
|
|
|
27
26
|
drawStress(io, self.sheet, self.t)
|
|
28
27
|
|
|
29
28
|
fun main(io: Io) -> Stress =
|
|
30
|
-
Stress(sheet:
|
|
29
|
+
Stress(sheet: gfx.loadTexture(io, "sprites.png"), t: 0)
|
|
31
30
|
|
|
32
31
|
fun hue(i: Int) -> Color =
|
|
33
32
|
Color(r: Float(i % 7) / 7.0, g: Float(i % 5) / 5.0, b: 0.4 + Float(i % 3) / 5.0, a: 0.8)
|
|
34
33
|
|
|
35
34
|
fun drawStress(io: Io, sheet: Texture, t: Int) =
|
|
36
|
-
|
|
35
|
+
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
37
|
-
|
|
36
|
+
gfx.setCamera(io, 0.0, 0.0, 0.8)
|
|
38
|
-
for i := range
|
|
37
|
+
for i := range Sprites
|
|
39
|
-
x := {i * 37 + t * {1 + i % 5}} %
|
|
38
|
+
x := {i * 37 + t * {1 + i % 5}} % WorldW
|
|
40
|
-
y := {i * 53 + t * {1 + i % 3}} %
|
|
39
|
+
y := {i * 53 + t * {1 + i % 3}} % WorldH
|
|
41
40
|
frame := {i + t / 6} % 4
|
|
42
|
-
|
|
41
|
+
gfx.drawTextureEx(io, sheet.id, Float(frame * 16), 0.0, 16.0, 16.0, Float(x), Float(y), 16.0, 16.0, Float(t) * 0.02 + Float(i), i % 2 == 0, Color.White)
|
|
43
|
-
for i := range
|
|
42
|
+
for i := range Rects
|
|
44
|
-
x := {i * 61 + t * 2} %
|
|
43
|
+
x := {i * 61 + t * 2} % WorldW
|
|
45
|
-
y := {i * 29} %
|
|
44
|
+
y := {i * 29} % WorldH
|
|
46
|
-
|
|
45
|
+
gfx.drawRect(io, Float(x), Float(y), 12.0, 8.0, hue(i))
|
|
47
|
-
for i := range
|
|
46
|
+
for i := range Circles
|
|
48
|
-
x := {i * 83 + t * 3} %
|
|
47
|
+
x := {i * 83 + t * 3} % WorldW
|
|
49
|
-
y := {i * 47 + t} %
|
|
48
|
+
y := {i * 47 + t} % WorldH
|
|
50
|
-
|
|
49
|
+
gfx.drawCircle(io, Float(x), Float(y), 6.0, hue(i + 3))
|
|
51
|
-
for i := range
|
|
50
|
+
for i := range Texts
|
|
52
|
-
|
|
51
|
+
gfx.drawText(io, "n {t + i}", Float(i * 30 % WorldW), Float(i * 17 % WorldH), 14.0, Color.White)
|
|
53
|
-
|
|
52
|
+
gfx.resetCamera(io)
|
compiler/game/web-test/fixtures/stress_state_view.plum
CHANGED
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
#
|
|
10
10
|
# Entity counts: 5000 sprites (50 groups x 100), 500 rects, 200 circles, 50 texts,
|
|
11
11
|
# plus 200 animated sprites (Pulsers, pose = Anim.at(anim, clock - start)) and
|
|
12
|
-
# 20
|
|
12
|
+
# 20 ui.button buttons (tagged ids 40000..40019, screen space, outside the camera).
|
|
13
13
|
# `State.ui` is a Ui.UiState fed by mouse input: update turns the mouse into a
|
|
14
|
-
# shared InputEvent, hit-tests the button layer with SceneNode.hitId, and calls
|
|
14
|
+
# shared InputEvent, hit-tests the button layer with SceneNode.hitId, and calls ui.step.
|
|
15
15
|
module stress_state_view
|
|
16
16
|
import std/Str
|
|
17
17
|
import std/Int
|
|
@@ -21,23 +21,22 @@ import std/Option
|
|
|
21
21
|
import std/List
|
|
22
22
|
import std/game/Vec2
|
|
23
23
|
import std/game/Color
|
|
24
|
-
import std/game/
|
|
24
|
+
import std/game/gfx
|
|
25
|
-
import std/game/
|
|
25
|
+
import std/game/scene
|
|
26
26
|
import std/game/Anim
|
|
27
|
-
import std/game/
|
|
27
|
+
import std/game/ui
|
|
28
|
-
import std/game/
|
|
28
|
+
import std/game/input
|
|
29
29
|
import std/Io
|
|
30
30
|
|
|
31
|
-
primitive Counts =
|
|
32
|
-
|
|
31
|
+
Sprites = 5000
|
|
33
|
-
|
|
32
|
+
Rects = 500
|
|
34
|
-
|
|
33
|
+
Circles = 200
|
|
35
|
-
|
|
34
|
+
Texts = 50
|
|
36
|
-
|
|
35
|
+
Pulsers = 200
|
|
37
|
-
|
|
36
|
+
Buttons = 20
|
|
38
|
-
|
|
37
|
+
Groups = 50
|
|
39
|
-
|
|
38
|
+
WorldW = 1600
|
|
40
|
-
|
|
39
|
+
WorldH = 900
|
|
41
40
|
|
|
42
41
|
|
|
43
42
|
fun mapLink[A, B](xs: List[A], f: fn(A) -> B) -> List[B] = match xs
|
|
@@ -98,30 +97,30 @@ fun newDrifter(id: Int, c: Color, x: Float, y: Float, w: Float, h: Float, dx: Fl
|
|
|
98
97
|
Drifter(id: id, x: x, y: y, w: w, h: h, dx: dx, dy: dy, color: c)
|
|
99
98
|
|
|
100
99
|
fun newDancer(gi: Int, j: Int) -> Dancer =
|
|
101
|
-
i := gi * {
|
|
100
|
+
i := gi * {Sprites / Groups} + j
|
|
102
101
|
Dancer(id: 1000 + i, x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16))
|
|
103
102
|
|
|
104
103
|
fun newSpinner(gi: Int) -> Spinner =
|
|
105
|
-
Spinner(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0, dancers: rangeLink(0,
|
|
104
|
+
Spinner(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0, dancers: rangeLink(0, Sprites / Groups, |j| newDancer(gi, j)))
|
|
106
105
|
|
|
107
106
|
fun newState(sheet: Texture, white: Texture) -> State =
|
|
108
|
-
rects := rangeLink(0,
|
|
107
|
+
rects := rangeLink(0, Rects, |i| newDrifter(10000 + i, hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0))
|
|
109
|
-
circles := rangeLink(0,
|
|
108
|
+
circles := rangeLink(0, Circles, |i| newDrifter(20000 + i, hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0))
|
|
110
109
|
State(
|
|
111
|
-
sheet: sheet, white: white, spinners: rangeLink(0,
|
|
110
|
+
sheet: sheet, white: white, spinners: rangeLink(0, Groups, |gi| newSpinner(gi)),
|
|
112
111
|
drifters: appendLink(rects, circles),
|
|
113
|
-
counters: rangeLink(0,
|
|
112
|
+
counters: rangeLink(0, Texts, |i| Counter(id: 30000 + i, x: Float(i * 30 % WorldW), y: Float(i * 17 % WorldH), n: i)),
|
|
114
|
-
pulsers: rangeLink(0,
|
|
113
|
+
pulsers: rangeLink(0, Pulsers, |i| newPulser(i)), anim: pulseAnim(), clock: 0.0, ui: ui.init(), clicks: 0)
|
|
115
114
|
|
|
116
115
|
# --- step: pure ---
|
|
117
116
|
|
|
118
117
|
fun stepDrifter(d: Drifter) -> Drifter =
|
|
119
118
|
nx := d.x + d.dx
|
|
120
119
|
ny := d.y + d.dy
|
|
121
|
-
if nx > Float(
|
|
120
|
+
if nx > Float(WorldW)
|
|
122
|
-
nx = nx - Float(
|
|
121
|
+
nx = nx - Float(WorldW)
|
|
123
|
-
if ny > Float(
|
|
122
|
+
if ny > Float(WorldH)
|
|
124
|
-
ny = ny - Float(
|
|
123
|
+
ny = ny - Float(WorldH)
|
|
125
124
|
Drifter(id: d.id, x: nx, y: ny, w: d.w, h: d.h, dx: d.dx, dy: d.dy, color: d.color)
|
|
126
125
|
|
|
127
126
|
fun stepDancer(d: Dancer, dt: Float) -> Dancer =
|
|
@@ -143,14 +142,14 @@ fun countClicks(es: List[UiEvent]) -> Int = match es
|
|
|
143
142
|
Nil => 0
|
|
144
143
|
Cons(e, t) => {if e.kind == Click then 1 else 0} + countClicks(t)
|
|
145
144
|
|
|
146
|
-
# Feeds one pointer input through
|
|
145
|
+
# Feeds one pointer input through ui.step against the button layer.
|
|
147
146
|
fun stepUi(s: State, input: InputEvent) -> State =
|
|
148
147
|
po := input.position()
|
|
149
148
|
if po.isNone()
|
|
150
149
|
return s
|
|
151
150
|
pos := po.unwrap()
|
|
152
151
|
hit := buttonsView(s.ui).hitId(pos.x, pos.y)
|
|
153
|
-
r :=
|
|
152
|
+
r := ui.step(s.ui, input, hit)
|
|
154
153
|
State(
|
|
155
154
|
sheet: s.sheet, white: s.white, spinners: s.spinners, drifters: s.drifters, counters: s.counters,
|
|
156
155
|
pulsers: s.pulsers, anim: s.anim, clock: s.clock, ui: r.ui, clicks: s.clicks + countClicks(r.events))
|
|
@@ -185,11 +184,11 @@ fun pulserView(sheet: Texture, anim: Anim, clock: Float, p: Pulser) -> SceneNode
|
|
|
185
184
|
tex: sheet, x: 0.0, y: 0.0, w: 16.0, h: 16.0, srcX: p.srcX, srcY: 0.0, srcW: 16.0, srcH: 16.0,
|
|
186
185
|
tint: Color.White), tail: Nil))
|
|
187
186
|
|
|
188
|
-
fun buttonNodes(i: Int,
|
|
187
|
+
fun buttonNodes(i: Int, uiState: UiState) -> List[SceneNode[Int]] =
|
|
189
|
-
if i >=
|
|
188
|
+
if i >= Buttons then Nil else Cons(head: ui.button(40000 + i, 40000 + i, "b{i}", Float(i % 10 * 70 + 10), Float(i / 10 * 30 + 10), 64.0, 24.0, uiState), tail: buttonNodes(i + 1, uiState))
|
|
190
189
|
|
|
191
|
-
fun buttonsView(
|
|
190
|
+
fun buttonsView(uiState: UiState) -> SceneNode[Int] =
|
|
192
|
-
Group(transform: Identity, children: buttonNodes(0,
|
|
191
|
+
Group(transform: Identity, children: buttonNodes(0, uiState))
|
|
193
192
|
|
|
194
193
|
fun view(s: State) -> SceneNode[Int] =
|
|
195
194
|
texts := toNodes(s.counters, |c| counterView(c), Nil)
|
|
@@ -199,10 +198,10 @@ fun view(s: State) -> SceneNode[Int] =
|
|
|
199
198
|
Group(transform: Identity, children: [world, buttonsView(s.ui)])
|
|
200
199
|
|
|
201
200
|
fun whiteTexture(io: Io) -> Texture =
|
|
202
|
-
t :=
|
|
201
|
+
t := gfx.createTexture(io, 1, 1)
|
|
203
202
|
t.renderTarget(io)
|
|
204
|
-
|
|
203
|
+
gfx.clear(io, Color.White)
|
|
205
|
-
|
|
204
|
+
gfx.renderToScreen(io)
|
|
206
205
|
t
|
|
207
206
|
|
|
208
207
|
struct World(state: State, input: Input) =
|
|
@@ -215,11 +214,11 @@ struct World(state: State, input: Input) =
|
|
|
215
214
|
World(state: s, input: input)
|
|
216
215
|
|
|
217
216
|
fun draw(self, io: Io) =
|
|
218
|
-
|
|
217
|
+
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
219
218
|
view(self.state).draw(io)
|
|
220
219
|
|
|
221
220
|
fun main(io: Io) -> World =
|
|
222
|
-
World(state: newState(
|
|
221
|
+
World(state: newState(gfx.loadTexture(io, "sprites.png"), whiteTexture(io)), input: Input.create())
|
|
223
222
|
|
|
224
223
|
test "ten frames of step run"
|
|
225
224
|
s := newState(Texture(id: 0), Texture(id: 0))
|
|
@@ -254,7 +253,7 @@ test "button click counts and pulsers animate"
|
|
|
254
253
|
down := stepUi(s, PointerDown(x: 20.0, y: 20.0))
|
|
255
254
|
up := stepUi(down, PointerUp(x: 20.0, y: 20.0))
|
|
256
255
|
assert up.clicks == 1
|
|
257
|
-
assert
|
|
256
|
+
assert ui.hovered(up.ui, 40000)
|
|
258
257
|
p := newPulser(0)
|
|
259
258
|
a := Anim.at(s.anim, 0.5 - p.start)
|
|
260
259
|
assert a.dx > 14.9 && a.dx < 15.1
|
compiler/game/web-test/fixtures/stress_state_view_deep.plum
CHANGED
|
@@ -16,18 +16,17 @@ import std/Slice
|
|
|
16
16
|
import std/List
|
|
17
17
|
import std/game/Vec2
|
|
18
18
|
import std/game/Color
|
|
19
|
-
import std/game/
|
|
19
|
+
import std/game/gfx
|
|
20
|
-
import std/game/
|
|
20
|
+
import std/game/scene
|
|
21
21
|
import std/Io
|
|
22
22
|
|
|
23
|
-
primitive Counts =
|
|
24
|
-
|
|
23
|
+
Sprites = 5000
|
|
25
|
-
|
|
24
|
+
Rects = 500
|
|
26
|
-
|
|
25
|
+
Circles = 200
|
|
27
|
-
|
|
26
|
+
Texts = 50
|
|
28
|
-
|
|
27
|
+
Groups = 50
|
|
29
|
-
|
|
28
|
+
WorldW = 1600
|
|
30
|
-
|
|
29
|
+
WorldH = 900
|
|
31
30
|
|
|
32
31
|
|
|
33
32
|
fun mapLink[A, B](xs: List[A], f: fn(A) -> B) -> List[B] = match xs
|
|
@@ -77,7 +76,7 @@ fun newDrifter(id: Int, c: Color, x: Float, y: Float, w: Float, h: Float, dx: Fl
|
|
|
77
76
|
Drifter(id: id, x: x, y: y, w: w, h: h, dx: dx, dy: dy, color: c)
|
|
78
77
|
|
|
79
78
|
fun newDancer(gi: Int, j: Int) -> Dancer =
|
|
80
|
-
i := gi * {
|
|
79
|
+
i := gi * {Sprites / Groups} + j
|
|
81
80
|
Dancer(gi: gi, id: 1000 + i, x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16))
|
|
82
81
|
|
|
83
82
|
fun newSpinner(gi: Int) -> Spinner =
|
|
@@ -85,25 +84,25 @@ fun newSpinner(gi: Int) -> Spinner =
|
|
|
85
84
|
|
|
86
85
|
# All dancers, group after group, built by recursion over the spinner index.
|
|
87
86
|
fun allDancers(gi: Int) -> List[Dancer] =
|
|
88
|
-
if gi >=
|
|
87
|
+
if gi >= Groups then Nil else appendLink(rangeLink(0, Sprites / Groups, |j| newDancer(gi, j)), allDancers(gi + 1))
|
|
89
88
|
|
|
90
89
|
fun newState(sheet: Texture, white: Texture) -> State =
|
|
91
|
-
rects := rangeLink(0,
|
|
90
|
+
rects := rangeLink(0, Rects, |i| newDrifter(10000 + i, hue(i), Float(i * 61 % WorldW), Float(i * 29 % WorldH), 12.0, 8.0, 2.0, 0.0))
|
|
92
|
-
circles := rangeLink(0,
|
|
91
|
+
circles := rangeLink(0, Circles, |i| newDrifter(20000 + i, hue(i + 3), Float(i * 83 % WorldW), Float(i * 47 % WorldH), 12.0, 12.0, 3.0, 1.0))
|
|
93
92
|
State(
|
|
94
|
-
sheet: sheet, white: white, spinners: rangeLink(0,
|
|
93
|
+
sheet: sheet, white: white, spinners: rangeLink(0, Groups, |gi| newSpinner(gi)), dancers: allDancers(0),
|
|
95
94
|
drifters: appendLink(rects, circles),
|
|
96
|
-
counters: rangeLink(0,
|
|
95
|
+
counters: rangeLink(0, Texts, |i| Counter(id: 30000 + i, x: Float(i * 30 % WorldW), y: Float(i * 17 % WorldH), n: i)))
|
|
97
96
|
|
|
98
97
|
# --- step: pure ---
|
|
99
98
|
|
|
100
99
|
fun stepDrifter(d: Drifter) -> Drifter =
|
|
101
100
|
nx := d.x + d.dx
|
|
102
101
|
ny := d.y + d.dy
|
|
103
|
-
if nx > Float(
|
|
102
|
+
if nx > Float(WorldW)
|
|
104
|
-
nx = nx - Float(
|
|
103
|
+
nx = nx - Float(WorldW)
|
|
105
|
-
if ny > Float(
|
|
104
|
+
if ny > Float(WorldH)
|
|
106
|
-
ny = ny - Float(
|
|
105
|
+
ny = ny - Float(WorldH)
|
|
107
106
|
Drifter(id: d.id, x: nx, y: ny, w: d.w, h: d.h, dx: d.dx, dy: d.dy, color: d.color)
|
|
108
107
|
|
|
109
108
|
fun stepDancer(d: Dancer, dt: Float) -> Dancer =
|
|
@@ -163,10 +162,10 @@ fun view(s: State) -> SceneNode[Int] =
|
|
|
163
162
|
Group(transform: Scale(sx: 0.8, sy: 0.8), children: spinnerNodes(s.sheet, s.spinners, s.dancers, drifts))
|
|
164
163
|
|
|
165
164
|
fun whiteTexture(io: Io) -> Texture =
|
|
166
|
-
t :=
|
|
165
|
+
t := gfx.createTexture(io, 1, 1)
|
|
167
166
|
t.renderTarget(io)
|
|
168
|
-
|
|
167
|
+
gfx.clear(io, Color.White)
|
|
169
|
-
|
|
168
|
+
gfx.renderToScreen(io)
|
|
170
169
|
t
|
|
171
170
|
|
|
172
171
|
struct World(state: State) =
|
|
@@ -174,11 +173,11 @@ struct World(state: State) =
|
|
|
174
173
|
World(state: step(self.state, dt))
|
|
175
174
|
|
|
176
175
|
fun draw(self, io: Io) =
|
|
177
|
-
|
|
176
|
+
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
178
177
|
view(self.state).draw(io)
|
|
179
178
|
|
|
180
179
|
fun main(io: Io) -> World =
|
|
181
|
-
World(state: newState(
|
|
180
|
+
World(state: newState(gfx.loadTexture(io, "sprites.png"), whiteTexture(io)))
|
|
182
181
|
|
|
183
182
|
test "ten frames of step run"
|
|
184
183
|
s := newState(Texture(id: 0), Texture(id: 0))
|
compiler/game/web-test/fixtures/stress_world.plum
CHANGED
|
@@ -7,22 +7,21 @@ module stress_world
|
|
|
7
7
|
import std/Str
|
|
8
8
|
import std/Int
|
|
9
9
|
import std/Float
|
|
10
|
-
import std/
|
|
10
|
+
import std/math
|
|
11
11
|
import std/List
|
|
12
12
|
import std/Slice
|
|
13
13
|
import std/game/Vec2
|
|
14
14
|
import std/game/Color
|
|
15
|
-
import std/game/
|
|
15
|
+
import std/game/gfx
|
|
16
|
-
import std/game/
|
|
16
|
+
import std/game/scene
|
|
17
17
|
import std/Io
|
|
18
18
|
|
|
19
|
-
primitive World =
|
|
20
|
-
|
|
19
|
+
Sprites = 20000
|
|
21
|
-
|
|
20
|
+
Walkers = 500
|
|
22
|
-
|
|
21
|
+
Width = 4000
|
|
23
|
-
|
|
22
|
+
Height = 2300
|
|
24
|
-
|
|
23
|
+
ViewW = 1280.0
|
|
25
|
-
|
|
24
|
+
ViewH = 720.0
|
|
26
25
|
|
|
27
26
|
# `walker` is the index among the walking sprites, or -1 for one that stands still.
|
|
28
27
|
struct Spr(x: Float, y: Float, srcX: Float, walker: Int)
|
|
@@ -30,13 +29,13 @@ struct Spr(x: Float, y: Float, srcX: Float, walker: Int)
|
|
|
30
29
|
struct State(sheet: Texture, sprites: List[Spr], frame: Int, camX: Float, camY: Float)
|
|
31
30
|
|
|
32
31
|
fun walkerOf(i: Int) -> Int =
|
|
33
|
-
if i % 37 == 0 && i / 37 <
|
|
32
|
+
if i % 37 == 0 && i / 37 < Walkers then i / 37 else -1
|
|
34
33
|
|
|
35
34
|
fun spriteAt(i: Int) -> Spr =
|
|
36
|
-
Spr(x: Float({i * 7919 + 13} %
|
|
35
|
+
Spr(x: Float({i * 7919 + 13} % Width), y: Float({i * i * 31 / 7 + i * 1013} % Height), srcX: Float(i % 4 * 16), walker: walkerOf(i))
|
|
37
36
|
|
|
38
37
|
fun spritesFrom(i: Int) -> List[Spr] =
|
|
39
|
-
if i >=
|
|
38
|
+
if i >= Sprites then Nil else Cons(head: spriteAt(i), tail: spritesFrom(i + 1))
|
|
40
39
|
|
|
41
40
|
fun newState(sheet: Texture) -> State =
|
|
42
41
|
State(sheet: sheet, sprites: spritesFrom(0), frame: 0, camX: 0.0, camY: 0.0)
|
|
@@ -45,7 +44,7 @@ fun walk(frame: Int, s: Spr) -> Spr =
|
|
|
45
44
|
if s.walker < 0
|
|
46
45
|
s
|
|
47
46
|
else
|
|
48
|
-
Spr(..s, y: s.y +
|
|
47
|
+
Spr(..s, y: s.y + math.sin(Float(frame) * 0.05 + Float(s.walker)))
|
|
49
48
|
|
|
50
49
|
# One frame: the camera drifts, some sprites walk, the list is sorted by y.
|
|
51
50
|
fun step(s: State) -> State =
|
|
@@ -53,10 +52,10 @@ fun step(s: State) -> State =
|
|
|
53
52
|
t := Float(frame) * 0.01
|
|
54
53
|
moved := s.sprites.map(|k| walk(frame, k))
|
|
55
54
|
sorted := List.fromSlice(moved.toSlice().sort(|a, b| a.y < b.y))
|
|
56
|
-
State(..s, sprites: sorted, frame: frame, camX: 1300.0 + 600.0 *
|
|
55
|
+
State(..s, sprites: sorted, frame: frame, camX: 1300.0 + 600.0 * math.sin(t), camY: 800.0 + 350.0 * math.cos(t * 0.7))
|
|
57
56
|
|
|
58
57
|
fun inView(s: State, k: Spr) -> Bool =
|
|
59
|
-
k.x + 16.0 >= s.camX && k.x <= s.camX +
|
|
58
|
+
k.x + 16.0 >= s.camX && k.x <= s.camX + ViewW && k.y + 16.0 >= s.camY && k.y <= s.camY + ViewH
|
|
60
59
|
|
|
61
60
|
fun visible(s: State) -> List[Spr] =
|
|
62
61
|
s.sprites.filter(|k| inView(s, k))
|
|
@@ -72,11 +71,11 @@ struct Demo(state: State) =
|
|
|
72
71
|
Demo(state: step(self.state))
|
|
73
72
|
|
|
74
73
|
fun draw(self, io: Io) =
|
|
75
|
-
|
|
74
|
+
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
76
75
|
view(self.state).draw(io)
|
|
77
76
|
|
|
78
77
|
fun main(io: Io) -> Demo =
|
|
79
|
-
Demo(state: newState(
|
|
78
|
+
Demo(state: newState(gfx.loadTexture(io, "sprites.png")))
|
|
80
79
|
|
|
81
80
|
# --- tests ---
|
|
82
81
|
|
compiler/game/web-test/fixtures/text_sizes.plum
CHANGED
|
@@ -7,7 +7,7 @@ import std/Int
|
|
|
7
7
|
import std/Float
|
|
8
8
|
import std/game/Vec2
|
|
9
9
|
import std/game/Color
|
|
10
|
-
import std/game/
|
|
10
|
+
import std/game/gfx
|
|
11
11
|
import std/Io
|
|
12
12
|
|
|
13
13
|
struct Sizes(t: Int) =
|
|
@@ -21,15 +21,15 @@ fun main(io: Io) -> Sizes =
|
|
|
21
21
|
Sizes(t: 0)
|
|
22
22
|
|
|
23
23
|
fun drawSizes(io: Io, t: Int) =
|
|
24
|
-
|
|
24
|
+
gfx.clear(io, Color.rgb(0.08, 0.09, 0.14))
|
|
25
|
-
|
|
25
|
+
gfx.drawText(io, "Size 8: The quick brown fox jumps over the lazy dog 0123456789", 10.0, 6.0, 8.0, Color.White)
|
|
26
|
-
|
|
26
|
+
gfx.drawText(io, "Size 16: The quick brown fox jumps over the lazy dog", 10.0, 24.0, 16.0, Color.White)
|
|
27
|
-
|
|
27
|
+
gfx.drawText(io, "Size 48: Quick brown fox", 10.0, 52.0, 48.0, Color.Yellow)
|
|
28
|
-
|
|
28
|
+
gfx.drawText(io, "Size 128 Wg", 10.0, 112.0, 128.0, Color.rgb(0.5, 0.9, 1.0))
|
|
29
|
-
|
|
29
|
+
gfx.drawText(io, "Latin-1: café naïve über ½ ©", 10.0, 250.0, 24.0, Color.White)
|
|
30
|
-
|
|
30
|
+
gfx.drawText(io, "frame {t}", 700.0, 8.0, 16.0, Color.Green)
|
|
31
|
-
|
|
31
|
+
gfx.drawRect(io, Float(t % 400), 300.0, 60.0, 4.0, Color.Red)
|
|
32
|
-
|
|
32
|
+
gfx.setCamera(io, 0.0, 0.0, 3.0)
|
|
33
|
-
|
|
33
|
+
gfx.drawText(io, "Zoomed x3: size 16", 10.0, 112.0, 16.0, Color.White)
|
|
34
|
-
|
|
34
|
+
gfx.drawText(io, "Zoomed x3: size 8", 10.0, 134.0, 8.0, Color.White)
|
|
35
|
-
|
|
35
|
+
gfx.resetCamera(io)
|
compiler/host/src/lib.rs
CHANGED
|
@@ -411,7 +411,7 @@ pub fn hostImports(
|
|
|
411
411
|
},
|
|
412
412
|
)))
|
|
413
413
|
}
|
|
414
|
-
// A `plum` import this host doesn't define (the game API of `std/game/
|
|
414
|
+
// A `plum` import this host doesn't define (the game API of `std/game/gfx`)
|
|
415
415
|
// is stubbed with a function that traps when called, so a program
|
|
416
416
|
// that imports it can still run or test code that never calls it.
|
|
417
417
|
("plum", n) => {
|
compiler/lsp/src/completion.rs
CHANGED
|
@@ -107,8 +107,8 @@ pub fn topLevelItems(source: &ast::Source) -> Vec<CompletionItem> {
|
|
|
107
107
|
ast::Item::Test(_) => {}
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
|
-
// `primitive` blocks: a
|
|
110
|
+
// `primitive` blocks: a constant group (`Key`) or a built-in type's API (`Int`, `Array`),
|
|
111
|
-
//
|
|
111
|
+
// reached as `Name.f()`.
|
|
112
112
|
for p in &source.primitives {
|
|
113
113
|
if items.iter().any(|i| i.label == p.name) {
|
|
114
114
|
continue;
|
|
@@ -563,9 +563,20 @@ pub fn stdLibIndex(lib_path: &Path) -> HashMap<String, String> {
|
|
|
563
563
|
continue;
|
|
564
564
|
};
|
|
565
565
|
let source = plum_core::AstParser::new(&text).parseSourceRaw(tree.root_node());
|
|
566
|
+
// A file with module-level functions or constants is a module: its name (`os`,
|
|
567
|
+
// `gfx`) is what completion offers and auto-imports. The functions themselves
|
|
568
|
+
// are written `os.readFile(..)`, so they are not indexed by name.
|
|
569
|
+
let isModule = source.items.iter().any(|i| match i {
|
|
570
|
+
ast::Item::Fn(f) => f.type_param.is_none() && !f.is_test,
|
|
571
|
+
ast::Item::Const(c) => !c.name.contains(ast::MEMBER_SEP),
|
|
572
|
+
_ => false,
|
|
573
|
+
});
|
|
574
|
+
if isModule {
|
|
575
|
+
map.entry(plum_core::modules::moduleAlias(&import_path)).or_insert_with(|| import_path.clone());
|
|
576
|
+
}
|
|
566
577
|
for item in &source.items {
|
|
567
578
|
let name = match item {
|
|
568
|
-
ast::Item::Fn(
|
|
579
|
+
ast::Item::Fn(_) => None,
|
|
569
580
|
ast::Item::Enum(e) => {
|
|
570
581
|
map.entry(e.name.clone())
|
|
571
582
|
.or_insert_with(|| import_path.clone());
|
|
@@ -575,14 +586,13 @@ pub fn stdLibIndex(lib_path: &Path) -> HashMap<String, String> {
|
|
|
575
586
|
}
|
|
576
587
|
None
|
|
577
588
|
}
|
|
578
|
-
ast::Item::Const(c) => Some(c.name.clone()),
|
|
579
589
|
_ => None,
|
|
580
590
|
};
|
|
581
591
|
if let Some(name) = name {
|
|
582
592
|
map.entry(name).or_insert_with(|| import_path.clone());
|
|
583
593
|
}
|
|
584
594
|
}
|
|
585
|
-
// `primitive`
|
|
595
|
+
// `primitive` built-in APIs and constant groups (`Int`, `Key`).
|
|
586
596
|
for p in &source.primitives {
|
|
587
597
|
map.entry(p.name.clone())
|
|
588
598
|
.or_insert_with(|| import_path.clone());
|
compiler/lsp/src/main.rs
CHANGED
|
@@ -330,7 +330,7 @@ fn memberCompletionFor(
|
|
|
330
330
|
// `module.`: an imported module's functions and constants, unless a local has that name.
|
|
331
331
|
// Before the load: the placeholder member (`zzzzzz`) is not a function of the module.
|
|
332
332
|
let isModuleName = receiver.chars().next().is_some_and(|c| c.is_ascii_lowercase());
|
|
333
|
-
if let Some(imp) = own_source.imports.iter().filter(|_| isModuleName).find(|i| i.path
|
|
333
|
+
if let Some(imp) = own_source.imports.iter().filter(|_| isModuleName).find(|i| plum_core::modules::moduleAlias(&i.path) == receiver) {
|
|
334
334
|
let isLocal = completion::enclosingFn(&own_source, cursor_line)
|
|
335
335
|
.is_some_and(|f| plum_core::modules::fnLocals(f).contains(receiver));
|
|
336
336
|
if !isLocal {
|
|
@@ -605,17 +605,17 @@ mod tests {
|
|
|
605
605
|
let _ = std::fs::remove_dir_all(&dir);
|
|
606
606
|
}
|
|
607
607
|
|
|
608
|
-
/// `Float.` / `Int.`
|
|
608
|
+
/// `Float.` / `Int.` offer their consts and statics, and
|
|
609
609
|
/// not instance methods.
|
|
610
610
|
#[test]
|
|
611
611
|
fn lsp_completes_statics() {
|
|
612
612
|
let dir = std::env::temp_dir().join(format!("plum-lsp-statics-{}", std::process::id()));
|
|
613
613
|
std::fs::create_dir_all(&dir).unwrap();
|
|
614
614
|
let path = dir.join("t.plum");
|
|
615
|
-
let text = "module t\nimport std/Int\nimport std/Float\n\
|
|
615
|
+
let text = "module t\nimport std/Int\nimport std/Float\n\nfun main() =\n x := Float.zzzzzz\n";
|
|
616
616
|
std::fs::write(&path, text).unwrap();
|
|
617
617
|
let labels = |recv: &str| -> Vec<String> {
|
|
618
|
-
memberCompletionFor(&path, &repoRoot(), text,
|
|
618
|
+
memberCompletionFor(&path, &repoRoot(), text, 6, recv)
|
|
619
619
|
.into_iter()
|
|
620
620
|
.map(|i| i.label)
|
|
621
621
|
.collect()
|
|
@@ -635,28 +635,25 @@ mod tests {
|
|
|
635
635
|
for want in ["Min", "Max", "parse"] {
|
|
636
636
|
assert!(int.iter().any(|l| l == want), "missing {want} in {int:?}");
|
|
637
637
|
}
|
|
638
|
-
let geo = labels("Geo");
|
|
639
|
-
assert!(
|
|
640
|
-
geo.iter().any(|l| l == "Sides") && geo.iter().any(|l| l == "twice"),
|
|
641
|
-
"{geo:?}"
|
|
642
|
-
);
|
|
643
638
|
let _ = std::fs::remove_dir_all(&dir);
|
|
644
639
|
}
|
|
645
640
|
|
|
646
|
-
/// The std
|
|
641
|
+
/// The std modules (`os`, `base64`, `testing`, `http`) are indexed for auto-import by
|
|
647
|
-
///
|
|
642
|
+
/// module name and complete their functions after `name.`.
|
|
648
643
|
#[test]
|
|
649
644
|
fn stdNamespacesCompleteAndAutoImport() {
|
|
650
645
|
let index = completion::stdLibIndex(&repoRoot());
|
|
651
646
|
for (name, path) in [
|
|
652
|
-
("
|
|
647
|
+
("os", "std/os"),
|
|
653
|
-
("
|
|
648
|
+
("base64", "std/base64"),
|
|
654
|
-
("
|
|
649
|
+
("testing", "std/testing"),
|
|
655
|
-
("
|
|
650
|
+
("http", "std/http"),
|
|
651
|
+
("gfx", "std/game/gfx"),
|
|
652
|
+
("input", "std/game/input"),
|
|
656
653
|
("Int", "std/Int"),
|
|
657
|
-
("SceneNode", "std/game/
|
|
654
|
+
("SceneNode", "std/game/scene"),
|
|
658
655
|
("Io", "std/Io"),
|
|
659
|
-
("Key", "std/game/
|
|
656
|
+
("Key", "std/game/input"),
|
|
660
657
|
("Vec2", "std/game/Vec2"),
|
|
661
658
|
] {
|
|
662
659
|
assert_eq!(index.get(name).map(String::as_str), Some(path), "{name}");
|
|
@@ -670,7 +667,7 @@ mod tests {
|
|
|
670
667
|
let dir = std::env::temp_dir().join(format!("plum-lsp-ns-{}", std::process::id()));
|
|
671
668
|
std::fs::create_dir_all(&dir).unwrap();
|
|
672
669
|
let path = dir.join("t.plum");
|
|
673
|
-
let text = "module t\nimport std/Int\nimport std/Str\nimport std/
|
|
670
|
+
let text = "module t\nimport std/Int\nimport std/Str\nimport std/os\nimport std/base64\n\nfun main() =\n x := os.zzzzzz\n";
|
|
674
671
|
std::fs::write(&path, text).unwrap();
|
|
675
672
|
let labels = |recv: &str| -> Vec<String> {
|
|
676
673
|
memberCompletionFor(&path, &repoRoot(), text, 7, recv)
|
|
@@ -678,25 +675,18 @@ mod tests {
|
|
|
678
675
|
.map(|i| i.label)
|
|
679
676
|
.collect()
|
|
680
677
|
};
|
|
681
|
-
let os = labels("
|
|
678
|
+
let os = labels("os");
|
|
682
679
|
assert!(
|
|
683
680
|
os.iter().any(|l| l == "readFile") && os.iter().any(|l| l == "writeFile"),
|
|
684
681
|
"{os:?}"
|
|
685
682
|
);
|
|
686
|
-
let b64 = labels("
|
|
683
|
+
let b64 = labels("base64");
|
|
687
684
|
assert!(
|
|
688
685
|
b64.iter().any(|l| l == "encode") && b64.iter().any(|l| l == "decode"),
|
|
689
686
|
"{b64:?}"
|
|
690
687
|
);
|
|
691
|
-
|
|
688
|
+
// A module's functions are not indexed by name: they are written `os.readFile`.
|
|
692
|
-
let top: Vec<String> = completion::topLevelItems(&merged)
|
|
693
|
-
.into_iter()
|
|
694
|
-
.map(|i| i.label)
|
|
695
|
-
.collect();
|
|
696
|
-
assert!(
|
|
697
|
-
|
|
689
|
+
assert!(index.get("readFile").is_none() && index.get("encode").is_none());
|
|
698
|
-
"{top:?}"
|
|
699
|
-
);
|
|
700
690
|
let _ = std::fs::remove_dir_all(&dir);
|
|
701
691
|
}
|
|
702
692
|
|
compiler/wasm-codegen/src/driver.rs
CHANGED
|
@@ -405,7 +405,7 @@ impl<'a> Setup<'a> {
|
|
|
405
405
|
let imp_params: Vec<ValType> = param_types[skip..].iter().map(narrow).collect();
|
|
406
406
|
let imp_results: Vec<ValType> = ret.iter().map(narrow).collect();
|
|
407
407
|
let type_idx = module.addType(&imp_params, &imp_results);
|
|
408
|
-
let func_idx = module.addImport("plum", &f.name, type_idx);
|
|
408
|
+
let func_idx = module.addImport("plum", plum_core::modules::sourceFnName(&f.name), type_idx);
|
|
409
409
|
extern_wrappers.push((key.clone(), func_idx, param_types, ret, skip));
|
|
410
410
|
func_sigs.insert(
|
|
411
411
|
key,
|
compiler/wasm-codegen/src/emit.rs
CHANGED
|
@@ -38,7 +38,7 @@ impl<'a> Emit<'a> {
|
|
|
38
38
|
};
|
|
39
39
|
compiled_bodies.push((idx, body));
|
|
40
40
|
}
|
|
41
|
-
if units.iter().any(|u| u.f
|
|
41
|
+
if units.iter().any(|u| crate::intrinsics::isMemFn(u.f)) {
|
|
42
42
|
module.enableMemory(16);
|
|
43
43
|
}
|
|
44
44
|
for (idx, body) in &compiled_bodies {
|
compiler/wasm-codegen/src/intrinsics.rs
CHANGED
|
@@ -11,10 +11,10 @@ use crate::*;
|
|
|
11
11
|
/// here — by `fnKey` — instead of compiling their `todo` body to `unreachable`.
|
|
12
12
|
/// Returns `None` for any other function, meaning "compile it normally."
|
|
13
13
|
pub(crate) fn compileIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<Vec<u8>> {
|
|
14
|
+
if isMemFn(f) {
|
|
15
|
+
return compileMemIntrinsicFnBody(f);
|
|
16
|
+
}
|
|
14
17
|
if let Some(recv) = f.type_param.as_deref() {
|
|
15
|
-
if recv == "Mem" {
|
|
16
|
-
return compileMemIntrinsicFnBody(f);
|
|
17
|
-
}
|
|
18
18
|
if isArraySpecialization(recv) {
|
|
19
19
|
return compileArrayIntrinsicFnBody(f, subst);
|
|
20
20
|
}
|
|
@@ -22,8 +22,13 @@ pub(crate) fn compileIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<Vec<u
|
|
|
22
22
|
None
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/// A function of the std module `mem` (`std/mem.plum`): its bodies are intrinsics.
|
|
26
|
+
pub(crate) fn isMemFn(f: &ast::Fn) -> bool {
|
|
27
|
+
f.type_param.is_none() && f.file.replace('\\', "/").ends_with("std/mem.plum")
|
|
28
|
+
}
|
|
29
|
+
|
|
25
|
-
/// `
|
|
30
|
+
/// `mem`'s linear-memory primitives; the declared params start at local 0.
|
|
26
|
-
///
|
|
31
|
+
/// Addresses and values are `Int`
|
|
27
32
|
/// (i64) wrapped to i32; `Float` is demoted to / promoted from f32.
|
|
28
33
|
pub(crate) fn compileMemIntrinsicFnBody(f: &ast::Fn) -> Option<Vec<u8>> {
|
|
29
34
|
let mut body = vec![0u8];
|
|
@@ -36,7 +41,7 @@ pub(crate) fn compileMemIntrinsicFnBody(f: &ast::Fn) -> Option<Vec<u8>> {
|
|
|
36
41
|
align,
|
|
37
42
|
memory_index: 0,
|
|
38
43
|
};
|
|
39
|
-
match f.name
|
|
44
|
+
match plum_core::modules::sourceFnName(&f.name) {
|
|
40
45
|
"size" => {
|
|
41
46
|
Instruction::MemorySize(0).encode(&mut body);
|
|
42
47
|
Instruction::I64ExtendI32U.encode(&mut body);
|
|
@@ -44,38 +49,38 @@ pub(crate) fn compileMemIntrinsicFnBody(f: &ast::Fn) -> Option<Vec<u8>> {
|
|
|
44
49
|
Instruction::I64Mul.encode(&mut body);
|
|
45
50
|
}
|
|
46
51
|
"grow" => {
|
|
47
|
-
arg(&mut body,
|
|
52
|
+
arg(&mut body, 0);
|
|
48
53
|
Instruction::MemoryGrow(0).encode(&mut body);
|
|
49
54
|
Instruction::I64ExtendI32S.encode(&mut body);
|
|
50
55
|
}
|
|
51
56
|
"storeF32" => {
|
|
52
|
-
arg(&mut body,
|
|
57
|
+
arg(&mut body, 0);
|
|
53
|
-
Instruction::LocalGet(
|
|
58
|
+
Instruction::LocalGet(1).encode(&mut body);
|
|
54
59
|
Instruction::F32DemoteF64.encode(&mut body);
|
|
55
60
|
Instruction::F32Store(mem(0)).encode(&mut body);
|
|
56
61
|
}
|
|
57
62
|
"storeI32" => {
|
|
63
|
+
arg(&mut body, 0);
|
|
58
64
|
arg(&mut body, 1);
|
|
59
|
-
arg(&mut body, 2);
|
|
60
65
|
Instruction::I32Store(mem(0)).encode(&mut body);
|
|
61
66
|
}
|
|
62
67
|
"storeU8" => {
|
|
68
|
+
arg(&mut body, 0);
|
|
63
69
|
arg(&mut body, 1);
|
|
64
|
-
arg(&mut body, 2);
|
|
65
70
|
Instruction::I32Store8(mem(0)).encode(&mut body);
|
|
66
71
|
}
|
|
67
72
|
"loadF32" => {
|
|
68
|
-
arg(&mut body,
|
|
73
|
+
arg(&mut body, 0);
|
|
69
74
|
Instruction::F32Load(mem(0)).encode(&mut body);
|
|
70
75
|
Instruction::F64PromoteF32.encode(&mut body);
|
|
71
76
|
}
|
|
72
77
|
"loadI32" => {
|
|
73
|
-
arg(&mut body,
|
|
78
|
+
arg(&mut body, 0);
|
|
74
79
|
Instruction::I32Load(mem(0)).encode(&mut body);
|
|
75
80
|
Instruction::I64ExtendI32S.encode(&mut body);
|
|
76
81
|
}
|
|
77
82
|
"loadU8" => {
|
|
78
|
-
arg(&mut body,
|
|
83
|
+
arg(&mut body, 0);
|
|
79
84
|
Instruction::I32Load8U(mem(0)).encode(&mut body);
|
|
80
85
|
Instruction::I64ExtendI32U.encode(&mut body);
|
|
81
86
|
}
|
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs
CHANGED
|
@@ -1801,15 +1801,14 @@ fun main() -> Int =
|
|
|
1801
1801
|
fn const_list_table() {
|
|
1802
1802
|
let src = format!(
|
|
1803
1803
|
"{}{}\
|
|
1804
|
-
primitive Tables =
|
|
1805
|
-
|
|
1804
|
+
Values = [10, 20, 30].toSlice()
|
|
1806
1805
|
|
|
1807
1806
|
fun total() -> Int =
|
|
1808
|
-
reduceList(
|
|
1807
|
+
reduceList(Values, 0, |a, b| a + b)
|
|
1809
1808
|
|
|
1810
1809
|
fun main() -> Int =
|
|
1811
|
-
|
|
1810
|
+
Values.push(4)
|
|
1812
|
-
|
|
1811
|
+
Values.get(1)! + Values.length() + total() - 78 + 4
|
|
1813
1812
|
",
|
|
1814
1813
|
STD_HEAD, LIST_FNS
|
|
1815
1814
|
);
|
|
@@ -2186,15 +2185,13 @@ fun main() -> Int =
|
|
|
2186
2185
|
|
|
2187
2186
|
#[test]
|
|
2188
2187
|
fn primitive_not_a_type() {
|
|
2188
|
+
// `Key` is one of std's constant groups (a `primitive`): not a type, not a value.
|
|
2189
|
-
let head = STD_HEAD;
|
|
2189
|
+
let head = format!("{STD_HEAD}import std/game/input\n");
|
|
2190
2190
|
let as_type = checkErrorsMerged(
|
|
2191
2191
|
"prim_type",
|
|
2192
2192
|
&format!(
|
|
2193
2193
|
"{head}\
|
|
2194
|
-
primitive Space =
|
|
2195
|
-
Count = 1
|
|
2196
|
-
|
|
2197
|
-
fun f(s:
|
|
2194
|
+
fun f(s: Key) -> Int =
|
|
2198
2195
|
0
|
|
2199
2196
|
|
|
2200
2197
|
fun main() -> Int =
|
|
@@ -2207,11 +2204,8 @@ fun main() -> Int =
|
|
|
2207
2204
|
"prim_value",
|
|
2208
2205
|
&format!(
|
|
2209
2206
|
"{head}\
|
|
2210
|
-
primitive Space =
|
|
2211
|
-
Count = 1
|
|
2212
|
-
|
|
2213
2207
|
fun main() -> Int =
|
|
2214
|
-
x :=
|
|
2208
|
+
x := Key
|
|
2215
2209
|
0
|
|
2216
2210
|
"
|
|
2217
2211
|
),
|
|
@@ -2219,25 +2213,6 @@ fun main() -> Int =
|
|
|
2219
2213
|
assert!(as_value.contains("primitive namespace"), "{as_value}");
|
|
2220
2214
|
}
|
|
2221
2215
|
|
|
2222
|
-
#[test]
|
|
2223
|
-
fn primitive_namespace_self_rejected() {
|
|
2224
|
-
let msg = checkErrorsMerged(
|
|
2225
|
-
"prim_self",
|
|
2226
|
-
&format!(
|
|
2227
|
-
"{}\
|
|
2228
|
-
primitive Space =
|
|
2229
|
-
fun f(self) -> Int =
|
|
2230
|
-
1
|
|
2231
|
-
|
|
2232
|
-
fun main() -> Int =
|
|
2233
|
-
0
|
|
2234
|
-
",
|
|
2235
|
-
STD_HEAD
|
|
2236
|
-
),
|
|
2237
|
-
);
|
|
2238
|
-
assert!(msg.contains("can't take self"), "{msg}");
|
|
2239
|
-
}
|
|
2240
|
-
|
|
2241
2216
|
/// `Str` is `(data, start, len)`: the type section holds exactly one struct of
|
|
2242
2217
|
/// a ref to the packed `array<i8>` plus two i64s, and the only 2-field
|
|
2243
2218
|
/// array-first struct is `Buffer` itself.
|
|
@@ -2703,16 +2678,16 @@ fn memRoundTripsAndGrows() {
|
|
|
2703
2678
|
let src = "\
|
|
2704
2679
|
import std/Int
|
|
2705
2680
|
import std/Float
|
|
2706
|
-
import std/
|
|
2681
|
+
import std/mem
|
|
2707
2682
|
|
|
2708
2683
|
fun main() -> Int =
|
|
2709
|
-
|
|
2684
|
+
mem.storeI32(8, -7)
|
|
2710
|
-
|
|
2685
|
+
mem.storeF32(12, 2.5f)
|
|
2711
|
-
|
|
2686
|
+
mem.storeU8(16, 513)
|
|
2712
|
-
ok :=
|
|
2687
|
+
ok := mem.loadI32(8) == -7 && mem.loadF32(12) == 2.5f && mem.loadU8(16) == 1
|
|
2713
|
-
before :=
|
|
2688
|
+
before := mem.size()
|
|
2714
|
-
old :=
|
|
2689
|
+
old := mem.grow(2)
|
|
2715
|
-
if ok && before == 16 * 65536 && old == 16 &&
|
|
2690
|
+
if ok && before == 16 * 65536 && old == 16 && mem.size() == 18 * 65536 && mem.grow(100000) == -1
|
|
2716
2691
|
return 1
|
|
2717
2692
|
0
|
|
2718
2693
|
";
|
|
@@ -2723,10 +2698,10 @@ fun main() -> Int =
|
|
|
2723
2698
|
fn memOutOfBoundsTraps() {
|
|
2724
2699
|
let src = "\
|
|
2725
2700
|
import std/Int
|
|
2726
|
-
import std/
|
|
2701
|
+
import std/mem
|
|
2727
2702
|
|
|
2728
2703
|
fun main() -> Int =
|
|
2729
|
-
|
|
2704
|
+
mem.loadI32(16 * 65536)
|
|
2730
2705
|
";
|
|
2731
2706
|
let dir = std::env::temp_dir().join(format!("plum_mem_oob_{}", std::process::id()));
|
|
2732
2707
|
std::fs::create_dir_all(&dir).unwrap();
|
|
@@ -2751,10 +2726,10 @@ fun main() -> Int =
|
|
|
2751
2726
|
fn memoryExportedOnlyWhenMemUsed() {
|
|
2752
2727
|
let with = "\
|
|
2753
2728
|
import std/Int
|
|
2754
|
-
import std/
|
|
2729
|
+
import std/mem
|
|
2755
2730
|
|
|
2756
2731
|
fun main() -> Int =
|
|
2757
|
-
|
|
2732
|
+
mem.size()
|
|
2758
2733
|
";
|
|
2759
2734
|
let without = "import std/Int\n\nfun main() -> Int =\n 1\n";
|
|
2760
2735
|
let exportsMemory = |name: &str, src: &str| {
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_types/io_entry.rs
CHANGED
|
@@ -15,12 +15,12 @@ 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\n\n";
|
|
18
|
+
const PRE_IO: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/Io\nimport std/game/gfx\n\n";
|
|
19
19
|
|
|
20
20
|
#[test]
|
|
21
21
|
fn entry_point_receives_io() {
|
|
22
22
|
let src = format!(
|
|
23
|
-
"{PRE_IO}export fun update(io: Io, n: Int) -> Int =\n w :=
|
|
23
|
+
"{PRE_IO}export fun update(io: Io, n: Int) -> Int =\n w := gfx.screenWidth(io)\n n + 1\n\nfun main(io: Io) -> Int =\n h := gfx.screenHeight(io)\n 41\n"
|
|
24
24
|
);
|
|
25
25
|
let (engine, module) = build("recv", &src);
|
|
26
26
|
let (mut store, instance) = instantiate(&engine, &module);
|
|
@@ -32,7 +32,7 @@ fn entry_point_receives_io() {
|
|
|
32
32
|
|
|
33
33
|
#[test]
|
|
34
34
|
fn export_abi_unchanged_with_io_param() {
|
|
35
|
-
let withIo = format!("{PRE_IO}export fun update(io: Io, n: Int, f: Float) -> Int =\n w :=
|
|
35
|
+
let withIo = format!("{PRE_IO}export fun update(io: Io, n: Int, f: Float) -> Int =\n w := gfx.screenWidth(io)\n n\n");
|
|
36
36
|
let without = format!("{PRE_IO}export fun update(n: Int, f: Float) -> Int = n\n");
|
|
37
37
|
let sig = |name: &str, src: &str| {
|
|
38
38
|
let (_, module) = build(name, src);
|
compiler/wasm-codegen/tests/wasm_codegen/examples_test.rs
CHANGED
|
@@ -148,29 +148,29 @@ fn array_int_native() {
|
|
|
148
148
|
);
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
-
/// L1 `const_table_1000_entries`: 1000
|
|
151
|
+
/// L1 `const_table_1000_entries`: 1000 module-level consts (spread over two
|
|
152
152
|
/// bodies, before and between other decls) plus a 1000-element list literal
|
|
153
153
|
/// parse, type-check and are usable inside methods.
|
|
154
154
|
#[test]
|
|
155
155
|
fn const_table_1000_entries() {
|
|
156
156
|
let mut src = String::from(
|
|
157
|
-
"module t\nimport std/Int\nimport std/Float\nimport std/Slice\n\
|
|
157
|
+
"module t\nimport std/Int\nimport std/Float\nimport std/Slice\n\n",
|
|
158
158
|
);
|
|
159
159
|
for i in 0..500 {
|
|
160
|
-
src.push_str(&format!("
|
|
160
|
+
src.push_str(&format!("E{} = {}\n", i, i * 3 + 1));
|
|
161
161
|
}
|
|
162
162
|
src.push('\n');
|
|
163
|
-
src.push_str("struct Holder(n: Int) =\n\n fun at(self) -> Int =
|
|
163
|
+
src.push_str("struct Holder(n: Int) =\n\n fun at(self) -> Int = E499 + self.n\n\n");
|
|
164
164
|
for i in 500..1000 {
|
|
165
|
-
src.push_str(&format!("
|
|
165
|
+
src.push_str(&format!("E{} = {}\n", i, i * 3 + 1));
|
|
166
166
|
}
|
|
167
167
|
src.push_str(
|
|
168
|
-
"
|
|
168
|
+
"Flag = true\nDouble = E0 * 2 + 1\n\nfun table() -> Slice[Int] =\n out := Slice[Int]()\n",
|
|
169
169
|
);
|
|
170
170
|
for i in 0..1000 {
|
|
171
171
|
src.push_str(&format!(" out.push({})\n", i * i));
|
|
172
172
|
}
|
|
173
|
-
src.push_str(" return out\n\nfun probe() -> Int =\n return
|
|
173
|
+
src.push_str(" return out\n\nfun probe() -> Int =\n return E999 + Double\n");
|
|
174
174
|
let dir = std::env::temp_dir().join(format!("plum_const_table_{}", std::process::id()));
|
|
175
175
|
std::fs::create_dir_all(&dir).unwrap();
|
|
176
176
|
let path = dir.join("t.plum");
|
docs/backlog.md
CHANGED
|
@@ -35,7 +35,7 @@ Open work, in the order the user queued it, plus smaller items found during buil
|
|
|
35
35
|
- **One way to set up a struct.** Drop `fun init(self)` in favour of field defaults + ordinary constructor functions. `init` is what forces the Boxed layout and the EmbedInit machinery in `ctors.rs`. Main user: `std/game/imperative/Scene.plum`.
|
|
36
36
|
- **From Pony:** (1) a two-level ownership model (unique + mutable vs shared + immutable, like Pony's `iso`/`val` with `consume`) as the visible face of FBIP, replacing `mut` fields — take into the FBIP plan; (2) no ambient authority: no globals, a function without `Io` provably does no IO — what deterministic sim needs; (3) Pony partial functions (`?`, no error value) argue for `Option` + `?` as the common path and `Result` only when the error value matters. Not copied: union types, structural interfaces, six capabilities.
|
|
37
37
|
|
|
38
|
-
- **Self-hosting groundwork** (user 2026-11-04: plan now, build later) — `docs/plans/2026-11-04-self-hosting-groundwork.review.md`, design in `docs/plans/self-hosting.md`. All host I/O onto `Io` (`
|
|
38
|
+
- **Self-hosting groundwork** (user 2026-11-04: plan now, build later) — `docs/plans/2026-11-04-self-hosting-groundwork.review.md`, design in `docs/plans/self-hosting.md`. All host I/O onto `Io` (`os.plum` deleted, `io.now()`, `io.httpGet`), then a Plum lexer, a winnow-style combinator library with chumsky-style errors, an AST and a parser in `compiler/` that parses every `.plum` file. AST comparison with the Rust parser and new host calls (args, exit, env, stderr, binary files) wait for cleanup phase 2a. The `Io` move should land before the `Io`-primitive plan above.
|
|
39
39
|
|
|
40
40
|
## FBIP worklist: `mut` fields left after language-restrictions
|
|
41
41
|
|
docs/game.md
CHANGED
|
@@ -26,22 +26,24 @@ import std/Int
|
|
|
26
26
|
import std/Float
|
|
27
27
|
import std/Str
|
|
28
28
|
import std/Io
|
|
29
|
-
import std/game/
|
|
29
|
+
import std/game/gfx
|
|
30
|
+
import std/game/audio
|
|
31
|
+
import std/game/input
|
|
30
32
|
import std/game/Color
|
|
31
33
|
|
|
32
34
|
struct Ball(x: Float, sprite: Texture) =
|
|
33
35
|
fun update(self, io: Io, dt: Float) -> Ball =
|
|
34
|
-
if
|
|
36
|
+
if input.isKeyDown(io, Key.Right)
|
|
35
37
|
Ball(x: self.x + 100.0 * dt, sprite: self.sprite)
|
|
36
38
|
else
|
|
37
39
|
self
|
|
38
40
|
|
|
39
41
|
fun draw(self, io: Io) =
|
|
40
|
-
|
|
42
|
+
gfx.clear(io, Color.Black)
|
|
41
43
|
self.sprite.draw(io, self.x, 100.0)
|
|
42
44
|
|
|
43
45
|
fun main(io: Io) -> Ball =
|
|
44
|
-
Ball(x: 0.0, sprite:
|
|
46
|
+
Ball(x: 0.0, sprite: gfx.loadTexture(io, "ball.png"))
|
|
45
47
|
```
|
|
46
48
|
|
|
47
49
|
`main` runs once, after your assets have loaded. `update` and `draw` then run every frame. If `main` returns a type without these two methods, `plum run` runs it as an ordinary program instead.
|
|
@@ -50,7 +52,7 @@ Keep your rules in plain functions over plain data, like `steer(ship, dt)`. Thos
|
|
|
50
52
|
|
|
51
53
|
## What `io` gives you
|
|
52
54
|
|
|
53
|
-
|
|
55
|
+
The host's calls are module functions that take `io` first: drawing and textures in [`std/game/gfx.plum`](../std/game/gfx.plum) (`gfx.clear(io, Color.Black)`, `gfx.loadTexture(io, "sprites.png")`), keys and the mouse in [`std/game/input.plum`](../std/game/input.plum) (`input.axis(io, Key.Left, Key.Right)`), sound in [`std/game/audio.plum`](../std/game/audio.plum). General calls such as `io.printLn` stay methods of `io` ([`std/Io.plum`](../std/Io.plum)).
|
|
54
56
|
|
|
55
57
|
| Group | Functions |
|
|
56
58
|
|---|---|
|
|
@@ -67,18 +69,18 @@ Images and sounds are handles you load once, in `main`, and keep in your game. D
|
|
|
67
69
|
|
|
68
70
|
| Handle | Functions |
|
|
69
71
|
|---|---|
|
|
70
|
-
| `
|
|
72
|
+
| `gfx.loadTexture(io, name)` | `draw(io, x, y)`, `width(io)`, `height(io)`, `setSmooth(io, smooth)` |
|
|
71
|
-
| `
|
|
73
|
+
| `gfx.createTexture(io, w, h)` | a blank texture; `renderTarget(io)` draws into it and `gfx.renderToScreen(io)` goes back to the screen |
|
|
72
|
-
| `
|
|
74
|
+
| `audio.loadSound(io, name)` | `play(io)`, `loop(io)`, `stop(io)`, `setVolume(io, v)` |
|
|
73
|
-
| `loadFile(io, name)` | the file's text |
|
|
75
|
+
| `gfx.loadFile(io, name)` | the file's text |
|
|
74
76
|
|
|
75
|
-
A missing file stops the game and names the file, so typos show up straight away. For a texture region, rotation or flip, use `
|
|
77
|
+
A missing file stops the game and names the file, so typos show up straight away. For a texture region, rotation or flip, use `gfx.drawTextureEx(io, ...)`.
|
|
76
78
|
|
|
77
79
|
Colors come from `Color.White`, `Color.Red` and so on, or `Color.rgb(r, g, b)`.
|
|
78
80
|
|
|
79
81
|
### Input as events
|
|
80
82
|
|
|
81
|
-
`InputEvent.poll(io, prev)` in [`std/game/
|
|
83
|
+
`InputEvent.poll(io, prev)` in [`std/game/input.plum`](../std/game/input.plum) is the one place that reads input. It returns this frame's `InputEvent`s (`PointerDown`, `PointerUp`, `PointerMove`, `KeyDown`, `KeyUp`) and the keys now held. A game that feeds every event into its state reads nothing else, so a recorded list of events replays the game exactly.
|
|
82
84
|
|
|
83
85
|
## Assets
|
|
84
86
|
|
|
@@ -92,7 +94,7 @@ If the new code has a compile error, the old game keeps running and the error ap
|
|
|
92
94
|
|
|
93
95
|
## Scenes
|
|
94
96
|
|
|
95
|
-
For drawing more than a few shapes, build a picture and draw it. [`std/game/
|
|
97
|
+
For drawing more than a few shapes, build a picture and draw it. [`std/game/scene.plum`](../std/game/scene.plum) has one scene style: `SceneNode[M]` is a plain value, a tree of `Group`, `Sprite`, `Text`, `RectShape`, `CircleShape`, `LineShape`, `Filter` and `Clickable` nodes. `render(self)` builds a fresh tree from your state every frame, and `draw(io)` draws it. Nothing in the tree is retained or changed in place.
|
|
96
98
|
|
|
97
99
|
A `Clickable` carries a message of type `M`. `hitId(x, y)` tells you which one is under a point, and `msgOf(id)` gives its message, so clicks go through your state like any other event.
|
|
98
100
|
|
|
@@ -103,15 +105,17 @@ import std/Str
|
|
|
103
105
|
import std/Option
|
|
104
106
|
import std/List
|
|
105
107
|
import std/Io
|
|
106
|
-
import std/game/
|
|
108
|
+
import std/game/gfx
|
|
109
|
+
import std/game/audio
|
|
110
|
+
import std/game/input
|
|
107
111
|
import std/game/Color
|
|
108
|
-
import std/game/
|
|
112
|
+
import std/game/scene
|
|
109
113
|
|
|
110
114
|
struct Counter(clicks: Int) =
|
|
111
115
|
fun update(self, io: Io, dt: Float) -> Counter =
|
|
112
|
-
if !
|
|
116
|
+
if !input.isMousePressed(io, Mouse.Left)
|
|
113
117
|
return self
|
|
114
|
-
p :=
|
|
118
|
+
p := input.mousePos(io)
|
|
115
119
|
match self.render().hitId(p.x, p.y)
|
|
116
120
|
Some(id) => Counter(clicks: self.clicks + 1)
|
|
117
121
|
None => self
|
|
@@ -123,14 +127,14 @@ struct Counter(clicks: Int) =
|
|
|
123
127
|
])
|
|
124
128
|
|
|
125
129
|
fun draw(self, io: Io) =
|
|
126
|
-
|
|
130
|
+
gfx.clear(io, Color.Black)
|
|
127
131
|
self.render().draw(io)
|
|
128
132
|
|
|
129
133
|
fun main(io: Io) -> Counter =
|
|
130
134
|
Counter(clicks: 0)
|
|
131
135
|
```
|
|
132
136
|
|
|
133
|
-
[`std/game/
|
|
137
|
+
[`std/game/ui.plum`](../std/game/ui.plum) adds buttons on top of this, and [`std/game/Anim.plum`](../std/game/Anim.plum) adds animation by time. A full game written this way is [`orb_run.plum`](../examples/games/orb_run.plum); its header comment explains how it is put together.
|
|
134
138
|
|
|
135
139
|
## Testing a game
|
|
136
140
|
|
docs/language.md
CHANGED
|
@@ -410,16 +410,17 @@ struct Vec2(x: Float, y: Float) =
|
|
|
410
410
|
self.x + self.y
|
|
411
411
|
```
|
|
412
412
|
|
|
413
|
-
|
|
413
|
+
Constants and helper functions with no data live at the top level of a file. Another file reaches them through the module name, the last path segment of the import in lowercase:
|
|
414
414
|
|
|
415
415
|
```plum
|
|
416
|
-
primitive Config =
|
|
417
|
-
|
|
416
|
+
MaxRetries = 3
|
|
418
417
|
|
|
419
|
-
|
|
418
|
+
fun doubled() -> Int =
|
|
420
|
-
|
|
419
|
+
MaxRetries * 2
|
|
421
420
|
```
|
|
422
421
|
|
|
422
|
+
A file that writes `import std/math` calls `math.sqrt(2.0)`; its own functions and constants need no prefix. `primitive` is only for std.
|
|
423
|
+
|
|
423
424
|
## Operators on your own types
|
|
424
425
|
|
|
425
426
|
Define the matching method and the operator works:
|
|
@@ -472,7 +473,7 @@ $ plum test math.plum
|
|
|
472
473
|
1 passed, 0 failed
|
|
473
474
|
```
|
|
474
475
|
|
|
475
|
-
A failing `assert` on `==` prints both values. `plum test` accepts files and folders, and `std/
|
|
476
|
+
A failing `assert` on `==` prints both values. `plum test` accepts files and folders, and `std/testing` adds helpers like `testing.expectEq`.
|
|
476
477
|
|
|
477
478
|
## Talking to the outside world
|
|
478
479
|
|
|
@@ -481,10 +482,10 @@ Everything that leaves your program goes through an `Io` value: printing, files,
|
|
|
481
482
|
```plum
|
|
482
483
|
import std/Io
|
|
483
484
|
import std/Str
|
|
484
|
-
import std/
|
|
485
|
+
import std/os
|
|
485
486
|
|
|
486
487
|
fun main(io: Io) =
|
|
487
|
-
match
|
|
488
|
+
match os.readFile(io, "notes.txt")
|
|
488
489
|
Ok(text) => io.printLn(text)
|
|
489
490
|
Err(e) => io.printLn("could not read the file")
|
|
490
491
|
```
|
docs/std.md
CHANGED
|
@@ -7,15 +7,15 @@ The [game engine](game.md) has its own page.
|
|
|
7
7
|
| Module | What it's for |
|
|
8
8
|
|---|---|
|
|
9
9
|
| [`Int`, `Float`, `Bool`, `Byte`](#numbers) | numbers and booleans |
|
|
10
|
-
| [`
|
|
10
|
+
| [`math`](#numbers) | `sqrt`, `sin`, `exp` and friends |
|
|
11
11
|
| [`Str`, `Buffer`](#text) | text |
|
|
12
12
|
| [`List`, `Slice`, `Array`, `Grid`](#sequences) | sequences |
|
|
13
13
|
| [`Map`, `Set`, `Deque`, `Heap`](#collections) | other collections |
|
|
14
14
|
| [`Option`, `Result`](#option-and-result) | missing values and failures |
|
|
15
15
|
| [`Json`](#json) | reading and writing JSON |
|
|
16
|
-
| [`
|
|
16
|
+
| [`os`, `http`](#files-and-network) | files and the network |
|
|
17
|
-
| [`Time`, `Random`, `Uuid`, `
|
|
17
|
+
| [`Time`, `Random`, `Uuid`, `base64`](#utilities) | utilities |
|
|
18
|
-
| [`
|
|
18
|
+
| [`testing`](#testing) | helpers for tests |
|
|
19
19
|
|
|
20
20
|
## Numbers
|
|
21
21
|
|
|
@@ -23,18 +23,18 @@ The [game engine](game.md) has its own page.
|
|
|
23
23
|
import std/Int
|
|
24
24
|
import std/Float
|
|
25
25
|
import std/Str
|
|
26
|
-
import std/
|
|
26
|
+
import std/math
|
|
27
27
|
|
|
28
28
|
fun main() =
|
|
29
29
|
a := 5.max(3)
|
|
30
30
|
b := Float.Pi * 2.0
|
|
31
|
-
c :=
|
|
31
|
+
c := math.sqrt(2.0)
|
|
32
32
|
d := Int.parse("42").unwrapOr(0)
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
- `Int`: `abs`, `sign`, `min`, `max`, `pow`, `toStr`, `Int.parse`, `Int.Min`, `Int.Max`
|
|
36
36
|
- `Float`: `abs`, `sqrt`, `pow`, `floor`, `ceil`, `round`, `trunc`, `isNaN`, `toStr`, `Float.parse`, `Float.Pi`, `Float.Tau`, `Float.E`
|
|
37
|
-
- `
|
|
37
|
+
- `math`: `math.sqrt`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `ln`, `hypot`, `cbrt`
|
|
38
38
|
- `Bool`: `toStr`, `Bool.parse`
|
|
39
39
|
|
|
40
40
|
## Text
|
|
@@ -142,25 +142,25 @@ All of these need an `Io` and return a `Result`.
|
|
|
142
142
|
```plum
|
|
143
143
|
import std/Io
|
|
144
144
|
import std/Str
|
|
145
|
-
import std/
|
|
145
|
+
import std/os
|
|
146
|
-
import std/
|
|
146
|
+
import std/http
|
|
147
147
|
|
|
148
148
|
fun main(io: Io) =
|
|
149
|
-
_ :=
|
|
149
|
+
_ := os.writeFile(io, "note.txt", "hello")
|
|
150
|
-
text :=
|
|
150
|
+
text := os.readFile(io, "note.txt").unwrapOr("")
|
|
151
151
|
io.printLn(text)
|
|
152
152
|
```
|
|
153
153
|
|
|
154
|
-
- **`
|
|
154
|
+
- **`os`:** `readFile`, `writeFile`, `appendFile`, `exists`, `mkdir`, `remove`, `rename`, `copyFile`, `readdir`
|
|
155
|
-
- **`
|
|
155
|
+
- **`http`:** `get`, `post`, `put`, `patch`, `delete`, `head`, `postJson`. A `Response` has `status`, `headers`, `body`, `ok()` and `json()`
|
|
156
156
|
|
|
157
157
|
## Utilities
|
|
158
158
|
|
|
159
159
|
- **`Time`:** `Time.now(io)` and `Duration` values such as `Duration.seconds(5)`
|
|
160
160
|
- **`Random`:** `Random.seeded(n)`. Each call returns the value and the next generator, so the same seed always gives the same sequence. `io.randomSeed()` gives a seed from the clock
|
|
161
161
|
- **`Uuid`:** `Uuid.v4(rng)`, `Uuid.fromStr`, `Uuid.isValid`
|
|
162
|
-
- **`
|
|
162
|
+
- **`base64`:** `base64.encode`, `base64.decode`, `base64.encodeURL`
|
|
163
163
|
|
|
164
164
|
## Testing
|
|
165
165
|
|
|
166
|
-
`assert` covers most tests. `std/
|
|
166
|
+
`assert` covers most tests. `std/testing` adds `testing.expectEq`, `expectNotEq`, `expectTrue`, `expectFalse`, `expectSuccess` and `expectFailure`.
|
examples/basics.plum
CHANGED
|
@@ -7,12 +7,10 @@ import std/Io
|
|
|
7
7
|
|
|
8
8
|
# ==== basics ====
|
|
9
9
|
|
|
10
|
-
# A `primitive` with a non-built-in name is a stateless namespace: constants and
|
|
11
|
-
#
|
|
10
|
+
# Module-level constants: `MaxRetries` is a name for the value, not a variable.
|
|
12
|
-
primitive Config =
|
|
13
|
-
|
|
11
|
+
MaxRetries = 3
|
|
14
|
-
|
|
12
|
+
GoldenRatio = 1.61803
|
|
15
|
-
|
|
13
|
+
Greeting = "hello"
|
|
16
14
|
|
|
17
15
|
fun syntaxTour() =
|
|
18
16
|
dec := 42
|
examples/control_flow.plum
CHANGED
|
@@ -4,7 +4,7 @@ import std/Int
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Slice
|
|
6
6
|
import std/Array
|
|
7
|
-
import std/
|
|
7
|
+
import std/testing
|
|
8
8
|
import std/List
|
|
9
9
|
|
|
10
10
|
# ==== control flow ====
|
examples/games/kids/balloon_pop.plum
CHANGED
|
@@ -17,29 +17,28 @@ import std/Float
|
|
|
17
17
|
import std/Slice
|
|
18
18
|
import std/Option
|
|
19
19
|
import std/List
|
|
20
|
-
import std/
|
|
20
|
+
import std/math
|
|
21
21
|
import std/Random
|
|
22
22
|
import std/game/Vec2
|
|
23
23
|
import std/game/Color
|
|
24
|
-
import std/game/
|
|
24
|
+
import std/game/gfx
|
|
25
|
+
import std/game/audio
|
|
25
|
-
import std/game/
|
|
26
|
+
import std/game/scene
|
|
26
27
|
import std/game/Anim
|
|
27
|
-
import std/game/
|
|
28
|
+
import std/game/input
|
|
28
29
|
import std/Io
|
|
29
30
|
|
|
30
|
-
primitive Rules =
|
|
31
|
-
|
|
31
|
+
ArenaW = 800.0
|
|
32
|
-
|
|
32
|
+
ArenaH = 600.0
|
|
33
|
-
|
|
33
|
+
Count = 6
|
|
34
|
-
|
|
34
|
+
Radius = 40.0
|
|
35
|
-
|
|
35
|
+
MinSpeed = 35.0
|
|
36
|
-
|
|
36
|
+
MaxSpeed = 70.0
|
|
37
|
-
|
|
37
|
+
PopTime = 0.6
|
|
38
|
-
|
|
38
|
+
PartyEvery = 10
|
|
39
|
-
|
|
39
|
+
PartyTime = 2.5
|
|
40
40
|
|
|
41
|
-
primitive Id =
|
|
42
|
-
|
|
41
|
+
BalloonId = 100
|
|
43
42
|
|
|
44
43
|
# The balloon colours a child can name.
|
|
45
44
|
struct Hue(name: Str, color: Color) =
|
|
@@ -88,9 +87,9 @@ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float
|
|
|
88
87
|
rx := rng.nextFloat()
|
|
89
88
|
rs := rx.rng.nextFloat()
|
|
90
89
|
rh := rs.rng.nextIntBelow(Hue.count())
|
|
91
|
-
x := 60.0 + rx.value * {
|
|
90
|
+
x := 60.0 + rx.value * {ArenaW - 120.0}
|
|
92
|
-
speed :=
|
|
91
|
+
speed := MinSpeed + rs.value * {MaxSpeed - MinSpeed}
|
|
93
|
-
b := Balloon(id: id, x: x, y:
|
|
92
|
+
b := Balloon(id: id, x: x, y: ArenaH + Radius + depth, speed: speed, hue: rh.value, phase: rx.value * Float.Tau, poppedAt: -1.0)
|
|
94
93
|
Spawned(balloon: b, rng: rh.rng)
|
|
95
94
|
|
|
96
95
|
fun popped(self) -> Bool =
|
|
@@ -98,7 +97,7 @@ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float
|
|
|
98
97
|
|
|
99
98
|
# Where the balloon is drawn: it sways side to side as it rises.
|
|
100
99
|
fun swayX(self, clock: Float) -> Float =
|
|
101
|
-
self.x + 14.0 *
|
|
100
|
+
self.x + 14.0 * math.sin(clock * 1.3 + self.phase)
|
|
102
101
|
|
|
103
102
|
# Rises while whole; once popped it stays where it burst.
|
|
104
103
|
fun update(self, dt: Float) -> Balloon =
|
|
@@ -106,13 +105,13 @@ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float
|
|
|
106
105
|
|
|
107
106
|
# Gone off the top, or popped long enough ago that the burst has faded.
|
|
108
107
|
fun done(self, clock: Float) -> Bool =
|
|
109
|
-
self.y < 0.0 -
|
|
108
|
+
self.y < 0.0 - Radius * 3.0 || {self.popped() && clock - self.poppedAt > PopTime}
|
|
110
109
|
|
|
111
110
|
fun render(self, clock: Float) -> SceneNode[Msg] =
|
|
112
111
|
if self.popped() then self.renderBurst(clock - self.poppedAt) else self.renderWhole(clock)
|
|
113
112
|
|
|
114
113
|
fun renderWhole(self, clock: Float) -> SceneNode[Msg] =
|
|
115
|
-
r :=
|
|
114
|
+
r := Radius
|
|
116
115
|
c := Hue.of(self.hue).color
|
|
117
116
|
Clickable(
|
|
118
117
|
id: self.id,
|
|
@@ -120,7 +119,7 @@ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float
|
|
|
120
119
|
child: Group(
|
|
121
120
|
transform: Translate(dx: self.swayX(clock), dy: self.y),
|
|
122
121
|
children: [
|
|
123
|
-
LineShape(x1: 0.0, y1: r, x2: 6.0 *
|
|
122
|
+
LineShape(x1: 0.0, y1: r, x2: 6.0 * math.sin(clock * 3.0 + self.phase), y2: r * 2.6, thickness: 2.0, color: Color.rgb(0.35, 0.35, 0.35)),
|
|
124
123
|
CircleShape(cx: 0.0, cy: r + 2.0, r: 6.0, color: c),
|
|
125
124
|
CircleShape(cx: 0.0, cy: 0.0, r: r, color: c),
|
|
126
125
|
CircleShape(cx: 0.0 - r * 0.35, cy: 0.0 - r * 0.4, r: r * 0.22, color: Color.White.withAlpha(0.55))
|
|
@@ -130,7 +129,7 @@ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float
|
|
|
130
129
|
|
|
131
130
|
# Eight dots fly out and fade, and the colour's name floats up.
|
|
132
131
|
fun renderBurst(self, age: Float) -> SceneNode[Msg] =
|
|
133
|
-
t := {age /
|
|
132
|
+
t := {age / PopTime}.min(1.0)
|
|
134
133
|
fade := 1.0 - t
|
|
135
134
|
hue := Hue.of(self.hue)
|
|
136
135
|
reach := 20.0 + 70.0 * t
|
|
@@ -147,7 +146,7 @@ fun burstDots(i: Int, reach: Float, c: Color) -> List[SceneNode[Msg]] =
|
|
|
147
146
|
Nil
|
|
148
147
|
else
|
|
149
148
|
a := Float(i) * Float.Tau / 8.0
|
|
150
|
-
Cons(head: CircleShape(cx:
|
|
149
|
+
Cons(head: CircleShape(cx: math.cos(a) * reach, cy: math.sin(a) * reach, r: 8.0, color: c), tail: burstDots(i + 1, reach, c))
|
|
151
150
|
|
|
152
151
|
struct Spawned(balloon: Balloon, rng: Random)
|
|
153
152
|
|
|
@@ -165,9 +164,9 @@ struct State(balloons: List[Balloon], rng: Random, pops: Int, clock: Float, part
|
|
|
165
164
|
|
|
166
165
|
# Balloons `i` and up, spread out below the screen.
|
|
167
166
|
fun fill(self, i: Int) -> State =
|
|
168
|
-
if i >=
|
|
167
|
+
if i >= Count
|
|
169
168
|
return self
|
|
170
|
-
sp := Balloon.spawn(
|
|
169
|
+
sp := Balloon.spawn(BalloonId + i, self.rng, Float(i) * 110.0 - ArenaH * 0.6)
|
|
171
170
|
State(..self, balloons: self.balloons.append([sp.balloon]), rng: sp.rng).fill(i + 1)
|
|
172
171
|
|
|
173
172
|
fun update(self, msg: Msg) -> State = match msg
|
|
@@ -195,12 +194,12 @@ struct State(balloons: List[Balloon], rng: Random, pops: Int, clock: Float, part
|
|
|
195
194
|
State(
|
|
196
195
|
..self,
|
|
197
196
|
pops: pops,
|
|
198
|
-
partyAt: if pops %
|
|
197
|
+
partyAt: if pops % PartyEvery == 0 then self.clock else self.partyAt,
|
|
199
198
|
balloons: self.balloons.map(|b| if b.id == id then Balloon(..b, x: b.swayX(self.clock), poppedAt: self.clock) else b)
|
|
200
199
|
)
|
|
201
200
|
|
|
202
201
|
fun partying(self) -> Bool =
|
|
203
|
-
self.clock - self.partyAt <
|
|
202
|
+
self.clock - self.partyAt < PartyTime
|
|
204
203
|
|
|
205
204
|
# A press pops the balloon under it; everything else is ignored.
|
|
206
205
|
fun onInput(self, e: InputEvent) -> State = match e
|
|
@@ -217,13 +216,13 @@ struct State(balloons: List[Balloon], rng: Random, pops: Int, clock: Float, part
|
|
|
217
216
|
# --- render ---
|
|
218
217
|
|
|
219
218
|
fun zoom(self) -> Float =
|
|
220
|
-
{self.sw /
|
|
219
|
+
{self.sw / ArenaW}.min(self.sh / ArenaH)
|
|
221
220
|
|
|
222
221
|
fun offsetX(self) -> Float =
|
|
223
|
-
{self.sw - self.zoom() *
|
|
222
|
+
{self.sw - self.zoom() * ArenaW} / 2.0
|
|
224
223
|
|
|
225
224
|
fun offsetY(self) -> Float =
|
|
226
|
-
{self.sh - self.zoom() *
|
|
225
|
+
{self.sh - self.zoom() * ArenaH} / 2.0
|
|
227
226
|
|
|
228
227
|
fun render(self) -> SceneNode[Msg] =
|
|
229
228
|
z := self.zoom()
|
|
@@ -257,7 +256,7 @@ struct State(balloons: List[Balloon], rng: Random, pops: Int, clock: Float, part
|
|
|
257
256
|
children: [
|
|
258
257
|
Group(transform: Identity, children: confetti(0, age)),
|
|
259
258
|
Group(
|
|
260
|
-
transform: Compose(first: Translate(dx:
|
|
259
|
+
transform: Compose(first: Translate(dx: ArenaW / 2.0, dy: 250.0), then: Scale(sx: p.scaleX, sy: p.scaleY)),
|
|
261
260
|
children: [
|
|
262
261
|
centred("Hooray!", 0.0, -40.0, 72.0, Color.rgb(0.95, 0.3, 0.5)),
|
|
263
262
|
centred("{self.pops} balloons!", 0.0, 40.0, 40.0, Color.rgb(0.15, 0.15, 0.3))
|
|
@@ -273,7 +272,7 @@ fun confetti(i: Int, age: Float) -> List[SceneNode[Msg]] =
|
|
|
273
272
|
else
|
|
274
273
|
x := Float({i * 7919} % 800)
|
|
275
274
|
y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
|
|
276
|
-
wob := 10.0 *
|
|
275
|
+
wob := 10.0 * math.sin(age * 4.0 + Float(i))
|
|
277
276
|
Cons(head: RectShape(x: x + wob, y: y, w: 12.0, h: 12.0, color: Hue.of(i).color), tail: confetti(i + 1, age))
|
|
278
277
|
|
|
279
278
|
# Sky, two drifting clouds and the grass.
|
|
@@ -281,17 +280,17 @@ fun renderSky(clock: Float) -> SceneNode[Msg] =
|
|
|
281
280
|
Group(
|
|
282
281
|
transform: Identity,
|
|
283
282
|
children: [
|
|
284
|
-
RectShape(x: 0.0, y: 0.0, w:
|
|
283
|
+
RectShape(x: 0.0, y: 0.0, w: ArenaW, h: ArenaH, color: Color.rgb(0.55, 0.8, 1.0)),
|
|
285
|
-
RectShape(x: 0.0, y: 0.0, w:
|
|
284
|
+
RectShape(x: 0.0, y: 0.0, w: ArenaW, h: 200.0, color: Color.rgb(0.45, 0.72, 0.98)),
|
|
286
285
|
CircleShape(cx: 690.0, cy: 90.0, r: 46.0, color: Color.rgb(1.0, 0.9, 0.35)),
|
|
287
286
|
cloud(wrapX(120.0 + clock * 12.0), 130.0),
|
|
288
287
|
cloud(wrapX(520.0 + clock * 8.0), 220.0),
|
|
289
|
-
RectShape(x: 0.0, y:
|
|
288
|
+
RectShape(x: 0.0, y: ArenaH - 50.0, w: ArenaW, h: 50.0, color: Color.rgb(0.4, 0.78, 0.35))
|
|
290
289
|
]
|
|
291
290
|
)
|
|
292
291
|
|
|
293
292
|
fun wrapX(x: Float) -> Float =
|
|
294
|
-
span :=
|
|
293
|
+
span := ArenaW + 200.0
|
|
295
294
|
x - span * Float(Int(x / span)) - 100.0
|
|
296
295
|
|
|
297
296
|
fun cloud(x: Float, y: Float) -> SceneNode[Msg] =
|
|
@@ -313,7 +312,7 @@ struct Balloons(state: State, input: Input, popSound: Sound, partySound: Sound,
|
|
|
313
312
|
# pop and a fanfare when a party starts. Returns the game with the next state.
|
|
314
313
|
fun update(self, io: Io, dt: Float) -> Balloons =
|
|
315
314
|
input := self.input.poll(io)
|
|
316
|
-
s := self.state.update(Resize(w:
|
|
315
|
+
s := self.state.update(Resize(w: gfx.screenWidth(io), h: gfx.screenHeight(io)))
|
|
317
316
|
before := s
|
|
318
317
|
inputs := input.events
|
|
319
318
|
for i := range inputs.length()
|
|
@@ -325,16 +324,16 @@ struct Balloons(state: State, input: Input, popSound: Sound, partySound: Sound,
|
|
|
325
324
|
Balloons(..self, state: s.update(Tick(dt: dt)), input: input)
|
|
326
325
|
|
|
327
326
|
fun draw(self, io: Io) =
|
|
328
|
-
|
|
327
|
+
gfx.clear(io, Color.rgb(0.55, 0.8, 1.0))
|
|
329
328
|
self.state.render().draw(io)
|
|
330
329
|
|
|
331
330
|
fun main(io: Io) -> Balloons =
|
|
332
331
|
game := Balloons(
|
|
333
|
-
state: State.start(io.randomSeed(),
|
|
332
|
+
state: State.start(io.randomSeed(), ArenaW, ArenaH),
|
|
334
333
|
input: Input.create(),
|
|
335
|
-
popSound:
|
|
334
|
+
popSound: audio.loadSound(io, "pickup.wav"),
|
|
336
|
-
partySound:
|
|
335
|
+
partySound: audio.loadSound(io, "gameover.wav"),
|
|
337
|
-
musicSound:
|
|
336
|
+
musicSound: audio.loadSound(io, "music.wav")
|
|
338
337
|
)
|
|
339
338
|
game.musicSound.loop(io, 0.2)
|
|
340
339
|
game
|
|
@@ -342,20 +341,20 @@ fun main(io: Io) -> Balloons =
|
|
|
342
341
|
# --- tests ---
|
|
343
342
|
|
|
344
343
|
fun newState() -> State =
|
|
345
|
-
State.start(3,
|
|
344
|
+
State.start(3, ArenaW, ArenaH)
|
|
346
345
|
|
|
347
346
|
# A state whose first balloon is still and in the middle of the screen.
|
|
348
347
|
fun withCentred(s: State) -> State =
|
|
349
|
-
State(..s, balloons: s.balloons.map(|b| if b.id ==
|
|
348
|
+
State(..s, balloons: s.balloons.map(|b| if b.id == BalloonId then Balloon(..b, x: 400.0, y: 300.0, speed: 0.0, phase: 0.0) else b))
|
|
350
349
|
|
|
351
350
|
fun first(s: State) -> Balloon =
|
|
352
351
|
s.balloons.at(0)
|
|
353
352
|
|
|
354
353
|
test "a new game has its balloons below the screen and no pops"
|
|
355
354
|
s := newState()
|
|
356
|
-
assert s.balloons.length() ==
|
|
355
|
+
assert s.balloons.length() == Count
|
|
357
356
|
assert s.pops == 0
|
|
358
|
-
assert s.balloons.fold(true, |ok, b| ok && b.y >
|
|
357
|
+
assert s.balloons.fold(true, |ok, b| ok && b.y > ArenaH * 0.4)
|
|
359
358
|
|
|
360
359
|
test "balloons rise"
|
|
361
360
|
s := newState()
|
|
@@ -377,20 +376,20 @@ test "pressing the sky does nothing"
|
|
|
377
376
|
assert t.pops == 0
|
|
378
377
|
|
|
379
378
|
test "a popped balloon comes back at the bottom"
|
|
380
|
-
s := withCentred(newState()).update(Pop(id:
|
|
379
|
+
s := withCentred(newState()).update(Pop(id: BalloonId))
|
|
381
|
-
t := s.update(Tick(dt:
|
|
380
|
+
t := s.update(Tick(dt: PopTime + 0.1))
|
|
382
381
|
assert !first(t).popped()
|
|
383
|
-
assert first(t).y >
|
|
382
|
+
assert first(t).y > ArenaH
|
|
384
383
|
|
|
385
384
|
test "every tenth pop starts a party that ends"
|
|
386
385
|
s := newState()
|
|
387
386
|
for i := range 9
|
|
388
387
|
s = State(..s, pops: s.pops + 1)
|
|
389
388
|
assert !s.partying()
|
|
390
|
-
t := withCentred(s).update(Pop(id:
|
|
389
|
+
t := withCentred(s).update(Pop(id: BalloonId))
|
|
391
390
|
assert t.pops == 10
|
|
392
391
|
assert t.partying()
|
|
393
|
-
u := t.update(Tick(dt:
|
|
392
|
+
u := t.update(Tick(dt: PartyTime + 0.1))
|
|
394
393
|
assert !u.partying()
|
|
395
394
|
|
|
396
395
|
test "the press is found through the camera"
|
|
@@ -401,7 +400,7 @@ test "the press is found through the camera"
|
|
|
401
400
|
assert hit.pops == 1
|
|
402
401
|
|
|
403
402
|
test "the same seed gives the same balloons"
|
|
404
|
-
a := State.start(9,
|
|
403
|
+
a := State.start(9, ArenaW, ArenaH)
|
|
405
|
-
b := State.start(9,
|
|
404
|
+
b := State.start(9, ArenaW, ArenaH)
|
|
406
405
|
assert first(a).x == first(b).x
|
|
407
406
|
assert first(a).hue == first(b).hue
|
examples/games/orb_run.plum
CHANGED
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
# player input, a Ui event); `State.update(msg)` is a short sequence of named steps and
|
|
12
12
|
# `State.render()` builds a fresh picture every frame, which `SceneNode.draw` interprets
|
|
13
13
|
# (the compiler fuses the two, so the tree is never built). There is no retained
|
|
14
|
-
# scene: the restart button is a `
|
|
14
|
+
# scene: the restart button is a `ui.button` in the picture. The host polls the
|
|
15
15
|
# player's input once a frame (`InputEvent.poll`, its only input read) and sends each
|
|
16
16
|
# `InputEvent` to the state as an `Event`: keys update the held keys that steer the ship,
|
|
17
17
|
# and a pointer input finds what is under it with `SceneNode.hitId` on the picture the
|
|
18
|
-
# player is looking at and runs `
|
|
18
|
+
# player is looking at and runs `ui.step`. A click on a button sends the button's own
|
|
19
|
-
# message (`RestartClicked`): `
|
|
19
|
+
# message (`RestartClicked`): `ui.messages` reads it from the picture, and it goes to
|
|
20
20
|
# `State.update` like any other `Msg`. The picture is a `SceneNode[Msg]`.
|
|
21
21
|
# The game-over title and the ship's hurt flash are `Anim`s of time since they began.
|
|
22
22
|
# `OrbGame` below is the host shell: `main` returns it, and its `update(self, io, dt)`
|
|
@@ -29,38 +29,37 @@ import std/Float
|
|
|
29
29
|
import std/Slice
|
|
30
30
|
import std/Option
|
|
31
31
|
import std/List
|
|
32
|
-
import std/
|
|
32
|
+
import std/math
|
|
33
33
|
import std/Random
|
|
34
34
|
import std/game/Vec2
|
|
35
35
|
import std/game/Color
|
|
36
|
-
import std/game/
|
|
36
|
+
import std/game/gfx
|
|
37
|
+
import std/game/audio
|
|
37
|
-
import std/game/
|
|
38
|
+
import std/game/scene
|
|
38
39
|
import std/game/Anim
|
|
39
|
-
import std/game/
|
|
40
|
+
import std/game/ui
|
|
40
|
-
import std/game/
|
|
41
|
+
import std/game/input
|
|
41
42
|
import std/Io
|
|
42
43
|
|
|
43
|
-
primitive Rules =
|
|
44
|
-
|
|
44
|
+
ArenaW = 800.0
|
|
45
|
-
|
|
45
|
+
ArenaH = 600.0
|
|
46
|
-
|
|
46
|
+
ShipRadius = 10.0
|
|
47
|
-
|
|
47
|
+
OrbRadius = 10.0
|
|
48
|
-
|
|
48
|
+
MineRadius = 11.0
|
|
49
|
-
|
|
49
|
+
Thrust = 900.0
|
|
50
|
-
|
|
50
|
+
Drag = 2.2
|
|
51
|
-
|
|
51
|
+
OrbCount = 3
|
|
52
|
-
|
|
52
|
+
StartLives = 3
|
|
53
|
-
|
|
53
|
+
HurtTime = 1.5
|
|
54
|
-
|
|
54
|
+
OrbPoints = 10
|
|
55
|
-
|
|
55
|
+
SheetCell = 16.0
|
|
56
|
-
|
|
56
|
+
SpriteSize = 48.0
|
|
57
|
-
|
|
57
|
+
SpriteHalf = 24.0
|
|
58
|
-
|
|
58
|
+
|
|
59
|
-
# Entity ids: orb `i` is `
|
|
59
|
+
# Entity ids: orb `i` is `OrbId + i`, mine `i` is `MineId + i`.
|
|
60
|
-
primitive Id =
|
|
61
|
-
|
|
60
|
+
OrbId = 100
|
|
62
|
-
|
|
61
|
+
MineId = 200
|
|
63
|
-
|
|
62
|
+
RestartId = 1
|
|
64
63
|
|
|
65
64
|
# A position and velocity: what a spawn returns and what drifters are bounced with.
|
|
66
65
|
struct Motion(x: Float, y: Float, vx: Float, vy: Float)
|
|
@@ -84,15 +83,15 @@ fun cell(sheet: Texture, x: Float, y: Float, size: Float, col: Int, row: Int) ->
|
|
|
84
83
|
y: y,
|
|
85
84
|
w: size,
|
|
86
85
|
h: size,
|
|
87
|
-
srcX: Float(col) *
|
|
86
|
+
srcX: Float(col) * SheetCell,
|
|
88
|
-
srcY: Float(row) *
|
|
87
|
+
srcY: Float(row) * SheetCell,
|
|
89
|
-
srcW:
|
|
88
|
+
srcW: SheetCell,
|
|
90
|
-
srcH:
|
|
89
|
+
srcH: SheetCell,
|
|
91
90
|
tint: Color.White
|
|
92
91
|
)
|
|
93
92
|
|
|
94
93
|
fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool =
|
|
95
|
-
|
|
94
|
+
math.hypot(ax - bx, ay - by) < ra + rb
|
|
96
95
|
|
|
97
96
|
# A random spot at least `gap` away from (ax, ay), drifting at up to `speed`.
|
|
98
97
|
fun spawn(rng: Random, ax: Float, ay: Float, gap: Float, speed: Float) -> Spawned =
|
|
@@ -105,23 +104,23 @@ fun spawn(rng: Random, ax: Float, ay: Float, gap: Float, speed: Float) -> Spawne
|
|
|
105
104
|
dx := r.nextFloat()
|
|
106
105
|
dy := dx.rng.nextFloat()
|
|
107
106
|
r = dy.rng
|
|
108
|
-
x = margin + dx.value * {
|
|
107
|
+
x = margin + dx.value * {ArenaW - 2.0 * margin}
|
|
109
|
-
y = margin + dy.value * {
|
|
108
|
+
y = margin + dy.value * {ArenaH - 2.0 * margin}
|
|
110
|
-
if
|
|
109
|
+
if math.hypot(x - ax, y - ay) >= gap
|
|
111
110
|
break
|
|
112
111
|
tries = tries + 1
|
|
113
112
|
dh := r.nextFloat()
|
|
114
113
|
dp := dh.rng.nextFloat()
|
|
115
114
|
heading := dh.value * Float.Tau
|
|
116
115
|
pace := speed * {0.4 + 0.6 * dp.value}
|
|
117
|
-
Spawned(at: Motion(x: x, y: y, vx:
|
|
116
|
+
Spawned(at: Motion(x: x, y: y, vx: math.cos(heading) * pace, vy: math.sin(heading) * pace), rng: dp.rng)
|
|
118
117
|
|
|
119
118
|
# `b` moved for `dt` seconds and bounced off the arena walls; `b` itself is unchanged.
|
|
120
119
|
fun driftOf(b: Motion, r: Float, dt: Float) -> Motion =
|
|
121
120
|
x0 := b.x + b.vx * dt
|
|
122
121
|
y0 := b.y + b.vy * dt
|
|
123
|
-
x := x0.max(r).min(
|
|
122
|
+
x := x0.max(r).min(ArenaW - r)
|
|
124
|
-
y := y0.max(r).min(
|
|
123
|
+
y := y0.max(r).min(ArenaH - r)
|
|
125
124
|
Motion(x: x, y: y, vx: if x != x0 then 0.0 - b.vx else b.vx, vy: if y != y0 then 0.0 - b.vy else b.vy)
|
|
126
125
|
|
|
127
126
|
# How many mines are out: more as the score grows.
|
|
@@ -153,18 +152,18 @@ fun titlePose(t: Float) -> AnimPose =
|
|
|
153
152
|
struct Ship(x: Float, y: Float, vx: Float, vy: Float, rotation: Float, hurt: Float) =
|
|
154
153
|
|
|
155
154
|
fun start() -> Ship =
|
|
156
|
-
Ship(x:
|
|
155
|
+
Ship(x: ArenaW / 2.0, y: ArenaH / 2.0, vx: 0.0, vy: 0.0, rotation: 0.0, hurt: 0.0)
|
|
157
156
|
|
|
158
157
|
# Accelerates by the input axes, applies drag and keeps the ship in the arena.
|
|
159
158
|
fun update(self, ax: Float, ay: Float, dt: Float) -> Ship =
|
|
160
|
-
keep := {1.0 -
|
|
159
|
+
keep := {1.0 - Drag * dt}.max(0.0)
|
|
161
|
-
r :=
|
|
160
|
+
r := ShipRadius
|
|
162
|
-
vx0 := {self.vx + ax *
|
|
161
|
+
vx0 := {self.vx + ax * Thrust * dt} * keep
|
|
163
|
-
vy0 := {self.vy + ay *
|
|
162
|
+
vy0 := {self.vy + ay * Thrust * dt} * keep
|
|
164
163
|
x0 := self.x + vx0 * dt
|
|
165
164
|
y0 := self.y + vy0 * dt
|
|
166
|
-
x := x0.max(r).min(
|
|
165
|
+
x := x0.max(r).min(ArenaW - r)
|
|
167
|
-
y := y0.max(r).min(
|
|
166
|
+
y := y0.max(r).min(ArenaH - r)
|
|
168
167
|
vx := if x != x0 then 0.0 else vx0
|
|
169
168
|
vy := if y != y0 then 0.0 else vy0
|
|
170
169
|
Ship(
|
|
@@ -172,12 +171,12 @@ struct Ship(x: Float, y: Float, vx: Float, vy: Float, rotation: Float, hurt: Flo
|
|
|
172
171
|
y: y,
|
|
173
172
|
vx: vx,
|
|
174
173
|
vy: vy,
|
|
175
|
-
rotation: if vx * vx + vy * vy > 400.0 then
|
|
174
|
+
rotation: if vx * vx + vy * vy > 400.0 then math.atan2(vx, 0.0 - vy) else self.rotation,
|
|
176
175
|
hurt: {self.hurt - dt}.max(0.0)
|
|
177
176
|
)
|
|
178
177
|
|
|
179
178
|
fun touches(self, at: Motion, radius: Float) -> Bool =
|
|
180
|
-
overlaps(self.x, self.y,
|
|
179
|
+
overlaps(self.x, self.y, ShipRadius, at.x, at.y, radius)
|
|
181
180
|
|
|
182
181
|
# The ship blinks while hurt (`hurtAge` seconds since the hit).
|
|
183
182
|
fun render(self, sheet: Texture, clock: Float, hurtAge: Float) -> SceneNode[Msg] =
|
|
@@ -189,7 +188,7 @@ struct Ship(x: Float, y: Float, vx: Float, vy: Float, rotation: Float, hurt: Flo
|
|
|
189
188
|
transform: Compose(first: Translate(dx: self.x, dy: self.y), then: Rotate(radians: self.rotation)),
|
|
190
189
|
children: [
|
|
191
190
|
CircleShape(cx: 0.0, cy: 0.0, r: 17.0, color: Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12)),
|
|
192
|
-
cell(sheet, 0.0 -
|
|
191
|
+
cell(sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(clock, 4, 14.0), 0)
|
|
193
192
|
]
|
|
194
193
|
)
|
|
195
194
|
|
|
@@ -197,7 +196,7 @@ struct Ship(x: Float, y: Float, vx: Float, vy: Float, rotation: Float, hurt: Flo
|
|
|
197
196
|
struct Orb(id: Int, at: Motion, phase: Float, clock: Float) =
|
|
198
197
|
|
|
199
198
|
fun update(self, dt: Float) -> Orb =
|
|
200
|
-
Orb(..self, at: driftOf(self.at,
|
|
199
|
+
Orb(..self, at: driftOf(self.at, OrbRadius, dt), clock: self.clock + dt)
|
|
201
200
|
|
|
202
201
|
fun moved(self, to: Motion) -> Orb =
|
|
203
202
|
Orb(..self, at: to)
|
|
@@ -222,7 +221,7 @@ struct Orb(id: Int, at: Motion, phase: Float, clock: Float) =
|
|
|
222
221
|
),
|
|
223
222
|
target: Texture(id: 0 - 1)
|
|
224
223
|
),
|
|
225
|
-
cell(sheet, 0.0 -
|
|
224
|
+
cell(sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock + self.phase, 4, 8.0), 1)
|
|
226
225
|
]
|
|
227
226
|
)
|
|
228
227
|
|
|
@@ -230,7 +229,7 @@ struct Orb(id: Int, at: Motion, phase: Float, clock: Float) =
|
|
|
230
229
|
struct Mine(id: Int, at: Motion, rotation: Float, spin: Float, clock: Float) =
|
|
231
230
|
|
|
232
231
|
fun update(self, dt: Float) -> Mine =
|
|
233
|
-
Mine(..self, at: driftOf(self.at,
|
|
232
|
+
Mine(..self, at: driftOf(self.at, MineRadius, dt), rotation: self.rotation + self.spin * dt, clock: self.clock + dt)
|
|
234
233
|
|
|
235
234
|
fun moved(self, to: Motion) -> Mine =
|
|
236
235
|
Mine(..self, at: to)
|
|
@@ -242,7 +241,7 @@ struct Mine(id: Int, at: Motion, rotation: Float, spin: Float, clock: Float) =
|
|
|
242
241
|
fun render(self, sheet: Texture) -> SceneNode[Msg] =
|
|
243
242
|
Group(
|
|
244
243
|
transform: Compose(first: Translate(dx: self.at.x, dy: self.at.y), then: Rotate(radians: self.rotation)),
|
|
245
|
-
children: [cell(sheet, 0.0 -
|
|
244
|
+
children: [cell(sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 4.0), 2)]
|
|
246
245
|
)
|
|
247
246
|
|
|
248
247
|
# A twinkling background star; it never moves.
|
|
@@ -254,7 +253,7 @@ struct Star(i: Int) =
|
|
|
254
253
|
|
|
255
254
|
fun render(self, clock: Float) -> SceneNode[Msg] =
|
|
256
255
|
r := 1.0 + Float(self.i % 3) * 0.5
|
|
257
|
-
twinkle := 0.25 + 0.2 *
|
|
256
|
+
twinkle := 0.25 + 0.2 * math.sin(clock * 2.0 + Float(self.i))
|
|
258
257
|
CircleShape(cx: Float({self.i * 7919} % 800), cy: Float({self.i * 104729} % 600), r: r, color: Color(r: 0.7, g: 0.8, b: 1.0, a: twinkle))
|
|
259
258
|
|
|
260
259
|
# What can happen to the state.
|
|
@@ -299,13 +298,13 @@ struct State(
|
|
|
299
298
|
rng: Random.seeded(seed),
|
|
300
299
|
score: 0,
|
|
301
300
|
best: best,
|
|
302
|
-
lives:
|
|
301
|
+
lives: StartLives,
|
|
303
302
|
over: false,
|
|
304
303
|
clock: 0.0,
|
|
305
304
|
overClock: 0.0,
|
|
306
305
|
hurtAt: -1.0,
|
|
307
306
|
overAt: -1.0,
|
|
308
|
-
ui:
|
|
307
|
+
ui: ui.init(),
|
|
309
308
|
held: Held.none(),
|
|
310
309
|
sw: sw,
|
|
311
310
|
sh: sh,
|
|
@@ -341,7 +340,7 @@ struct State(
|
|
|
341
340
|
self.orbs.fold(self, |s, o| s.takeOrb(o))
|
|
342
341
|
|
|
343
342
|
fun takeOrb(self, o: Orb) -> State =
|
|
344
|
-
if self.ship.touches(o.at,
|
|
343
|
+
if self.ship.touches(o.at, OrbRadius) then self.respawnOrb(o) else self
|
|
345
344
|
|
|
346
345
|
# Scores `o` and puts it at a new random spot.
|
|
347
346
|
fun respawnOrb(self, o: Orb) -> State =
|
|
@@ -350,18 +349,18 @@ struct State(
|
|
|
350
349
|
..self,
|
|
351
350
|
orbs: self.orbs.map(|x| if x.id == o.id then x.moved(sp.at) else x),
|
|
352
351
|
rng: sp.rng,
|
|
353
|
-
score: self.score +
|
|
352
|
+
score: self.score + OrbPoints
|
|
354
353
|
)
|
|
355
354
|
|
|
356
355
|
# Orbs `i` and up to OrbCount, each at a random spot away from the ship.
|
|
357
356
|
fun fillOrbs(self, i: Int) -> State =
|
|
358
|
-
if i >=
|
|
357
|
+
if i >= OrbCount then self else self.addOrb(i).fillOrbs(i + 1)
|
|
359
358
|
|
|
360
359
|
fun addOrb(self, i: Int) -> State =
|
|
361
360
|
sp := spawn(self.rng, self.ship.x, self.ship.y, 120.0, 40.0)
|
|
362
361
|
State(
|
|
363
362
|
..self,
|
|
364
|
-
orbs: self.orbs.append([Orb(id:
|
|
363
|
+
orbs: self.orbs.append([Orb(id: OrbId + i, at: sp.at, phase: Float(i) * 0.1, clock: 0.0)]),
|
|
365
364
|
rng: sp.rng
|
|
366
365
|
)
|
|
367
366
|
|
|
@@ -373,12 +372,12 @@ struct State(
|
|
|
373
372
|
sp := spawn(self.rng, self.ship.x, self.ship.y, 220.0, 90.0)
|
|
374
373
|
State(
|
|
375
374
|
..self,
|
|
376
|
-
mines: self.mines.append([Mine(id:
|
|
375
|
+
mines: self.mines.append([Mine(id: MineId + self.mines.length(), at: sp.at, rotation: 0.0, spin: 2.0, clock: 0.0)]),
|
|
377
376
|
rng: sp.rng
|
|
378
377
|
)
|
|
379
378
|
|
|
380
379
|
fun touchesMine(self) -> Bool =
|
|
381
|
-
self.mines.fold(false, |hit, k| hit || self.ship.touches(k.at,
|
|
380
|
+
self.mines.fold(false, |hit, k| hit || self.ship.touches(k.at, MineRadius))
|
|
382
381
|
|
|
383
382
|
# A mine costs a life, makes the ship flash and, at the last life, ends the game.
|
|
384
383
|
fun hurt(self) -> State =
|
|
@@ -391,7 +390,7 @@ struct State(
|
|
|
391
390
|
State(
|
|
392
391
|
..self,
|
|
393
392
|
lives: lives,
|
|
394
|
-
ship: Ship(..ship, hurt:
|
|
393
|
+
ship: Ship(..ship, hurt: HurtTime),
|
|
395
394
|
hurtAt: self.clock,
|
|
396
395
|
over: done,
|
|
397
396
|
overAt: if done then self.clock else self.overAt,
|
|
@@ -432,20 +431,20 @@ struct State(
|
|
|
432
431
|
return self
|
|
433
432
|
pos := po.unwrap()
|
|
434
433
|
view := self.render()
|
|
435
|
-
r :=
|
|
434
|
+
r := ui.step(self.ui, input, view.hitId(pos.x, pos.y))
|
|
436
|
-
|
|
435
|
+
ui.messages(view, r.events).fold(State(..self, ui: r.ui), |s, m| s.update(m))
|
|
437
436
|
|
|
438
437
|
# --- render ---
|
|
439
438
|
|
|
440
439
|
# The zoom that fits the arena into the screen, and where the arena's corner lands.
|
|
441
440
|
fun zoom(self) -> Float =
|
|
442
|
-
{self.sw /
|
|
441
|
+
{self.sw / ArenaW}.min(self.sh / ArenaH)
|
|
443
442
|
|
|
444
443
|
fun offsetX(self) -> Float =
|
|
445
|
-
{self.sw - self.zoom() *
|
|
444
|
+
{self.sw - self.zoom() * ArenaW} / 2.0
|
|
446
445
|
|
|
447
446
|
fun offsetY(self) -> Float =
|
|
448
|
-
{self.sh - self.zoom() *
|
|
447
|
+
{self.sh - self.zoom() * ArenaH} / 2.0
|
|
449
448
|
|
|
450
449
|
# The whole picture, in drawing order, under the camera that fits the arena on screen.
|
|
451
450
|
fun render(self) -> SceneNode[Msg] =
|
|
@@ -453,7 +452,7 @@ struct State(
|
|
|
453
452
|
Group(
|
|
454
453
|
transform: Compose(first: Translate(dx: self.offsetX(), dy: self.offsetY()), then: Scale(sx: z, sy: z)),
|
|
455
454
|
children: [
|
|
456
|
-
RectShape(x: 0.0, y: 0.0, w:
|
|
455
|
+
RectShape(x: 0.0, y: 0.0, w: ArenaW, h: ArenaH, color: Color.rgb(0.07, 0.08, 0.16)),
|
|
457
456
|
Group(transform: Identity, children: self.stars.map(|st| st.render(self.clock))),
|
|
458
457
|
Group(transform: Identity, children: self.mines.map(|k| k.render(self.sheet))),
|
|
459
458
|
Group(transform: Identity, children: self.orbs.map(|o| o.render(self.sheet))),
|
|
@@ -472,7 +471,7 @@ struct State(
|
|
|
472
471
|
if i >= self.lives
|
|
473
472
|
Nil
|
|
474
473
|
else
|
|
475
|
-
Cons(head: cell(self.sheet,
|
|
474
|
+
Cons(head: cell(self.sheet, ArenaW - 40.0 - Float(i) * 36.0, 12.0, 32.0, 0, 0), tail: self.lifeIcons(i + 1))
|
|
476
475
|
|
|
477
476
|
# `Cons` (not `List(..).append(..)`) so the life icons fuse into the draw walk too.
|
|
478
477
|
fun renderHud(self) -> SceneNode[Msg] =
|
|
@@ -497,16 +496,16 @@ struct State(
|
|
|
497
496
|
|
|
498
497
|
# The panel with the restart button, faded in through a render-target filter.
|
|
499
498
|
fun renderPanel(self) -> SceneNode[Msg] =
|
|
500
|
-
|
|
499
|
+
btn := ui.button(RestartId, RestartClicked, "Again", 340.0, 342.0, 120.0, 44.0, self.ui)
|
|
501
500
|
Filter(
|
|
502
501
|
effect: Alpha(alpha: {self.overClock * 2.0}.min(1.0)),
|
|
503
502
|
child: Group(
|
|
504
503
|
transform: Identity,
|
|
505
504
|
children: [
|
|
506
|
-
RectShape(x: 0.0, y: 230.0, w:
|
|
505
|
+
RectShape(x: 0.0, y: 230.0, w: ArenaW, h: 170.0, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6)),
|
|
507
506
|
self.renderTitle(),
|
|
508
507
|
Text(text: "Press Enter to play again", x: 270.0, y: 300.0, size: 24.0, color: Color.White),
|
|
509
|
-
|
|
508
|
+
btn
|
|
510
509
|
]
|
|
511
510
|
),
|
|
512
511
|
target: self.target
|
|
@@ -514,7 +513,7 @@ struct State(
|
|
|
514
513
|
|
|
515
514
|
# True when (x, y) in screen pixels is on the restart button of the picture `render` builds.
|
|
516
515
|
fun onRestart(self, x: Float, y: Float) -> Bool =
|
|
517
|
-
self.render().hitId(x, y).unwrapOr(-1) ==
|
|
516
|
+
self.render().hitId(x, y).unwrapOr(-1) == RestartId
|
|
518
517
|
|
|
519
518
|
# Enter or R going down.
|
|
520
519
|
fun isRestartKey(e: InputEvent) -> Bool = match e
|
|
@@ -533,15 +532,15 @@ struct OrbGame(state: State, input: Input, pickupSound: Sound, hitSound: Sound,
|
|
|
533
532
|
# Polls the input once, sends its events to the state, then one tick steered by the
|
|
534
533
|
# held keys; plays sounds for what changed. Returns the game with the next state.
|
|
535
534
|
fun update(self, io: Io, dt: Float) -> OrbGame =
|
|
536
|
-
|
|
535
|
+
polled := self.input.poll(io)
|
|
537
|
-
s := self.state.update(Resize(w:
|
|
536
|
+
s := self.state.update(Resize(w: gfx.screenWidth(io), h: gfx.screenHeight(io)))
|
|
538
537
|
clicked := s
|
|
539
|
-
inputs :=
|
|
538
|
+
inputs := polled.events
|
|
540
539
|
for i := range inputs.length()
|
|
541
540
|
clicked = clicked.update(Event(input: inputs.at(i)))
|
|
542
541
|
if s.over && !clicked.over
|
|
543
542
|
self.startMusic(io)
|
|
544
|
-
OrbGame(..self, state: clicked, input:
|
|
543
|
+
OrbGame(..self, state: clicked, input: polled)
|
|
545
544
|
else
|
|
546
545
|
t := clicked.update(Tick(dt: dt, ax: clicked.axisX(), ay: clicked.axisY()))
|
|
547
546
|
if t.score > clicked.score
|
|
@@ -552,24 +551,24 @@ struct OrbGame(state: State, input: Input, pickupSound: Sound, hitSound: Sound,
|
|
|
552
551
|
self.overSound.play(io, 1.0)
|
|
553
552
|
else
|
|
554
553
|
self.hitSound.play(io, 1.0)
|
|
555
|
-
OrbGame(..self, state: t, input:
|
|
554
|
+
OrbGame(..self, state: t, input: polled)
|
|
556
555
|
|
|
557
556
|
fun draw(self, io: Io) =
|
|
558
|
-
|
|
557
|
+
gfx.clear(io, Color.rgb(0.04, 0.05, 0.1))
|
|
559
558
|
self.state.render().draw(io)
|
|
560
559
|
|
|
561
560
|
fun musicVolume() -> Float =
|
|
562
561
|
0.3
|
|
563
562
|
|
|
564
563
|
fun main(io: Io) -> OrbGame =
|
|
565
|
-
s := State.start(io.randomSeed(), 0,
|
|
564
|
+
s := State.start(io.randomSeed(), 0, gfx.loadTexture(io, "sprites.png"), gfx.createTexture(io, 1600, 1200), ArenaW, ArenaH)
|
|
566
565
|
game := OrbGame(
|
|
567
566
|
state: s,
|
|
568
567
|
input: Input.create(),
|
|
569
|
-
pickupSound:
|
|
568
|
+
pickupSound: audio.loadSound(io, "pickup.wav"),
|
|
570
|
-
hitSound:
|
|
569
|
+
hitSound: audio.loadSound(io, "hit.wav"),
|
|
571
|
-
overSound:
|
|
570
|
+
overSound: audio.loadSound(io, "gameover.wav"),
|
|
572
|
-
musicSound:
|
|
571
|
+
musicSound: audio.loadSound(io, "music.wav")
|
|
573
572
|
)
|
|
574
573
|
game.startMusic(io)
|
|
575
574
|
game
|
|
@@ -594,13 +593,13 @@ fun away() -> Motion =
|
|
|
594
593
|
Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
|
|
595
594
|
|
|
596
595
|
fun newState(seed: Int) -> State =
|
|
597
|
-
State.start(seed, 0, Texture(id: -1), Texture(id: -1),
|
|
596
|
+
State.start(seed, 0, Texture(id: -1), Texture(id: -1), ArenaW, ArenaH)
|
|
598
597
|
|
|
599
598
|
fun withOrb(s: State, i: Int, m: Motion) -> State =
|
|
600
|
-
State(..s, orbs: s.orbs.map(|o| if o.id ==
|
|
599
|
+
State(..s, orbs: s.orbs.map(|o| if o.id == OrbId + i then Orb(id: o.id, at: m, phase: Float(i) * 0.1, clock: 0.0) else o))
|
|
601
600
|
|
|
602
601
|
fun withMine(s: State, i: Int, m: Motion) -> State =
|
|
603
|
-
State(..s, mines: s.mines.map(|k| if k.id ==
|
|
602
|
+
State(..s, mines: s.mines.map(|k| if k.id == MineId + i then Mine(id: k.id, at: m, rotation: 0.0, spin: 2.0, clock: 0.0) else k))
|
|
604
603
|
|
|
605
604
|
# A state with the orbs and mines moved out of the way.
|
|
606
605
|
fun emptyState() -> State =
|
|
@@ -625,7 +624,7 @@ fun countKids(ks: List[SceneNode[Msg]]) -> Int = match ks
|
|
|
625
624
|
test "steering accelerates and drag slows the ship"
|
|
626
625
|
s := Ship.start().update(1.0, 0.0, 0.1)
|
|
627
626
|
assert s.vx > 0.0
|
|
628
|
-
assert s.x >
|
|
627
|
+
assert s.x > ArenaW / 2.0
|
|
629
628
|
fast := s.vx
|
|
630
629
|
t := s
|
|
631
630
|
for i := range 30
|
|
@@ -636,25 +635,25 @@ test "the ship stops at the arena walls"
|
|
|
636
635
|
s := Ship(x: 20.0, y: 20.0, vx: 0.0, vy: 0.0, rotation: 0.0, hurt: 0.0)
|
|
637
636
|
for i := range 20
|
|
638
637
|
s = s.update(-1.0, -1.0, 0.1)
|
|
639
|
-
assert s.x ==
|
|
638
|
+
assert s.x == ShipRadius
|
|
640
|
-
assert s.y ==
|
|
639
|
+
assert s.y == ShipRadius
|
|
641
640
|
assert s.vx == 0.0
|
|
642
641
|
|
|
643
642
|
test "shipStep leaves its input unchanged"
|
|
644
643
|
s := Ship.start()
|
|
645
644
|
_ := s.update(1.0, 1.0, 0.1)
|
|
646
645
|
assert s.vx == 0.0
|
|
647
|
-
assert s.x ==
|
|
646
|
+
assert s.x == ArenaW / 2.0
|
|
648
647
|
|
|
649
648
|
test "drifters bounce off the walls"
|
|
650
|
-
b := driftOf(Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0),
|
|
649
|
+
b := driftOf(Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), OrbRadius, 0.1)
|
|
651
650
|
assert b.vx == -100.0
|
|
652
|
-
assert b.x ==
|
|
651
|
+
assert b.x == ArenaW - 10.0
|
|
653
|
-
orb := Orb(id:
|
|
652
|
+
orb := Orb(id: OrbId, at: Motion(x: 795.0, y: 300.0, vx: 100.0, vy: 0.0), phase: 0.0, clock: 0.0).update(0.1)
|
|
654
|
-
assert near(orb.at.x,
|
|
653
|
+
assert near(orb.at.x, ArenaW - 10.0)
|
|
655
654
|
|
|
656
655
|
test "a mine spins as it drifts"
|
|
657
|
-
mine := Mine(id:
|
|
656
|
+
mine := Mine(id: MineId, at: Motion(x: 400.0, y: 300.0, vx: 10.0, vy: 0.0), rotation: 0.0, spin: 2.0, clock: 0.0)
|
|
658
657
|
next := mine.update(0.5)
|
|
659
658
|
assert near(next.rotation, 1.0)
|
|
660
659
|
assert near(next.at.x, 405.0)
|
|
@@ -664,16 +663,16 @@ test "collecting an orb scores and respawns it elsewhere"
|
|
|
664
663
|
s := withOrb(emptyState(), 0, onShip(emptyState()))
|
|
665
664
|
t := tickOf(s, 0.0, 0.0, 0.016)
|
|
666
665
|
orb := t.orbs.at(0)
|
|
667
|
-
assert t.score ==
|
|
666
|
+
assert t.score == OrbPoints
|
|
668
|
-
assert
|
|
667
|
+
assert math.hypot(orb.at.x - t.ship.x, orb.at.y - t.ship.y) >= 120.0
|
|
669
668
|
assert orb.at.x < 5000.0
|
|
670
|
-
assert t.orbs.length() ==
|
|
669
|
+
assert t.orbs.length() == OrbCount
|
|
671
670
|
|
|
672
671
|
test "a mine costs one life and makes the ship flash"
|
|
673
672
|
e := emptyState()
|
|
674
673
|
s := withMine(e, 0, onShip(e))
|
|
675
674
|
t := tickOf(s, 0.0, 0.0, 0.016)
|
|
676
|
-
assert t.lives ==
|
|
675
|
+
assert t.lives == StartLives - 1
|
|
677
676
|
assert t.ship.hurt > 0.0
|
|
678
677
|
t = withMine(t, 0, away())
|
|
679
678
|
hidden := 0
|
|
@@ -688,13 +687,13 @@ test "a mine costs one life and makes the ship flash"
|
|
|
688
687
|
assert shown > 0
|
|
689
688
|
assert t.ship.hurt == 0.0
|
|
690
689
|
assert countNodes(t.renderShip()) == 3
|
|
691
|
-
assert t.lives ==
|
|
690
|
+
assert t.lives == StartLives - 1
|
|
692
691
|
|
|
693
692
|
test "the ship is briefly safe after a hit"
|
|
694
693
|
e := emptyState()
|
|
695
694
|
t := tickOf(withMine(e, 0, onShip(e)), 0.0, 0.0, 0.016)
|
|
696
695
|
t = tickOf(t, 0.0, 0.0, 0.016)
|
|
697
|
-
assert t.lives ==
|
|
696
|
+
assert t.lives == StartLives - 1
|
|
698
697
|
|
|
699
698
|
test "the game ends at zero lives and then ignores steps"
|
|
700
699
|
e := emptyState()
|
|
@@ -719,7 +718,7 @@ test "after game over nothing moves but the animations keep running"
|
|
|
719
718
|
after := t.mines.at(0)
|
|
720
719
|
assert after.at.x == mine.at.x
|
|
721
720
|
assert after.rotation == mine.rotation
|
|
722
|
-
assert t.ship.x ==
|
|
721
|
+
assert t.ship.x == ArenaW / 2.0
|
|
723
722
|
assert after.clock > mine.clock + 0.9
|
|
724
723
|
assert t.orbs.at(0).clock > 0.9
|
|
725
724
|
assert t.clock > 0.9
|
|
@@ -732,8 +731,8 @@ test "restart resets the run and keeps the best score"
|
|
|
732
731
|
assert !r.over
|
|
733
732
|
assert r.score == 0
|
|
734
733
|
assert r.best == 90
|
|
735
|
-
assert r.lives ==
|
|
734
|
+
assert r.lives == StartLives
|
|
736
|
-
assert r.ship.x ==
|
|
735
|
+
assert r.ship.x == ArenaW / 2.0
|
|
737
736
|
assert r.mines.length() == mineCount(0)
|
|
738
737
|
assert countNodes(r.renderShip()) == 3
|
|
739
738
|
assert countNodes(r.renderOverlay()) == 1
|
|
@@ -835,12 +834,12 @@ test "restart_click_through_ui"
|
|
|
835
834
|
s := forceOver(State(..e, score: 90))
|
|
836
835
|
down := s.feed(PointerDown(x: 400.0, y: 364.0))
|
|
837
836
|
assert down.over
|
|
838
|
-
assert
|
|
837
|
+
assert ui.pressed(down.ui, RestartId)
|
|
839
838
|
up := down.feed(PointerUp(x: 400.0, y: 364.0))
|
|
840
839
|
assert !up.over
|
|
841
840
|
assert up.score == 0
|
|
842
841
|
assert up.best == 90
|
|
843
|
-
assert up.lives ==
|
|
842
|
+
assert up.lives == StartLives
|
|
844
843
|
off := s.feed(PointerDown(x: 400.0, y: 364.0)).feed(PointerUp(x: 100.0, y: 100.0))
|
|
845
844
|
assert off.over
|
|
846
845
|
miss := s.feed(PointerDown(x: 100.0, y: 100.0)).feed(PointerUp(x: 100.0, y: 100.0))
|
examples/numbers.plum
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import std/Str
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
|
-
import std/
|
|
5
|
+
import std/math
|
|
6
6
|
import std/Slice
|
|
7
7
|
import std/List
|
|
8
8
|
import std/Option
|
|
@@ -48,16 +48,15 @@ fun double[T](a: T) -> T =
|
|
|
48
48
|
# reached as `Type.Name` / `Type.f()` from anywhere, including inside the same
|
|
49
49
|
# body. Constant names are unique per type, not global.
|
|
50
50
|
|
|
51
|
-
#
|
|
51
|
+
# Module-level constants and functions.
|
|
52
|
-
primitive Grid =
|
|
53
|
-
|
|
52
|
+
GridWidth = 8
|
|
54
|
-
|
|
53
|
+
GridHeight = GridWidth * 2
|
|
55
|
-
|
|
54
|
+
CellScale = 2.5
|
|
56
|
-
|
|
55
|
+
GridName = "plum"
|
|
57
|
-
|
|
56
|
+
DebugDraw = true
|
|
58
57
|
|
|
59
|
-
|
|
58
|
+
fun cells() -> Int =
|
|
60
|
-
|
|
59
|
+
GridWidth * GridHeight
|
|
61
60
|
|
|
62
61
|
struct Tile(x: Int) =
|
|
63
62
|
|
|
@@ -70,23 +69,22 @@ struct Tile(x: Int) =
|
|
|
70
69
|
|
|
71
70
|
struct Wrap[T](v: T) =
|
|
72
71
|
|
|
73
|
-
fun area(self) -> Int =
|
|
72
|
+
fun area(self) -> Int = GridWidth * GridHeight
|
|
74
73
|
|
|
75
74
|
struct ConstVec2(x: Float, y: Float) =
|
|
76
75
|
|
|
77
76
|
Zero = ConstVec2(x: 0.0, y: 0.0)
|
|
78
77
|
|
|
79
|
-
fun scaled(n: Float) -> Float = n *
|
|
78
|
+
fun scaled(n: Float) -> Float = n * CellScale
|
|
80
79
|
|
|
81
|
-
primitive Shelf =
|
|
82
|
-
|
|
80
|
+
Sides = 4
|
|
83
|
-
|
|
81
|
+
ShelfNames = ["a", "b", "c"].toSlice()
|
|
84
82
|
|
|
85
|
-
|
|
83
|
+
fun sidesTwice() -> Int =
|
|
86
|
-
|
|
84
|
+
twice(Sides)
|
|
87
85
|
|
|
88
|
-
|
|
86
|
+
fun twice(n: Int) -> Int =
|
|
89
|
-
|
|
87
|
+
n * 2
|
|
90
88
|
|
|
91
89
|
# ==== numbers tests ====
|
|
92
90
|
|
|
@@ -129,7 +127,7 @@ test "pow computes integer powers exactly for both Int and Float self"
|
|
|
129
127
|
|
|
130
128
|
test "log2/log10 agree between Int and the equivalent Float"
|
|
131
129
|
# `log`/`log2`/`log10` are built on the Taylor-series `ln` approximation
|
|
132
|
-
# (see `std/
|
|
130
|
+
# (see `std/math.plum`'s `ln`), not exact libm — compare within a
|
|
133
131
|
# small epsilon rather than requiring bit-exact equality.
|
|
134
132
|
a := 8.log2()
|
|
135
133
|
b := 8.0.log2()
|
|
@@ -167,9 +165,9 @@ test "Int.parse/Float.parse round-trip a rendered number"
|
|
|
167
165
|
assert Float.parse("").unwrapOr(-1.0f) == -1.0f
|
|
168
166
|
|
|
169
167
|
test "Math namespace functions and hyperbolic methods work"
|
|
170
|
-
assert
|
|
168
|
+
assert math.sin(0.0f) == 0.0f
|
|
171
|
-
assert
|
|
169
|
+
assert math.cos(0.0f) == 1.0f
|
|
172
|
-
assert
|
|
170
|
+
assert math.sqrt(16.0f) == 4.0f
|
|
173
171
|
assert 0.sinh() == 0.0f
|
|
174
172
|
assert 0.cosh() == 1.0f
|
|
175
173
|
|
|
@@ -232,22 +230,22 @@ test "operators work through a generic"
|
|
|
232
230
|
# ==== constants tests ====
|
|
233
231
|
|
|
234
232
|
test "consts are usable in fns, methods, generics and derived consts"
|
|
235
|
-
assert
|
|
233
|
+
assert GridHeight == 16
|
|
236
|
-
assert
|
|
234
|
+
assert cells() == 128
|
|
237
235
|
assert Tile(x: 1).offset() == 101
|
|
238
236
|
assert Wrap(v: 3.5).area() == 128
|
|
239
237
|
assert scaled(2.0) == 5.0
|
|
240
|
-
assert
|
|
238
|
+
assert GridName == "plum"
|
|
241
|
-
assert
|
|
239
|
+
assert DebugDraw
|
|
242
240
|
|
|
243
241
|
test "the same const name can live on two types"
|
|
244
|
-
assert
|
|
242
|
+
assert GridWidth == 8
|
|
245
243
|
assert Tile.Width == 100
|
|
246
244
|
|
|
247
245
|
test "a struct can hold a constant instance of itself"
|
|
248
246
|
assert ConstVec2.Zero.x == 0.0
|
|
249
247
|
assert Tile.origin().x == 0
|
|
250
248
|
|
|
251
|
-
test "a
|
|
249
|
+
test "a module holds a list constant and a function reading a sibling constant"
|
|
252
|
-
assert
|
|
250
|
+
assert ShelfNames.length() == 3
|
|
253
|
-
assert
|
|
251
|
+
assert sidesTwice() == 8
|
examples/sequences.plum
CHANGED
|
@@ -5,7 +5,7 @@ import std/Slice
|
|
|
5
5
|
import std/Map
|
|
6
6
|
import std/Pair
|
|
7
7
|
import std/Str
|
|
8
|
-
import std/
|
|
8
|
+
import std/testing
|
|
9
9
|
import std/List
|
|
10
10
|
import std/Option
|
|
11
11
|
|
std/Base64.plum
DELETED
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Str
|
|
4
|
-
import std/Buffer
|
|
5
|
-
import std/Int
|
|
6
|
-
import std/Float
|
|
7
|
-
import std/Option
|
|
8
|
-
import std/Result
|
|
9
|
-
|
|
10
|
-
# The Base64 package contains support for doing Base64 binary-to-text encodings.
|
|
11
|
-
#
|
|
12
|
-
# Implemented on top of `Buffer` and `Str.byteAt`.
|
|
13
|
-
#
|
|
14
|
-
# `data`/the decoded payload are represented as `Str` throughout (matching
|
|
15
|
-
# the original public shape) rather than a byte array — `Str` is itself just a
|
|
16
|
-
# byte array here (see `libs/std/str.plum`), so this is a plain byte string,
|
|
17
|
-
# not a claim that the content is valid UTF-8 text.
|
|
18
|
-
|
|
19
|
-
# Why `Base64.decode` failed.
|
|
20
|
-
enum Base64Error = InvalidBase64
|
|
21
|
-
|
|
22
|
-
primitive Base64 =
|
|
23
|
-
# Encode for PEM (RFC 1421): 64-character lines.
|
|
24
|
-
fun encodePEM(data: Str) -> Str =
|
|
25
|
-
return encode(data, "+", "/", "=", 64, "\r\n")
|
|
26
|
-
|
|
27
|
-
# Encode for MIME (RFC 2045): 76-character lines.
|
|
28
|
-
fun encodeMIME(data: Str) -> Str =
|
|
29
|
-
return encode(data, "+", "/", "=", 76, "\r\n")
|
|
30
|
-
|
|
31
|
-
# Encode for URLs (RFC 4648). Padding characters are stripped by default.
|
|
32
|
-
fun encodeURL(data: Str, pad: Bool = false) -> Str =
|
|
33
|
-
return encode(data, "-", "_", if pad then "=" else "", 0, "")
|
|
34
|
-
|
|
35
|
-
# Configurable encoding. The defaults are for RFC 4648. `pad` is the padding
|
|
36
|
-
# character, or `""` to omit padding entirely; `linelen` is the output line
|
|
37
|
-
# length to wrap at (`0` disables wrapping), separated by `linesep`.
|
|
38
|
-
fun encode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=", linelen: Int = 0, linesep: Str = "\r\n") -> Str =
|
|
39
|
-
at62b := at62.byteAt(0)
|
|
40
|
-
at63b := at63.byteAt(0)
|
|
41
|
-
has_pad := pad.length() > 0
|
|
42
|
-
padb := if has_pad then pad.byteAt(0) else 0
|
|
43
|
-
res := Buffer()
|
|
44
|
-
n := data.length()
|
|
45
|
-
i := 0
|
|
46
|
-
line_chars := 0
|
|
47
|
-
while i < n
|
|
48
|
-
b0 := data.byteAt(i)
|
|
49
|
-
has1 := i + 1 < n
|
|
50
|
-
has2 := i + 2 < n
|
|
51
|
-
b1 := if has1 then data.byteAt(i + 1) else 0
|
|
52
|
-
b2 := if has2 then data.byteAt(i + 2) else 0
|
|
53
|
-
res.writeByte(Byte(encodeByte(b0 >> 2, at62b, at63b)))
|
|
54
|
-
res.writeByte(Byte(encodeByte({b0 & 0x03} << 4 | b1 >> 4, at62b, at63b)))
|
|
55
|
-
line_chars = line_chars + 2
|
|
56
|
-
if has1
|
|
57
|
-
res.writeByte(Byte(encodeByte({b1 & 0x0F} << 2 | b2 >> 6, at62b, at63b)))
|
|
58
|
-
line_chars = line_chars + 1
|
|
59
|
-
else if has_pad
|
|
60
|
-
res.writeByte(Byte(padb))
|
|
61
|
-
line_chars = line_chars + 1
|
|
62
|
-
if has2
|
|
63
|
-
res.writeByte(Byte(encodeByte(b2 & 0x3F, at62b, at63b)))
|
|
64
|
-
line_chars = line_chars + 1
|
|
65
|
-
else if has_pad
|
|
66
|
-
res.writeByte(Byte(padb))
|
|
67
|
-
line_chars = line_chars + 1
|
|
68
|
-
i = i + 3
|
|
69
|
-
if linelen > 0 && line_chars >= linelen && i < n
|
|
70
|
-
res.write(linesep)
|
|
71
|
-
line_chars = 0
|
|
72
|
-
return res.toStr()
|
|
73
|
-
|
|
74
|
-
# Encodes a single 6-bit value (0-63) as its base64 alphabet character.
|
|
75
|
-
fun encodeByte(i: Int, at62: Int, at63: Int) -> Int =
|
|
76
|
-
if i < 26
|
|
77
|
-
return 65 + i # 'A'..'Z'
|
|
78
|
-
if i < 52
|
|
79
|
-
return 97 + {i - 26} # 'a'..'z'
|
|
80
|
-
if i < 62
|
|
81
|
-
return 48 + {i - 52} # '0'..'9'
|
|
82
|
-
if i == 62
|
|
83
|
-
return at62
|
|
84
|
-
return at63
|
|
85
|
-
|
|
86
|
-
# The inverse of `encodeByte`: a base64 alphabet character's 6-bit value, or
|
|
87
|
-
# -1 if `b` isn't one of the 64 alphabet characters (whitespace/padding are
|
|
88
|
-
# handled by the caller, not here).
|
|
89
|
-
fun decodeByte(b: Int, at62: Int, at63: Int) -> Int =
|
|
90
|
-
if b >= 65 && b <= 90
|
|
91
|
-
return b - 65
|
|
92
|
-
if b >= 97 && b <= 122
|
|
93
|
-
return b - 97 + 26
|
|
94
|
-
if b >= 48 && b <= 57
|
|
95
|
-
return b - 48 + 52
|
|
96
|
-
if b == at62
|
|
97
|
-
return 62
|
|
98
|
-
if b == at63
|
|
99
|
-
return 63
|
|
100
|
-
return -1
|
|
101
|
-
|
|
102
|
-
fun isBase64Whitespace(b: Int) -> Bool =
|
|
103
|
-
b == 32 || b == 9 || b == 10 || b == 13
|
|
104
|
-
|
|
105
|
-
# Decode for URLs (RFC 4648).
|
|
106
|
-
fun decodeUrl(data: Str) -> Result[Str, Base64Error] =
|
|
107
|
-
return decode(data, "-", "_", "=")
|
|
108
|
-
|
|
109
|
-
# Configurable decoding. The defaults are for RFC 4648. Missing padding is
|
|
110
|
-
# not an error. Non-base64 data, other than whitespace (which can appear at
|
|
111
|
-
# any point), fails with `Err(InvalidBase64)`.
|
|
112
|
-
fun decode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=") -> Result[Str, Base64Error] =
|
|
113
|
-
at62b := at62.byteAt(0)
|
|
114
|
-
at63b := at63.byteAt(0)
|
|
115
|
-
has_pad := pad.length() > 0
|
|
116
|
-
padb := if has_pad then pad.byteAt(0) else -1
|
|
117
|
-
res := Buffer()
|
|
118
|
-
n := data.length()
|
|
119
|
-
i := 0
|
|
120
|
-
bits := 0
|
|
121
|
-
nbits := 0
|
|
122
|
-
while i < n
|
|
123
|
-
b := data.byteAt(i)
|
|
124
|
-
i = i + 1
|
|
125
|
-
if isBase64Whitespace(b) || b == padb
|
|
126
|
-
continue
|
|
127
|
-
v := decodeByte(b, at62b, at63b)
|
|
128
|
-
if v < 0
|
|
129
|
-
return Err(InvalidBase64)
|
|
130
|
-
bits = {bits << 6} | v
|
|
131
|
-
nbits = nbits + 6
|
|
132
|
-
if nbits >= 8
|
|
133
|
-
nbits = nbits - 8
|
|
134
|
-
res.writeByte(Byte({bits >> nbits} & 0xFF))
|
|
135
|
-
return Ok(res.toStr())
|
|
136
|
-
|
|
137
|
-
test "statics are reached through the Base64 namespace and round-trip"
|
|
138
|
-
assert Base64.decode(Base64.encodePEM("hello"))! == "hello"
|
|
139
|
-
assert Base64.decode(Base64.encodeMIME("hi there"))! == "hi there"
|
std/Float.plum
CHANGED
|
@@ -2,7 +2,7 @@ module std
|
|
|
2
2
|
|
|
3
3
|
import std/Str
|
|
4
4
|
import std/Int
|
|
5
|
-
import std/
|
|
5
|
+
import std/math
|
|
6
6
|
import std/Option
|
|
7
7
|
import std/Result
|
|
8
8
|
|
|
@@ -107,28 +107,28 @@ primitive Float =
|
|
|
107
107
|
return if neg then -r else r
|
|
108
108
|
|
|
109
109
|
fun log(self) -> Float =
|
|
110
|
-
|
|
110
|
+
math.ln(self)
|
|
111
111
|
|
|
112
112
|
fun log2(self) -> Float =
|
|
113
|
-
|
|
113
|
+
math.ln(self) * Float.Log2E
|
|
114
114
|
|
|
115
115
|
fun log10(self) -> Float =
|
|
116
|
-
|
|
116
|
+
math.ln(self) * Float.Log10E
|
|
117
117
|
|
|
118
118
|
# floor(log2(|self|)).
|
|
119
119
|
fun logb(self) -> Float =
|
|
120
120
|
if self == 0.0f
|
|
121
121
|
return -1.0f / 0.0f
|
|
122
|
-
return {
|
|
122
|
+
return {math.ln(if self < 0.0f then -self else self) * Float.Log2E}.floor()
|
|
123
123
|
|
|
124
124
|
fun sqrt(self) -> Float =
|
|
125
|
-
|
|
125
|
+
math.sqrt(self)
|
|
126
126
|
|
|
127
127
|
# self^y. A whole-number `y` (including negative) is computed exactly by
|
|
128
128
|
# repeated squaring; a fractional `y` falls back to self^y = exp(y *
|
|
129
129
|
# ln(self)), which requires self > 0.
|
|
130
130
|
fun pow(self, y: Float) -> Float =
|
|
131
|
-
|
|
131
|
+
math.powFloat(self, y)
|
|
132
132
|
|
|
133
133
|
# Check whether this number is finite, ie not +/-infinity and not NaN.
|
|
134
134
|
fun isFinite(self) -> Bool =
|
|
@@ -150,26 +150,26 @@ primitive Float =
|
|
|
150
150
|
fun acosh(self) -> Float =
|
|
151
151
|
if self < 1.0f
|
|
152
152
|
return 0.0f / 0.0f
|
|
153
|
-
return
|
|
153
|
+
return math.ln(self + math.sqrt(self * self - 1.0f))
|
|
154
154
|
|
|
155
155
|
fun sinh(self) -> Float =
|
|
156
|
-
return {
|
|
156
|
+
return {math.exp(self) - math.exp(-self)} / 2.0f
|
|
157
157
|
|
|
158
158
|
fun cosh(self) -> Float =
|
|
159
|
-
return {
|
|
159
|
+
return {math.exp(self) + math.exp(-self)} / 2.0f
|
|
160
160
|
|
|
161
161
|
fun tanh(self) -> Float =
|
|
162
162
|
return self.sinh() / self.cosh()
|
|
163
163
|
|
|
164
164
|
# Inverse hyperbolic sine: asinh(x) = ln(x + sqrt(x^2 + 1)).
|
|
165
165
|
fun asinh(self) -> Float =
|
|
166
|
-
return
|
|
166
|
+
return math.ln(self + math.sqrt(self * self + 1.0f))
|
|
167
167
|
|
|
168
168
|
# Inverse hyperbolic tangent: atanh(x) = 0.5*ln((1+x)/(1-x)), |x| < 1.
|
|
169
169
|
fun atanh(self) -> Float =
|
|
170
170
|
if self <= -1.0f || self >= 1.0f
|
|
171
171
|
return 0.0f / 0.0f
|
|
172
|
-
return 0.5f *
|
|
172
|
+
return 0.5f * math.ln({1.0f + self} / {1.0f - self})
|
|
173
173
|
|
|
174
174
|
# Rounded to 6 fractional digits, with trailing zeros trimmed (but always
|
|
175
175
|
# at least one digit after the point, e.g. `3.0` not `3.`).
|
std/Http.plum
DELETED
|
@@ -1,156 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Buffer
|
|
4
|
-
import std/Json
|
|
5
|
-
import std/Slice
|
|
6
|
-
import std/Map
|
|
7
|
-
import std/Str
|
|
8
|
-
import std/Int
|
|
9
|
-
import std/Float
|
|
10
|
-
import std/Io
|
|
11
|
-
import std/Option
|
|
12
|
-
import std/Result
|
|
13
|
-
|
|
14
|
-
# Transport failure, or a response that is not valid HTTP.
|
|
15
|
-
enum HttpError =
|
|
16
|
-
| HttpFailed
|
|
17
|
-
| BadResponse
|
|
18
|
-
|
|
19
|
-
fun name(self) -> Str =
|
|
20
|
-
match self
|
|
21
|
-
HttpFailed => "HttpFailed"
|
|
22
|
-
BadResponse => "BadResponse"
|
|
23
|
-
|
|
24
|
-
# An HTTP response: status code, response headers, and the raw response
|
|
25
|
-
# body as a `Str` (a byte array, so binary bodies round-trip intact).
|
|
26
|
-
struct Response(status: Int, headers: Map[Str, Str], body: Str) =
|
|
27
|
-
|
|
28
|
-
# 2xx status codes are success; everything else (redirects, 4xx, 5xx) is
|
|
29
|
-
# surfaced here rather than as an error from `request` — a non-2xx
|
|
30
|
-
# response is still a complete, well-formed HTTP exchange, not a failed
|
|
31
|
-
# one (`request` itself only fails for transport-level problems like a
|
|
32
|
-
# DNS/connection error).
|
|
33
|
-
fun ok(self) -> Bool =
|
|
34
|
-
self.status >= 200 && self.status < 300
|
|
35
|
-
|
|
36
|
-
# Parses `body` as JSON. Fails the same way `Json.fromStr` does for a
|
|
37
|
-
# response body that isn't valid JSON.
|
|
38
|
-
fun json(self) -> Result[Json, JsonError] =
|
|
39
|
-
return Json.fromStr(self.body)
|
|
40
|
-
|
|
41
|
-
# A single blocking network round trip — this VM has no async/event-loop
|
|
42
|
-
# mechanism, so `rawHttpRequest` runs to completion before returning (same
|
|
43
|
-
# idea as `libs/std/os.plum`'s `rawReadFile`). `headers` is `"Key: Value"`
|
|
44
|
-
# lines joined by `\n` (`""` for none). The result packs an outcome flag,
|
|
45
|
-
# then either the status code and response headers (success) or an error
|
|
46
|
-
# message (failure), as fields joined by `\x01`, up to the first `\x00` —
|
|
47
|
-
# everything after that byte is the raw response body. `\x00`/`\x01` can
|
|
48
|
-
# never occur in the metadata fields themselves (the flag/status are
|
|
49
|
-
# decimal digits, header names/values and the error message are always
|
|
50
|
-
# plain text), so they safely mark where the opaque body bytes start even
|
|
51
|
-
# when the body itself is arbitrary binary data.
|
|
52
|
-
|
|
53
|
-
primitive Http =
|
|
54
|
-
fun emptyHeaders() -> Map[Str, Str] =
|
|
55
|
-
return Map.empty()
|
|
56
|
-
|
|
57
|
-
# Packs `headers` into the `"Key: Value"`-per-line format `rawHttpRequest`
|
|
58
|
-
# expects for its own `headers` argument.
|
|
59
|
-
fun encodeHeaders(headers: Map[Str, Str]) -> Str =
|
|
60
|
-
buf := Buffer()
|
|
61
|
-
for e := range headers.entries()
|
|
62
|
-
if buf.length() > 0
|
|
63
|
-
buf.write("\n")
|
|
64
|
-
buf.write(e.first)
|
|
65
|
-
buf.write(": ")
|
|
66
|
-
buf.write(e.second)
|
|
67
|
-
return buf.toStr()
|
|
68
|
-
|
|
69
|
-
# The reverse of `encodeHeaders`, for the response headers `rawHttpRequest`
|
|
70
|
-
# packs into its result.
|
|
71
|
-
fun decodeHeaders(raw: Str) -> Map[Str, Str] =
|
|
72
|
-
result := emptyHeaders()
|
|
73
|
-
if raw == ""
|
|
74
|
-
return result
|
|
75
|
-
for line := range raw.split("\n", 0)
|
|
76
|
-
idx := line.indexOf(": ")
|
|
77
|
-
if idx >= 0
|
|
78
|
-
key := line.sub(0, idx)
|
|
79
|
-
val := line.sub(idx + 2, line.length())
|
|
80
|
-
result.set(key, val)
|
|
81
|
-
return result
|
|
82
|
-
|
|
83
|
-
# Performs a single HTTP request and waits for the full response. Fails
|
|
84
|
-
# only for a transport-level problem (DNS failure, connection refused, TLS
|
|
85
|
-
# error, ...) — an HTTP-level error status (404, 500, ...) is still a
|
|
86
|
-
# successful round trip, returned as a `Response` with that status (check
|
|
87
|
-
# `Response.ok()`). Fails with `HttpFailed` for a transport error and
|
|
88
|
-
# `BadResponse` for a reply whose status line can't be read.
|
|
89
|
-
fun request(io: Io, method: Str, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
90
|
-
raw := io.rawHttpRequest(method, url, encodeHeaders(headers), body)
|
|
91
|
-
sep := raw.indexOf("\x00")
|
|
92
|
-
meta := if sep >= 0 then raw.sub(0, sep) else raw
|
|
93
|
-
resp_body := if sep >= 0 then raw.sub(sep + 1, raw.length()) else ""
|
|
94
|
-
parts := meta.split("\x01", 3)
|
|
95
|
-
flag := parts.get(0).unwrapOr("")
|
|
96
|
-
if flag != "1"
|
|
97
|
-
return Err(HttpFailed)
|
|
98
|
-
match Int.parse(parts.get(1).unwrapOr(""))
|
|
99
|
-
Ok(status) => Ok(Response(status: status, headers: decodeHeaders(parts.get(2).unwrapOr("")), body: resp_body))
|
|
100
|
-
Err(e) => Err(BadResponse)
|
|
101
|
-
|
|
102
|
-
fun get(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
|
|
103
|
-
return request(io, "GET", url, headers, "")
|
|
104
|
-
|
|
105
|
-
fun head(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
|
|
106
|
-
return request(io, "HEAD", url, headers, "")
|
|
107
|
-
|
|
108
|
-
fun delete(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
|
|
109
|
-
return request(io, "DELETE", url, headers, "")
|
|
110
|
-
|
|
111
|
-
fun post(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
112
|
-
return request(io, "POST", url, headers, body)
|
|
113
|
-
|
|
114
|
-
fun put(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
115
|
-
return request(io, "PUT", url, headers, body)
|
|
116
|
-
|
|
117
|
-
fun patch(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
118
|
-
return request(io, "PATCH", url, headers, body)
|
|
119
|
-
|
|
120
|
-
# Convenience wrapper: sends `body` as a JSON `Str`, adding a
|
|
121
|
-
# `Content-Type: application/json` header, and parses the response back as
|
|
122
|
-
# JSON via `Response.json()`.
|
|
123
|
-
fun postJson(io: Io, url: Str, headers: Map[Str, Str], body: Json) -> Result[Response, HttpError] =
|
|
124
|
-
headers.set("Content-Type", "application/json")
|
|
125
|
-
return post(io, url, headers, body.toStr())
|
|
126
|
-
|
|
127
|
-
test "encodeHeaders/decodeHeaders round-trip a header map"
|
|
128
|
-
h := Http.emptyHeaders()
|
|
129
|
-
h.set("Content-Type", "application/json")
|
|
130
|
-
h.set("Accept", "*/*")
|
|
131
|
-
decoded := Http.decodeHeaders(Http.encodeHeaders(h))
|
|
132
|
-
assert decoded.get("Content-Type")! == "application/json"
|
|
133
|
-
assert decoded.get("Accept")! == "*/*"
|
|
134
|
-
|
|
135
|
-
test "decodeHeaders returns an empty map for an empty string"
|
|
136
|
-
assert Http.decodeHeaders("").isEmpty() == true
|
|
137
|
-
|
|
138
|
-
test "get performs a real HTTP round trip"
|
|
139
|
-
resp := Http.get(io, "https://httpbin.org/get", Http.emptyHeaders())!
|
|
140
|
-
assert resp.ok() == true
|
|
141
|
-
assert resp.status == 200
|
|
142
|
-
|
|
143
|
-
test "get reports a non-2xx status without failing the request"
|
|
144
|
-
resp := Http.get(io, "https://httpbin.org/status/404", Http.emptyHeaders())!
|
|
145
|
-
assert resp.ok() == false
|
|
146
|
-
assert resp.status == 404
|
|
147
|
-
|
|
148
|
-
test "post sends a body and the server echoes it back"
|
|
149
|
-
resp := Http.post(io, "https://httpbin.org/post", Http.emptyHeaders(), "hello world")!
|
|
150
|
-
assert resp.ok() == true
|
|
151
|
-
j := resp.json()!
|
|
152
|
-
assert j.asMap()!.get("data")!.asStr()! == "hello world"
|
|
153
|
-
|
|
154
|
-
test "request fails for an unreachable host"
|
|
155
|
-
resp := Http.get(io, "http://this-host-does-not-exist.invalid/", Http.emptyHeaders()).unwrapOr(Response(status: 0, headers: Http.emptyHeaders(), body: ""))
|
|
156
|
-
assert resp.status == 0
|
std/Int.plum
CHANGED
|
@@ -2,7 +2,7 @@ module std
|
|
|
2
2
|
|
|
3
3
|
import std/Str
|
|
4
4
|
import std/Float
|
|
5
|
-
import std/
|
|
5
|
+
import std/math
|
|
6
6
|
import std/Pair
|
|
7
7
|
import std/Option
|
|
8
8
|
import std/Result
|
|
@@ -62,13 +62,13 @@ primitive Int =
|
|
|
62
62
|
Float(self)
|
|
63
63
|
|
|
64
64
|
fun log(self) -> Float =
|
|
65
|
-
|
|
65
|
+
math.ln(Float(self))
|
|
66
66
|
|
|
67
67
|
fun log2(self) -> Float =
|
|
68
|
-
|
|
68
|
+
math.ln(Float(self)) * Float.Log2E
|
|
69
69
|
|
|
70
70
|
fun log10(self) -> Float =
|
|
71
|
-
|
|
71
|
+
math.ln(Float(self)) * Float.Log10E
|
|
72
72
|
|
|
73
73
|
# floor(log2(|self|)), computed exactly with integer division rather than
|
|
74
74
|
# through Float rounding error.
|
|
@@ -83,10 +83,10 @@ primitive Int =
|
|
|
83
83
|
return Float(k)
|
|
84
84
|
|
|
85
85
|
fun sqrt(self) -> Float =
|
|
86
|
-
|
|
86
|
+
math.sqrt(Float(self))
|
|
87
87
|
|
|
88
88
|
fun pow(self, y: Float) -> Float =
|
|
89
|
-
|
|
89
|
+
math.powFloat(Float(self), y)
|
|
90
90
|
|
|
91
91
|
fun isFinite(self) -> Bool =
|
|
92
92
|
true
|
std/Io.plum
CHANGED
|
@@ -3,74 +3,18 @@ module std
|
|
|
3
3
|
import std/Int
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Str
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import std/game/Color
|
|
8
6
|
|
|
9
7
|
# The host capability. Every call that leaves the program (drawing, input, sound,
|
|
10
|
-
# files, environment, clock, randomness, network)
|
|
8
|
+
# files, environment, clock, randomness, network) takes an `Io`. `Io` is a built-in
|
|
11
|
-
#
|
|
9
|
+
# primitive with no fields. The general host calls are the `extern fun` methods below;
|
|
10
|
+
# the game host's calls are module functions that take `io` first: `std/game/gfx`,
|
|
12
|
-
#
|
|
11
|
+
# `std/game/input` and `std/game/audio`. The host entry points pass the one `Io` value,
|
|
13
|
-
# function with no `Io` reachable cannot touch the host: that is what "pure" means.
|
|
12
|
+
# so a function with no `Io` reachable cannot touch the host: that is what "pure" means.
|
|
14
13
|
#
|
|
15
|
-
# Texture and sound handles are -1 on failure. File, texture and sound paths are
|
|
16
|
-
#
|
|
14
|
+
# `Int` in an extern signature is narrowed to i32 at the host boundary, so wall-clock
|
|
17
|
-
#
|
|
15
|
+
# time travels as `Float`.
|
|
18
16
|
|
|
19
17
|
primitive Io =
|
|
20
|
-
extern fun screenWidth(self) -> Float
|
|
21
|
-
extern fun screenHeight(self) -> Float
|
|
22
|
-
extern fun frameTime(self) -> Float
|
|
23
|
-
extern fun clear(self, c: Color)
|
|
24
|
-
extern fun drawRect(self, x: Float, y: Float, w: Float, h: Float, c: Color)
|
|
25
|
-
extern fun drawCircle(self, x: Float, y: Float, r: Float, c: Color)
|
|
26
|
-
extern fun drawLine(self, x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, c: Color)
|
|
27
|
-
extern fun drawText(self, s: Str, x: Float, y: Float, size: Float, c: Color)
|
|
28
|
-
extern fun setCamera(self, x: Float, y: Float, scale: Float)
|
|
29
|
-
extern fun resetCamera(self)
|
|
30
|
-
# Loads any image the host decodes (PNG at least); -1 on failure.
|
|
31
|
-
extern fun textureLoad(self, path: Str) -> Int
|
|
32
|
-
# Size in pixels; 0 for a bad handle.
|
|
33
|
-
extern fun textureWidth(self, t: Int) -> Int
|
|
34
|
-
extern fun textureHeight(self, t: Int) -> Int
|
|
35
|
-
# Linear (true) or nearest (false, the default) filtering.
|
|
36
|
-
extern fun textureSetSmooth(self, t: Int, smooth: Bool)
|
|
37
|
-
# A blank, transparent texture of w x h pixels that can be drawn into with
|
|
38
|
-
# `renderTarget`; -1 if a side is below 1 or above 8192.
|
|
39
|
-
extern fun textureCreate(self, w: Int, h: Int) -> Int
|
|
40
|
-
# Sends the following draws (and `clear`) into texture `t` made by `textureCreate`,
|
|
41
|
-
# or back to the screen with -1; any other handle is ignored. Each target has its
|
|
42
|
-
# own camera: selecting a target resets its camera to its pixels, and returning to
|
|
43
|
-
# the screen restores the screen's camera. The texture's contents persist between
|
|
44
|
-
# frames; draw it like any texture once the screen is selected again.
|
|
45
|
-
extern fun renderTarget(self, t: Int)
|
|
46
|
-
# The blend mode of the following draws: a `Blend` constant (other values are
|
|
47
|
-
# ignored). Every frame starts with `Blend.Normal`.
|
|
48
|
-
extern fun blendMode(self, m: Int)
|
|
49
|
-
# The texture at its natural size, top-left at (x, y).
|
|
50
|
-
extern fun drawTexture(self, t: Int, x: Float, y: Float, tint: Color)
|
|
51
|
-
# The source rect (sx, sy, sw, sh) in texture pixels drawn into the dest rect
|
|
52
|
-
# (x, y, w, h), rotated `rotation` radians clockwise about the dest centre.
|
|
53
|
-
extern fun drawTextureEx(self, t: Int, sx: Float, sy: Float, sw: Float, sh: Float, x: Float, y: Float, w: Float, h: Float, rotation: Float, flipX: Bool, tint: Color)
|
|
54
|
-
extern fun fileExists(self, path: Str) -> Bool
|
|
55
|
-
# The whole file; "" if it is missing.
|
|
56
|
-
extern fun fileLoad(self, path: Str) -> Str
|
|
57
|
-
# Loads a WAV or OGG file relative to the asset root; -1 on failure. The host
|
|
58
|
-
# decodes every sound file in the asset root before `init` runs.
|
|
59
|
-
extern fun soundLoad(self, path: Str) -> Int
|
|
60
|
-
# A one-shot play; plays of the same sound may overlap. Volume is 0..1.
|
|
61
|
-
extern fun soundPlay(self, s: Int, volume: Float)
|
|
62
|
-
# Starts the sound looping. Call `soundStop` first to restart it cleanly.
|
|
63
|
-
extern fun soundLoop(self, s: Int, volume: Float)
|
|
64
|
-
# Stops every play and loop of the sound.
|
|
65
|
-
extern fun soundStop(self, s: Int)
|
|
66
|
-
# Changes the volume of a sound that is playing or looping.
|
|
67
|
-
extern fun soundSetVolume(self, s: Int, volume: Float)
|
|
68
|
-
extern fun isKeyDown(self, k: Int) -> Bool
|
|
69
|
-
extern fun isKeyPressed(self, k: Int) -> Bool
|
|
70
|
-
extern fun mousePos(self) -> Vec2
|
|
71
|
-
extern fun isMouseDown(self, b: Int) -> Bool
|
|
72
|
-
extern fun isMousePressed(self, b: Int) -> Bool
|
|
73
|
-
extern fun mouseWheel(self) -> Float
|
|
74
18
|
extern fun printLn(self, s: Str)
|
|
75
19
|
extern fun rawReadFile(self, path: Str) -> Str
|
|
76
20
|
extern fun rawWriteFile(self, path: Str, data: Str) -> Int
|
std/Math.plum
DELETED
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
|
|
6
|
-
# Free-standing floating-point math: `Math.sqrt(x)`, `Math.sin(x)`, ... A
|
|
7
|
-
# stateless namespace, not a type.
|
|
8
|
-
primitive Math =
|
|
9
|
-
# Shared `base^y` algorithm behind `Int.pow` and `Float.pow`, extracted so both the `Int`
|
|
10
|
-
# and `Float` self cases (which only differ in how `base` was obtained) share
|
|
11
|
-
# one body.
|
|
12
|
-
fun powFloat(base: Float, y: Float) -> Float =
|
|
13
|
-
if y == 0.0f
|
|
14
|
-
return 1.0f
|
|
15
|
-
yi := Int(y)
|
|
16
|
-
if Float(yi) == y
|
|
17
|
-
neg := yi < 0
|
|
18
|
-
n := if neg then -yi else yi
|
|
19
|
-
result := 1.0f
|
|
20
|
-
b := base
|
|
21
|
-
m := n
|
|
22
|
-
while m > 0
|
|
23
|
-
if m % 2 == 1
|
|
24
|
-
result = result * b
|
|
25
|
-
b = b * b
|
|
26
|
-
m = m / 2
|
|
27
|
-
return if neg then 1.0f / result else result
|
|
28
|
-
if base < 0.0f
|
|
29
|
-
return 0.0f / 0.0f
|
|
30
|
-
return exp(y * ln(base))
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
# Natural exponential, e^x, via range reduction (halve x until |x| <= 0.5,
|
|
34
|
-
# run the Taylor series there where it converges fast, then square the
|
|
35
|
-
# result back up the same number of halvings).
|
|
36
|
-
fun exp(x: Float) -> Float =
|
|
37
|
-
if x != x
|
|
38
|
-
return x
|
|
39
|
-
if x > 700.0f
|
|
40
|
-
return 1.0f / 0.0f
|
|
41
|
-
if x < -700.0f
|
|
42
|
-
return 0.0f
|
|
43
|
-
v := x
|
|
44
|
-
k := 0
|
|
45
|
-
while v > 0.5f || v < -0.5f
|
|
46
|
-
v = v / 2.0f
|
|
47
|
-
k = k + 1
|
|
48
|
-
term := 1.0f
|
|
49
|
-
sum := 1.0f
|
|
50
|
-
n := 1
|
|
51
|
-
while n < 25
|
|
52
|
-
term = term * v / Float(n)
|
|
53
|
-
sum = sum + term
|
|
54
|
-
n = n + 1
|
|
55
|
-
result := sum
|
|
56
|
-
i := 0
|
|
57
|
-
while i < k
|
|
58
|
-
result = result * result
|
|
59
|
-
i = i + 1
|
|
60
|
-
return result
|
|
61
|
-
|
|
62
|
-
# Natural logarithm, via range reduction to v in [1, 2) plus the
|
|
63
|
-
# fast-converging series ln(v) = 2*atanh((v-1)/(v+1)).
|
|
64
|
-
fun ln(x: Float) -> Float =
|
|
65
|
-
if x != x || x < 0.0f
|
|
66
|
-
return 0.0f / 0.0f
|
|
67
|
-
if x == 0.0f
|
|
68
|
-
return -1.0f / 0.0f
|
|
69
|
-
if x > Float.Max
|
|
70
|
-
return x
|
|
71
|
-
v := x
|
|
72
|
-
k := 0
|
|
73
|
-
while v >= 2.0f
|
|
74
|
-
v = v / 2.0f
|
|
75
|
-
k = k + 1
|
|
76
|
-
while v < 1.0f
|
|
77
|
-
v = v * 2.0f
|
|
78
|
-
k = k - 1
|
|
79
|
-
t := {v - 1.0f} / {v + 1.0f}
|
|
80
|
-
t2 := t * t
|
|
81
|
-
term := t
|
|
82
|
-
sum := t
|
|
83
|
-
n := 1
|
|
84
|
-
while n < 30
|
|
85
|
-
term = term * t2
|
|
86
|
-
sum = sum + term / Float(2 * n + 1)
|
|
87
|
-
n = n + 1
|
|
88
|
-
return Float(k) * Float.Ln2 + 2.0f * sum
|
|
89
|
-
|
|
90
|
-
# Square root via Newton's method, iterating to a fixed point.
|
|
91
|
-
fun sqrt(x: Float) -> Float =
|
|
92
|
-
if x < 0.0f
|
|
93
|
-
return 0.0f / 0.0f
|
|
94
|
-
if x == 0.0f || x != x
|
|
95
|
-
return x
|
|
96
|
-
guess := x
|
|
97
|
-
prev := 0.0f
|
|
98
|
-
i := 0
|
|
99
|
-
while guess != prev && i < 100
|
|
100
|
-
prev = guess
|
|
101
|
-
guess = 0.5f * {guess + x / guess}
|
|
102
|
-
i = i + 1
|
|
103
|
-
return guess
|
|
104
|
-
|
|
105
|
-
# Reduces `x` into roughly `[-Float.Pi, Float.Pi]` by subtracting the nearest multiple of
|
|
106
|
-
# `Float.Tau` — the range `sin`/`cos`'s Taylor series below actually converge
|
|
107
|
-
# quickly over. For very large `|x|` (many multiples of `Float.Tau`), floating-point
|
|
108
|
-
# cancellation in `x - k*Float.Tau` loses precision the same way any naive
|
|
109
|
-
# range-reduction by subtraction does; a real libm uses extended-precision
|
|
110
|
-
# constants to avoid this, which isn't attempted here.
|
|
111
|
-
fun reduceToPi(x: Float) -> Float =
|
|
112
|
-
k := Int(x / Float.Tau + {if x >= 0.0f then 0.5f else -0.5f})
|
|
113
|
-
return x - Float(k) * Float.Tau
|
|
114
|
-
|
|
115
|
-
fun sin(x: Float) -> Float =
|
|
116
|
-
if x != x || x > Float.Max || x < -Float.Max
|
|
117
|
-
return 0.0f / 0.0f
|
|
118
|
-
r := reduceToPi(x)
|
|
119
|
-
r2 := r * r
|
|
120
|
-
term := r
|
|
121
|
-
sum := r
|
|
122
|
-
n := 1
|
|
123
|
-
while n < 10
|
|
124
|
-
term = term * {-r2} / Float({2 * n} * {2 * n + 1})
|
|
125
|
-
sum = sum + term
|
|
126
|
-
n = n + 1
|
|
127
|
-
return sum
|
|
128
|
-
|
|
129
|
-
fun cos(x: Float) -> Float =
|
|
130
|
-
if x != x || x > Float.Max || x < -Float.Max
|
|
131
|
-
return 0.0f / 0.0f
|
|
132
|
-
return sin(x + Float.HalfPi)
|
|
133
|
-
|
|
134
|
-
fun tan(x: Float) -> Float =
|
|
135
|
-
return sin(x) / cos(x)
|
|
136
|
-
|
|
137
|
-
# Arctangent, via repeated argument-halving (`atan(x) = 2*atan(x / (1 +
|
|
138
|
-
# sqrt(1+x^2)))`) until `|x| <= 0.5` (where the Taylor series below converges
|
|
139
|
-
# quickly), then doubling the result back up the same number of times.
|
|
140
|
-
fun atan(x: Float) -> Float =
|
|
141
|
-
if x != x
|
|
142
|
-
return x
|
|
143
|
-
neg := x < 0.0f
|
|
144
|
-
v := if neg then -x else x
|
|
145
|
-
k := 0
|
|
146
|
-
while v > 0.5f && k < 8
|
|
147
|
-
v = v / {1.0f + sqrt(1.0f + v * v)}
|
|
148
|
-
k = k + 1
|
|
149
|
-
v2 := v * v
|
|
150
|
-
term := v
|
|
151
|
-
sum := v
|
|
152
|
-
n := 1
|
|
153
|
-
while n < 20
|
|
154
|
-
term = term * {-v2}
|
|
155
|
-
sum = sum + term / Float(2 * n + 1)
|
|
156
|
-
n = n + 1
|
|
157
|
-
scale := Float(1 << k)
|
|
158
|
-
result := sum * scale
|
|
159
|
-
return if neg then -result else result
|
|
160
|
-
|
|
161
|
-
fun asin(x: Float) -> Float =
|
|
162
|
-
if x != x || x < -1.0f || x > 1.0f
|
|
163
|
-
return 0.0f / 0.0f
|
|
164
|
-
if x == 1.0f
|
|
165
|
-
return Float.HalfPi
|
|
166
|
-
if x == -1.0f
|
|
167
|
-
return -Float.HalfPi
|
|
168
|
-
return atan(x / sqrt(1.0f - x * x))
|
|
169
|
-
|
|
170
|
-
fun acos(x: Float) -> Float =
|
|
171
|
-
return Float.HalfPi - asin(x)
|
|
172
|
-
|
|
173
|
-
# Angle (in radians) of the point `(x, y)` from the origin, in the correct
|
|
174
|
-
# quadrant for any sign combination of `x`/`y` (unlike plain `atan(y/x)`,
|
|
175
|
-
# which can't distinguish opposite quadrants).
|
|
176
|
-
fun atan2(y: Float, x: Float) -> Float =
|
|
177
|
-
if x > 0.0f
|
|
178
|
-
return atan(y / x)
|
|
179
|
-
if x < 0.0f && y >= 0.0f
|
|
180
|
-
return atan(y / x) + Float.Pi
|
|
181
|
-
if x < 0.0f && y < 0.0f
|
|
182
|
-
return atan(y / x) - Float.Pi
|
|
183
|
-
if x == 0.0f && y > 0.0f
|
|
184
|
-
return Float.HalfPi
|
|
185
|
-
if x == 0.0f && y < 0.0f
|
|
186
|
-
return -Float.HalfPi
|
|
187
|
-
return 0.0f
|
|
188
|
-
|
|
189
|
-
fun hypot(a: Float, b: Float) -> Float =
|
|
190
|
-
return sqrt(a * a + b * b)
|
|
191
|
-
|
|
192
|
-
# Cube root via Newton's method (fixed iteration count, unlike `sqrt`'s
|
|
193
|
-
# converge-to-a-fixed-point loop, since the cubic update step doesn't reach an
|
|
194
|
-
# exact fixed point in float precision as reliably as the quadratic one does).
|
|
195
|
-
fun cbrt(x: Float) -> Float =
|
|
196
|
-
if x == 0.0f || x != x
|
|
197
|
-
return x
|
|
198
|
-
neg := x < 0.0f
|
|
199
|
-
v := if neg then -x else x
|
|
200
|
-
guess := v
|
|
201
|
-
i := 0
|
|
202
|
-
while i < 60
|
|
203
|
-
guess = {2.0f * guess + v / {guess * guess}} / 3.0f
|
|
204
|
-
i = i + 1
|
|
205
|
-
return if neg then -guess else guess
|
std/Mem.plum
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
|
|
6
|
-
# The program's linear memory: one growable wasm memory (16 pages of 64 KiB to
|
|
7
|
-
# start), exported to the host as "memory". Present only in programs that use
|
|
8
|
-
# `Mem`. Addresses are byte offsets; every access is little-endian and traps
|
|
9
|
-
# when out of bounds. Integers are stored as 32 bits (`storeI32` truncates,
|
|
10
|
-
# `loadI32` sign-extends) and floats as f32.
|
|
11
|
-
primitive Mem =
|
|
12
|
-
# Current memory size in bytes.
|
|
13
|
-
fun size() -> Int =
|
|
14
|
-
todo
|
|
15
|
-
|
|
16
|
-
# Adds `pages` 64 KiB pages; returns the old page count, or -1 on failure.
|
|
17
|
-
fun grow(pages: Int) -> Int =
|
|
18
|
-
todo
|
|
19
|
-
|
|
20
|
-
fun storeF32(addr: Int, v: Float) =
|
|
21
|
-
todo
|
|
22
|
-
|
|
23
|
-
fun storeI32(addr: Int, v: Int) =
|
|
24
|
-
todo
|
|
25
|
-
|
|
26
|
-
# Stores the low 8 bits of `v`.
|
|
27
|
-
fun storeU8(addr: Int, v: Int) =
|
|
28
|
-
todo
|
|
29
|
-
|
|
30
|
-
fun loadF32(addr: Int) -> Float =
|
|
31
|
-
todo
|
|
32
|
-
|
|
33
|
-
fun loadI32(addr: Int) -> Int =
|
|
34
|
-
todo
|
|
35
|
-
|
|
36
|
-
# The byte at `addr`, 0..255.
|
|
37
|
-
fun loadU8(addr: Int) -> Int =
|
|
38
|
-
todo
|
|
39
|
-
|
|
40
|
-
test "Mem round trips"
|
|
41
|
-
Mem.storeI32(16, -5)
|
|
42
|
-
assert Mem.loadI32(16) == -5
|
|
43
|
-
Mem.storeF32(32, 1.5f)
|
|
44
|
-
assert Mem.loadF32(32) == 1.5f
|
|
45
|
-
Mem.storeU8(40, 300)
|
|
46
|
-
assert Mem.loadU8(40) == 44
|
|
47
|
-
assert Mem.size() == 1048576
|
|
48
|
-
assert Mem.grow(1) == 16
|
|
49
|
-
assert Mem.size() == 1114112
|
std/Os.plum
DELETED
|
@@ -1,322 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Slice
|
|
4
|
-
import std/Str
|
|
5
|
-
import std/Uuid
|
|
6
|
-
import std/Random
|
|
7
|
-
import std/Int
|
|
8
|
-
import std/Float
|
|
9
|
-
import std/Io
|
|
10
|
-
import std/Option
|
|
11
|
-
import std/Result
|
|
12
|
-
|
|
13
|
-
# What the file functions that may hit either problem can fail with.
|
|
14
|
-
enum IoError =
|
|
15
|
-
| IoFailed
|
|
16
|
-
| NoSuchPath
|
|
17
|
-
|
|
18
|
-
fun name(self) -> Str = match self
|
|
19
|
-
IoFailed => "IoFailed"
|
|
20
|
-
NoSuchPath => "NoSuchPath"
|
|
21
|
-
|
|
22
|
-
# Writes the specified data, followed by the current line terminator, to the
|
|
23
|
-
# standard output stream. `extern` means this compiles to a genuine wasm import
|
|
24
|
-
# (`plum::printLn`) instead of a Plum body — printing isn't expressible in wasm
|
|
25
|
-
# on its own; the embedding host (`plum-cli run`/`plum build`) provides it.
|
|
26
|
-
|
|
27
|
-
# Raw host-provided filesystem primitives — each maps to a genuine wasm
|
|
28
|
-
# import backed by a real OS call in the embedder (`plum-cli`/`plum-runtime`),
|
|
29
|
-
# not something expressible in wasm on its own (same idea as `printLn`).
|
|
30
|
-
# Returns `Int` (0/1), not `Bool`, for the success/failure ones — the host
|
|
31
|
-
# closure that satisfies a wasm import runs BEFORE the module is instantiated
|
|
32
|
-
# (it's part of setting up the imports an instance needs), so it has no way
|
|
33
|
-
# to reach the instance's own globals; a plain `i64` has no such
|
|
34
|
-
# problem. `rawReadFile` returns `""` for a file that doesn't exist or can't
|
|
35
|
-
# be read (there's no way to signal an error through a bare `Str` return);
|
|
36
|
-
# callers needing to tell "empty file" apart from "missing file" should check
|
|
37
|
-
# `exists` first, which every wrapper below does.
|
|
38
|
-
# Every directory entry's name (not full path), joined with `\n`; `""` for a
|
|
39
|
-
# missing/unreadable directory (same ambiguity `rawReadFile` already has with
|
|
40
|
-
# an empty file — `exists`/`readdir` below both check existence first).
|
|
41
|
-
|
|
42
|
-
primitive Os =
|
|
43
|
-
# NOTE: the original file modeled `stdin`/`stdout`/`stderr` as bare top-level
|
|
44
|
-
# variable bindings and a `File(...)` constructor, but this language has no
|
|
45
|
-
# top-level `let` and `File` is never defined anywhere in the stdlib. Reduced
|
|
46
|
-
# to the underlying path so this at least parses; a real `File` type is
|
|
47
|
-
# still needed here.
|
|
48
|
-
fun stdin() -> Str =
|
|
49
|
-
"/dev/stdin"
|
|
50
|
-
|
|
51
|
-
fun stdout() -> Str =
|
|
52
|
-
"/dev/stdout"
|
|
53
|
-
|
|
54
|
-
fun stderr() -> Str =
|
|
55
|
-
"/dev/stderr"
|
|
56
|
-
|
|
57
|
-
# Reads the whole file at `path` as a `Str` (`Str` is a byte array here — see
|
|
58
|
-
# `libs/std/str.plum` — so this works for binary content too, not just text).
|
|
59
|
-
fun readFile(io: Io, path: Str) -> Result[Str, IoError] =
|
|
60
|
-
if !exists(io, path)
|
|
61
|
-
return Err(NoSuchPath)
|
|
62
|
-
return Ok(io.rawReadFile(path))
|
|
63
|
-
|
|
64
|
-
# Writes `data` to `path`, replacing its previous contents (or creating it).
|
|
65
|
-
fun writeFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
|
|
66
|
-
if io.rawWriteFile(path, data) != 1
|
|
67
|
-
return Err(IoFailed)
|
|
68
|
-
Ok(Unit)
|
|
69
|
-
|
|
70
|
-
fun exists(io: Io, path: Str) -> Bool =
|
|
71
|
-
return io.rawExists(path) == 1
|
|
72
|
-
|
|
73
|
-
fun mkdir(io: Io, path: Str) -> Result[Unit, IoError] =
|
|
74
|
-
if io.rawMkdir(path) != 1
|
|
75
|
-
return Err(IoFailed)
|
|
76
|
-
Ok(Unit)
|
|
77
|
-
|
|
78
|
-
# Removes the file (not directory) at `path`.
|
|
79
|
-
fun remove(io: Io, path: Str) -> Result[Unit, IoError] =
|
|
80
|
-
if !exists(io, path)
|
|
81
|
-
return Err(NoSuchPath)
|
|
82
|
-
if io.rawRemove(path) != 1
|
|
83
|
-
return Err(IoFailed)
|
|
84
|
-
Ok(Unit)
|
|
85
|
-
|
|
86
|
-
# Whether `path` exists and is reachable — this VM has no notion of a
|
|
87
|
-
# process' effective uid/gid, so (unlike POSIX `access(2)`) there is no mode
|
|
88
|
-
# argument to check permission bits against.
|
|
89
|
-
fun access(io: Io, path: Str) -> Bool =
|
|
90
|
-
return exists(io, path)
|
|
91
|
-
|
|
92
|
-
# Appends `data` to the file at `path`, creating it (with just `data` as its
|
|
93
|
-
# contents) if it doesn't already exist. There's no host-level "open for
|
|
94
|
-
# append" primitive, so this reads the existing bytes and writes the
|
|
95
|
-
# concatenation back — not atomic, and O(existing file size) per call.
|
|
96
|
-
fun appendFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
|
|
97
|
-
if exists(io, path)
|
|
98
|
-
existing := readFile(io, path)?
|
|
99
|
-
return writeFile(io, path, existing + data)
|
|
100
|
-
writeFile(io, path, data)
|
|
101
|
-
|
|
102
|
-
# Unix permission bits only (e.g. `0o644`) — this VM has no Windows ACL
|
|
103
|
-
# equivalent to fall back to.
|
|
104
|
-
fun chmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
|
|
105
|
-
if io.rawChmod(path, mode) != 1
|
|
106
|
-
return Err(IoFailed)
|
|
107
|
-
Ok(Unit)
|
|
108
|
-
|
|
109
|
-
# There is no host primitive for changing file ownership (it needs a uid/gid
|
|
110
|
-
# syscall this VM doesn't expose), unlike the permission-bits-only `chmod`.
|
|
111
|
-
fun chown(path: Str, uid: Int, gid: Int) =
|
|
112
|
-
todo
|
|
113
|
-
|
|
114
|
-
fun copyFile(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
|
|
115
|
-
data := readFile(io, src)?
|
|
116
|
-
writeFile(io, dest, data)
|
|
117
|
-
|
|
118
|
-
fun cp(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
|
|
119
|
-
copyFile(io, src, dest)
|
|
120
|
-
|
|
121
|
-
# Symlinks aren't modeled separately from regular files/dirs by this VM's
|
|
122
|
-
# host primitives (`rawChmod` always follows them), so this is the same as
|
|
123
|
-
# `chmod`.
|
|
124
|
-
fun lchmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
|
|
125
|
-
chmod(io, path, mode)
|
|
126
|
-
|
|
127
|
-
# See `chown` — no uid/gid syscall exposed by this VM.
|
|
128
|
-
fun lchown(path: Str, uid: Int, gid: Int) =
|
|
129
|
-
todo
|
|
130
|
-
|
|
131
|
-
# Setting a file's atime/mtime needs a syscall (`utimensat`/`SetFileTime`)
|
|
132
|
-
# this VM doesn't expose (`std::fs` itself has no equivalent either).
|
|
133
|
-
fun lutimes(path: Str, atime: Int, mtime: Int) =
|
|
134
|
-
todo
|
|
135
|
-
|
|
136
|
-
fun link(io: Io, existing_path: Str, new_path: Str) -> Result[Unit, IoError] =
|
|
137
|
-
if io.rawLink(existing_path, new_path) != 1
|
|
138
|
-
return Err(IoFailed)
|
|
139
|
-
Ok(Unit)
|
|
140
|
-
|
|
141
|
-
# Would need a real `Stat` struct type (size/mode/mtime/uid/gid/...) to
|
|
142
|
-
# return anything useful — no such type exists in the stdlib yet.
|
|
143
|
-
fun lstat(path: Str) =
|
|
144
|
-
todo
|
|
145
|
-
|
|
146
|
-
# Creates a fresh directory named `prefix` followed by a random suffix,
|
|
147
|
-
# retrying on the (astronomically unlikely) chance of a collision, and
|
|
148
|
-
# returns the path actually created.
|
|
149
|
-
fun mkdtemp(io: Io, prefix: Str) -> Result[Str, IoError] =
|
|
150
|
-
path := prefix + Uuid.v4(Random.seeded(io.randomSeed())).value.toStr()
|
|
151
|
-
if exists(io, path)
|
|
152
|
-
return mkdtemp(io, prefix)
|
|
153
|
-
mkdir(io, path)?
|
|
154
|
-
return Ok(path)
|
|
155
|
-
|
|
156
|
-
# Would need a host-side open-file-descriptor table (this VM's other file
|
|
157
|
-
# ops are all one-shot: open+read/write+close in a single host call) plus a
|
|
158
|
-
# `File` handle type — neither exists yet.
|
|
159
|
-
fun open(path: Str, flags: Int) =
|
|
160
|
-
todo
|
|
161
|
-
|
|
162
|
-
# See `open` — same missing handle-table/type problem, for directories.
|
|
163
|
-
fun opendir(path: Str) =
|
|
164
|
-
todo
|
|
165
|
-
|
|
166
|
-
# The names of `path`'s directory entries (not full paths).
|
|
167
|
-
fun readdir(io: Io, path: Str) -> Result[Slice[Str], IoError] =
|
|
168
|
-
if !exists(io, path)
|
|
169
|
-
return Err(NoSuchPath)
|
|
170
|
-
# skipping empty names handles both a genuinely empty directory (whose
|
|
171
|
-
# joined `""` would otherwise split into one bogus `""` entry) and
|
|
172
|
-
# `rawReadDir`'s "unreadable" fallback (already ruled out by the `exists`
|
|
173
|
-
# check above) the same way — no directory entry is ever named `""`.
|
|
174
|
-
names := Slice[Str]()
|
|
175
|
-
for n := range io.rawReadDir(path).split("\n", 0)
|
|
176
|
-
if n != ""
|
|
177
|
-
names.push(n)
|
|
178
|
-
return Ok(names)
|
|
179
|
-
|
|
180
|
-
fun readlink(io: Io, path: Str) -> Result[Str, IoError] =
|
|
181
|
-
if !exists(io, path)
|
|
182
|
-
return Err(NoSuchPath)
|
|
183
|
-
return Ok(io.rawReadlink(path))
|
|
184
|
-
|
|
185
|
-
fun realpath(io: Io, path: Str) -> Result[Str, IoError] =
|
|
186
|
-
if !exists(io, path)
|
|
187
|
-
return Err(NoSuchPath)
|
|
188
|
-
return Ok(io.rawRealpath(path))
|
|
189
|
-
|
|
190
|
-
fun rename(io: Io, old_path: Str, new_path: Str) -> Result[Unit, IoError] =
|
|
191
|
-
if !exists(io, old_path)
|
|
192
|
-
return Err(NoSuchPath)
|
|
193
|
-
if io.rawRename(old_path, new_path) != 1
|
|
194
|
-
return Err(IoFailed)
|
|
195
|
-
Ok(Unit)
|
|
196
|
-
|
|
197
|
-
# Removes an empty directory. (`remove` above covers plain files.)
|
|
198
|
-
fun rmdir(io: Io, path: Str) -> Result[Unit, IoError] =
|
|
199
|
-
if !exists(io, path)
|
|
200
|
-
return Err(NoSuchPath)
|
|
201
|
-
if io.rawRemoveDir(path) != 1
|
|
202
|
-
return Err(IoFailed)
|
|
203
|
-
Ok(Unit)
|
|
204
|
-
|
|
205
|
-
# See `lstat` — needs a `Stat` struct type.
|
|
206
|
-
fun stat(path: Str) =
|
|
207
|
-
todo
|
|
208
|
-
|
|
209
|
-
# Needs a filesystem-info struct type, same gap as `stat`.
|
|
210
|
-
fun statfs(path: Str) =
|
|
211
|
-
todo
|
|
212
|
-
|
|
213
|
-
fun symlink(io: Io, target: Str, path: Str) -> Result[Unit, IoError] =
|
|
214
|
-
if io.rawSymlink(target, path) != 1
|
|
215
|
-
return Err(IoFailed)
|
|
216
|
-
Ok(Unit)
|
|
217
|
-
|
|
218
|
-
# Resizes the file at `path` to exactly `len` bytes — truncated if shorter,
|
|
219
|
-
# zero-padded if longer.
|
|
220
|
-
fun truncate(io: Io, path: Str, len: Int) -> Result[Unit, IoError] =
|
|
221
|
-
if !exists(io, path)
|
|
222
|
-
return Err(NoSuchPath)
|
|
223
|
-
if io.rawTruncate(path, len) != 1
|
|
224
|
-
return Err(IoFailed)
|
|
225
|
-
Ok(Unit)
|
|
226
|
-
|
|
227
|
-
# See `lutimes` — same missing syscall.
|
|
228
|
-
fun utimes(path: Str, atime: Int, mtime: Int) =
|
|
229
|
-
todo
|
|
230
|
-
|
|
231
|
-
# Would need an async/callback mechanism to deliver filesystem change events
|
|
232
|
-
# into a running Plum program — nothing like that exists in this VM (every
|
|
233
|
-
# host call here is a synchronous, one-shot request/response).
|
|
234
|
-
fun watch(filename: Str) =
|
|
235
|
-
todo
|
|
236
|
-
|
|
237
|
-
test "writeFile/readFile/appendFile/remove round-trip on a real file"
|
|
238
|
-
dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
|
|
239
|
-
path := dir + "/a.txt"
|
|
240
|
-
Os.writeFile(io, path, "hello")!
|
|
241
|
-
assert Os.readFile(io, path)! == "hello"
|
|
242
|
-
Os.appendFile(io, path, " world")!
|
|
243
|
-
assert Os.readFile(io, path)! == "hello world"
|
|
244
|
-
assert Os.exists(io, path) == true
|
|
245
|
-
Os.remove(io, path)!
|
|
246
|
-
assert Os.exists(io, path) == false
|
|
247
|
-
Os.rmdir(io, dir)!
|
|
248
|
-
|
|
249
|
-
test "copyFile/cp/rename move and duplicate file contents correctly"
|
|
250
|
-
dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
|
|
251
|
-
a := dir + "/a.txt"
|
|
252
|
-
b := dir + "/b.txt"
|
|
253
|
-
c := dir + "/c.txt"
|
|
254
|
-
Os.writeFile(io, a, "data")!
|
|
255
|
-
Os.copyFile(io, a, b)!
|
|
256
|
-
assert Os.readFile(io, b)! == "data"
|
|
257
|
-
Os.rename(io, b, c)!
|
|
258
|
-
assert Os.exists(io, b) == false
|
|
259
|
-
assert Os.readFile(io, c)! == "data"
|
|
260
|
-
Os.remove(io, a)!
|
|
261
|
-
Os.remove(io, c)!
|
|
262
|
-
Os.rmdir(io, dir)!
|
|
263
|
-
|
|
264
|
-
test "readdir lists the entries created in a fresh directory"
|
|
265
|
-
dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
|
|
266
|
-
assert Os.readdir(io, dir)!.length() == 0
|
|
267
|
-
Os.writeFile(io, dir + "/only.txt", "x")!
|
|
268
|
-
names := Os.readdir(io, dir)!
|
|
269
|
-
assert names.length() == 1
|
|
270
|
-
assert names.join(",") == "only.txt"
|
|
271
|
-
Os.remove(io, dir + "/only.txt")!
|
|
272
|
-
Os.rmdir(io, dir)!
|
|
273
|
-
|
|
274
|
-
test "symlink/readlink/realpath resolve a linked file correctly"
|
|
275
|
-
dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
|
|
276
|
-
target := dir + "/target.txt"
|
|
277
|
-
link_path := dir + "/link.txt"
|
|
278
|
-
Os.writeFile(io, target, "linked")!
|
|
279
|
-
Os.symlink(io, target, link_path)!
|
|
280
|
-
assert Os.readlink(io, link_path)! == target
|
|
281
|
-
assert Os.readFile(io, link_path)! == "linked"
|
|
282
|
-
_ := Os.realpath(io, link_path)!
|
|
283
|
-
Os.remove(io, link_path)!
|
|
284
|
-
Os.remove(io, target)!
|
|
285
|
-
Os.rmdir(io, dir)!
|
|
286
|
-
|
|
287
|
-
test "truncate resizes a file's contents"
|
|
288
|
-
dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
|
|
289
|
-
path := dir + "/a.txt"
|
|
290
|
-
Os.writeFile(io, path, "hello world")!
|
|
291
|
-
Os.truncate(io, path, 5)!
|
|
292
|
-
assert Os.readFile(io, path)! == "hello"
|
|
293
|
-
Os.remove(io, path)!
|
|
294
|
-
Os.rmdir(io, dir)!
|
|
295
|
-
|
|
296
|
-
test "chmod changes a file's permission bits"
|
|
297
|
-
dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
|
|
298
|
-
path := dir + "/a.txt"
|
|
299
|
-
Os.writeFile(io, path, "x")!
|
|
300
|
-
Os.chmod(io, path, 384)! # 0o600
|
|
301
|
-
Os.remove(io, path)!
|
|
302
|
-
Os.rmdir(io, dir)!
|
|
303
|
-
|
|
304
|
-
test "link creates a second name for the same file"
|
|
305
|
-
dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
|
|
306
|
-
a := dir + "/a.txt"
|
|
307
|
-
b := dir + "/b.txt"
|
|
308
|
-
Os.writeFile(io, a, "shared")!
|
|
309
|
-
Os.link(io, a, b)!
|
|
310
|
-
assert Os.readFile(io, b)! == "shared"
|
|
311
|
-
Os.remove(io, a)!
|
|
312
|
-
Os.remove(io, b)!
|
|
313
|
-
Os.rmdir(io, dir)!
|
|
314
|
-
|
|
315
|
-
test "readFile/remove/rmdir report errors for missing paths"
|
|
316
|
-
assert Os.readFile(io, "/tmp/plum_os_test_does_not_exist.txt").unwrapOr("gone") == "gone"
|
|
317
|
-
failed := 0
|
|
318
|
-
if Err(e) := Os.remove(io, "/tmp/plum_os_test_does_not_exist.txt")
|
|
319
|
-
failed = failed + 1
|
|
320
|
-
if Err(e) := Os.rmdir(io, "/tmp/plum_os_test_does_not_exist_dir")
|
|
321
|
-
failed = failed + 1
|
|
322
|
-
assert failed == 2
|
std/base64.plum
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Str
|
|
4
|
+
import std/Buffer
|
|
5
|
+
import std/Int
|
|
6
|
+
import std/Float
|
|
7
|
+
import std/Option
|
|
8
|
+
import std/Result
|
|
9
|
+
|
|
10
|
+
# The Base64 package contains support for doing Base64 binary-to-text encodings.
|
|
11
|
+
#
|
|
12
|
+
# Implemented on top of `Buffer` and `Str.byteAt`.
|
|
13
|
+
#
|
|
14
|
+
# `data`/the decoded payload are represented as `Str` throughout (matching
|
|
15
|
+
# the original public shape) rather than a byte array — `Str` is itself just a
|
|
16
|
+
# byte array here (see `libs/std/str.plum`), so this is a plain byte string,
|
|
17
|
+
# not a claim that the content is valid UTF-8 text.
|
|
18
|
+
|
|
19
|
+
# Why `decode` failed.
|
|
20
|
+
enum Base64Error = InvalidBase64
|
|
21
|
+
|
|
22
|
+
# Encode for PEM (RFC 1421): 64-character lines.
|
|
23
|
+
fun encodePEM(data: Str) -> Str =
|
|
24
|
+
return encode(data, "+", "/", "=", 64, "\r\n")
|
|
25
|
+
|
|
26
|
+
# Encode for MIME (RFC 2045): 76-character lines.
|
|
27
|
+
fun encodeMIME(data: Str) -> Str =
|
|
28
|
+
return encode(data, "+", "/", "=", 76, "\r\n")
|
|
29
|
+
|
|
30
|
+
# Encode for URLs (RFC 4648). Padding characters are stripped by default.
|
|
31
|
+
fun encodeURL(data: Str, pad: Bool = false) -> Str =
|
|
32
|
+
return encode(data, "-", "_", if pad then "=" else "", 0, "")
|
|
33
|
+
|
|
34
|
+
# Configurable encoding. The defaults are for RFC 4648. `pad` is the padding
|
|
35
|
+
# character, or `""` to omit padding entirely; `linelen` is the output line
|
|
36
|
+
# length to wrap at (`0` disables wrapping), separated by `linesep`.
|
|
37
|
+
fun encode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=", linelen: Int = 0, linesep: Str = "\r\n") -> Str =
|
|
38
|
+
at62b := at62.byteAt(0)
|
|
39
|
+
at63b := at63.byteAt(0)
|
|
40
|
+
has_pad := pad.length() > 0
|
|
41
|
+
padb := if has_pad then pad.byteAt(0) else 0
|
|
42
|
+
res := Buffer()
|
|
43
|
+
n := data.length()
|
|
44
|
+
i := 0
|
|
45
|
+
line_chars := 0
|
|
46
|
+
while i < n
|
|
47
|
+
b0 := data.byteAt(i)
|
|
48
|
+
has1 := i + 1 < n
|
|
49
|
+
has2 := i + 2 < n
|
|
50
|
+
b1 := if has1 then data.byteAt(i + 1) else 0
|
|
51
|
+
b2 := if has2 then data.byteAt(i + 2) else 0
|
|
52
|
+
res.writeByte(Byte(encodeByte(b0 >> 2, at62b, at63b)))
|
|
53
|
+
res.writeByte(Byte(encodeByte({b0 & 0x03} << 4 | b1 >> 4, at62b, at63b)))
|
|
54
|
+
line_chars = line_chars + 2
|
|
55
|
+
if has1
|
|
56
|
+
res.writeByte(Byte(encodeByte({b1 & 0x0F} << 2 | b2 >> 6, at62b, at63b)))
|
|
57
|
+
line_chars = line_chars + 1
|
|
58
|
+
else if has_pad
|
|
59
|
+
res.writeByte(Byte(padb))
|
|
60
|
+
line_chars = line_chars + 1
|
|
61
|
+
if has2
|
|
62
|
+
res.writeByte(Byte(encodeByte(b2 & 0x3F, at62b, at63b)))
|
|
63
|
+
line_chars = line_chars + 1
|
|
64
|
+
else if has_pad
|
|
65
|
+
res.writeByte(Byte(padb))
|
|
66
|
+
line_chars = line_chars + 1
|
|
67
|
+
i = i + 3
|
|
68
|
+
if linelen > 0 && line_chars >= linelen && i < n
|
|
69
|
+
res.write(linesep)
|
|
70
|
+
line_chars = 0
|
|
71
|
+
return res.toStr()
|
|
72
|
+
|
|
73
|
+
# Encodes a single 6-bit value (0-63) as its base64 alphabet character.
|
|
74
|
+
fun encodeByte(i: Int, at62: Int, at63: Int) -> Int =
|
|
75
|
+
if i < 26
|
|
76
|
+
return 65 + i # 'A'..'Z'
|
|
77
|
+
if i < 52
|
|
78
|
+
return 97 + {i - 26} # 'a'..'z'
|
|
79
|
+
if i < 62
|
|
80
|
+
return 48 + {i - 52} # '0'..'9'
|
|
81
|
+
if i == 62
|
|
82
|
+
return at62
|
|
83
|
+
return at63
|
|
84
|
+
|
|
85
|
+
# The inverse of `encodeByte`: a base64 alphabet character's 6-bit value, or
|
|
86
|
+
# -1 if `b` isn't one of the 64 alphabet characters (whitespace/padding are
|
|
87
|
+
# handled by the caller, not here).
|
|
88
|
+
fun decodeByte(b: Int, at62: Int, at63: Int) -> Int =
|
|
89
|
+
if b >= 65 && b <= 90
|
|
90
|
+
return b - 65
|
|
91
|
+
if b >= 97 && b <= 122
|
|
92
|
+
return b - 97 + 26
|
|
93
|
+
if b >= 48 && b <= 57
|
|
94
|
+
return b - 48 + 52
|
|
95
|
+
if b == at62
|
|
96
|
+
return 62
|
|
97
|
+
if b == at63
|
|
98
|
+
return 63
|
|
99
|
+
return -1
|
|
100
|
+
|
|
101
|
+
fun isBase64Whitespace(b: Int) -> Bool =
|
|
102
|
+
b == 32 || b == 9 || b == 10 || b == 13
|
|
103
|
+
|
|
104
|
+
# Decode for URLs (RFC 4648).
|
|
105
|
+
fun decodeUrl(data: Str) -> Result[Str, Base64Error] =
|
|
106
|
+
return decode(data, "-", "_", "=")
|
|
107
|
+
|
|
108
|
+
# Configurable decoding. The defaults are for RFC 4648. Missing padding is
|
|
109
|
+
# not an error. Non-base64 data, other than whitespace (which can appear at
|
|
110
|
+
# any point), fails with `Err(InvalidBase64)`.
|
|
111
|
+
fun decode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=") -> Result[Str, Base64Error] =
|
|
112
|
+
at62b := at62.byteAt(0)
|
|
113
|
+
at63b := at63.byteAt(0)
|
|
114
|
+
has_pad := pad.length() > 0
|
|
115
|
+
padb := if has_pad then pad.byteAt(0) else -1
|
|
116
|
+
res := Buffer()
|
|
117
|
+
n := data.length()
|
|
118
|
+
i := 0
|
|
119
|
+
bits := 0
|
|
120
|
+
nbits := 0
|
|
121
|
+
while i < n
|
|
122
|
+
b := data.byteAt(i)
|
|
123
|
+
i = i + 1
|
|
124
|
+
if isBase64Whitespace(b) || b == padb
|
|
125
|
+
continue
|
|
126
|
+
v := decodeByte(b, at62b, at63b)
|
|
127
|
+
if v < 0
|
|
128
|
+
return Err(InvalidBase64)
|
|
129
|
+
bits = {bits << 6} | v
|
|
130
|
+
nbits = nbits + 6
|
|
131
|
+
if nbits >= 8
|
|
132
|
+
nbits = nbits - 8
|
|
133
|
+
res.writeByte(Byte({bits >> nbits} & 0xFF))
|
|
134
|
+
return Ok(res.toStr())
|
|
135
|
+
|
|
136
|
+
test "statics are reached through the Base64 namespace and round-trip"
|
|
137
|
+
assert decode(encodePEM("hello"))! == "hello"
|
|
138
|
+
assert decode(encodeMIME("hi there"))! == "hi there"
|
std/game/Affine.plum
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
module std
|
|
2
2
|
|
|
3
3
|
import std/Float
|
|
4
|
-
import std/
|
|
4
|
+
import std/math
|
|
5
5
|
import std/game/Vec2
|
|
6
6
|
import std/Option
|
|
7
7
|
|
|
@@ -52,13 +52,13 @@ struct Affine(a: Float, b: Float, c: Float, d: Float, e: Float, f: Float) =
|
|
|
52
52
|
f: 0.0 - {ib * self.e + id * self.f}))
|
|
53
53
|
|
|
54
54
|
fun scaleX(self) -> Float =
|
|
55
|
-
|
|
55
|
+
math.hypot(self.a, self.b)
|
|
56
56
|
|
|
57
57
|
fun scaleY(self) -> Float =
|
|
58
|
-
|
|
58
|
+
math.hypot(self.c, self.d)
|
|
59
59
|
|
|
60
60
|
fun rotation(self) -> Float =
|
|
61
|
-
|
|
61
|
+
math.atan2(self.b, self.a)
|
|
62
62
|
|
|
63
63
|
test "invert_singular_is_none"
|
|
64
64
|
s := Affine(a: 0.0, b: 0.0, c: 0.0, d: 0.0, e: 1.0, f: 1.0)
|
std/game/Game.plum
DELETED
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
import std/Str
|
|
6
|
-
import std/game/Vec2
|
|
7
|
-
import std/game/Color
|
|
8
|
-
import std/Io
|
|
9
|
-
|
|
10
|
-
# The host API of a game: drawing, textures, sounds, files and input, all provided by
|
|
11
|
-
# the game host (`plum run`) as methods of `Io` (see std/Io). A game is any type that
|
|
12
|
-
# `main(io: Io)` returns and that has `update(self, io: Io, dt: Float) -> Self` and
|
|
13
|
-
# `draw(self, io: Io)`; the host calls `update` then `draw` every frame, and the state
|
|
14
|
-
# `update` returns is the next frame's `self`. This file holds the key codes and the
|
|
15
|
-
# `Texture` and `Sound` handles. A path that escapes the asset root fails like a
|
|
16
|
-
# missing file. Coordinates are world units once `io.setCamera` is set.
|
|
17
|
-
|
|
18
|
-
# Key codes (GLFW numbering) for `isKeyDown` / `isKeyPressed`.
|
|
19
|
-
# Letter keys are `KeyA`..`KeyZ` (a constant name needs two characters).
|
|
20
|
-
primitive Key =
|
|
21
|
-
Space = 32
|
|
22
|
-
KeyA = 65
|
|
23
|
-
KeyB = 66
|
|
24
|
-
KeyC = 67
|
|
25
|
-
KeyD = 68
|
|
26
|
-
KeyE = 69
|
|
27
|
-
KeyF = 70
|
|
28
|
-
KeyG = 71
|
|
29
|
-
KeyH = 72
|
|
30
|
-
KeyI = 73
|
|
31
|
-
KeyJ = 74
|
|
32
|
-
KeyK = 75
|
|
33
|
-
KeyL = 76
|
|
34
|
-
KeyM = 77
|
|
35
|
-
KeyN = 78
|
|
36
|
-
KeyO = 79
|
|
37
|
-
KeyP = 80
|
|
38
|
-
KeyQ = 81
|
|
39
|
-
KeyR = 82
|
|
40
|
-
KeyS = 83
|
|
41
|
-
KeyT = 84
|
|
42
|
-
KeyU = 85
|
|
43
|
-
KeyV = 86
|
|
44
|
-
KeyW = 87
|
|
45
|
-
KeyX = 88
|
|
46
|
-
KeyY = 89
|
|
47
|
-
KeyZ = 90
|
|
48
|
-
Num0 = 48
|
|
49
|
-
Num1 = 49
|
|
50
|
-
Num2 = 50
|
|
51
|
-
Num3 = 51
|
|
52
|
-
Num4 = 52
|
|
53
|
-
Num5 = 53
|
|
54
|
-
Num6 = 54
|
|
55
|
-
Num7 = 55
|
|
56
|
-
Num8 = 56
|
|
57
|
-
Num9 = 57
|
|
58
|
-
Escape = 256
|
|
59
|
-
Enter = 257
|
|
60
|
-
Tab = 258
|
|
61
|
-
Backspace = 259
|
|
62
|
-
Right = 262
|
|
63
|
-
Left = 263
|
|
64
|
-
Down = 264
|
|
65
|
-
Up = 265
|
|
66
|
-
LeftShift = 340
|
|
67
|
-
LeftControl = 341
|
|
68
|
-
|
|
69
|
-
# Blend modes for `blendMode`: alpha blending, additive (brightens), multiply
|
|
70
|
-
# (darkens, white leaves the target unchanged) and screen (lightens).
|
|
71
|
-
primitive Blend =
|
|
72
|
-
Normal = 0
|
|
73
|
-
Add = 1
|
|
74
|
-
Multiply = 2
|
|
75
|
-
Screen = 3
|
|
76
|
-
|
|
77
|
-
# Mouse button numbers for `isMouseDown` / `isMousePressed`.
|
|
78
|
-
primitive Mouse =
|
|
79
|
-
Left = 0
|
|
80
|
-
Right = 1
|
|
81
|
-
Middle = 2
|
|
82
|
-
|
|
83
|
-
# A texture handle; the id is the host's. A handle of -1 is no texture.
|
|
84
|
-
struct Texture(id: Int) =
|
|
85
|
-
# Loads an image relative to the asset root; crashes naming the file if it is missing.
|
|
86
|
-
fun load(io: Io, name: Str) -> Texture =
|
|
87
|
-
id := io.textureLoad(name)
|
|
88
|
-
if id < 0
|
|
89
|
-
crash missingAsset("texture", name)
|
|
90
|
-
Texture(id: id)
|
|
91
|
-
|
|
92
|
-
# A blank transparent texture to draw into with `renderTarget`; crashes if a side is
|
|
93
|
-
# below 1 or above 8192.
|
|
94
|
-
fun create(io: Io, w: Int, h: Int) -> Texture =
|
|
95
|
-
id := io.textureCreate(w, h)
|
|
96
|
-
if id < 0
|
|
97
|
-
crash "cannot create a {w}x{h} texture"
|
|
98
|
-
Texture(id: id)
|
|
99
|
-
|
|
100
|
-
fun width(self, io: Io) -> Int = io.textureWidth(self.id)
|
|
101
|
-
|
|
102
|
-
fun height(self, io: Io) -> Int = io.textureHeight(self.id)
|
|
103
|
-
|
|
104
|
-
# Linear (true) or nearest (false, the default) filtering.
|
|
105
|
-
fun setSmooth(self, io: Io, smooth: Bool) =
|
|
106
|
-
io.textureSetSmooth(self.id, smooth)
|
|
107
|
-
|
|
108
|
-
# The texture at its natural size, top-left at (x, y).
|
|
109
|
-
fun draw(self, io: Io, x: Float, y: Float, tint: Color = Color.White) =
|
|
110
|
-
io.drawTexture(self.id, x, y, tint)
|
|
111
|
-
|
|
112
|
-
# Sends the following draws into this texture; `Texture.screen` goes back to the screen.
|
|
113
|
-
# Each target has its own camera, which starts as its pixels.
|
|
114
|
-
fun renderTarget(self, io: Io) =
|
|
115
|
-
io.renderTarget(self.id)
|
|
116
|
-
|
|
117
|
-
fun screen(io: Io) =
|
|
118
|
-
io.renderTarget(-1)
|
|
119
|
-
|
|
120
|
-
# A sound handle; the id is the host's. Volume is 0..1.
|
|
121
|
-
struct Sound(id: Int) =
|
|
122
|
-
# Loads a sound relative to the asset root; crashes naming the file if it is missing.
|
|
123
|
-
fun load(io: Io, name: Str) -> Sound =
|
|
124
|
-
id := io.soundLoad(name)
|
|
125
|
-
if id < 0
|
|
126
|
-
crash missingAsset("sound", name)
|
|
127
|
-
Sound(id: id)
|
|
128
|
-
|
|
129
|
-
fun play(self, io: Io, volume: Float = 1.0) =
|
|
130
|
-
io.soundPlay(self.id, volume)
|
|
131
|
-
|
|
132
|
-
fun loop(self, io: Io, volume: Float = 1.0) =
|
|
133
|
-
io.soundLoop(self.id, volume)
|
|
134
|
-
|
|
135
|
-
fun stop(self, io: Io) =
|
|
136
|
-
io.soundStop(self.id)
|
|
137
|
-
|
|
138
|
-
fun setVolume(self, io: Io, volume: Float) =
|
|
139
|
-
io.soundSetVolume(self.id, volume)
|
|
140
|
-
|
|
141
|
-
fun missingAsset(kind: Str, name: Str) -> Str =
|
|
142
|
-
"missing {kind}: {name}"
|
|
143
|
-
|
|
144
|
-
# The whole file as text, relative to the asset root; crashes naming the file if it is missing.
|
|
145
|
-
fun loadFile(io: Io, name: Str) -> Str =
|
|
146
|
-
if !io.fileExists(name)
|
|
147
|
-
crash missingAsset("file", name)
|
|
148
|
-
io.fileLoad(name)
|
|
149
|
-
|
|
150
|
-
test "a missing asset message names the file"
|
|
151
|
-
assert missingAsset("texture", "ship.png") == "missing texture: ship.png"
|
|
152
|
-
|
|
153
|
-
test "key and mouse constants use GLFW numbering"
|
|
154
|
-
assert Key.KeyW == 87
|
|
155
|
-
assert Key.Left == 263
|
|
156
|
-
assert Key.Num0 == 48
|
|
157
|
-
assert Key.LeftControl == 341
|
|
158
|
-
assert Mouse.Right == 1
|
|
159
|
-
|
|
160
|
-
test "blend constants"
|
|
161
|
-
assert Blend.Normal == 0
|
|
162
|
-
assert Blend.Screen == 3
|
std/game/Ui.plum
DELETED
|
@@ -1,225 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
import std/Str
|
|
6
|
-
import std/Slice
|
|
7
|
-
import std/List
|
|
8
|
-
import std/Option
|
|
9
|
-
import std/game/Color
|
|
10
|
-
import std/game/Scene
|
|
11
|
-
import std/game/Input
|
|
12
|
-
|
|
13
|
-
# A pure UI layer for the functional scene style. `Ui.step` takes the previous
|
|
14
|
-
# UiState, one pointer input and the id under the pointer (from SceneNode.hitId on
|
|
15
|
-
# the current view) and returns the new state plus the UiEvents it raised.
|
|
16
|
-
# `Ui.messages` turns the Clicks among them into the game's own messages, read from
|
|
17
|
-
# the `Clickable` nodes of that view. Same
|
|
18
|
-
# button rules as the old pure scene: Down captures the pressed id; while captured only
|
|
19
|
-
# that id gets Enter/Exit; Up releases (Click only when still over it).
|
|
20
|
-
|
|
21
|
-
struct UiState(x: Float, y: Float, down: Bool, hot: Option[Int], captured: Option[Int])
|
|
22
|
-
|
|
23
|
-
struct UiStep(ui: UiState, events: List[UiEvent])
|
|
24
|
-
|
|
25
|
-
fun uiSame(a: Option[Int], b: Option[Int]) -> Bool =
|
|
26
|
-
if Some(va) := a
|
|
27
|
-
if Some(vb) := b
|
|
28
|
-
return va == vb
|
|
29
|
-
return false
|
|
30
|
-
if Some(vb) := b
|
|
31
|
-
return false
|
|
32
|
-
true
|
|
33
|
-
|
|
34
|
-
# Exit for the old hot id and Enter for the new one when they differ.
|
|
35
|
-
fun uiHover(out: Slice[UiEvent], old: Option[Int], now: Option[Int]) =
|
|
36
|
-
if !uiSame(old, now)
|
|
37
|
-
if Some(o) := old
|
|
38
|
-
out.push(UiEvent(id: o, kind: Exit))
|
|
39
|
-
if Some(n) := now
|
|
40
|
-
out.push(UiEvent(id: n, kind: Enter))
|
|
41
|
-
|
|
42
|
-
primitive Ui =
|
|
43
|
-
fun init() -> UiState =
|
|
44
|
-
UiState(x: 0.0, y: 0.0, down: false, hot: None, captured: None)
|
|
45
|
-
|
|
46
|
-
# A key changes nothing here (keys go to the game).
|
|
47
|
-
fun step(ui: UiState, input: InputEvent, hit: Option[Int]) -> UiStep =
|
|
48
|
-
maybePos := input.position()
|
|
49
|
-
if maybePos.isNone()
|
|
50
|
-
return UiStep(ui: ui, events: Nil)
|
|
51
|
-
pos := maybePos!
|
|
52
|
-
out := Slice[UiEvent]()
|
|
53
|
-
# a capture left over without a held button is stale
|
|
54
|
-
cap: Option[Int] := ui.captured
|
|
55
|
-
if !ui.down
|
|
56
|
-
cap = None
|
|
57
|
-
hot: Option[Int] := ui.hot
|
|
58
|
-
down := ui.down
|
|
59
|
-
match input
|
|
60
|
-
PointerDown(_, _) =>
|
|
61
|
-
cap = None
|
|
62
|
-
uiHover(out, hot, hit)
|
|
63
|
-
hot = hit
|
|
64
|
-
down = true
|
|
65
|
-
if Some(h) := hit
|
|
66
|
-
out.push(UiEvent(id: h, kind: Press))
|
|
67
|
-
cap = Some(h)
|
|
68
|
-
PointerMove(_, _) =>
|
|
69
|
-
if Some(c) := cap
|
|
70
|
-
now: Option[Int] := None
|
|
71
|
-
if uiSame(hit, cap)
|
|
72
|
-
now = cap
|
|
73
|
-
uiHover(out, hot, now)
|
|
74
|
-
hot = now
|
|
75
|
-
else
|
|
76
|
-
uiHover(out, hot, hit)
|
|
77
|
-
hot = hit
|
|
78
|
-
PointerUp(_, _) =>
|
|
79
|
-
if Some(c) := cap
|
|
80
|
-
out.push(UiEvent(id: c, kind: Release))
|
|
81
|
-
if uiSame(hit, cap)
|
|
82
|
-
out.push(UiEvent(id: c, kind: Click))
|
|
83
|
-
cap = None
|
|
84
|
-
hot = hit
|
|
85
|
-
else
|
|
86
|
-
uiHover(out, hot, hit)
|
|
87
|
-
hot = hit
|
|
88
|
-
down = false
|
|
89
|
-
_ => 0
|
|
90
|
-
UiStep(ui: UiState(x: pos.x, y: pos.y, down: down, hot: hot, captured: cap), events: List.fromSlice(out))
|
|
91
|
-
|
|
92
|
-
fun pressed(ui: UiState, id: Int) -> Bool =
|
|
93
|
-
if Some(c) := ui.captured
|
|
94
|
-
return c == id && uiSame(ui.hot, ui.captured)
|
|
95
|
-
false
|
|
96
|
-
|
|
97
|
-
fun hovered(ui: UiState, id: Int) -> Bool =
|
|
98
|
-
if Some(h) := ui.hot
|
|
99
|
-
return h == id
|
|
100
|
-
false
|
|
101
|
-
|
|
102
|
-
# A tagged, translated rectangle with a label whose colour follows the state.
|
|
103
|
-
# The messages of the Clickables that `events` clicked, in order, read from `view`.
|
|
104
|
-
fun messages[M](view: SceneNode[M], events: List[UiEvent]) -> List[M] = match events
|
|
105
|
-
Nil => Nil
|
|
106
|
-
Cons(e, rest) =>
|
|
107
|
-
later := Ui.messages(view, rest)
|
|
108
|
-
if e.kind != Click
|
|
109
|
-
return later
|
|
110
|
-
if Some(m) := view.msgOf(e.id)
|
|
111
|
-
return Cons(head: m, tail: later)
|
|
112
|
-
later
|
|
113
|
-
|
|
114
|
-
# A button that sends `msg` when clicked; `id` identifies it for hover and press.
|
|
115
|
-
fun button[M](id: Int, msg: M, label: Str, x: Float, y: Float, w: Float, h: Float, ui: UiState) -> SceneNode[M] =
|
|
116
|
-
color := uiIdleColor()
|
|
117
|
-
if Ui.pressed(ui, id)
|
|
118
|
-
color = uiPressedColor()
|
|
119
|
-
else if Ui.hovered(ui, id)
|
|
120
|
-
color = uiHoverColor()
|
|
121
|
-
Clickable(id: id, msg: msg, child: Group(transform: Translate(dx: x, dy: y), children: [
|
|
122
|
-
RectShape(x: 0.0, y: 0.0, w: w, h: h, color: color),
|
|
123
|
-
Text(text: label, x: 4.0, y: 4.0, size: h * 0.5, color: Color.White)]))
|
|
124
|
-
|
|
125
|
-
fun uiIdleColor() -> Color = Color.rgb(0.2, 0.2, 0.3)
|
|
126
|
-
|
|
127
|
-
fun uiHoverColor() -> Color = Color.rgb(0.35, 0.35, 0.5)
|
|
128
|
-
|
|
129
|
-
fun uiPressedColor() -> Color = Color.rgb(0.6, 0.2, 0.2)
|
|
130
|
-
|
|
131
|
-
fun uiKinds(s: UiStep) -> List[UiKind] = s.events.map(|e| e.kind)
|
|
132
|
-
|
|
133
|
-
fun uiDown(x: Float) -> InputEvent = PointerDown(x: x, y: 0.0)
|
|
134
|
-
|
|
135
|
-
fun uiUp(x: Float) -> InputEvent = PointerUp(x: x, y: 0.0)
|
|
136
|
-
|
|
137
|
-
fun uiMove(x: Float) -> InputEvent = PointerMove(x: x, y: 0.0)
|
|
138
|
-
|
|
139
|
-
fun uiCount(s: UiStep, k: UiKind) -> Int =
|
|
140
|
-
n := 0
|
|
141
|
-
for e := range s.events
|
|
142
|
-
if e.kind == k
|
|
143
|
-
n = n + 1
|
|
144
|
-
n
|
|
145
|
-
|
|
146
|
-
fun uiIs(e: UiEvent, id: Int, kind: UiKind) -> Bool = e.id == id && e.kind == kind
|
|
147
|
-
|
|
148
|
-
fun uiButtonColor(n: SceneNode[Int]) -> Color = match n
|
|
149
|
-
Clickable(_, _, child) => uiButtonColor(child)
|
|
150
|
-
Group(_, children) => uiButtonColor(children.at(0))
|
|
151
|
-
RectShape(_, _, _, _, c) => c
|
|
152
|
-
_ => Color.Black
|
|
153
|
-
|
|
154
|
-
test "press_sets_capture"
|
|
155
|
-
s1 := Ui.step(Ui.init(), uiDown(1.0), Some(5))
|
|
156
|
-
assert s1.events.length() == 2
|
|
157
|
-
assert uiIs(s1.events.at(0), 5, Enter)
|
|
158
|
-
assert uiIs(s1.events.at(1), 5, Press)
|
|
159
|
-
assert Ui.pressed(s1.ui, 5)
|
|
160
|
-
s2 := Ui.step(s1.ui, uiUp(1.0), Some(5))
|
|
161
|
-
assert s2.events.length() == 2
|
|
162
|
-
assert uiIs(s2.events.at(0), 5, Release)
|
|
163
|
-
assert uiIs(s2.events.at(1), 5, Click)
|
|
164
|
-
assert !Ui.pressed(s2.ui, 5)
|
|
165
|
-
assert Ui.hovered(s2.ui, 5)
|
|
166
|
-
|
|
167
|
-
test "release_elsewhere_no_click"
|
|
168
|
-
s1 := Ui.step(Ui.init(), uiDown(1.0), Some(5))
|
|
169
|
-
s2 := Ui.step(s1.ui, uiMove(99.0), None)
|
|
170
|
-
assert s2.events.length() == 1
|
|
171
|
-
assert uiIs(s2.events.at(0), 5, Exit)
|
|
172
|
-
s3 := Ui.step(s2.ui, uiUp(99.0), None)
|
|
173
|
-
assert s3.events.length() == 1
|
|
174
|
-
assert uiIs(s3.events.at(0), 5, Release)
|
|
175
|
-
assert uiCount(s3, Click) == 0
|
|
176
|
-
|
|
177
|
-
test "drag_off_and_back_one_click"
|
|
178
|
-
s1 := Ui.step(Ui.init(), uiDown(1.0), Some(5))
|
|
179
|
-
s2 := Ui.step(s1.ui, uiMove(99.0), None)
|
|
180
|
-
s3 := Ui.step(s2.ui, uiMove(1.0), Some(5))
|
|
181
|
-
assert s3.events.length() == 1
|
|
182
|
-
assert uiIs(s3.events.at(0), 5, Enter)
|
|
183
|
-
s4 := Ui.step(s3.ui, uiUp(1.0), Some(5))
|
|
184
|
-
assert uiCount(s4, Click) == 1
|
|
185
|
-
assert uiCount(s4, Release) == 1
|
|
186
|
-
|
|
187
|
-
test "stale_capture_dropped"
|
|
188
|
-
stale := UiState(x: 0.0, y: 0.0, down: false, hot: None, captured: Some(5))
|
|
189
|
-
s := Ui.step(stale, uiMove(50.0), None)
|
|
190
|
-
assert s.events.length() == 0
|
|
191
|
-
if Some(c) := s.ui.captured
|
|
192
|
-
assert false
|
|
193
|
-
assert !Ui.pressed(s.ui, 5)
|
|
194
|
-
|
|
195
|
-
test "hover_without_press_routes_move"
|
|
196
|
-
s1 := Ui.step(Ui.init(), uiMove(1.0), Some(5))
|
|
197
|
-
assert s1.events.length() == 1
|
|
198
|
-
assert uiIs(s1.events.at(0), 5, Enter)
|
|
199
|
-
assert Ui.hovered(s1.ui, 5)
|
|
200
|
-
s2 := Ui.step(s1.ui, uiMove(2.0), Some(5))
|
|
201
|
-
assert s2.events.length() == 0
|
|
202
|
-
s3 := Ui.step(s2.ui, uiMove(99.0), None)
|
|
203
|
-
assert s3.events.length() == 1
|
|
204
|
-
assert uiIs(s3.events.at(0), 5, Exit)
|
|
205
|
-
assert !Ui.hovered(s3.ui, 5)
|
|
206
|
-
|
|
207
|
-
test "button_visual_reflects_state"
|
|
208
|
-
idle := Ui.button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, Ui.init())
|
|
209
|
-
hov := Ui.button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, Ui.step(Ui.init(), uiMove(1.0), Some(3)).ui)
|
|
210
|
-
prs := Ui.button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, Ui.step(Ui.init(), uiDown(1.0), Some(3)).ui)
|
|
211
|
-
assert uiButtonColor(idle).eq(uiIdleColor())
|
|
212
|
-
assert uiButtonColor(hov).eq(uiHoverColor())
|
|
213
|
-
assert uiButtonColor(prs).eq(uiPressedColor())
|
|
214
|
-
if Some(hid) := idle.hitId(20.0, 30.0)
|
|
215
|
-
assert hid == 3
|
|
216
|
-
else
|
|
217
|
-
assert false
|
|
218
|
-
|
|
219
|
-
test "messages_are_the_clicked_buttons_messages"
|
|
220
|
-
view := Group(transform: Identity, children: [Ui.button(3, 30, "Go", 0.0, 0.0, 10.0, 10.0, Ui.init()), Ui.button(4, 40, "Stop", 20.0, 0.0, 10.0, 10.0, Ui.init())])
|
|
221
|
-
evs := [UiEvent(id: 4, kind: Press), UiEvent(id: 4, kind: Click), UiEvent(id: 9, kind: Click), UiEvent(id: 3, kind: Click)]
|
|
222
|
-
ms := Ui.messages(view, evs)
|
|
223
|
-
assert ms.length() == 2
|
|
224
|
-
assert ms.get(0).unwrapOr(-1) == 40
|
|
225
|
-
assert ms.get(1).unwrapOr(-1) == 30
|
std/game/Vec2.plum
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
module std
|
|
2
2
|
|
|
3
3
|
import std/Float
|
|
4
|
-
import std/
|
|
4
|
+
import std/math
|
|
5
5
|
|
|
6
6
|
# A 2D point or vector. Operators work through the methods below:
|
|
7
7
|
# `a + b` is `a.add(b)`, `a - b` is `a.sub(b)`, `a * s` is `a.mul(s)`,
|
|
@@ -26,7 +26,7 @@ struct Vec2(x: Float, y: Float) =
|
|
|
26
26
|
self.x == o.x && self.y == o.y
|
|
27
27
|
|
|
28
28
|
fun length(self) -> Float =
|
|
29
|
-
|
|
29
|
+
math.sqrt(self.x * self.x + self.y * self.y)
|
|
30
30
|
|
|
31
31
|
fun distance(self, o: Vec2) -> Float =
|
|
32
32
|
self.sub(o).length()
|
std/game/audio.plum
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Str
|
|
6
|
+
import std/Io
|
|
7
|
+
import std/game/gfx
|
|
8
|
+
|
|
9
|
+
# Sound: module functions that take the `Io` capability first, and the `Sound` handle.
|
|
10
|
+
# `audio.loadSound(io, "boop.wav")`. Volume is 0..1. A sound handle is -1 on failure. Paths
|
|
11
|
+
# are relative to the asset root. The host decodes every sound file in the asset root
|
|
12
|
+
# before `init` runs.
|
|
13
|
+
|
|
14
|
+
# Loads a WAV or OGG file relative to the asset root; -1 on failure.
|
|
15
|
+
extern fun soundLoad(io: Io, path: Str) -> Int
|
|
16
|
+
# A one-shot play; plays of the same sound may overlap. Volume is 0..1.
|
|
17
|
+
extern fun soundPlay(io: Io, s: Int, volume: Float)
|
|
18
|
+
# Starts the sound looping. Call `soundStop` first to restart it cleanly.
|
|
19
|
+
extern fun soundLoop(io: Io, s: Int, volume: Float)
|
|
20
|
+
# Stops every play and loop of the sound.
|
|
21
|
+
extern fun soundStop(io: Io, s: Int)
|
|
22
|
+
# Changes the volume of a sound that is playing or looping.
|
|
23
|
+
extern fun soundSetVolume(io: Io, s: Int, volume: Float)
|
|
24
|
+
|
|
25
|
+
# A sound handle; the id is the host's.
|
|
26
|
+
struct Sound(id: Int) =
|
|
27
|
+
fun play(self, io: Io, volume: Float = 1.0) =
|
|
28
|
+
soundPlay(io, self.id, volume)
|
|
29
|
+
|
|
30
|
+
fun loop(self, io: Io, volume: Float = 1.0) =
|
|
31
|
+
soundLoop(io, self.id, volume)
|
|
32
|
+
|
|
33
|
+
fun stop(self, io: Io) =
|
|
34
|
+
soundStop(io, self.id)
|
|
35
|
+
|
|
36
|
+
fun setVolume(self, io: Io, volume: Float) =
|
|
37
|
+
soundSetVolume(io, self.id, volume)
|
|
38
|
+
|
|
39
|
+
# Loads a sound relative to the asset root; crashes naming the file if it is missing.
|
|
40
|
+
fun loadSound(io: Io, name: Str) -> Sound =
|
|
41
|
+
id := soundLoad(io, name)
|
|
42
|
+
if id < 0
|
|
43
|
+
crash gfx.missingAsset("sound", name)
|
|
44
|
+
Sound(id: id)
|
std/game/gfx.plum
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Str
|
|
6
|
+
import std/game/Vec2
|
|
7
|
+
import std/game/Color
|
|
8
|
+
import std/Io
|
|
9
|
+
|
|
10
|
+
# Drawing, textures and files: the game host's graphics API (`plum run`), as module
|
|
11
|
+
# functions that take the `Io` capability first: `gfx.clear(io, Color.Black)`,
|
|
12
|
+
# `gfx.loadTexture(io, "sprites.png")`. A game is any type that `main(io: Io)` returns and
|
|
13
|
+
# that has `update(self, io: Io, dt: Float) -> Self` and `draw(self, io: Io)`; the host
|
|
14
|
+
# calls `update` then `draw` every frame, and the state `update` returns is the next
|
|
15
|
+
# frame's `self`. Input is `std/game/input`, sound is `std/game/audio`. This file also
|
|
16
|
+
# holds the `Blend` constants and the `Texture` handle. A path that escapes the asset root
|
|
17
|
+
# fails like a missing file. Coordinates are world units once `gfx.setCamera` is set.
|
|
18
|
+
#
|
|
19
|
+
# Texture handles are -1 on failure. File and texture paths are relative to the asset
|
|
20
|
+
# root. `Int` in an extern signature is narrowed to i32 at the host boundary.
|
|
21
|
+
|
|
22
|
+
extern fun screenWidth(io: Io) -> Float
|
|
23
|
+
extern fun screenHeight(io: Io) -> Float
|
|
24
|
+
extern fun frameTime(io: Io) -> Float
|
|
25
|
+
extern fun clear(io: Io, c: Color)
|
|
26
|
+
extern fun drawRect(io: Io, x: Float, y: Float, w: Float, h: Float, c: Color)
|
|
27
|
+
extern fun drawCircle(io: Io, x: Float, y: Float, r: Float, c: Color)
|
|
28
|
+
extern fun drawLine(io: Io, x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, c: Color)
|
|
29
|
+
extern fun drawText(io: Io, s: Str, x: Float, y: Float, size: Float, c: Color)
|
|
30
|
+
extern fun setCamera(io: Io, x: Float, y: Float, scale: Float)
|
|
31
|
+
extern fun resetCamera(io: Io)
|
|
32
|
+
# Loads any image the host decodes (PNG at least); -1 on failure.
|
|
33
|
+
extern fun textureLoad(io: Io, path: Str) -> Int
|
|
34
|
+
# Size in pixels; 0 for a bad handle.
|
|
35
|
+
extern fun textureWidth(io: Io, t: Int) -> Int
|
|
36
|
+
extern fun textureHeight(io: Io, t: Int) -> Int
|
|
37
|
+
# Linear (true) or nearest (false, the default) filtering.
|
|
38
|
+
extern fun textureSetSmooth(io: Io, t: Int, smooth: Bool)
|
|
39
|
+
# A blank, transparent texture of w x h pixels that can be drawn into with
|
|
40
|
+
# `renderTarget`; -1 if a side is below 1 or above 8192.
|
|
41
|
+
extern fun textureCreate(io: Io, w: Int, h: Int) -> Int
|
|
42
|
+
# Sends the following draws (and `clear`) into texture `t` made by `textureCreate`,
|
|
43
|
+
# or back to the screen with -1; any other handle is ignored. Each target has its
|
|
44
|
+
# own camera: selecting a target resets its camera to its pixels, and returning to
|
|
45
|
+
# the screen restores the screen's camera. The texture's contents persist between
|
|
46
|
+
# frames; draw it like any texture once the screen is selected again.
|
|
47
|
+
extern fun renderTarget(io: Io, t: Int)
|
|
48
|
+
# The blend mode of the following draws: a `Blend` constant (other values are
|
|
49
|
+
# ignored). Every frame starts with `Blend.Normal`.
|
|
50
|
+
extern fun blendMode(io: Io, m: Int)
|
|
51
|
+
# The texture at its natural size, top-left at (x, y).
|
|
52
|
+
extern fun drawTexture(io: Io, t: Int, x: Float, y: Float, tint: Color)
|
|
53
|
+
# The source rect (sx, sy, sw, sh) in texture pixels drawn into the dest rect
|
|
54
|
+
# (x, y, w, h), rotated `rotation` radians clockwise about the dest centre.
|
|
55
|
+
extern fun drawTextureEx(io: Io, t: Int, sx: Float, sy: Float, sw: Float, sh: Float, x: Float, y: Float, w: Float, h: Float, rotation: Float, flipX: Bool, tint: Color)
|
|
56
|
+
extern fun fileExists(io: Io, path: Str) -> Bool
|
|
57
|
+
# The whole file; "" if it is missing.
|
|
58
|
+
extern fun fileLoad(io: Io, path: Str) -> Str
|
|
59
|
+
|
|
60
|
+
# Blend modes for `blendMode`: alpha blending, additive (brightens), multiply
|
|
61
|
+
# (darkens, white leaves the target unchanged) and screen (lightens).
|
|
62
|
+
primitive Blend =
|
|
63
|
+
Normal = 0
|
|
64
|
+
Add = 1
|
|
65
|
+
Multiply = 2
|
|
66
|
+
Screen = 3
|
|
67
|
+
|
|
68
|
+
# A texture handle; the id is the host's. A handle of -1 is no texture.
|
|
69
|
+
struct Texture(id: Int) =
|
|
70
|
+
fun width(self, io: Io) -> Int = textureWidth(io, self.id)
|
|
71
|
+
|
|
72
|
+
fun height(self, io: Io) -> Int = textureHeight(io, self.id)
|
|
73
|
+
|
|
74
|
+
# Linear (true) or nearest (false, the default) filtering.
|
|
75
|
+
fun setSmooth(self, io: Io, smooth: Bool) =
|
|
76
|
+
textureSetSmooth(io, self.id, smooth)
|
|
77
|
+
|
|
78
|
+
# The texture at its natural size, top-left at (x, y).
|
|
79
|
+
fun draw(self, io: Io, x: Float, y: Float, tint: Color = Color.White) =
|
|
80
|
+
drawTexture(io, self.id, x, y, tint)
|
|
81
|
+
|
|
82
|
+
# Sends the following draws into this texture; `gfx.renderToScreen` goes back to the screen.
|
|
83
|
+
# Each target has its own camera, which starts as its pixels.
|
|
84
|
+
fun renderTarget(self, io: Io) =
|
|
85
|
+
renderTarget(io, self.id)
|
|
86
|
+
|
|
87
|
+
# Loads an image relative to the asset root; crashes naming the file if it is missing.
|
|
88
|
+
fun loadTexture(io: Io, name: Str) -> Texture =
|
|
89
|
+
id := textureLoad(io, name)
|
|
90
|
+
if id < 0
|
|
91
|
+
crash missingAsset("texture", name)
|
|
92
|
+
Texture(id: id)
|
|
93
|
+
|
|
94
|
+
# A blank transparent texture to draw into with `renderTarget`; crashes if a side is
|
|
95
|
+
# below 1 or above 8192.
|
|
96
|
+
fun createTexture(io: Io, w: Int, h: Int) -> Texture =
|
|
97
|
+
id := textureCreate(io, w, h)
|
|
98
|
+
if id < 0
|
|
99
|
+
crash "cannot create a {w}x{h} texture"
|
|
100
|
+
Texture(id: id)
|
|
101
|
+
|
|
102
|
+
# Sends the following draws back to the screen.
|
|
103
|
+
fun renderToScreen(io: Io) =
|
|
104
|
+
renderTarget(io, -1)
|
|
105
|
+
|
|
106
|
+
fun missingAsset(kind: Str, name: Str) -> Str =
|
|
107
|
+
"missing {kind}: {name}"
|
|
108
|
+
|
|
109
|
+
# The whole file as text, relative to the asset root; crashes naming the file if it is missing.
|
|
110
|
+
fun loadFile(io: Io, name: Str) -> Str =
|
|
111
|
+
if !fileExists(io, name)
|
|
112
|
+
crash missingAsset("file", name)
|
|
113
|
+
fileLoad(io, name)
|
|
114
|
+
|
|
115
|
+
test "a missing asset message names the file"
|
|
116
|
+
assert missingAsset("texture", "ship.png") == "missing texture: ship.png"
|
|
117
|
+
|
|
118
|
+
test "blend constants"
|
|
119
|
+
assert Blend.Normal == 0
|
|
120
|
+
assert Blend.Screen == 3
|
std/game/{Input.plum → input.plum}
RENAMED
|
@@ -5,16 +5,86 @@ import std/Float
|
|
|
5
5
|
import std/Slice
|
|
6
6
|
import std/game/Vec2
|
|
7
7
|
import std/game/Affine
|
|
8
|
-
import std/game/Game
|
|
9
8
|
import std/Io
|
|
10
9
|
import std/Option
|
|
11
10
|
import std/List
|
|
12
11
|
|
|
13
|
-
# Player input
|
|
12
|
+
# Player input. `InputEvent.poll` is the only code that reads
|
|
14
13
|
# input from the host: a game that feeds every polled `InputEvent` into its state reads
|
|
15
14
|
# nothing else, so a recorded list of inputs replays the game exactly (see
|
|
16
15
|
# docs/game.md, "Input as events").
|
|
17
16
|
|
|
17
|
+
extern fun isKeyDown(io: Io, k: Int) -> Bool
|
|
18
|
+
extern fun isKeyPressed(io: Io, k: Int) -> Bool
|
|
19
|
+
extern fun mousePos(io: Io) -> Vec2
|
|
20
|
+
extern fun isMouseDown(io: Io, b: Int) -> Bool
|
|
21
|
+
extern fun isMousePressed(io: Io, b: Int) -> Bool
|
|
22
|
+
extern fun mouseWheel(io: Io) -> Float
|
|
23
|
+
|
|
24
|
+
# -1, 0 or 1: how far the key `high` is held against the key `low`. `input.axis(io, Key.Left, Key.Right)`
|
|
25
|
+
# is the horizontal steering of a ship.
|
|
26
|
+
fun axis(io: Io, low: Int, high: Int) -> Float =
|
|
27
|
+
right := if isKeyDown(io, high) then 1.0 else 0.0
|
|
28
|
+
left := if isKeyDown(io, low) then 1.0 else 0.0
|
|
29
|
+
right - left
|
|
30
|
+
|
|
31
|
+
# Key codes (GLFW numbering) for `isKeyDown` / `isKeyPressed`.
|
|
32
|
+
# Letter keys are `KeyA`..`KeyZ` (a constant name needs two characters).
|
|
33
|
+
primitive Key =
|
|
34
|
+
Space = 32
|
|
35
|
+
KeyA = 65
|
|
36
|
+
KeyB = 66
|
|
37
|
+
KeyC = 67
|
|
38
|
+
KeyD = 68
|
|
39
|
+
KeyE = 69
|
|
40
|
+
KeyF = 70
|
|
41
|
+
KeyG = 71
|
|
42
|
+
KeyH = 72
|
|
43
|
+
KeyI = 73
|
|
44
|
+
KeyJ = 74
|
|
45
|
+
KeyK = 75
|
|
46
|
+
KeyL = 76
|
|
47
|
+
KeyM = 77
|
|
48
|
+
KeyN = 78
|
|
49
|
+
KeyO = 79
|
|
50
|
+
KeyP = 80
|
|
51
|
+
KeyQ = 81
|
|
52
|
+
KeyR = 82
|
|
53
|
+
KeyS = 83
|
|
54
|
+
KeyT = 84
|
|
55
|
+
KeyU = 85
|
|
56
|
+
KeyV = 86
|
|
57
|
+
KeyW = 87
|
|
58
|
+
KeyX = 88
|
|
59
|
+
KeyY = 89
|
|
60
|
+
KeyZ = 90
|
|
61
|
+
Num0 = 48
|
|
62
|
+
Num1 = 49
|
|
63
|
+
Num2 = 50
|
|
64
|
+
Num3 = 51
|
|
65
|
+
Num4 = 52
|
|
66
|
+
Num5 = 53
|
|
67
|
+
Num6 = 54
|
|
68
|
+
Num7 = 55
|
|
69
|
+
Num8 = 56
|
|
70
|
+
Num9 = 57
|
|
71
|
+
Escape = 256
|
|
72
|
+
Enter = 257
|
|
73
|
+
Tab = 258
|
|
74
|
+
Backspace = 259
|
|
75
|
+
Right = 262
|
|
76
|
+
Left = 263
|
|
77
|
+
Down = 264
|
|
78
|
+
Up = 265
|
|
79
|
+
LeftShift = 340
|
|
80
|
+
LeftControl = 341
|
|
81
|
+
|
|
82
|
+
# Mouse button numbers for `isMouseDown` / `isMousePressed`.
|
|
83
|
+
primitive Mouse =
|
|
84
|
+
Left = 0
|
|
85
|
+
Right = 1
|
|
86
|
+
Middle = 2
|
|
87
|
+
|
|
18
88
|
# One input: a pointer event in screen pixels, or a key going down or up.
|
|
19
89
|
enum InputEvent =
|
|
20
90
|
| PointerDown(x: Float, y: Float)
|
|
@@ -29,13 +99,13 @@ enum InputEvent =
|
|
|
29
99
|
# began and ended between two polls gives a PointerDown and a PointerUp.
|
|
30
100
|
fun poll(io: Io, prev: Held) -> Polled =
|
|
31
101
|
out := Slice[InputEvent]()
|
|
32
|
-
m :=
|
|
102
|
+
m := mousePos(io)
|
|
33
|
-
down :=
|
|
103
|
+
down := isMouseDown(io, Mouse.Left)
|
|
34
104
|
if down && !prev.mouse
|
|
35
105
|
out.push(PointerDown(x: m.x, y: m.y))
|
|
36
106
|
else if !down && prev.mouse
|
|
37
107
|
out.push(PointerUp(x: m.x, y: m.y))
|
|
38
|
-
else if !down &&
|
|
108
|
+
else if !down && isMousePressed(io, Mouse.Left)
|
|
39
109
|
# pressed and released between two polls: a click must not be lost
|
|
40
110
|
out.push(PointerDown(x: m.x, y: m.y))
|
|
41
111
|
out.push(PointerUp(x: m.x, y: m.y))
|
|
@@ -45,7 +115,7 @@ enum InputEvent =
|
|
|
45
115
|
codes := InputEvent.keyCodes()
|
|
46
116
|
for i := range codes.length()
|
|
47
117
|
k := codes.at(i)
|
|
48
|
-
now :=
|
|
118
|
+
now := isKeyDown(io, k)
|
|
49
119
|
was := prev.isDown(k)
|
|
50
120
|
if now
|
|
51
121
|
keys.push(k)
|
|
@@ -55,7 +125,7 @@ enum InputEvent =
|
|
|
55
125
|
out.push(KeyUp(key: k))
|
|
56
126
|
Polled(inputs: out, held: Held(mouse: down, keys: keys))
|
|
57
127
|
|
|
58
|
-
# Every `Key` code in std/game/
|
|
128
|
+
# Every `Key` code in std/game/input, in increasing order.
|
|
59
129
|
fun keyCodes() -> Slice[Int] =
|
|
60
130
|
out := [Key.Space].toSlice()
|
|
61
131
|
for i := range 10
|
|
@@ -151,7 +221,7 @@ struct Input(held: Held, events: Slice[InputEvent], pos: Vec2, wheel: Float) =
|
|
|
151
221
|
# The input of this frame: the host polled once and compared with what was held before.
|
|
152
222
|
fun poll(self, io: Io) -> Input =
|
|
153
223
|
p := InputEvent.poll(io, self.held)
|
|
154
|
-
Input(held: p.held, events: p.inputs, pos:
|
|
224
|
+
Input(held: p.held, events: p.inputs, pos: mousePos(io), wheel: mouseWheel(io))
|
|
155
225
|
|
|
156
226
|
# Held at the start of this frame (a `Key` code).
|
|
157
227
|
fun isKeyDown(self, key: Int) -> Bool =
|
|
@@ -256,3 +326,10 @@ test "input agrees for the whole frame"
|
|
|
256
326
|
assert st.mouseWheel() == 1.5
|
|
257
327
|
assert st.mousePos().x == 3.0
|
|
258
328
|
assert st.pointer().pressed
|
|
329
|
+
|
|
330
|
+
test "key and mouse constants use GLFW numbering"
|
|
331
|
+
assert Key.KeyW == 87
|
|
332
|
+
assert Key.Left == 263
|
|
333
|
+
assert Key.Num0 == 48
|
|
334
|
+
assert Key.LeftControl == 341
|
|
335
|
+
assert Mouse.Right == 1
|
std/game/{Scene.plum → scene.plum}
RENAMED
|
@@ -5,18 +5,18 @@ import std/Float
|
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/Slice
|
|
7
7
|
import std/List
|
|
8
|
-
import std/
|
|
8
|
+
import std/math
|
|
9
9
|
import std/game/Vec2
|
|
10
10
|
import std/game/Color
|
|
11
11
|
import std/game/Affine
|
|
12
|
-
import std/game/
|
|
12
|
+
import std/game/gfx
|
|
13
13
|
import std/Io
|
|
14
14
|
import std/Option
|
|
15
15
|
|
|
16
16
|
# The functional scene: a `SceneNode[M]` is plain data (shapes, sprites, text, groups
|
|
17
17
|
# with a transform, filters, clickable areas), rebuilt every frame and never mutated.
|
|
18
18
|
# `M` is the game's own message type: a `Clickable(id, msg, child)` carries the
|
|
19
|
-
# message a click on it sends (see `
|
|
19
|
+
# message a click on it sends (see `ui.messages`), so games match on their messages
|
|
20
20
|
# instead of comparing ids; the id identifies the element for hover and press state. Its methods draw
|
|
21
21
|
# it, measure it and hit-test it by structural recursion, passing the parent matrix
|
|
22
22
|
# and alpha down as arguments. Children are a `List[SceneNode[M]]`; the static
|
|
@@ -34,11 +34,11 @@ enum Transform =
|
|
|
34
34
|
fun matrix(self) -> Affine = match self
|
|
35
35
|
Identity => Affine.Identity
|
|
36
36
|
Translate(dx, dy) => Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: dx, f: dy)
|
|
37
|
-
Rotate(rad) => Affine(a:
|
|
37
|
+
Rotate(rad) => Affine(a: math.cos(rad), b: math.sin(rad), c: 0.0 - math.sin(rad), d: math.cos(rad), e: 0.0, f: 0.0)
|
|
38
38
|
Scale(sx, sy) => Affine(a: sx, b: 0.0, c: 0.0, d: sy, e: 0.0, f: 0.0)
|
|
39
39
|
Compose(first, then) => first.matrix().mul(then.matrix())
|
|
40
40
|
|
|
41
|
-
# `mode` is a `Blend` constant from std/game/
|
|
41
|
+
# `mode` is a `Blend` constant from std/game/gfx.
|
|
42
42
|
enum Effect =
|
|
43
43
|
| Tint(color: Color)
|
|
44
44
|
| Alpha(alpha: Float)
|
|
@@ -141,22 +141,22 @@ enum SceneNode[M] =
|
|
|
141
141
|
sx := w * m.scaleX()
|
|
142
142
|
sy := h * m.scaleY()
|
|
143
143
|
c := m.apply(Vec2(x: x + w / 2.0, y: y + h / 2.0))
|
|
144
|
-
|
|
144
|
+
gfx.drawRect(io, c.x - sx / 2.0, c.y - sy / 2.0, sx, sy, color.withAlpha(color.a * alpha))
|
|
145
145
|
CircleShape(cx, cy, r, ccolor) =>
|
|
146
146
|
cc := m.apply(Vec2(x: cx, y: cy))
|
|
147
|
-
|
|
147
|
+
gfx.drawCircle(io, cc.x, cc.y, r * m.scaleX(), ccolor.withAlpha(ccolor.a * alpha))
|
|
148
148
|
LineShape(x1, y1, x2, y2, th, lcolor) =>
|
|
149
149
|
p := m.apply(Vec2(x: x1, y: y1))
|
|
150
150
|
q := m.apply(Vec2(x: x2, y: y2))
|
|
151
|
-
|
|
151
|
+
gfx.drawLine(io, p.x, p.y, q.x, q.y, th * m.scaleX(), lcolor.withAlpha(lcolor.a * alpha))
|
|
152
152
|
Sprite(tex, sx0, sy0, sw0, sh0, srcX, srcY, srcW, srcH, tint) =>
|
|
153
153
|
sw := sw0 * m.scaleX()
|
|
154
154
|
sh := sh0 * m.scaleY()
|
|
155
155
|
sc := m.apply(Vec2(x: sx0 + sw0 / 2.0, y: sy0 + sh0 / 2.0))
|
|
156
|
-
|
|
156
|
+
gfx.drawTextureEx(io, tex.id, srcX, srcY, srcW, srcH, sc.x - sw / 2.0, sc.y - sh / 2.0, sw, sh, m.rotation(), false, tint.withAlpha(tint.a * alpha))
|
|
157
157
|
Text(txt, tx, ty, size, tcolor) =>
|
|
158
158
|
tp := m.apply(Vec2(x: tx, y: ty))
|
|
159
|
-
|
|
159
|
+
gfx.drawText(io, txt, tp.x, tp.y, size * m.scaleY(), tcolor.withAlpha(tcolor.a * alpha))
|
|
160
160
|
Group(tr, kids) => SceneNode.drawKids(io, kids, m.mul(tr.matrix()), alpha, target)
|
|
161
161
|
Filter(effect, child, tex) => SceneNode.drawFiltered(io, effect, child, tex, m, alpha, target)
|
|
162
162
|
Clickable(_, _, child) => child.drawWith(io, m, alpha, target)
|
|
@@ -169,20 +169,20 @@ enum SceneNode[M] =
|
|
|
169
169
|
|
|
170
170
|
fun drawFiltered(io: Io, effect: Effect, child: SceneNode[M], tex: Texture, m: Affine, alpha: Float, target: Texture) = match effect
|
|
171
171
|
BlendFx(mode) =>
|
|
172
|
-
|
|
172
|
+
gfx.blendMode(io, mode)
|
|
173
173
|
child.drawWith(io, m, alpha, target)
|
|
174
|
-
|
|
174
|
+
gfx.blendMode(io, Blend.Normal)
|
|
175
175
|
_ =>
|
|
176
176
|
if Some(b) := child.boundsWith(m)
|
|
177
177
|
if tex.id >= 0
|
|
178
|
-
w := {Int(b.w) + 1}.min(
|
|
178
|
+
w := {Int(b.w) + 1}.min(gfx.textureWidth(io, tex.id))
|
|
179
|
-
h := {Int(b.h) + 1}.min(
|
|
179
|
+
h := {Int(b.h) + 1}.min(gfx.textureHeight(io, tex.id))
|
|
180
|
-
|
|
180
|
+
gfx.renderTarget(io, tex.id)
|
|
181
|
-
|
|
181
|
+
gfx.clear(io, Color.Transparent)
|
|
182
182
|
shift := Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0 - b.x, f: 0.0 - b.y)
|
|
183
183
|
child.drawWith(io, shift.mul(m), 1.0, tex)
|
|
184
|
-
|
|
184
|
+
gfx.renderTarget(io, target.id)
|
|
185
|
-
|
|
185
|
+
gfx.drawTextureEx(io, tex.id, 0.0, 0.0, Float(w), Float(h), b.x, b.y, Float(w), Float(h), 0.0, false, effect.tint(alpha))
|
|
186
186
|
|
|
187
187
|
# --- bounds ---
|
|
188
188
|
|
|
@@ -211,7 +211,7 @@ enum SceneNode[M] =
|
|
|
211
211
|
# that is hit is an empty path. (px, py) is in the node's own space.
|
|
212
212
|
fun hitWith(self, px: Float, py: Float) -> Option[Slice[Int]] = match self
|
|
213
213
|
RectShape(x, y, w, h, _) => hitLeaf(Rect(x: x, y: y, w: w, h: h).contains(px, py))
|
|
214
|
-
CircleShape(cx, cy, r, _) => hitLeaf(
|
|
214
|
+
CircleShape(cx, cy, r, _) => hitLeaf(math.hypot(px - cx, py - cy) <= r)
|
|
215
215
|
LineShape(x1, y1, x2, y2, th, _) => hitLeaf(nearLine(x1, y1, x2, y2, th, px, py))
|
|
216
216
|
Sprite(_, sx, sy, sw, sh, _, _, _, _, _) => hitLeaf(Rect(x: sx, y: sy, w: sw, h: sh).contains(px, py))
|
|
217
217
|
Text(txt, tx, ty, size, _) => hitLeaf(Rect(x: tx, y: ty, w: size * 0.6 * Float(txt.length()), h: size).contains(px, py))
|
|
@@ -294,7 +294,7 @@ fun nearLine(x1: Float, y1: Float, x2: Float, y2: Float, thickness: Float, px: F
|
|
|
294
294
|
tc := t.max(0.0).min(1.0)
|
|
295
295
|
qx := x1 + dx * tc
|
|
296
296
|
qy := y1 + dy * tc
|
|
297
|
-
|
|
297
|
+
math.hypot(px - qx, py - qy) <= thickness.max(1.0) / 2.0
|
|
298
298
|
|
|
299
299
|
fun picNear(a: Float, b: Float) -> Bool =
|
|
300
300
|
{a - b}.abs() < 1e-6
|
std/game/ui.plum
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Str
|
|
6
|
+
import std/Slice
|
|
7
|
+
import std/List
|
|
8
|
+
import std/Option
|
|
9
|
+
import std/game/Color
|
|
10
|
+
import std/game/scene
|
|
11
|
+
import std/game/input
|
|
12
|
+
|
|
13
|
+
# A pure UI layer for the functional scene style. `step` takes the previous
|
|
14
|
+
# UiState, one pointer input and the id under the pointer (from SceneNode.hitId on
|
|
15
|
+
# the current view) and returns the new state plus the UiEvents it raised.
|
|
16
|
+
# `messages` turns the Clicks among them into the game's own messages, read from
|
|
17
|
+
# the `Clickable` nodes of that view. Same
|
|
18
|
+
# button rules as the old pure scene: Down captures the pressed id; while captured only
|
|
19
|
+
# that id gets Enter/Exit; Up releases (Click only when still over it).
|
|
20
|
+
|
|
21
|
+
struct UiState(x: Float, y: Float, down: Bool, hot: Option[Int], captured: Option[Int])
|
|
22
|
+
|
|
23
|
+
struct UiStep(ui: UiState, events: List[UiEvent])
|
|
24
|
+
|
|
25
|
+
fun uiSame(a: Option[Int], b: Option[Int]) -> Bool =
|
|
26
|
+
if Some(va) := a
|
|
27
|
+
if Some(vb) := b
|
|
28
|
+
return va == vb
|
|
29
|
+
return false
|
|
30
|
+
if Some(vb) := b
|
|
31
|
+
return false
|
|
32
|
+
true
|
|
33
|
+
|
|
34
|
+
# Exit for the old hot id and Enter for the new one when they differ.
|
|
35
|
+
fun uiHover(out: Slice[UiEvent], old: Option[Int], now: Option[Int]) =
|
|
36
|
+
if !uiSame(old, now)
|
|
37
|
+
if Some(o) := old
|
|
38
|
+
out.push(UiEvent(id: o, kind: Exit))
|
|
39
|
+
if Some(n) := now
|
|
40
|
+
out.push(UiEvent(id: n, kind: Enter))
|
|
41
|
+
|
|
42
|
+
fun init() -> UiState =
|
|
43
|
+
UiState(x: 0.0, y: 0.0, down: false, hot: None, captured: None)
|
|
44
|
+
|
|
45
|
+
# A key changes nothing here (keys go to the game).
|
|
46
|
+
fun step(ui: UiState, input: InputEvent, hit: Option[Int]) -> UiStep =
|
|
47
|
+
maybePos := input.position()
|
|
48
|
+
if maybePos.isNone()
|
|
49
|
+
return UiStep(ui: ui, events: Nil)
|
|
50
|
+
pos := maybePos!
|
|
51
|
+
out := Slice[UiEvent]()
|
|
52
|
+
# a capture left over without a held button is stale
|
|
53
|
+
cap: Option[Int] := ui.captured
|
|
54
|
+
if !ui.down
|
|
55
|
+
cap = None
|
|
56
|
+
hot: Option[Int] := ui.hot
|
|
57
|
+
down := ui.down
|
|
58
|
+
match input
|
|
59
|
+
PointerDown(_, _) =>
|
|
60
|
+
cap = None
|
|
61
|
+
uiHover(out, hot, hit)
|
|
62
|
+
hot = hit
|
|
63
|
+
down = true
|
|
64
|
+
if Some(h) := hit
|
|
65
|
+
out.push(UiEvent(id: h, kind: Press))
|
|
66
|
+
cap = Some(h)
|
|
67
|
+
PointerMove(_, _) =>
|
|
68
|
+
if Some(c) := cap
|
|
69
|
+
now: Option[Int] := None
|
|
70
|
+
if uiSame(hit, cap)
|
|
71
|
+
now = cap
|
|
72
|
+
uiHover(out, hot, now)
|
|
73
|
+
hot = now
|
|
74
|
+
else
|
|
75
|
+
uiHover(out, hot, hit)
|
|
76
|
+
hot = hit
|
|
77
|
+
PointerUp(_, _) =>
|
|
78
|
+
if Some(c) := cap
|
|
79
|
+
out.push(UiEvent(id: c, kind: Release))
|
|
80
|
+
if uiSame(hit, cap)
|
|
81
|
+
out.push(UiEvent(id: c, kind: Click))
|
|
82
|
+
cap = None
|
|
83
|
+
hot = hit
|
|
84
|
+
else
|
|
85
|
+
uiHover(out, hot, hit)
|
|
86
|
+
hot = hit
|
|
87
|
+
down = false
|
|
88
|
+
_ => 0
|
|
89
|
+
UiStep(ui: UiState(x: pos.x, y: pos.y, down: down, hot: hot, captured: cap), events: List.fromSlice(out))
|
|
90
|
+
|
|
91
|
+
fun pressed(ui: UiState, id: Int) -> Bool =
|
|
92
|
+
if Some(c) := ui.captured
|
|
93
|
+
return c == id && uiSame(ui.hot, ui.captured)
|
|
94
|
+
false
|
|
95
|
+
|
|
96
|
+
fun hovered(ui: UiState, id: Int) -> Bool =
|
|
97
|
+
if Some(h) := ui.hot
|
|
98
|
+
return h == id
|
|
99
|
+
false
|
|
100
|
+
|
|
101
|
+
# A tagged, translated rectangle with a label whose colour follows the state.
|
|
102
|
+
# The messages of the Clickables that `events` clicked, in order, read from `view`.
|
|
103
|
+
fun messages[M](view: SceneNode[M], events: List[UiEvent]) -> List[M] = match events
|
|
104
|
+
Nil => Nil
|
|
105
|
+
Cons(e, rest) =>
|
|
106
|
+
later := messages(view, rest)
|
|
107
|
+
if e.kind != Click
|
|
108
|
+
return later
|
|
109
|
+
if Some(m) := view.msgOf(e.id)
|
|
110
|
+
return Cons(head: m, tail: later)
|
|
111
|
+
later
|
|
112
|
+
|
|
113
|
+
# A button that sends `msg` when clicked; `id` identifies it for hover and press.
|
|
114
|
+
fun button[M](id: Int, msg: M, label: Str, x: Float, y: Float, w: Float, h: Float, ui: UiState) -> SceneNode[M] =
|
|
115
|
+
color := uiIdleColor()
|
|
116
|
+
if pressed(ui, id)
|
|
117
|
+
color = uiPressedColor()
|
|
118
|
+
else if hovered(ui, id)
|
|
119
|
+
color = uiHoverColor()
|
|
120
|
+
Clickable(id: id, msg: msg, child: Group(transform: Translate(dx: x, dy: y), children: [
|
|
121
|
+
RectShape(x: 0.0, y: 0.0, w: w, h: h, color: color),
|
|
122
|
+
Text(text: label, x: 4.0, y: 4.0, size: h * 0.5, color: Color.White)]))
|
|
123
|
+
|
|
124
|
+
fun uiIdleColor() -> Color = Color.rgb(0.2, 0.2, 0.3)
|
|
125
|
+
|
|
126
|
+
fun uiHoverColor() -> Color = Color.rgb(0.35, 0.35, 0.5)
|
|
127
|
+
|
|
128
|
+
fun uiPressedColor() -> Color = Color.rgb(0.6, 0.2, 0.2)
|
|
129
|
+
|
|
130
|
+
fun uiKinds(s: UiStep) -> List[UiKind] = s.events.map(|e| e.kind)
|
|
131
|
+
|
|
132
|
+
fun uiDown(x: Float) -> InputEvent = PointerDown(x: x, y: 0.0)
|
|
133
|
+
|
|
134
|
+
fun uiUp(x: Float) -> InputEvent = PointerUp(x: x, y: 0.0)
|
|
135
|
+
|
|
136
|
+
fun uiMove(x: Float) -> InputEvent = PointerMove(x: x, y: 0.0)
|
|
137
|
+
|
|
138
|
+
fun uiCount(s: UiStep, k: UiKind) -> Int =
|
|
139
|
+
n := 0
|
|
140
|
+
for e := range s.events
|
|
141
|
+
if e.kind == k
|
|
142
|
+
n = n + 1
|
|
143
|
+
n
|
|
144
|
+
|
|
145
|
+
fun uiIs(e: UiEvent, id: Int, kind: UiKind) -> Bool = e.id == id && e.kind == kind
|
|
146
|
+
|
|
147
|
+
fun uiButtonColor(n: SceneNode[Int]) -> Color = match n
|
|
148
|
+
Clickable(_, _, child) => uiButtonColor(child)
|
|
149
|
+
Group(_, children) => uiButtonColor(children.at(0))
|
|
150
|
+
RectShape(_, _, _, _, c) => c
|
|
151
|
+
_ => Color.Black
|
|
152
|
+
|
|
153
|
+
test "press_sets_capture"
|
|
154
|
+
s1 := step(init(), uiDown(1.0), Some(5))
|
|
155
|
+
assert s1.events.length() == 2
|
|
156
|
+
assert uiIs(s1.events.at(0), 5, Enter)
|
|
157
|
+
assert uiIs(s1.events.at(1), 5, Press)
|
|
158
|
+
assert pressed(s1.ui, 5)
|
|
159
|
+
s2 := step(s1.ui, uiUp(1.0), Some(5))
|
|
160
|
+
assert s2.events.length() == 2
|
|
161
|
+
assert uiIs(s2.events.at(0), 5, Release)
|
|
162
|
+
assert uiIs(s2.events.at(1), 5, Click)
|
|
163
|
+
assert !pressed(s2.ui, 5)
|
|
164
|
+
assert hovered(s2.ui, 5)
|
|
165
|
+
|
|
166
|
+
test "release_elsewhere_no_click"
|
|
167
|
+
s1 := step(init(), uiDown(1.0), Some(5))
|
|
168
|
+
s2 := step(s1.ui, uiMove(99.0), None)
|
|
169
|
+
assert s2.events.length() == 1
|
|
170
|
+
assert uiIs(s2.events.at(0), 5, Exit)
|
|
171
|
+
s3 := step(s2.ui, uiUp(99.0), None)
|
|
172
|
+
assert s3.events.length() == 1
|
|
173
|
+
assert uiIs(s3.events.at(0), 5, Release)
|
|
174
|
+
assert uiCount(s3, Click) == 0
|
|
175
|
+
|
|
176
|
+
test "drag_off_and_back_one_click"
|
|
177
|
+
s1 := step(init(), uiDown(1.0), Some(5))
|
|
178
|
+
s2 := step(s1.ui, uiMove(99.0), None)
|
|
179
|
+
s3 := step(s2.ui, uiMove(1.0), Some(5))
|
|
180
|
+
assert s3.events.length() == 1
|
|
181
|
+
assert uiIs(s3.events.at(0), 5, Enter)
|
|
182
|
+
s4 := step(s3.ui, uiUp(1.0), Some(5))
|
|
183
|
+
assert uiCount(s4, Click) == 1
|
|
184
|
+
assert uiCount(s4, Release) == 1
|
|
185
|
+
|
|
186
|
+
test "stale_capture_dropped"
|
|
187
|
+
stale := UiState(x: 0.0, y: 0.0, down: false, hot: None, captured: Some(5))
|
|
188
|
+
s := step(stale, uiMove(50.0), None)
|
|
189
|
+
assert s.events.length() == 0
|
|
190
|
+
if Some(c) := s.ui.captured
|
|
191
|
+
assert false
|
|
192
|
+
assert !pressed(s.ui, 5)
|
|
193
|
+
|
|
194
|
+
test "hover_without_press_routes_move"
|
|
195
|
+
s1 := step(init(), uiMove(1.0), Some(5))
|
|
196
|
+
assert s1.events.length() == 1
|
|
197
|
+
assert uiIs(s1.events.at(0), 5, Enter)
|
|
198
|
+
assert hovered(s1.ui, 5)
|
|
199
|
+
s2 := step(s1.ui, uiMove(2.0), Some(5))
|
|
200
|
+
assert s2.events.length() == 0
|
|
201
|
+
s3 := step(s2.ui, uiMove(99.0), None)
|
|
202
|
+
assert s3.events.length() == 1
|
|
203
|
+
assert uiIs(s3.events.at(0), 5, Exit)
|
|
204
|
+
assert !hovered(s3.ui, 5)
|
|
205
|
+
|
|
206
|
+
test "button_visual_reflects_state"
|
|
207
|
+
idle := button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, init())
|
|
208
|
+
hov := button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, step(init(), uiMove(1.0), Some(3)).ui)
|
|
209
|
+
prs := button(3, 30, "Go", 10.0, 20.0, 100.0, 40.0, step(init(), uiDown(1.0), Some(3)).ui)
|
|
210
|
+
assert uiButtonColor(idle).eq(uiIdleColor())
|
|
211
|
+
assert uiButtonColor(hov).eq(uiHoverColor())
|
|
212
|
+
assert uiButtonColor(prs).eq(uiPressedColor())
|
|
213
|
+
if Some(hid) := idle.hitId(20.0, 30.0)
|
|
214
|
+
assert hid == 3
|
|
215
|
+
else
|
|
216
|
+
assert false
|
|
217
|
+
|
|
218
|
+
test "messages_are_the_clicked_buttons_messages"
|
|
219
|
+
view := Group(transform: Identity, children: [button(3, 30, "Go", 0.0, 0.0, 10.0, 10.0, init()), button(4, 40, "Stop", 20.0, 0.0, 10.0, 10.0, init())])
|
|
220
|
+
evs := [UiEvent(id: 4, kind: Press), UiEvent(id: 4, kind: Click), UiEvent(id: 9, kind: Click), UiEvent(id: 3, kind: Click)]
|
|
221
|
+
ms := messages(view, evs)
|
|
222
|
+
assert ms.length() == 2
|
|
223
|
+
assert ms.get(0).unwrapOr(-1) == 40
|
|
224
|
+
assert ms.get(1).unwrapOr(-1) == 30
|
std/http.plum
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Buffer
|
|
4
|
+
import std/Json
|
|
5
|
+
import std/Slice
|
|
6
|
+
import std/Map
|
|
7
|
+
import std/Str
|
|
8
|
+
import std/Int
|
|
9
|
+
import std/Float
|
|
10
|
+
import std/Io
|
|
11
|
+
import std/Option
|
|
12
|
+
import std/Result
|
|
13
|
+
|
|
14
|
+
# Transport failure, or a response that is not valid HTTP.
|
|
15
|
+
enum HttpError =
|
|
16
|
+
| HttpFailed
|
|
17
|
+
| BadResponse
|
|
18
|
+
|
|
19
|
+
fun name(self) -> Str =
|
|
20
|
+
match self
|
|
21
|
+
HttpFailed => "HttpFailed"
|
|
22
|
+
BadResponse => "BadResponse"
|
|
23
|
+
|
|
24
|
+
# An HTTP response: status code, response headers, and the raw response
|
|
25
|
+
# body as a `Str` (a byte array, so binary bodies round-trip intact).
|
|
26
|
+
struct Response(status: Int, headers: Map[Str, Str], body: Str) =
|
|
27
|
+
|
|
28
|
+
# 2xx status codes are success; everything else (redirects, 4xx, 5xx) is
|
|
29
|
+
# surfaced here rather than as an error from `request` — a non-2xx
|
|
30
|
+
# response is still a complete, well-formed HTTP exchange, not a failed
|
|
31
|
+
# one (`request` itself only fails for transport-level problems like a
|
|
32
|
+
# DNS/connection error).
|
|
33
|
+
fun ok(self) -> Bool =
|
|
34
|
+
self.status >= 200 && self.status < 300
|
|
35
|
+
|
|
36
|
+
# Parses `body` as JSON. Fails the same way `Json.fromStr` does for a
|
|
37
|
+
# response body that isn't valid JSON.
|
|
38
|
+
fun json(self) -> Result[Json, JsonError] =
|
|
39
|
+
return Json.fromStr(self.body)
|
|
40
|
+
|
|
41
|
+
# A single blocking network round trip — this VM has no async/event-loop
|
|
42
|
+
# mechanism, so `rawHttpRequest` runs to completion before returning (same
|
|
43
|
+
# idea as `libs/std/os.plum`'s `rawReadFile`). `headers` is `"Key: Value"`
|
|
44
|
+
# lines joined by `\n` (`""` for none). The result packs an outcome flag,
|
|
45
|
+
# then either the status code and response headers (success) or an error
|
|
46
|
+
# message (failure), as fields joined by `\x01`, up to the first `\x00` —
|
|
47
|
+
# everything after that byte is the raw response body. `\x00`/`\x01` can
|
|
48
|
+
# never occur in the metadata fields themselves (the flag/status are
|
|
49
|
+
# decimal digits, header names/values and the error message are always
|
|
50
|
+
# plain text), so they safely mark where the opaque body bytes start even
|
|
51
|
+
# when the body itself is arbitrary binary data.
|
|
52
|
+
|
|
53
|
+
fun emptyHeaders() -> Map[Str, Str] =
|
|
54
|
+
return Map.empty()
|
|
55
|
+
|
|
56
|
+
# Packs `headers` into the `"Key: Value"`-per-line format `rawHttpRequest`
|
|
57
|
+
# expects for its own `headers` argument.
|
|
58
|
+
fun encodeHeaders(headers: Map[Str, Str]) -> Str =
|
|
59
|
+
buf := Buffer()
|
|
60
|
+
for e := range headers.entries()
|
|
61
|
+
if buf.length() > 0
|
|
62
|
+
buf.write("\n")
|
|
63
|
+
buf.write(e.first)
|
|
64
|
+
buf.write(": ")
|
|
65
|
+
buf.write(e.second)
|
|
66
|
+
return buf.toStr()
|
|
67
|
+
|
|
68
|
+
# The reverse of `encodeHeaders`, for the response headers `rawHttpRequest`
|
|
69
|
+
# packs into its result.
|
|
70
|
+
fun decodeHeaders(raw: Str) -> Map[Str, Str] =
|
|
71
|
+
result := emptyHeaders()
|
|
72
|
+
if raw == ""
|
|
73
|
+
return result
|
|
74
|
+
for line := range raw.split("\n", 0)
|
|
75
|
+
idx := line.indexOf(": ")
|
|
76
|
+
if idx >= 0
|
|
77
|
+
key := line.sub(0, idx)
|
|
78
|
+
val := line.sub(idx + 2, line.length())
|
|
79
|
+
result.set(key, val)
|
|
80
|
+
return result
|
|
81
|
+
|
|
82
|
+
# Performs a single HTTP request and waits for the full response. Fails
|
|
83
|
+
# only for a transport-level problem (DNS failure, connection refused, TLS
|
|
84
|
+
# error, ...) — an HTTP-level error status (404, 500, ...) is still a
|
|
85
|
+
# successful round trip, returned as a `Response` with that status (check
|
|
86
|
+
# `Response.ok()`). Fails with `HttpFailed` for a transport error and
|
|
87
|
+
# `BadResponse` for a reply whose status line can't be read.
|
|
88
|
+
fun request(io: Io, method: Str, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
89
|
+
raw := io.rawHttpRequest(method, url, encodeHeaders(headers), body)
|
|
90
|
+
sep := raw.indexOf("\x00")
|
|
91
|
+
meta := if sep >= 0 then raw.sub(0, sep) else raw
|
|
92
|
+
resp_body := if sep >= 0 then raw.sub(sep + 1, raw.length()) else ""
|
|
93
|
+
parts := meta.split("\x01", 3)
|
|
94
|
+
flag := parts.get(0).unwrapOr("")
|
|
95
|
+
if flag != "1"
|
|
96
|
+
return Err(HttpFailed)
|
|
97
|
+
match Int.parse(parts.get(1).unwrapOr(""))
|
|
98
|
+
Ok(status) => Ok(Response(status: status, headers: decodeHeaders(parts.get(2).unwrapOr("")), body: resp_body))
|
|
99
|
+
Err(e) => Err(BadResponse)
|
|
100
|
+
|
|
101
|
+
fun get(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
|
|
102
|
+
return request(io, "GET", url, headers, "")
|
|
103
|
+
|
|
104
|
+
fun head(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
|
|
105
|
+
return request(io, "HEAD", url, headers, "")
|
|
106
|
+
|
|
107
|
+
fun delete(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
|
|
108
|
+
return request(io, "DELETE", url, headers, "")
|
|
109
|
+
|
|
110
|
+
fun post(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
111
|
+
return request(io, "POST", url, headers, body)
|
|
112
|
+
|
|
113
|
+
fun put(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
114
|
+
return request(io, "PUT", url, headers, body)
|
|
115
|
+
|
|
116
|
+
fun patch(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
|
|
117
|
+
return request(io, "PATCH", url, headers, body)
|
|
118
|
+
|
|
119
|
+
# Convenience wrapper: sends `body` as a JSON `Str`, adding a
|
|
120
|
+
# `Content-Type: application/json` header, and parses the response back as
|
|
121
|
+
# JSON via `Response.json()`.
|
|
122
|
+
fun postJson(io: Io, url: Str, headers: Map[Str, Str], body: Json) -> Result[Response, HttpError] =
|
|
123
|
+
headers.set("Content-Type", "application/json")
|
|
124
|
+
return post(io, url, headers, body.toStr())
|
|
125
|
+
|
|
126
|
+
test "encodeHeaders/decodeHeaders round-trip a header map"
|
|
127
|
+
h := emptyHeaders()
|
|
128
|
+
h.set("Content-Type", "application/json")
|
|
129
|
+
h.set("Accept", "*/*")
|
|
130
|
+
decoded := decodeHeaders(encodeHeaders(h))
|
|
131
|
+
assert decoded.get("Content-Type")! == "application/json"
|
|
132
|
+
assert decoded.get("Accept")! == "*/*"
|
|
133
|
+
|
|
134
|
+
test "decodeHeaders returns an empty map for an empty string"
|
|
135
|
+
assert decodeHeaders("").isEmpty() == true
|
|
136
|
+
|
|
137
|
+
test "get performs a real HTTP round trip"
|
|
138
|
+
resp := get(io, "https://httpbin.org/get", emptyHeaders())!
|
|
139
|
+
assert resp.ok() == true
|
|
140
|
+
assert resp.status == 200
|
|
141
|
+
|
|
142
|
+
test "get reports a non-2xx status without failing the request"
|
|
143
|
+
resp := get(io, "https://httpbin.org/status/404", emptyHeaders())!
|
|
144
|
+
assert resp.ok() == false
|
|
145
|
+
assert resp.status == 404
|
|
146
|
+
|
|
147
|
+
test "post sends a body and the server echoes it back"
|
|
148
|
+
resp := post(io, "https://httpbin.org/post", emptyHeaders(), "hello world")!
|
|
149
|
+
assert resp.ok() == true
|
|
150
|
+
j := resp.json()!
|
|
151
|
+
assert j.asMap()!.get("data")!.asStr()! == "hello world"
|
|
152
|
+
|
|
153
|
+
test "request fails for an unreachable host"
|
|
154
|
+
resp := get(io, "http://this-host-does-not-exist.invalid/", emptyHeaders()).unwrapOr(Response(status: 0, headers: emptyHeaders(), body: ""))
|
|
155
|
+
assert resp.status == 0
|
std/math.plum
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
|
|
6
|
+
# Free-standing floating-point math: `sqrt(x)`, `sin(x)`, ... A
|
|
7
|
+
# stateless namespace, not a type.
|
|
8
|
+
# Shared `base^y` algorithm behind `Int.pow` and `Float.pow`, extracted so both the `Int`
|
|
9
|
+
# and `Float` self cases (which only differ in how `base` was obtained) share
|
|
10
|
+
# one body.
|
|
11
|
+
fun powFloat(base: Float, y: Float) -> Float =
|
|
12
|
+
if y == 0.0f
|
|
13
|
+
return 1.0f
|
|
14
|
+
yi := Int(y)
|
|
15
|
+
if Float(yi) == y
|
|
16
|
+
neg := yi < 0
|
|
17
|
+
n := if neg then -yi else yi
|
|
18
|
+
result := 1.0f
|
|
19
|
+
b := base
|
|
20
|
+
m := n
|
|
21
|
+
while m > 0
|
|
22
|
+
if m % 2 == 1
|
|
23
|
+
result = result * b
|
|
24
|
+
b = b * b
|
|
25
|
+
m = m / 2
|
|
26
|
+
return if neg then 1.0f / result else result
|
|
27
|
+
if base < 0.0f
|
|
28
|
+
return 0.0f / 0.0f
|
|
29
|
+
return exp(y * ln(base))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Natural exponential, e^x, via range reduction (halve x until |x| <= 0.5,
|
|
33
|
+
# run the Taylor series there where it converges fast, then square the
|
|
34
|
+
# result back up the same number of halvings).
|
|
35
|
+
fun exp(x: Float) -> Float =
|
|
36
|
+
if x != x
|
|
37
|
+
return x
|
|
38
|
+
if x > 700.0f
|
|
39
|
+
return 1.0f / 0.0f
|
|
40
|
+
if x < -700.0f
|
|
41
|
+
return 0.0f
|
|
42
|
+
v := x
|
|
43
|
+
k := 0
|
|
44
|
+
while v > 0.5f || v < -0.5f
|
|
45
|
+
v = v / 2.0f
|
|
46
|
+
k = k + 1
|
|
47
|
+
term := 1.0f
|
|
48
|
+
sum := 1.0f
|
|
49
|
+
n := 1
|
|
50
|
+
while n < 25
|
|
51
|
+
term = term * v / Float(n)
|
|
52
|
+
sum = sum + term
|
|
53
|
+
n = n + 1
|
|
54
|
+
result := sum
|
|
55
|
+
i := 0
|
|
56
|
+
while i < k
|
|
57
|
+
result = result * result
|
|
58
|
+
i = i + 1
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
# Natural logarithm, via range reduction to v in [1, 2) plus the
|
|
62
|
+
# fast-converging series ln(v) = 2*atanh((v-1)/(v+1)).
|
|
63
|
+
fun ln(x: Float) -> Float =
|
|
64
|
+
if x != x || x < 0.0f
|
|
65
|
+
return 0.0f / 0.0f
|
|
66
|
+
if x == 0.0f
|
|
67
|
+
return -1.0f / 0.0f
|
|
68
|
+
if x > Float.Max
|
|
69
|
+
return x
|
|
70
|
+
v := x
|
|
71
|
+
k := 0
|
|
72
|
+
while v >= 2.0f
|
|
73
|
+
v = v / 2.0f
|
|
74
|
+
k = k + 1
|
|
75
|
+
while v < 1.0f
|
|
76
|
+
v = v * 2.0f
|
|
77
|
+
k = k - 1
|
|
78
|
+
t := {v - 1.0f} / {v + 1.0f}
|
|
79
|
+
t2 := t * t
|
|
80
|
+
term := t
|
|
81
|
+
sum := t
|
|
82
|
+
n := 1
|
|
83
|
+
while n < 30
|
|
84
|
+
term = term * t2
|
|
85
|
+
sum = sum + term / Float(2 * n + 1)
|
|
86
|
+
n = n + 1
|
|
87
|
+
return Float(k) * Float.Ln2 + 2.0f * sum
|
|
88
|
+
|
|
89
|
+
# Square root via Newton's method, iterating to a fixed point.
|
|
90
|
+
fun sqrt(x: Float) -> Float =
|
|
91
|
+
if x < 0.0f
|
|
92
|
+
return 0.0f / 0.0f
|
|
93
|
+
if x == 0.0f || x != x
|
|
94
|
+
return x
|
|
95
|
+
guess := x
|
|
96
|
+
prev := 0.0f
|
|
97
|
+
i := 0
|
|
98
|
+
while guess != prev && i < 100
|
|
99
|
+
prev = guess
|
|
100
|
+
guess = 0.5f * {guess + x / guess}
|
|
101
|
+
i = i + 1
|
|
102
|
+
return guess
|
|
103
|
+
|
|
104
|
+
# Reduces `x` into roughly `[-Float.Pi, Float.Pi]` by subtracting the nearest multiple of
|
|
105
|
+
# `Float.Tau` — the range `sin`/`cos`'s Taylor series below actually converge
|
|
106
|
+
# quickly over. For very large `|x|` (many multiples of `Float.Tau`), floating-point
|
|
107
|
+
# cancellation in `x - k*Float.Tau` loses precision the same way any naive
|
|
108
|
+
# range-reduction by subtraction does; a real libm uses extended-precision
|
|
109
|
+
# constants to avoid this, which isn't attempted here.
|
|
110
|
+
fun reduceToPi(x: Float) -> Float =
|
|
111
|
+
k := Int(x / Float.Tau + {if x >= 0.0f then 0.5f else -0.5f})
|
|
112
|
+
return x - Float(k) * Float.Tau
|
|
113
|
+
|
|
114
|
+
fun sin(x: Float) -> Float =
|
|
115
|
+
if x != x || x > Float.Max || x < -Float.Max
|
|
116
|
+
return 0.0f / 0.0f
|
|
117
|
+
r := reduceToPi(x)
|
|
118
|
+
r2 := r * r
|
|
119
|
+
term := r
|
|
120
|
+
sum := r
|
|
121
|
+
n := 1
|
|
122
|
+
while n < 10
|
|
123
|
+
term = term * {-r2} / Float({2 * n} * {2 * n + 1})
|
|
124
|
+
sum = sum + term
|
|
125
|
+
n = n + 1
|
|
126
|
+
return sum
|
|
127
|
+
|
|
128
|
+
fun cos(x: Float) -> Float =
|
|
129
|
+
if x != x || x > Float.Max || x < -Float.Max
|
|
130
|
+
return 0.0f / 0.0f
|
|
131
|
+
return sin(x + Float.HalfPi)
|
|
132
|
+
|
|
133
|
+
fun tan(x: Float) -> Float =
|
|
134
|
+
return sin(x) / cos(x)
|
|
135
|
+
|
|
136
|
+
# Arctangent, via repeated argument-halving (`atan(x) = 2*atan(x / (1 +
|
|
137
|
+
# sqrt(1+x^2)))`) until `|x| <= 0.5` (where the Taylor series below converges
|
|
138
|
+
# quickly), then doubling the result back up the same number of times.
|
|
139
|
+
fun atan(x: Float) -> Float =
|
|
140
|
+
if x != x
|
|
141
|
+
return x
|
|
142
|
+
neg := x < 0.0f
|
|
143
|
+
v := if neg then -x else x
|
|
144
|
+
k := 0
|
|
145
|
+
while v > 0.5f && k < 8
|
|
146
|
+
v = v / {1.0f + sqrt(1.0f + v * v)}
|
|
147
|
+
k = k + 1
|
|
148
|
+
v2 := v * v
|
|
149
|
+
term := v
|
|
150
|
+
sum := v
|
|
151
|
+
n := 1
|
|
152
|
+
while n < 20
|
|
153
|
+
term = term * {-v2}
|
|
154
|
+
sum = sum + term / Float(2 * n + 1)
|
|
155
|
+
n = n + 1
|
|
156
|
+
scale := Float(1 << k)
|
|
157
|
+
result := sum * scale
|
|
158
|
+
return if neg then -result else result
|
|
159
|
+
|
|
160
|
+
fun asin(x: Float) -> Float =
|
|
161
|
+
if x != x || x < -1.0f || x > 1.0f
|
|
162
|
+
return 0.0f / 0.0f
|
|
163
|
+
if x == 1.0f
|
|
164
|
+
return Float.HalfPi
|
|
165
|
+
if x == -1.0f
|
|
166
|
+
return -Float.HalfPi
|
|
167
|
+
return atan(x / sqrt(1.0f - x * x))
|
|
168
|
+
|
|
169
|
+
fun acos(x: Float) -> Float =
|
|
170
|
+
return Float.HalfPi - asin(x)
|
|
171
|
+
|
|
172
|
+
# Angle (in radians) of the point `(x, y)` from the origin, in the correct
|
|
173
|
+
# quadrant for any sign combination of `x`/`y` (unlike plain `atan(y/x)`,
|
|
174
|
+
# which can't distinguish opposite quadrants).
|
|
175
|
+
fun atan2(y: Float, x: Float) -> Float =
|
|
176
|
+
if x > 0.0f
|
|
177
|
+
return atan(y / x)
|
|
178
|
+
if x < 0.0f && y >= 0.0f
|
|
179
|
+
return atan(y / x) + Float.Pi
|
|
180
|
+
if x < 0.0f && y < 0.0f
|
|
181
|
+
return atan(y / x) - Float.Pi
|
|
182
|
+
if x == 0.0f && y > 0.0f
|
|
183
|
+
return Float.HalfPi
|
|
184
|
+
if x == 0.0f && y < 0.0f
|
|
185
|
+
return -Float.HalfPi
|
|
186
|
+
return 0.0f
|
|
187
|
+
|
|
188
|
+
fun hypot(a: Float, b: Float) -> Float =
|
|
189
|
+
return sqrt(a * a + b * b)
|
|
190
|
+
|
|
191
|
+
# Cube root via Newton's method (fixed iteration count, unlike `sqrt`'s
|
|
192
|
+
# converge-to-a-fixed-point loop, since the cubic update step doesn't reach an
|
|
193
|
+
# exact fixed point in float precision as reliably as the quadratic one does).
|
|
194
|
+
fun cbrt(x: Float) -> Float =
|
|
195
|
+
if x == 0.0f || x != x
|
|
196
|
+
return x
|
|
197
|
+
neg := x < 0.0f
|
|
198
|
+
v := if neg then -x else x
|
|
199
|
+
guess := v
|
|
200
|
+
i := 0
|
|
201
|
+
while i < 60
|
|
202
|
+
guess = {2.0f * guess + v / {guess * guess}} / 3.0f
|
|
203
|
+
i = i + 1
|
|
204
|
+
return if neg then -guess else guess
|
std/mem.plum
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
|
|
6
|
+
# The program's linear memory: one growable wasm memory (16 pages of 64 KiB to
|
|
7
|
+
# start), exported to the host as "memory". Present only in programs that use
|
|
8
|
+
# `Mem`. Addresses are byte offsets; every access is little-endian and traps
|
|
9
|
+
# when out of bounds. Integers are stored as 32 bits (`storeI32` truncates,
|
|
10
|
+
# `loadI32` sign-extends) and floats as f32.
|
|
11
|
+
# Current memory size in bytes.
|
|
12
|
+
fun size() -> Int =
|
|
13
|
+
todo
|
|
14
|
+
|
|
15
|
+
# Adds `pages` 64 KiB pages; returns the old page count, or -1 on failure.
|
|
16
|
+
fun grow(pages: Int) -> Int =
|
|
17
|
+
todo
|
|
18
|
+
|
|
19
|
+
fun storeF32(addr: Int, v: Float) =
|
|
20
|
+
todo
|
|
21
|
+
|
|
22
|
+
fun storeI32(addr: Int, v: Int) =
|
|
23
|
+
todo
|
|
24
|
+
|
|
25
|
+
# Stores the low 8 bits of `v`.
|
|
26
|
+
fun storeU8(addr: Int, v: Int) =
|
|
27
|
+
todo
|
|
28
|
+
|
|
29
|
+
fun loadF32(addr: Int) -> Float =
|
|
30
|
+
todo
|
|
31
|
+
|
|
32
|
+
fun loadI32(addr: Int) -> Int =
|
|
33
|
+
todo
|
|
34
|
+
|
|
35
|
+
# The byte at `addr`, 0..255.
|
|
36
|
+
fun loadU8(addr: Int) -> Int =
|
|
37
|
+
todo
|
|
38
|
+
|
|
39
|
+
test "Mem round trips"
|
|
40
|
+
storeI32(16, -5)
|
|
41
|
+
assert loadI32(16) == -5
|
|
42
|
+
storeF32(32, 1.5f)
|
|
43
|
+
assert loadF32(32) == 1.5f
|
|
44
|
+
storeU8(40, 300)
|
|
45
|
+
assert loadU8(40) == 44
|
|
46
|
+
assert size() == 1048576
|
|
47
|
+
assert grow(1) == 16
|
|
48
|
+
assert size() == 1114112
|
std/os.plum
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Slice
|
|
4
|
+
import std/Str
|
|
5
|
+
import std/Uuid
|
|
6
|
+
import std/Random
|
|
7
|
+
import std/Int
|
|
8
|
+
import std/Float
|
|
9
|
+
import std/Io
|
|
10
|
+
import std/Option
|
|
11
|
+
import std/Result
|
|
12
|
+
|
|
13
|
+
# What the file functions that may hit either problem can fail with.
|
|
14
|
+
enum IoError =
|
|
15
|
+
| IoFailed
|
|
16
|
+
| NoSuchPath
|
|
17
|
+
|
|
18
|
+
fun name(self) -> Str = match self
|
|
19
|
+
IoFailed => "IoFailed"
|
|
20
|
+
NoSuchPath => "NoSuchPath"
|
|
21
|
+
|
|
22
|
+
# Writes the specified data, followed by the current line terminator, to the
|
|
23
|
+
# standard output stream. `extern` means this compiles to a genuine wasm import
|
|
24
|
+
# (`plum::printLn`) instead of a Plum body — printing isn't expressible in wasm
|
|
25
|
+
# on its own; the embedding host (`plum-cli run`/`plum build`) provides it.
|
|
26
|
+
|
|
27
|
+
# Raw host-provided filesystem primitives — each maps to a genuine wasm
|
|
28
|
+
# import backed by a real OS call in the embedder (`plum-cli`/`plum-runtime`),
|
|
29
|
+
# not something expressible in wasm on its own (same idea as `printLn`).
|
|
30
|
+
# Returns `Int` (0/1), not `Bool`, for the success/failure ones — the host
|
|
31
|
+
# closure that satisfies a wasm import runs BEFORE the module is instantiated
|
|
32
|
+
# (it's part of setting up the imports an instance needs), so it has no way
|
|
33
|
+
# to reach the instance's own globals; a plain `i64` has no such
|
|
34
|
+
# problem. `rawReadFile` returns `""` for a file that doesn't exist or can't
|
|
35
|
+
# be read (there's no way to signal an error through a bare `Str` return);
|
|
36
|
+
# callers needing to tell "empty file" apart from "missing file" should check
|
|
37
|
+
# `exists` first, which every wrapper below does.
|
|
38
|
+
# Every directory entry's name (not full path), joined with `\n`; `""` for a
|
|
39
|
+
# missing/unreadable directory (same ambiguity `rawReadFile` already has with
|
|
40
|
+
# an empty file — `exists`/`readdir` below both check existence first).
|
|
41
|
+
|
|
42
|
+
# NOTE: the original file modeled `stdin`/`stdout`/`stderr` as bare top-level
|
|
43
|
+
# variable bindings and a `File(...)` constructor, but this language has no
|
|
44
|
+
# top-level `let` and `File` is never defined anywhere in the stdlib. Reduced
|
|
45
|
+
# to the underlying path so this at least parses; a real `File` type is
|
|
46
|
+
# still needed here.
|
|
47
|
+
fun stdin() -> Str =
|
|
48
|
+
"/dev/stdin"
|
|
49
|
+
|
|
50
|
+
fun stdout() -> Str =
|
|
51
|
+
"/dev/stdout"
|
|
52
|
+
|
|
53
|
+
fun stderr() -> Str =
|
|
54
|
+
"/dev/stderr"
|
|
55
|
+
|
|
56
|
+
# Reads the whole file at `path` as a `Str` (`Str` is a byte array here — see
|
|
57
|
+
# `libs/std/str.plum` — so this works for binary content too, not just text).
|
|
58
|
+
fun readFile(io: Io, path: Str) -> Result[Str, IoError] =
|
|
59
|
+
if !exists(io, path)
|
|
60
|
+
return Err(NoSuchPath)
|
|
61
|
+
return Ok(io.rawReadFile(path))
|
|
62
|
+
|
|
63
|
+
# Writes `data` to `path`, replacing its previous contents (or creating it).
|
|
64
|
+
fun writeFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
|
|
65
|
+
if io.rawWriteFile(path, data) != 1
|
|
66
|
+
return Err(IoFailed)
|
|
67
|
+
Ok(Unit)
|
|
68
|
+
|
|
69
|
+
fun exists(io: Io, path: Str) -> Bool =
|
|
70
|
+
return io.rawExists(path) == 1
|
|
71
|
+
|
|
72
|
+
fun mkdir(io: Io, path: Str) -> Result[Unit, IoError] =
|
|
73
|
+
if io.rawMkdir(path) != 1
|
|
74
|
+
return Err(IoFailed)
|
|
75
|
+
Ok(Unit)
|
|
76
|
+
|
|
77
|
+
# Removes the file (not directory) at `path`.
|
|
78
|
+
fun remove(io: Io, path: Str) -> Result[Unit, IoError] =
|
|
79
|
+
if !exists(io, path)
|
|
80
|
+
return Err(NoSuchPath)
|
|
81
|
+
if io.rawRemove(path) != 1
|
|
82
|
+
return Err(IoFailed)
|
|
83
|
+
Ok(Unit)
|
|
84
|
+
|
|
85
|
+
# Whether `path` exists and is reachable — this VM has no notion of a
|
|
86
|
+
# process' effective uid/gid, so (unlike POSIX `access(2)`) there is no mode
|
|
87
|
+
# argument to check permission bits against.
|
|
88
|
+
fun access(io: Io, path: Str) -> Bool =
|
|
89
|
+
return exists(io, path)
|
|
90
|
+
|
|
91
|
+
# Appends `data` to the file at `path`, creating it (with just `data` as its
|
|
92
|
+
# contents) if it doesn't already exist. There's no host-level "open for
|
|
93
|
+
# append" primitive, so this reads the existing bytes and writes the
|
|
94
|
+
# concatenation back — not atomic, and O(existing file size) per call.
|
|
95
|
+
fun appendFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
|
|
96
|
+
if exists(io, path)
|
|
97
|
+
existing := readFile(io, path)?
|
|
98
|
+
return writeFile(io, path, existing + data)
|
|
99
|
+
writeFile(io, path, data)
|
|
100
|
+
|
|
101
|
+
# Unix permission bits only (e.g. `0o644`) — this VM has no Windows ACL
|
|
102
|
+
# equivalent to fall back to.
|
|
103
|
+
fun chmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
|
|
104
|
+
if io.rawChmod(path, mode) != 1
|
|
105
|
+
return Err(IoFailed)
|
|
106
|
+
Ok(Unit)
|
|
107
|
+
|
|
108
|
+
# There is no host primitive for changing file ownership (it needs a uid/gid
|
|
109
|
+
# syscall this VM doesn't expose), unlike the permission-bits-only `chmod`.
|
|
110
|
+
fun chown(path: Str, uid: Int, gid: Int) =
|
|
111
|
+
todo
|
|
112
|
+
|
|
113
|
+
fun copyFile(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
|
|
114
|
+
data := readFile(io, src)?
|
|
115
|
+
writeFile(io, dest, data)
|
|
116
|
+
|
|
117
|
+
fun cp(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
|
|
118
|
+
copyFile(io, src, dest)
|
|
119
|
+
|
|
120
|
+
# Symlinks aren't modeled separately from regular files/dirs by this VM's
|
|
121
|
+
# host primitives (`rawChmod` always follows them), so this is the same as
|
|
122
|
+
# `chmod`.
|
|
123
|
+
fun lchmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
|
|
124
|
+
chmod(io, path, mode)
|
|
125
|
+
|
|
126
|
+
# See `chown` — no uid/gid syscall exposed by this VM.
|
|
127
|
+
fun lchown(path: Str, uid: Int, gid: Int) =
|
|
128
|
+
todo
|
|
129
|
+
|
|
130
|
+
# Setting a file's atime/mtime needs a syscall (`utimensat`/`SetFileTime`)
|
|
131
|
+
# this VM doesn't expose (`std::fs` itself has no equivalent either).
|
|
132
|
+
fun lutimes(path: Str, atime: Int, mtime: Int) =
|
|
133
|
+
todo
|
|
134
|
+
|
|
135
|
+
fun link(io: Io, existing_path: Str, new_path: Str) -> Result[Unit, IoError] =
|
|
136
|
+
if io.rawLink(existing_path, new_path) != 1
|
|
137
|
+
return Err(IoFailed)
|
|
138
|
+
Ok(Unit)
|
|
139
|
+
|
|
140
|
+
# Would need a real `Stat` struct type (size/mode/mtime/uid/gid/...) to
|
|
141
|
+
# return anything useful — no such type exists in the stdlib yet.
|
|
142
|
+
fun lstat(path: Str) =
|
|
143
|
+
todo
|
|
144
|
+
|
|
145
|
+
# Creates a fresh directory named `prefix` followed by a random suffix,
|
|
146
|
+
# retrying on the (astronomically unlikely) chance of a collision, and
|
|
147
|
+
# returns the path actually created.
|
|
148
|
+
fun mkdtemp(io: Io, prefix: Str) -> Result[Str, IoError] =
|
|
149
|
+
path := prefix + Uuid.v4(Random.seeded(io.randomSeed())).value.toStr()
|
|
150
|
+
if exists(io, path)
|
|
151
|
+
return mkdtemp(io, prefix)
|
|
152
|
+
mkdir(io, path)?
|
|
153
|
+
return Ok(path)
|
|
154
|
+
|
|
155
|
+
# Would need a host-side open-file-descriptor table (this VM's other file
|
|
156
|
+
# ops are all one-shot: open+read/write+close in a single host call) plus a
|
|
157
|
+
# `File` handle type — neither exists yet.
|
|
158
|
+
fun open(path: Str, flags: Int) =
|
|
159
|
+
todo
|
|
160
|
+
|
|
161
|
+
# See `open` — same missing handle-table/type problem, for directories.
|
|
162
|
+
fun opendir(path: Str) =
|
|
163
|
+
todo
|
|
164
|
+
|
|
165
|
+
# The names of `path`'s directory entries (not full paths).
|
|
166
|
+
fun readdir(io: Io, path: Str) -> Result[Slice[Str], IoError] =
|
|
167
|
+
if !exists(io, path)
|
|
168
|
+
return Err(NoSuchPath)
|
|
169
|
+
# skipping empty names handles both a genuinely empty directory (whose
|
|
170
|
+
# joined `""` would otherwise split into one bogus `""` entry) and
|
|
171
|
+
# `rawReadDir`'s "unreadable" fallback (already ruled out by the `exists`
|
|
172
|
+
# check above) the same way — no directory entry is ever named `""`.
|
|
173
|
+
names := Slice[Str]()
|
|
174
|
+
for n := range io.rawReadDir(path).split("\n", 0)
|
|
175
|
+
if n != ""
|
|
176
|
+
names.push(n)
|
|
177
|
+
return Ok(names)
|
|
178
|
+
|
|
179
|
+
fun readlink(io: Io, path: Str) -> Result[Str, IoError] =
|
|
180
|
+
if !exists(io, path)
|
|
181
|
+
return Err(NoSuchPath)
|
|
182
|
+
return Ok(io.rawReadlink(path))
|
|
183
|
+
|
|
184
|
+
fun realpath(io: Io, path: Str) -> Result[Str, IoError] =
|
|
185
|
+
if !exists(io, path)
|
|
186
|
+
return Err(NoSuchPath)
|
|
187
|
+
return Ok(io.rawRealpath(path))
|
|
188
|
+
|
|
189
|
+
fun rename(io: Io, old_path: Str, new_path: Str) -> Result[Unit, IoError] =
|
|
190
|
+
if !exists(io, old_path)
|
|
191
|
+
return Err(NoSuchPath)
|
|
192
|
+
if io.rawRename(old_path, new_path) != 1
|
|
193
|
+
return Err(IoFailed)
|
|
194
|
+
Ok(Unit)
|
|
195
|
+
|
|
196
|
+
# Removes an empty directory. (`remove` above covers plain files.)
|
|
197
|
+
fun rmdir(io: Io, path: Str) -> Result[Unit, IoError] =
|
|
198
|
+
if !exists(io, path)
|
|
199
|
+
return Err(NoSuchPath)
|
|
200
|
+
if io.rawRemoveDir(path) != 1
|
|
201
|
+
return Err(IoFailed)
|
|
202
|
+
Ok(Unit)
|
|
203
|
+
|
|
204
|
+
# See `lstat` — needs a `Stat` struct type.
|
|
205
|
+
fun stat(path: Str) =
|
|
206
|
+
todo
|
|
207
|
+
|
|
208
|
+
# Needs a filesystem-info struct type, same gap as `stat`.
|
|
209
|
+
fun statfs(path: Str) =
|
|
210
|
+
todo
|
|
211
|
+
|
|
212
|
+
fun symlink(io: Io, target: Str, path: Str) -> Result[Unit, IoError] =
|
|
213
|
+
if io.rawSymlink(target, path) != 1
|
|
214
|
+
return Err(IoFailed)
|
|
215
|
+
Ok(Unit)
|
|
216
|
+
|
|
217
|
+
# Resizes the file at `path` to exactly `len` bytes — truncated if shorter,
|
|
218
|
+
# zero-padded if longer.
|
|
219
|
+
fun truncate(io: Io, path: Str, len: Int) -> Result[Unit, IoError] =
|
|
220
|
+
if !exists(io, path)
|
|
221
|
+
return Err(NoSuchPath)
|
|
222
|
+
if io.rawTruncate(path, len) != 1
|
|
223
|
+
return Err(IoFailed)
|
|
224
|
+
Ok(Unit)
|
|
225
|
+
|
|
226
|
+
# See `lutimes` — same missing syscall.
|
|
227
|
+
fun utimes(path: Str, atime: Int, mtime: Int) =
|
|
228
|
+
todo
|
|
229
|
+
|
|
230
|
+
# Would need an async/callback mechanism to deliver filesystem change events
|
|
231
|
+
# into a running Plum program — nothing like that exists in this VM (every
|
|
232
|
+
# host call here is a synchronous, one-shot request/response).
|
|
233
|
+
fun watch(filename: Str) =
|
|
234
|
+
todo
|
|
235
|
+
|
|
236
|
+
test "writeFile/readFile/appendFile/remove round-trip on a real file"
|
|
237
|
+
dir := mkdtemp(io, "/tmp/plum_os_test_")!
|
|
238
|
+
path := dir + "/a.txt"
|
|
239
|
+
writeFile(io, path, "hello")!
|
|
240
|
+
assert readFile(io, path)! == "hello"
|
|
241
|
+
appendFile(io, path, " world")!
|
|
242
|
+
assert readFile(io, path)! == "hello world"
|
|
243
|
+
assert exists(io, path) == true
|
|
244
|
+
remove(io, path)!
|
|
245
|
+
assert exists(io, path) == false
|
|
246
|
+
rmdir(io, dir)!
|
|
247
|
+
|
|
248
|
+
test "copyFile/cp/rename move and duplicate file contents correctly"
|
|
249
|
+
dir := mkdtemp(io, "/tmp/plum_os_test_")!
|
|
250
|
+
a := dir + "/a.txt"
|
|
251
|
+
b := dir + "/b.txt"
|
|
252
|
+
c := dir + "/c.txt"
|
|
253
|
+
writeFile(io, a, "data")!
|
|
254
|
+
copyFile(io, a, b)!
|
|
255
|
+
assert readFile(io, b)! == "data"
|
|
256
|
+
rename(io, b, c)!
|
|
257
|
+
assert exists(io, b) == false
|
|
258
|
+
assert readFile(io, c)! == "data"
|
|
259
|
+
remove(io, a)!
|
|
260
|
+
remove(io, c)!
|
|
261
|
+
rmdir(io, dir)!
|
|
262
|
+
|
|
263
|
+
test "readdir lists the entries created in a fresh directory"
|
|
264
|
+
dir := mkdtemp(io, "/tmp/plum_os_test_")!
|
|
265
|
+
assert readdir(io, dir)!.length() == 0
|
|
266
|
+
writeFile(io, dir + "/only.txt", "x")!
|
|
267
|
+
names := readdir(io, dir)!
|
|
268
|
+
assert names.length() == 1
|
|
269
|
+
assert names.join(",") == "only.txt"
|
|
270
|
+
remove(io, dir + "/only.txt")!
|
|
271
|
+
rmdir(io, dir)!
|
|
272
|
+
|
|
273
|
+
test "symlink/readlink/realpath resolve a linked file correctly"
|
|
274
|
+
dir := mkdtemp(io, "/tmp/plum_os_test_")!
|
|
275
|
+
target := dir + "/target.txt"
|
|
276
|
+
link_path := dir + "/link.txt"
|
|
277
|
+
writeFile(io, target, "linked")!
|
|
278
|
+
symlink(io, target, link_path)!
|
|
279
|
+
assert readlink(io, link_path)! == target
|
|
280
|
+
assert readFile(io, link_path)! == "linked"
|
|
281
|
+
_ := realpath(io, link_path)!
|
|
282
|
+
remove(io, link_path)!
|
|
283
|
+
remove(io, target)!
|
|
284
|
+
rmdir(io, dir)!
|
|
285
|
+
|
|
286
|
+
test "truncate resizes a file's contents"
|
|
287
|
+
dir := mkdtemp(io, "/tmp/plum_os_test_")!
|
|
288
|
+
path := dir + "/a.txt"
|
|
289
|
+
writeFile(io, path, "hello world")!
|
|
290
|
+
truncate(io, path, 5)!
|
|
291
|
+
assert readFile(io, path)! == "hello"
|
|
292
|
+
remove(io, path)!
|
|
293
|
+
rmdir(io, dir)!
|
|
294
|
+
|
|
295
|
+
test "chmod changes a file's permission bits"
|
|
296
|
+
dir := mkdtemp(io, "/tmp/plum_os_test_")!
|
|
297
|
+
path := dir + "/a.txt"
|
|
298
|
+
writeFile(io, path, "x")!
|
|
299
|
+
chmod(io, path, 384)! # 0o600
|
|
300
|
+
remove(io, path)!
|
|
301
|
+
rmdir(io, dir)!
|
|
302
|
+
|
|
303
|
+
test "link creates a second name for the same file"
|
|
304
|
+
dir := mkdtemp(io, "/tmp/plum_os_test_")!
|
|
305
|
+
a := dir + "/a.txt"
|
|
306
|
+
b := dir + "/b.txt"
|
|
307
|
+
writeFile(io, a, "shared")!
|
|
308
|
+
link(io, a, b)!
|
|
309
|
+
assert readFile(io, b)! == "shared"
|
|
310
|
+
remove(io, a)!
|
|
311
|
+
remove(io, b)!
|
|
312
|
+
rmdir(io, dir)!
|
|
313
|
+
|
|
314
|
+
test "readFile/remove/rmdir report errors for missing paths"
|
|
315
|
+
assert readFile(io, "/tmp/plum_os_test_does_not_exist.txt").unwrapOr("gone") == "gone"
|
|
316
|
+
failed := 0
|
|
317
|
+
if Err(e) := remove(io, "/tmp/plum_os_test_does_not_exist.txt")
|
|
318
|
+
failed = failed + 1
|
|
319
|
+
if Err(e) := rmdir(io, "/tmp/plum_os_test_does_not_exist_dir")
|
|
320
|
+
failed = failed + 1
|
|
321
|
+
assert failed == 2
|
std/{Testing.plum → testing.plum}
RENAMED
|
@@ -11,8 +11,8 @@ import std/Result
|
|
|
11
11
|
# Small jest/rspec-style assertion helpers for use inside `test` blocks, e.g.
|
|
12
12
|
#
|
|
13
13
|
# test "add works"
|
|
14
|
-
# assert
|
|
14
|
+
# assert expectEq(add(1, 2), 3)
|
|
15
|
-
# assert
|
|
15
|
+
# assert expectTrue(isEven(4))
|
|
16
16
|
#
|
|
17
17
|
# These are statics returning `Bool` (`assert` only takes a bare
|
|
18
18
|
# boolean expression — see `compiler/core/parser.rs`'s `assert` rule), not a new
|
|
@@ -34,42 +34,41 @@ import std/Result
|
|
|
34
34
|
# those types, prefer the type's own `equals(self, other)` method (e.g.
|
|
35
35
|
# `Uuid.equals`, `Time.equals`) directly in `assert` instead.
|
|
36
36
|
|
|
37
|
-
primitive Testing =
|
|
38
|
-
|
|
37
|
+
fun expectTrue(cond: Bool) -> Bool =
|
|
39
|
-
|
|
38
|
+
cond
|
|
40
39
|
|
|
41
|
-
|
|
40
|
+
fun expectFalse(cond: Bool) -> Bool =
|
|
42
|
-
|
|
41
|
+
!cond
|
|
43
42
|
|
|
44
|
-
|
|
43
|
+
fun expectEq[T](a: T, b: T) -> Bool =
|
|
45
|
-
|
|
44
|
+
a == b
|
|
46
45
|
|
|
47
|
-
|
|
46
|
+
fun expectNotEq[T](a: T, b: T) -> Bool =
|
|
48
|
-
|
|
47
|
+
a != b
|
|
49
48
|
|
|
50
|
-
|
|
49
|
+
# See the module-level CAVEAT above — this is `expectEq` under a name that
|
|
51
|
-
|
|
50
|
+
# reads better at a class/struct call site; it does NOT do structural
|
|
52
|
-
|
|
51
|
+
# (field-by-field) comparison.
|
|
53
|
-
|
|
52
|
+
fun expectObject[T](a: T, b: T) -> Bool =
|
|
54
|
-
|
|
53
|
+
a == b
|
|
55
54
|
|
|
56
|
-
|
|
55
|
+
# Elementwise `Slice[T]` comparison — see the module-level CAVEAT above for
|
|
57
|
-
|
|
56
|
+
# what `Slice.equals`'s own `==` means when `T` is a class/enum.
|
|
58
|
-
|
|
57
|
+
fun expectArray[T](a: Slice[T], b: Slice[T]) -> Bool =
|
|
59
|
-
|
|
58
|
+
a.equals(b)
|
|
60
59
|
|
|
61
|
-
|
|
60
|
+
fun expectSuccess[T, E](r: Result[T, E]) -> Bool = match r
|
|
62
|
-
|
|
61
|
+
Ok(_) => true
|
|
63
|
-
|
|
62
|
+
Err(_) => false
|
|
64
63
|
|
|
65
|
-
|
|
64
|
+
fun expectFailure[T, E](r: Result[T, E]) -> Bool = match r
|
|
66
|
-
|
|
65
|
+
Ok(_) => false
|
|
67
|
-
|
|
66
|
+
Err(_) => true
|
|
68
67
|
|
|
69
|
-
|
|
68
|
+
# True when `r` failed with the error named `name`.
|
|
70
|
-
|
|
69
|
+
fun expectFailureNamed[T, E](r: Result[T, E], name: Str) -> Bool = match r
|
|
71
|
-
|
|
70
|
+
Ok(_) => false
|
|
72
|
-
|
|
71
|
+
Err(e) => e.name() == name
|
|
73
72
|
|
|
74
73
|
# The error enum the tests below use.
|
|
75
74
|
enum Oops =
|
|
@@ -81,20 +80,20 @@ enum Oops =
|
|
|
81
80
|
Worse => "Worse"
|
|
82
81
|
|
|
83
82
|
test "expectTrue and expectFalse"
|
|
84
|
-
assert
|
|
83
|
+
assert expectTrue(1 == 1)
|
|
85
|
-
assert
|
|
84
|
+
assert expectFalse(1 == 2)
|
|
86
85
|
|
|
87
86
|
test "expectEq and expectNotEq"
|
|
88
|
-
assert
|
|
87
|
+
assert expectEq(2 + 2, 4)
|
|
89
|
-
assert
|
|
88
|
+
assert expectEq("ab" + "c", "abc")
|
|
90
|
-
assert
|
|
89
|
+
assert expectNotEq(2 + 2, 5)
|
|
91
90
|
|
|
92
91
|
test "list equality via the Slice.equals method"
|
|
93
92
|
a := [1, 2, 3].toSlice()
|
|
94
93
|
b := [1, 2, 3].toSlice()
|
|
95
94
|
c := [1, 2].toSlice()
|
|
96
95
|
assert a.equals(b)
|
|
97
|
-
assert
|
|
96
|
+
assert expectFalse(a.equals(c))
|
|
98
97
|
|
|
99
98
|
test "Results are inspected with unwrapOr and !"
|
|
100
99
|
ok: Result[Int, Oops] := Ok(5)
|
|
@@ -106,18 +105,18 @@ test "expectArray compares two Slice[T]s elementwise"
|
|
|
106
105
|
a := [1, 2, 3].toSlice()
|
|
107
106
|
b := [1, 2, 3].toSlice()
|
|
108
107
|
c := [1, 2].toSlice()
|
|
109
|
-
assert
|
|
108
|
+
assert expectArray(a, b)
|
|
110
|
-
assert
|
|
109
|
+
assert expectFalse(expectArray(a, c))
|
|
111
110
|
d := ["x", "y"].toSlice()
|
|
112
111
|
e := ["x", "y"].toSlice()
|
|
113
|
-
assert
|
|
112
|
+
assert expectArray(d, e)
|
|
114
113
|
|
|
115
114
|
test "expectSuccess/expectFailure check the right variant"
|
|
116
115
|
ok: Result[Int, Oops] := Ok(5)
|
|
117
116
|
bad: Result[Int, Oops] := Err(Bad)
|
|
118
|
-
assert
|
|
117
|
+
assert expectSuccess(ok)
|
|
119
|
-
assert
|
|
118
|
+
assert expectFalse(expectSuccess(bad))
|
|
120
|
-
assert
|
|
119
|
+
assert expectFailure(bad)
|
|
121
|
-
assert
|
|
120
|
+
assert expectFalse(expectFailure(ok))
|
|
122
|
-
assert
|
|
121
|
+
assert expectFailureNamed(bad, "Bad")
|
|
123
|
-
assert
|
|
122
|
+
assert expectFalse(expectFailureNamed(ok, "Bad"))
|
tests/modules/Palette.plum
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
|
|
3
|
+
# A module whose file name is capitalised: importers call it `palette` (the last path
|
|
4
|
+
# segment, lowercased).
|
|
5
|
+
|
|
6
|
+
Dark = 10
|
|
7
|
+
|
|
8
|
+
fun shade(x: Int) -> Int = x - Dark
|