plum

#treesitter#compiler#wasm

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

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


d719176 — Peter John 2026-11-10T14:35:16+05:30
std: os becomes the Os namespace
benchmarks/scene_trees/scene_tree.plum CHANGED
@@ -3,7 +3,7 @@ import std/Float
3
3
  import std/Bool
4
4
  import std/Str
5
5
  import std/Io
6
- import std/os
6
+ import std/Os
7
7
  import std/Option
8
8
  import std/Result
9
9
  import std/collections/List
@@ -302,7 +302,7 @@ fun run(io: Io, w: Int, n: Int) -> Int =
302
302
  sum
303
303
 
304
304
  fun main(io: Io) =
305
- args := os.readFile(io, "scene_trees.args").unwrapOr("").trim().split(" ", 2)
305
+ args := Os.readFile(io, "scene_trees.args").unwrapOr("").trim().split(" ", 2)
306
306
  if args.length() == 2
307
307
  _ := run(io, Int.parse(args.at(0)).unwrapOr(1), Int.parse(args.at(1)).unwrapOr(100))
308
308
  else
compiler/core/src/ast.rs CHANGED
@@ -621,7 +621,7 @@ pub struct Fn {
621
621
  /// each bounded one.
622
622
  pub bounds: Vec<(String, Vec<Type>)>,
623
623
  /// `extern fun foo(...)` — declares a function with no Plum body, backed
624
- /// instead by a host-provided wasm import (see `libs/std/os.plum`'s
624
+ /// instead by a host-provided wasm import (see std/Io's
625
625
  /// `printLn`). `plum-checker` requires this to agree with `body` being
626
626
  /// `FnBody::Extern`, and requires `type_param` to be `None` (no extern methods).
627
627
  pub is_extern: bool,
compiler/core/tests/core/formatter_test.rs CHANGED
@@ -16,7 +16,7 @@ fn rejectsSyntaxError() {
16
16
  fn keywordsGetSpacedCorrectly() {
17
17
  let input = "\
18
18
  module test
19
- import std/os
19
+ import std/Os
20
20
 
21
21
  enum Cat =
22
22
  | Cat(name: Str, age: Int)
@@ -42,7 +42,7 @@ fun main() =
42
42
  ";
43
43
  let once = formatSource(input).expect("first pass");
44
44
  assert!(once.contains("module test"), "got: {once}");
45
- assert!(once.contains("import std/os"), "got: {once}");
45
+ assert!(once.contains("import std/Os"), "got: {once}");
46
46
  assert!(once.contains("enum Cat"), "got: {once}");
47
47
  assert!(once.contains("fun speak"), "got: {once}");
48
48
  assert!(once.contains("if x < 0"), "got: {once}");
@@ -51,7 +51,7 @@ fun main() =
51
51
  assert_eq!(once, twice, "formatting should be idempotent");
52
52
  }
53
53
 
54
- /// Regression test: `import std/os` used to format down to `import /` — the
54
+ /// Regression test: `import std/Os` used to format down to `import /` — the
55
55
  /// `url` grammar rule matched each path segment with a bare inline regex (no
56
56
  /// node of its own), and Topiary's leaf collection only ever copies a
57
57
  /// child NODE's own span, silently dropping any parent text a bare regex
compiler/game/tests/fixtures/assets_fixture.plum CHANGED
@@ -3,7 +3,7 @@ module assets_fixture
3
3
  import std/Int
4
4
  import std/Float
5
5
  import std/Str
6
- import std/os
6
+ import std/Os
7
7
  import std/math/Vec2
8
8
  import std/game/Color
9
9
  import std/game/gfx
compiler/game/tests/fixtures/host_fixture.plum CHANGED
@@ -3,7 +3,7 @@ module host_fixture
3
3
  import std/Int
4
4
  import std/Float
5
5
  import std/Str
6
- import std/os
6
+ import std/Os
7
7
  import std/math/Vec2
8
8
  import std/game/Color
9
9
  import std/game/gfx
compiler/lsp/src/completion.rs CHANGED
@@ -575,9 +575,9 @@ pub fn stdLibIndex(lib_path: &Path) -> HashMap<String, String> {
575
575
  continue;
576
576
  };
577
577
  let source = plum_core::AstParser::new(&text).parseSourceRaw(tree.root_node());
578
- // A file with module-level functions or constants is a module: its name (`os`,
578
+ // A file with module-level functions or constants is a module: its name (`http`,
579
579
  // `gfx`) is what completion offers and auto-imports. The functions themselves
580
- // are written `os.readFile(..)`, so they are not indexed by name.
580
+ // are written `http.get(..)`, so they are not indexed by name.
581
581
  let isModule = source.items.iter().any(|i| match i {
582
582
  ast::Item::Fn(f) => f.type_param.is_none() && !f.is_test,
583
583
  ast::Item::Const(c) => !c.name.contains(ast::MEMBER_SEP),
compiler/lsp/src/main.rs CHANGED
@@ -712,13 +712,13 @@ mod tests {
712
712
  let _ = std::fs::remove_dir_all(&dir);
713
713
  }
714
714
 
715
- /// The std modules (`os`, `testing`, `http`) and namespaces (`Base64`) are indexed for
715
+ /// The std modules (`testing`, `http`) and namespaces (`Os`, `Base64`) are indexed for
716
- /// auto-import by name and complete their functions after `name.`.
716
+ /// auto-import by name, and a namespace completes its functions after `Name.`.
717
717
  #[test]
718
718
  fn stdNamespacesCompleteAndAutoImport() {
719
719
  let index = completion::stdLibIndex(&repoRoot());
720
720
  for (name, path) in [
721
- ("os", "std/os"),
721
+ ("Os", "std/Os"),
722
722
  ("Base64", "std/encoding/Base64"),
723
723
  ("testing", "std/testing"),
724
724
  ("http", "std/http"),
@@ -732,6 +732,8 @@ mod tests {
732
732
  ] {
733
733
  assert_eq!(index.get(name).map(String::as_str), Some(path), "{name}");
734
734
  }
735
+ // The files are `primitive` namespaces now, not modules: no `os` or `base64` alias.
736
+ assert!(index.get("os").is_none() && index.get("base64").is_none());
735
737
  // Completing `Io` offers `std/Io` and auto-imports that path.
736
738
  let edit = completion::importInsertionEdit(
737
739
  "module t\nimport std/Int\n",
@@ -741,7 +743,7 @@ mod tests {
741
743
  let dir = std::env::temp_dir().join(format!("plum-lsp-ns-{}", std::process::id()));
742
744
  std::fs::create_dir_all(&dir).unwrap();
743
745
  let path = dir.join("t.plum");
744
- let text = "module t\nimport std/Int\nimport std/Str\nimport std/os\n\nfun main() =\n x := os.zzzzzz\n";
746
+ let text = "module t\nimport std/Int\nimport std/Str\nimport std/Os\nimport std/encoding/Base64\n\nfun main() =\n x := Os.zzzzzz\n";
745
747
  std::fs::write(&path, text).unwrap();
746
748
  let labels = |recv: &str| -> Vec<String> {
747
749
  memberCompletionFor(&path, &repoRoot(), text, 7, recv)
@@ -749,23 +751,17 @@ mod tests {
749
751
  .map(|i| i.label)
750
752
  .collect()
751
753
  };
752
- let os = labels("os");
754
+ let os = labels("Os");
753
755
  assert!(
754
756
  os.iter().any(|l| l == "readFile") && os.iter().any(|l| l == "writeFile"),
755
757
  "{os:?}"
756
758
  );
757
- // `Base64` is a namespace (`primitive Base64 =`): its statics complete after `Base64.`.
758
- let text = "module t\nimport std/Int\nimport std/Str\nimport std/encoding/Base64\n\nfun main() =\n x := Base64.zzzzzz\n";
759
- std::fs::write(&path, text).unwrap();
759
+ let b64 = labels("Base64");
760
- let b64: Vec<String> = memberCompletionFor(&path, &repoRoot(), text, 6, "Base64")
761
- .into_iter()
762
- .map(|i| i.label)
763
- .collect();
764
760
  assert!(
765
761
  b64.iter().any(|l| l == "encode") && b64.iter().any(|l| l == "decode"),
766
762
  "{b64:?}"
767
763
  );
768
- // A module's functions are not indexed by name: they are written `os.readFile`.
764
+ // A namespace's functions are not indexed by name: they are written `Os.readFile`.
769
765
  assert!(index.get("readFile").is_none() && index.get("encode").is_none());
770
766
  let _ = std::fs::remove_dir_all(&dir);
771
767
  }
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -88,7 +88,7 @@ module.exports = grammar({
88
88
  // directly in a `seq` (as this used to be) leaves the text it matches
89
89
  // with no node of its own, which Topiary's leaf-collection silently
90
90
  // drops entirely (it only copies each CHILD's own span, never a parent's
91
- // "gap" text) — `import std/os` formatted down to `import /`.
91
+ // "gap" text) — `import std/Os` formatted down to `import /`.
92
92
  url: ($) => sep1($.url_segment, "/"),
93
93
  url_segment: (_) => /[a-zA-Z_][a-zA-Z_0-9]*/,
94
94
 
@@ -249,7 +249,7 @@ module.exports = grammar({
249
249
  seq(
250
250
  // `extern fun foo(...)` (no `=` body at all) declares a function backed
251
251
  // by a host-provided wasm import instead of a compiled Plum body — see
252
- // `libs/std/os.plum`'s `printLn`. Whether the body is actually present
252
+ // std/Io's `printLn`. Whether the body is actually present
253
253
  // vs. legitimately absent is enforced by `plum-checker` (a clear semantic
254
254
  // error either way), not the grammar, to keep this rule simple.
255
255
  // `export fun foo(...) = ...` is a normal function that is also exported from
compiler/tooling/tree-sitter-plum/queries/plum/format.scm CHANGED
@@ -36,7 +36,7 @@
36
36
  ; ============================================================
37
37
  ; Binary operators — space before and after. Scoped to the specific
38
38
  ; operator-expression node types they appear in (NOT bare tokens):
39
- ; "/" is also the bare separator inside a `url` (`std/os`), which
39
+ ; "/" is also the bare separator inside a `url` (`std/Os`), which
40
40
  ; must stay glued with no spaces — matching it unscoped would insert
41
41
  ; spaces there too and make the import unparseable on a second pass.
42
42
  ; ============================================================
compiler/wasm-codegen/tests/wasm_codegen/examples_test.rs CHANGED
@@ -34,7 +34,7 @@ fn assertCompiles(name: &str) -> Vec<u8> {
34
34
  /// basics.plum exercises `extern fun` (see `Fn.is_extern`/`FnBody::Extern` in
35
35
  /// plum-core/src/ast.rs and their handling in plum-wasm-codegen/src/lib.rs) — it
36
36
  /// declares its own `extern fun printLn(s: Str)` (redeclared locally rather than a
37
- /// real `import std/os`, to keep this fixture self-contained for the single-file
37
+ /// real `import std/Os`, to keep this fixture self-contained for the single-file
38
38
  /// parse/check this test and plum-checker's examples test do), which codegen turns
39
39
  /// into a genuine wasm `(import "plum" "printLn" ...)` instead of a compiled body.
40
40
  /// Runs it for real, providing the import as a host function that records what
docs/language.md CHANGED
@@ -750,10 +750,10 @@ Everything that leaves your program goes through an `Io` value: printing, files,
750
750
  ```plum
751
751
  import std/Io
752
752
  import std/Str
753
- import std/os
753
+ import std/Os
754
754
 
755
755
  fun main(io: Io) =
756
- match os.readFile(io, "notes.txt")
756
+ match Os.readFile(io, "notes.txt")
757
757
  Ok(text) => io.printLn(text)
758
758
  Err(e) => io.printLn("could not read the file")
759
759
  ```
docs/std.md CHANGED
@@ -14,7 +14,7 @@ The [game engine](game.md) has its own page.
14
14
  | [`AvlTree`, `Trie`, `Graph`, ...](#persistent-trees-heaps-and-graphs) | persistent trees, heaps and graphs |
15
15
  | [`Option`, `Result`](#option-and-result) | missing values and failures |
16
16
  | [`Json`](#json) | reading and writing JSON |
17
- | [`os`, `http`](#files-and-network) | files and the network |
17
+ | [`Os`, `http`](#files-and-network) | files and the network |
18
18
  | [`Time`, `Random`, `Uuid`, `Base64`, `Aabb`, `ref`](#utilities) | utilities |
19
19
  | [`testing`](#testing) | helpers for tests |
20
20
  | [`game/Store`](#game-state-store) | a game's state as a `Reducer`, and its messages |
@@ -195,16 +195,16 @@ All of these need an `Io` and return a `Result`.
195
195
  ```plum
196
196
  import std/Io
197
197
  import std/Str
198
- import std/os
198
+ import std/Os
199
199
  import std/http
200
200
 
201
201
  fun main(io: Io) =
202
- _ := os.writeFile(io, "note.txt", "hello")
202
+ _ := Os.writeFile(io, "note.txt", "hello")
203
- text := os.readFile(io, "note.txt").unwrapOr("")
203
+ text := Os.readFile(io, "note.txt").unwrapOr("")
204
204
  io.printLn(text)
205
205
  ```
206
206
 
207
- - **`os`:** `readFile`, `writeFile`, `appendFile`, `exists`, `mkdir`, `remove`, `rename`, `copyFile`, `readdir`. There is no `stat`, `open`, `chown` or `utimes`: the host has no such call.
207
+ - **`Os`** (statics: `Os.readFile(io, path)`): `readFile`, `writeFile`, `appendFile`, `exists`, `mkdir`, `rmdir`, `remove`, `rename`, `copyFile`, `readdir`, `mkdtemp`, `truncate`, `chmod`, `link`, `symlink`, `readlink`, `realpath`. They fail with an `IoError` (`IoFailed`, `NoSuchPath`). There is no `stat`, `open`, `chown` or `utimes`: the host has no such call.
208
208
  - **`http`:** `get`, `post`, `put`, `patch`, `delete`, `head`, `postJson`. A `Response` has `status`, `headers`, `body`, `ok()` and `json()`
209
209
 
210
210
  ## Utilities
std/Os.plum ADDED
@@ -0,0 +1,281 @@
1
+ module std
2
+
3
+ import std/Slice
4
+ import std/Str
5
+ import std/Uuid
6
+ import std/math/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
+ # `Os` is the file system: `Os.readFile(io, path)`, `Os.writeFile(io, path, data)`,
23
+ # `Os.exists`, `Os.mkdir`, `Os.remove`, `Os.rename`, `Os.readdir` and the rest. Every
24
+ # function takes the `Io` first and goes through one of its raw host calls
25
+ # (`io.rawReadFile`, .. in std/Io). Those return an `Int` (0 or 1) or a bare `Str`, so a
26
+ # function here checks `exists` first where it has to tell a missing path from an empty
27
+ # file or directory, and returns a `Result` with an `IoError`.
28
+ primitive Os =
29
+ # The paths of the standard streams (there is no `File` type yet).
30
+ fun stdin() -> Str =
31
+ "/dev/stdin"
32
+
33
+ fun stdout() -> Str =
34
+ "/dev/stdout"
35
+
36
+ fun stderr() -> Str =
37
+ "/dev/stderr"
38
+
39
+ # Reads the whole file at `path` as a `Str` (a `Str` is a byte array, so
40
+ # this works for binary content too, not just text).
41
+ fun readFile(io: Io, path: Str) -> Result[Str, IoError] =
42
+ if !exists(io, path)
43
+ Err(NoSuchPath)
44
+ else
45
+ Ok(io.rawReadFile(path))
46
+
47
+ # Writes `data` to `path`, replacing its previous contents (or creating it).
48
+ fun writeFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
49
+ if io.rawWriteFile(path, data) != 1
50
+ Err(IoFailed)
51
+ else
52
+ Ok(Unit)
53
+
54
+ fun exists(io: Io, path: Str) -> Bool =
55
+ io.rawExists(path) == 1
56
+
57
+ fun mkdir(io: Io, path: Str) -> Result[Unit, IoError] =
58
+ if io.rawMkdir(path) != 1
59
+ Err(IoFailed)
60
+ else
61
+ Ok(Unit)
62
+
63
+ # Removes the file (not directory) at `path`.
64
+ fun remove(io: Io, path: Str) -> Result[Unit, IoError] =
65
+ if !exists(io, path)
66
+ Err(NoSuchPath)
67
+ else
68
+ if io.rawRemove(path) != 1
69
+ Err(IoFailed)
70
+ else
71
+ Ok(Unit)
72
+
73
+ # Whether `path` exists and is reachable — this VM has no notion of a
74
+ # process' effective uid/gid, so (unlike POSIX `access(2)`) there is no mode
75
+ # argument to check permission bits against.
76
+ fun access(io: Io, path: Str) -> Bool =
77
+ exists(io, path)
78
+
79
+ # Appends `data` to the file at `path`, creating it (with just `data` as its
80
+ # contents) if it doesn't already exist. There's no host-level "open for
81
+ # append" primitive, so this reads the existing bytes and writes the
82
+ # concatenation back — not atomic, and O(existing file size) per call.
83
+ fun appendFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
84
+ if exists(io, path)
85
+ existing := readFile(io, path)?
86
+ writeFile(io, path, existing + data)
87
+ else
88
+ writeFile(io, path, data)
89
+
90
+ # Unix permission bits only (e.g. `0o644`) — this VM has no Windows ACL
91
+ # equivalent to fall back to.
92
+ fun chmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
93
+ if io.rawChmod(path, mode) != 1
94
+ Err(IoFailed)
95
+ else
96
+ Ok(Unit)
97
+
98
+ fun copyFile(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
99
+ data := readFile(io, src)?
100
+ writeFile(io, dest, data)
101
+
102
+ fun cp(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
103
+ copyFile(io, src, dest)
104
+
105
+ # Symlinks aren't modeled separately from regular files/dirs by this VM's
106
+ # host primitives (`rawChmod` always follows them), so this is the same as
107
+ # `chmod`.
108
+ fun lchmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
109
+ chmod(io, path, mode)
110
+
111
+ fun link(io: Io, existingPath: Str, newPath: Str) -> Result[Unit, IoError] =
112
+ if io.rawLink(existingPath, newPath) != 1
113
+ Err(IoFailed)
114
+ else
115
+ Ok(Unit)
116
+
117
+ # Creates a fresh directory named `prefix` followed by a random suffix,
118
+ # retrying on the (astronomically unlikely) chance of a collision, and
119
+ # returns the path actually created.
120
+ fun mkdtemp(io: Io, prefix: Str) -> Result[Str, IoError] =
121
+ path := prefix + Uuid.v4(Random.seeded(io.randomSeed())).value.toStr()
122
+ if exists(io, path)
123
+ mkdtemp(io, prefix)
124
+ else
125
+ mkdir(io, path)?
126
+ Ok(path)
127
+
128
+ # The names of `path`'s directory entries (not full paths).
129
+ fun readdir(io: Io, path: Str) -> Result[Slice[Str], IoError] =
130
+ if !exists(io, path)
131
+ Err(NoSuchPath)
132
+ else
133
+ # skipping empty names handles both a genuinely empty directory (whose
134
+ # joined `""` would otherwise split into one bogus `""` entry) and
135
+ # `rawReadDir`'s "unreadable" fallback (already ruled out by the `exists`
136
+ # check above) the same way — no directory entry is ever named `""`.
137
+ names := Slice[Str]()
138
+ for n := range io.rawReadDir(path).split("\n", 0)
139
+ if n != ""
140
+ names.push(n)
141
+ Ok(names)
142
+
143
+ fun readlink(io: Io, path: Str) -> Result[Str, IoError] =
144
+ if !exists(io, path)
145
+ Err(NoSuchPath)
146
+ else
147
+ Ok(io.rawReadlink(path))
148
+
149
+ fun realpath(io: Io, path: Str) -> Result[Str, IoError] =
150
+ if !exists(io, path)
151
+ Err(NoSuchPath)
152
+ else
153
+ Ok(io.rawRealpath(path))
154
+
155
+ fun rename(io: Io, oldPath: Str, newPath: Str) -> Result[Unit, IoError] =
156
+ if !exists(io, oldPath)
157
+ Err(NoSuchPath)
158
+ else
159
+ if io.rawRename(oldPath, newPath) != 1
160
+ Err(IoFailed)
161
+ else
162
+ Ok(Unit)
163
+
164
+ # Removes an empty directory. (`remove` above covers plain files.)
165
+ fun rmdir(io: Io, path: Str) -> Result[Unit, IoError] =
166
+ if !exists(io, path)
167
+ Err(NoSuchPath)
168
+ else
169
+ if io.rawRemoveDir(path) != 1
170
+ Err(IoFailed)
171
+ else
172
+ Ok(Unit)
173
+
174
+ fun symlink(io: Io, target: Str, path: Str) -> Result[Unit, IoError] =
175
+ if io.rawSymlink(target, path) != 1
176
+ Err(IoFailed)
177
+ else
178
+ Ok(Unit)
179
+
180
+ # Resizes the file at `path` to exactly `len` bytes — truncated if shorter,
181
+ # zero-padded if longer.
182
+ fun truncate(io: Io, path: Str, len: Int) -> Result[Unit, IoError] =
183
+ if !exists(io, path)
184
+ Err(NoSuchPath)
185
+ else
186
+ if io.rawTruncate(path, len) != 1
187
+ Err(IoFailed)
188
+ else
189
+ Ok(Unit)
190
+
191
+ test "writeFile/readFile/appendFile/remove round-trip on a real file"
192
+ dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
193
+ path := dir + "/a.txt"
194
+ Os.writeFile(io, path, "hello")!
195
+ assert Os.readFile(io, path)! == "hello"
196
+ Os.appendFile(io, path, " world")!
197
+ assert Os.readFile(io, path)! == "hello world"
198
+ assert Os.exists(io, path) == true
199
+ Os.remove(io, path)!
200
+ assert Os.exists(io, path) == false
201
+ Os.rmdir(io, dir)!
202
+
203
+ test "copyFile/cp/rename move and duplicate file contents correctly"
204
+ dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
205
+ a := dir + "/a.txt"
206
+ b := dir + "/b.txt"
207
+ c := dir + "/c.txt"
208
+ Os.writeFile(io, a, "data")!
209
+ Os.copyFile(io, a, b)!
210
+ assert Os.readFile(io, b)! == "data"
211
+ Os.rename(io, b, c)!
212
+ assert Os.exists(io, b) == false
213
+ assert Os.readFile(io, c)! == "data"
214
+ Os.remove(io, a)!
215
+ Os.remove(io, c)!
216
+ Os.rmdir(io, dir)!
217
+
218
+ test "readdir lists the entries created in a fresh directory"
219
+ dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
220
+ assert Os.readdir(io, dir)!.length() == 0
221
+ Os.writeFile(io, dir + "/only.txt", "x")!
222
+ names := Os.readdir(io, dir)!
223
+ assert names.length() == 1
224
+ assert names.join(",") == "only.txt"
225
+ Os.remove(io, dir + "/only.txt")!
226
+ Os.rmdir(io, dir)!
227
+
228
+ test "symlink/readlink/realpath resolve a linked file correctly"
229
+ dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
230
+ target := dir + "/target.txt"
231
+ link_path := dir + "/link.txt"
232
+ Os.writeFile(io, target, "linked")!
233
+ Os.symlink(io, target, link_path)!
234
+ assert Os.readlink(io, link_path)! == target
235
+ assert Os.readFile(io, link_path)! == "linked"
236
+ _ := Os.realpath(io, link_path)!
237
+ Os.remove(io, link_path)!
238
+ Os.remove(io, target)!
239
+ Os.rmdir(io, dir)!
240
+
241
+ test "truncate resizes a file's contents"
242
+ dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
243
+ path := dir + "/a.txt"
244
+ Os.writeFile(io, path, "hello world")!
245
+ Os.truncate(io, path, 5)!
246
+ assert Os.readFile(io, path)! == "hello"
247
+ Os.remove(io, path)!
248
+ Os.rmdir(io, dir)!
249
+
250
+ test "chmod changes a file's permission bits"
251
+ dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
252
+ path := dir + "/a.txt"
253
+ Os.writeFile(io, path, "x")!
254
+ Os.chmod(io, path, 384)! # 0o600
255
+ Os.remove(io, path)!
256
+ Os.rmdir(io, dir)!
257
+
258
+ test "link creates a second name for the same file"
259
+ dir := Os.mkdtemp(io, "/tmp/plum_os_test_")!
260
+ a := dir + "/a.txt"
261
+ b := dir + "/b.txt"
262
+ Os.writeFile(io, a, "shared")!
263
+ Os.link(io, a, b)!
264
+ assert Os.readFile(io, b)! == "shared"
265
+ Os.remove(io, a)!
266
+ Os.remove(io, b)!
267
+ Os.rmdir(io, dir)!
268
+
269
+ test "readFile/remove/rmdir report errors for missing paths"
270
+ assert Os.readFile(io, "/tmp/plum_os_test_does_not_exist.txt").unwrapOr("gone") == "gone"
271
+ removeFailed := match Os.remove(io, "/tmp/plum_os_test_does_not_exist.txt")
272
+ Err(e) => 1
273
+ Ok(_) => 0
274
+ rmdirFailed := match Os.rmdir(io, "/tmp/plum_os_test_does_not_exist_dir")
275
+ Err(e) => 1
276
+ Ok(_) => 0
277
+ assert removeFailed + rmdirFailed == 2
278
+
279
+ test "the functions are statics of Os; the standard streams are paths"
280
+ assert Os.stdin() == "/dev/stdin" && Os.stdout() == "/dev/stdout" && Os.stderr() == "/dev/stderr"
281
+ assert Os.access(io, "/tmp") && !Os.exists(io, "/tmp/plum_os_test_does_not_exist.txt")
std/http.plum CHANGED
@@ -40,7 +40,7 @@ struct Response(status: Int, headers: Map[Str, Str], body: Str) =
40
40
 
41
41
  # A single blocking network round trip — this VM has no async/event-loop
42
42
  # mechanism, so `rawHttpRequest` runs to completion before returning (same
43
- # idea as `libs/std/os.plum`'s `rawReadFile`). `headers` is `"Key: Value"`
43
+ # idea as std/Io's `rawReadFile`). `headers` is `"Key: Value"`
44
44
  # lines joined by `\n` (`""` for none). The result packs an outcome flag,
45
45
  # then either the status code and response headers (success) or an error
46
46
  # message (failure), as fields joined by `\x01`, up to the first `\x00` —
std/os.plum DELETED
@@ -1,294 +0,0 @@
1
- module std
2
-
3
- import std/Slice
4
- import std/Str
5
- import std/Uuid
6
- import std/math/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
- Err(NoSuchPath)
61
- else
62
- 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
- Err(IoFailed)
68
- else
69
- Ok(Unit)
70
-
71
- fun exists(io: Io, path: Str) -> Bool =
72
- io.rawExists(path) == 1
73
-
74
- fun mkdir(io: Io, path: Str) -> Result[Unit, IoError] =
75
- if io.rawMkdir(path) != 1
76
- Err(IoFailed)
77
- else
78
- Ok(Unit)
79
-
80
- # Removes the file (not directory) at `path`.
81
- fun remove(io: Io, path: Str) -> Result[Unit, IoError] =
82
- if !exists(io, path)
83
- Err(NoSuchPath)
84
- else
85
- if io.rawRemove(path) != 1
86
- Err(IoFailed)
87
- else
88
- Ok(Unit)
89
-
90
- # Whether `path` exists and is reachable — this VM has no notion of a
91
- # process' effective uid/gid, so (unlike POSIX `access(2)`) there is no mode
92
- # argument to check permission bits against.
93
- fun access(io: Io, path: Str) -> Bool =
94
- exists(io, path)
95
-
96
- # Appends `data` to the file at `path`, creating it (with just `data` as its
97
- # contents) if it doesn't already exist. There's no host-level "open for
98
- # append" primitive, so this reads the existing bytes and writes the
99
- # concatenation back — not atomic, and O(existing file size) per call.
100
- fun appendFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
101
- if exists(io, path)
102
- existing := readFile(io, path)?
103
- writeFile(io, path, existing + data)
104
- else
105
- writeFile(io, path, data)
106
-
107
- # Unix permission bits only (e.g. `0o644`) — this VM has no Windows ACL
108
- # equivalent to fall back to.
109
- fun chmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
110
- if io.rawChmod(path, mode) != 1
111
- Err(IoFailed)
112
- else
113
- Ok(Unit)
114
-
115
- fun copyFile(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
116
- data := readFile(io, src)?
117
- writeFile(io, dest, data)
118
-
119
- fun cp(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
120
- copyFile(io, src, dest)
121
-
122
- # Symlinks aren't modeled separately from regular files/dirs by this VM's
123
- # host primitives (`rawChmod` always follows them), so this is the same as
124
- # `chmod`.
125
- fun lchmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
126
- chmod(io, path, mode)
127
-
128
- fun link(io: Io, existing_path: Str, new_path: Str) -> Result[Unit, IoError] =
129
- if io.rawLink(existing_path, new_path) != 1
130
- Err(IoFailed)
131
- else
132
- Ok(Unit)
133
-
134
- # Creates a fresh directory named `prefix` followed by a random suffix,
135
- # retrying on the (astronomically unlikely) chance of a collision, and
136
- # returns the path actually created.
137
- fun mkdtemp(io: Io, prefix: Str) -> Result[Str, IoError] =
138
- path := prefix + Uuid.v4(Random.seeded(io.randomSeed())).value.toStr()
139
- if exists(io, path)
140
- mkdtemp(io, prefix)
141
- else
142
- mkdir(io, path)?
143
- Ok(path)
144
-
145
- # The names of `path`'s directory entries (not full paths).
146
- fun readdir(io: Io, path: Str) -> Result[Slice[Str], IoError] =
147
- if !exists(io, path)
148
- Err(NoSuchPath)
149
- else
150
- # skipping empty names handles both a genuinely empty directory (whose
151
- # joined `""` would otherwise split into one bogus `""` entry) and
152
- # `rawReadDir`'s "unreadable" fallback (already ruled out by the `exists`
153
- # check above) the same way — no directory entry is ever named `""`.
154
- names := Slice[Str]()
155
- for n := range io.rawReadDir(path).split("\n", 0)
156
- if n != ""
157
- names.push(n)
158
- Ok(names)
159
-
160
- fun readlink(io: Io, path: Str) -> Result[Str, IoError] =
161
- if !exists(io, path)
162
- Err(NoSuchPath)
163
- else
164
- Ok(io.rawReadlink(path))
165
-
166
- fun realpath(io: Io, path: Str) -> Result[Str, IoError] =
167
- if !exists(io, path)
168
- Err(NoSuchPath)
169
- else
170
- Ok(io.rawRealpath(path))
171
-
172
- fun rename(io: Io, old_path: Str, new_path: Str) -> Result[Unit, IoError] =
173
- if !exists(io, old_path)
174
- Err(NoSuchPath)
175
- else
176
- if io.rawRename(old_path, new_path) != 1
177
- Err(IoFailed)
178
- else
179
- Ok(Unit)
180
-
181
- # Removes an empty directory. (`remove` above covers plain files.)
182
- fun rmdir(io: Io, path: Str) -> Result[Unit, IoError] =
183
- if !exists(io, path)
184
- Err(NoSuchPath)
185
- else
186
- if io.rawRemoveDir(path) != 1
187
- Err(IoFailed)
188
- else
189
- Ok(Unit)
190
-
191
- fun symlink(io: Io, target: Str, path: Str) -> Result[Unit, IoError] =
192
- if io.rawSymlink(target, path) != 1
193
- Err(IoFailed)
194
- else
195
- Ok(Unit)
196
-
197
- # Resizes the file at `path` to exactly `len` bytes — truncated if shorter,
198
- # zero-padded if longer.
199
- fun truncate(io: Io, path: Str, len: Int) -> Result[Unit, IoError] =
200
- if !exists(io, path)
201
- Err(NoSuchPath)
202
- else
203
- if io.rawTruncate(path, len) != 1
204
- Err(IoFailed)
205
- else
206
- Ok(Unit)
207
-
208
- test "writeFile/readFile/appendFile/remove round-trip on a real file"
209
- dir := mkdtemp(io, "/tmp/plum_os_test_")!
210
- path := dir + "/a.txt"
211
- writeFile(io, path, "hello")!
212
- assert readFile(io, path)! == "hello"
213
- appendFile(io, path, " world")!
214
- assert readFile(io, path)! == "hello world"
215
- assert exists(io, path) == true
216
- remove(io, path)!
217
- assert exists(io, path) == false
218
- rmdir(io, dir)!
219
-
220
- test "copyFile/cp/rename move and duplicate file contents correctly"
221
- dir := mkdtemp(io, "/tmp/plum_os_test_")!
222
- a := dir + "/a.txt"
223
- b := dir + "/b.txt"
224
- c := dir + "/c.txt"
225
- writeFile(io, a, "data")!
226
- copyFile(io, a, b)!
227
- assert readFile(io, b)! == "data"
228
- rename(io, b, c)!
229
- assert exists(io, b) == false
230
- assert readFile(io, c)! == "data"
231
- remove(io, a)!
232
- remove(io, c)!
233
- rmdir(io, dir)!
234
-
235
- test "readdir lists the entries created in a fresh directory"
236
- dir := mkdtemp(io, "/tmp/plum_os_test_")!
237
- assert readdir(io, dir)!.length() == 0
238
- writeFile(io, dir + "/only.txt", "x")!
239
- names := readdir(io, dir)!
240
- assert names.length() == 1
241
- assert names.join(",") == "only.txt"
242
- remove(io, dir + "/only.txt")!
243
- rmdir(io, dir)!
244
-
245
- test "symlink/readlink/realpath resolve a linked file correctly"
246
- dir := mkdtemp(io, "/tmp/plum_os_test_")!
247
- target := dir + "/target.txt"
248
- link_path := dir + "/link.txt"
249
- writeFile(io, target, "linked")!
250
- symlink(io, target, link_path)!
251
- assert readlink(io, link_path)! == target
252
- assert readFile(io, link_path)! == "linked"
253
- _ := realpath(io, link_path)!
254
- remove(io, link_path)!
255
- remove(io, target)!
256
- rmdir(io, dir)!
257
-
258
- test "truncate resizes a file's contents"
259
- dir := mkdtemp(io, "/tmp/plum_os_test_")!
260
- path := dir + "/a.txt"
261
- writeFile(io, path, "hello world")!
262
- truncate(io, path, 5)!
263
- assert readFile(io, path)! == "hello"
264
- remove(io, path)!
265
- rmdir(io, dir)!
266
-
267
- test "chmod changes a file's permission bits"
268
- dir := mkdtemp(io, "/tmp/plum_os_test_")!
269
- path := dir + "/a.txt"
270
- writeFile(io, path, "x")!
271
- chmod(io, path, 384)! # 0o600
272
- remove(io, path)!
273
- rmdir(io, dir)!
274
-
275
- test "link creates a second name for the same file"
276
- dir := mkdtemp(io, "/tmp/plum_os_test_")!
277
- a := dir + "/a.txt"
278
- b := dir + "/b.txt"
279
- writeFile(io, a, "shared")!
280
- link(io, a, b)!
281
- assert readFile(io, b)! == "shared"
282
- remove(io, a)!
283
- remove(io, b)!
284
- rmdir(io, dir)!
285
-
286
- test "readFile/remove/rmdir report errors for missing paths"
287
- assert readFile(io, "/tmp/plum_os_test_does_not_exist.txt").unwrapOr("gone") == "gone"
288
- removeFailed := match remove(io, "/tmp/plum_os_test_does_not_exist.txt")
289
- Err(e) => 1
290
- Ok(_) => 0
291
- rmdirFailed := match rmdir(io, "/tmp/plum_os_test_does_not_exist_dir")
292
- Err(e) => 1
293
- Ok(_) => 0
294
- assert removeFailed + rmdirFailed == 2