plum

#treesitter#compiler#wasm

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

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


51ee136 — Peter John 2026-11-10T14:31:23+05:30
std/encoding: base64 becomes the Base64 namespace
compiler/lsp/src/main.rs CHANGED
@@ -712,14 +712,14 @@ mod tests {
712
712
  let _ = std::fs::remove_dir_all(&dir);
713
713
  }
714
714
 
715
- /// The std modules (`os`, `base64`, `testing`, `http`) are indexed for auto-import by
715
+ /// The std modules (`os`, `testing`, `http`) and namespaces (`Base64`) are indexed for
716
- /// module name and complete their functions after `name.`.
716
+ /// auto-import by name and complete their functions after `name.`.
717
717
  #[test]
718
718
  fn stdNamespacesCompleteAndAutoImport() {
719
719
  let index = completion::stdLibIndex(&repoRoot());
720
720
  for (name, path) in [
721
721
  ("os", "std/os"),
722
- ("base64", "std/encoding/base64"),
722
+ ("Base64", "std/encoding/Base64"),
723
723
  ("testing", "std/testing"),
724
724
  ("http", "std/http"),
725
725
  ("gfx", "std/game/gfx"),
@@ -741,7 +741,7 @@ mod tests {
741
741
  let dir = std::env::temp_dir().join(format!("plum-lsp-ns-{}", std::process::id()));
742
742
  std::fs::create_dir_all(&dir).unwrap();
743
743
  let path = dir.join("t.plum");
744
- 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";
744
+ let text = "module t\nimport std/Int\nimport std/Str\nimport std/os\n\nfun main() =\n x := os.zzzzzz\n";
745
745
  std::fs::write(&path, text).unwrap();
746
746
  let labels = |recv: &str| -> Vec<String> {
747
747
  memberCompletionFor(&path, &repoRoot(), text, 7, recv)
@@ -754,7 +754,13 @@ mod tests {
754
754
  os.iter().any(|l| l == "readFile") && os.iter().any(|l| l == "writeFile"),
755
755
  "{os:?}"
756
756
  );
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";
757
- let b64 = labels("base64");
759
+ std::fs::write(&path, text).unwrap();
760
+ let b64: Vec<String> = memberCompletionFor(&path, &repoRoot(), text, 6, "Base64")
761
+ .into_iter()
762
+ .map(|i| i.label)
763
+ .collect();
758
764
  assert!(
759
765
  b64.iter().any(|l| l == "encode") && b64.iter().any(|l| l == "decode"),
760
766
  "{b64:?}"
docs/std.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # The standard library
2
2
 
3
- Import what you use: `import std/Str`, `import std/Slice`, and so on. Most modules sit right under `std`; the collections are in `std/collections` (`import std/collections/List`), `Json` and `base64` in `std/encoding`, `math`, `Random`, `Aabb`, `Vec2` and `Affine` in `std/math`, and the game engine in `std/game`. A folder is not a module: each file is imported by its full path. The source is in [`std/`](../std), and it is plain Plum, so it's a good place to read how things work.
3
+ Import what you use: `import std/Str`, `import std/Slice`, and so on. Most modules sit right under `std`; the collections are in `std/collections` (`import std/collections/List`), `Json` and `Base64` in `std/encoding`, `math`, `Random`, `Aabb`, `Vec2` and `Affine` in `std/math`, and the game engine in `std/game`. A folder is not a module: each file is imported by its full path. The source is in [`std/`](../std), and it is plain Plum, so it's a good place to read how things work.
4
4
 
5
5
  The [game engine](game.md) has its own page.
6
6
 
@@ -15,7 +15,7 @@ The [game engine](game.md) has its own page.
15
15
  | [`Option`, `Result`](#option-and-result) | missing values and failures |
16
16
  | [`Json`](#json) | reading and writing JSON |
17
17
  | [`os`, `http`](#files-and-network) | files and the network |
18
- | [`Time`, `Random`, `Uuid`, `base64`, `Aabb`, `ref`](#utilities) | utilities |
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 |
21
21
 
@@ -212,7 +212,7 @@ fun main(io: Io) =
212
212
  - **`Time`:** `Time.now(io)` and `Duration` values such as `Duration.seconds(5)`
213
213
  - **`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
214
214
  - **`Uuid`:** `Uuid.v4(rng)`, `Uuid.fromStr`, `Uuid.isValid`
215
- - **`base64`:** `base64.encode`, `base64.decode`, `base64.encodeURL`
215
+ - **`Base64`** (`import std/encoding/Base64`): `Base64.encode(data)` and `Base64.decode(text)` (a `Result`; whitespace and missing padding are fine), the URL alphabet `Base64.encodeUrl(data)` (no padding unless `pad` is true) and `Base64.decodeUrl(text)`, and the line-wrapped `Base64.encodePem` and `Base64.encodeMime`
216
216
  - **`Aabb`:** an axis-aligned box, corners included: `Aabb.of(x, y, w, h)`, `width`, `height`, `center`, `overlaps`, `contains`, `containsPoint`, `union`, `distSq`, `rayEntry`
217
217
  - **`ref`:** `ref.same(a, b)` is true when `a` and `b` are the very same object, not just equal ones: `ref.same(a, Box(..a))` is false. Only for values on the heap (a struct that isn't flat, an enum, a trait object, `Str`, `List`, ...); the checker rejects a scalar, a flat struct or a function. A persistent structure uses it to keep what didn't change: the scene tree's `input` and `Game`'s tick return a node as it was when its actor came back as the same object (see [the game engine](game.md)). The compiler never updates a value compared by `ref.same` in place, so an update always shows up as another object
218
218
  - **`io.args()`:** the program's arguments as a `Slice[Str]`: what follows `--` in `plum run app.plum -- a b`, or a built executable's own arguments (empty under `plum test` and in the browser)
std/encoding/Base64.plum ADDED
@@ -0,0 +1,175 @@
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
+ # `Base64` holds the Base64 binary-to-text encodings: `Base64.encode(data)`,
11
+ # `Base64.decode(text)` and the URL, PEM and MIME variants.
12
+ #
13
+ # Implemented on top of `Buffer` and `Str.byteAt`.
14
+ #
15
+ # `data`/the decoded payload are represented as `Str` throughout (matching
16
+ # the original public shape) rather than a byte array — `Str` is itself just a
17
+ # byte array here (see std/Str), so this is a plain byte string,
18
+ # not a claim that the content is valid UTF-8 text.
19
+
20
+ # Why `decode` failed.
21
+ enum Base64Error = InvalidBase64
22
+
23
+ primitive Base64 =
24
+ # Encode for PEM (RFC 1421): 64-character lines.
25
+ fun encodePem(data: Str) -> Str =
26
+ encode(data, "+", "/", "=", 64, "\r\n")
27
+
28
+ # Encode for MIME (RFC 2045): 76-character lines.
29
+ fun encodeMime(data: Str) -> Str =
30
+ encode(data, "+", "/", "=", 76, "\r\n")
31
+
32
+ # Encode for URLs (RFC 4648). Padding characters are stripped by default.
33
+ fun encodeUrl(data: Str, pad: Bool = false) -> Str =
34
+ encode(data, "-", "_", if pad then "=" else "", 0, "")
35
+
36
+ # Configurable encoding. The defaults are for RFC 4648. `pad` is the padding
37
+ # character, or `""` to omit padding entirely; `linelen` is the output line
38
+ # length to wrap at (`0` disables wrapping), separated by `linesep`.
39
+ fun encode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=", linelen: Int = 0, linesep: Str = "\r\n") -> Str =
40
+ at62b := at62.byteAt(0)
41
+ at63b := at63.byteAt(0)
42
+ hasPad := pad.length() > 0
43
+ padb := if hasPad then pad.byteAt(0) else 0
44
+ res := Buffer()
45
+ encodeFrom(data, res, 0, 0, at62b, at63b, hasPad, padb, linelen, linesep)
46
+ res.toStr()
47
+
48
+ # `encode`'s loop: writes the groups of `data` from byte `i` on into `res`.
49
+ # `lineChars` is how many characters the current output line holds so far.
50
+ fun encodeFrom(data: Str, res: Buffer, i: Int, lineChars: Int, at62b: Int, at63b: Int, hasPad: Bool, padb: Int, linelen: Int, linesep: Str) -> Unit =
51
+ n := data.length()
52
+ if i < n
53
+ b0 := data.byteAt(i)
54
+ has1 := i + 1 < n
55
+ has2 := i + 2 < n
56
+ b1 := if has1 then data.byteAt(i + 1) else 0
57
+ b2 := if has2 then data.byteAt(i + 2) else 0
58
+ res.writeByte(Byte(encodeByte(b0 >> 2, at62b, at63b)))
59
+ res.writeByte(Byte(encodeByte({b0 & 0x03} << 4 | b1 >> 4, at62b, at63b)))
60
+ if has1
61
+ res.writeByte(Byte(encodeByte({b1 & 0x0F} << 2 | b2 >> 6, at62b, at63b)))
62
+ else if hasPad
63
+ res.writeByte(Byte(padb))
64
+ if has2
65
+ res.writeByte(Byte(encodeByte(b2 & 0x3F, at62b, at63b)))
66
+ else if hasPad
67
+ res.writeByte(Byte(padb))
68
+ third := if has1 || hasPad then 1 else 0
69
+ fourth := if has2 || hasPad then 1 else 0
70
+ written := lineChars + 2 + third + fourth
71
+ next := i + 3
72
+ if linelen > 0 && written >= linelen && next < n
73
+ res.write(linesep)
74
+ encodeFrom(data, res, next, 0, at62b, at63b, hasPad, padb, linelen, linesep)
75
+ else
76
+ encodeFrom(data, res, next, written, at62b, at63b, hasPad, padb, linelen, linesep)
77
+
78
+ # Encodes a single 6-bit value (0-63) as its base64 alphabet character.
79
+ fun encodeByte(i: Int, at62: Int, at63: Int) -> Int =
80
+ if i < 26
81
+ 65 + i # 'A'..'Z'
82
+ else if i < 52
83
+ 97 + {i - 26} # 'a'..'z'
84
+ else if i < 62
85
+ 48 + {i - 52} # '0'..'9'
86
+ else if i == 62
87
+ at62
88
+ else
89
+ at63
90
+
91
+ # The inverse of `encodeByte`: a base64 alphabet character's 6-bit value, or
92
+ # -1 if `b` isn't one of the 64 alphabet characters (whitespace/padding are
93
+ # handled by the caller, not here).
94
+ fun decodeByte(b: Int, at62: Int, at63: Int) -> Int =
95
+ if b >= 65 && b <= 90
96
+ b - 65
97
+ else if b >= 97 && b <= 122
98
+ b - 97 + 26
99
+ else if b >= 48 && b <= 57
100
+ b - 48 + 52
101
+ else if b == at62
102
+ 62
103
+ else if b == at63
104
+ 63
105
+ else
106
+ -1
107
+
108
+ fun isBase64Whitespace(b: Int) -> Bool =
109
+ b == 32 || b == 9 || b == 10 || b == 13
110
+
111
+ # Decode for URLs (RFC 4648).
112
+ fun decodeUrl(data: Str) -> Result[Str, Base64Error] =
113
+ decode(data, "-", "_", "=")
114
+
115
+ # Configurable decoding. The defaults are for RFC 4648. Missing padding is
116
+ # not an error. Non-base64 data, other than whitespace (which can appear at
117
+ # any point), fails with `Err(InvalidBase64)`.
118
+ fun decode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=") -> Result[Str, Base64Error] =
119
+ at62b := at62.byteAt(0)
120
+ at63b := at63.byteAt(0)
121
+ hasPad := pad.length() > 0
122
+ padb := if hasPad then pad.byteAt(0) else -1
123
+ res := Buffer()
124
+ decodeFrom(data, res, 0, 0, 0, at62b, at63b, padb)
125
+
126
+ # `decode`'s loop: the bytes of `data` from `i` on, with `bits` / `nbits`
127
+ # the pending bits not yet written out as a whole byte.
128
+ fun decodeFrom(data: Str, res: Buffer, i: Int, bits: Int, nbits: Int, at62b: Int, at63b: Int, padb: Int) -> Result[Str, Base64Error] =
129
+ if i >= data.length()
130
+ Ok(res.toStr())
131
+ else
132
+ b := data.byteAt(i)
133
+ if isBase64Whitespace(b) || b == padb
134
+ decodeFrom(data, res, i + 1, bits, nbits, at62b, at63b, padb)
135
+ else
136
+ v := decodeByte(b, at62b, at63b)
137
+ if v < 0
138
+ Err(InvalidBase64)
139
+ else
140
+ acc := {bits << 6} | v
141
+ if nbits + 6 >= 8
142
+ left := nbits + 6 - 8
143
+ res.writeByte(Byte({acc >> left} & 0xFF))
144
+ decodeFrom(data, res, i + 1, acc, left, at62b, at63b, padb)
145
+ else
146
+ decodeFrom(data, res, i + 1, acc, nbits + 6, at62b, at63b, padb)
147
+
148
+ test "encode: RFC 4648 vectors, with and without padding"
149
+ assert Base64.encode("") == ""
150
+ assert Base64.encode("f") == "Zg=="
151
+ assert Base64.encode("fo") == "Zm8="
152
+ assert Base64.encode("foo") == "Zm9v"
153
+ assert Base64.encode("foobar") == "Zm9vYmFy"
154
+ assert Base64.encode("f", "+", "/", "") == "Zg"
155
+
156
+ test "decode: the inverse, whitespace and missing padding allowed, other bytes an error"
157
+ assert Base64.decode("Zm9vYmFy")! == "foobar"
158
+ assert Base64.decode("Zg==")! == "f" && Base64.decode("Zg")! == "f"
159
+ assert Base64.decode("Zm9v\r\nYmFy")! == "foobar"
160
+ assert Base64.decode("Zm9v*").isErr()
161
+
162
+ test "the URL alphabet: - and _ for + and /, no padding unless asked"
163
+ data := Str.byteToStr(251) + Str.byteToStr(255) + Str.byteToStr(190)
164
+ assert Base64.encode(data) == "+/++"
165
+ assert Base64.encodeUrl(data) == "-_--"
166
+ assert Base64.encodeUrl("f") == "Zg" && Base64.encodeUrl("f", true) == "Zg=="
167
+ assert Base64.decodeUrl("-_--")! == data
168
+ assert Base64.decode("-_--").isErr()
169
+
170
+ test "PEM and MIME wrap lines and round-trip"
171
+ long := "0123456789".repeat(10)
172
+ assert Base64.encodePem(long).split("\r\n", 0).at(0).length() == 64
173
+ assert Base64.encodeMime(long).split("\r\n", 0).at(0).length() == 76
174
+ assert Base64.decode(Base64.encodePem(long))! == long
175
+ assert Base64.decode(Base64.encodeMime("hi there"))! == "hi there"
std/encoding/base64.plum DELETED
@@ -1,148 +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 `decode` failed.
20
- enum Base64Error = InvalidBase64
21
-
22
- # Encode for PEM (RFC 1421): 64-character lines.
23
- fun encodePEM(data: Str) -> Str =
24
- encode(data, "+", "/", "=", 64, "\r\n")
25
-
26
- # Encode for MIME (RFC 2045): 76-character lines.
27
- fun encodeMIME(data: Str) -> Str =
28
- 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
- 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
- hasPad := pad.length() > 0
41
- padb := if hasPad then pad.byteAt(0) else 0
42
- res := Buffer()
43
- encodeFrom(data, res, 0, 0, at62b, at63b, hasPad, padb, linelen, linesep)
44
- res.toStr()
45
-
46
- # `encode`'s loop: writes the groups of `data` from byte `i` on into `res`.
47
- # `lineChars` is how many characters the current output line holds so far.
48
- fun encodeFrom(data: Str, res: Buffer, i: Int, lineChars: Int, at62b: Int, at63b: Int, hasPad: Bool, padb: Int, linelen: Int, linesep: Str) -> Unit =
49
- n := data.length()
50
- if i < n
51
- b0 := data.byteAt(i)
52
- has1 := i + 1 < n
53
- has2 := i + 2 < n
54
- b1 := if has1 then data.byteAt(i + 1) else 0
55
- b2 := if has2 then data.byteAt(i + 2) else 0
56
- res.writeByte(Byte(encodeByte(b0 >> 2, at62b, at63b)))
57
- res.writeByte(Byte(encodeByte({b0 & 0x03} << 4 | b1 >> 4, at62b, at63b)))
58
- if has1
59
- res.writeByte(Byte(encodeByte({b1 & 0x0F} << 2 | b2 >> 6, at62b, at63b)))
60
- else if hasPad
61
- res.writeByte(Byte(padb))
62
- if has2
63
- res.writeByte(Byte(encodeByte(b2 & 0x3F, at62b, at63b)))
64
- else if hasPad
65
- res.writeByte(Byte(padb))
66
- third := if has1 || hasPad then 1 else 0
67
- fourth := if has2 || hasPad then 1 else 0
68
- written := lineChars + 2 + third + fourth
69
- next := i + 3
70
- if linelen > 0 && written >= linelen && next < n
71
- res.write(linesep)
72
- encodeFrom(data, res, next, 0, at62b, at63b, hasPad, padb, linelen, linesep)
73
- else
74
- encodeFrom(data, res, next, written, at62b, at63b, hasPad, padb, linelen, linesep)
75
-
76
- # Encodes a single 6-bit value (0-63) as its base64 alphabet character.
77
- fun encodeByte(i: Int, at62: Int, at63: Int) -> Int =
78
- if i < 26
79
- 65 + i # 'A'..'Z'
80
- else if i < 52
81
- 97 + {i - 26} # 'a'..'z'
82
- else if i < 62
83
- 48 + {i - 52} # '0'..'9'
84
- else if i == 62
85
- at62
86
- else
87
- at63
88
-
89
- # The inverse of `encodeByte`: a base64 alphabet character's 6-bit value, or
90
- # -1 if `b` isn't one of the 64 alphabet characters (whitespace/padding are
91
- # handled by the caller, not here).
92
- fun decodeByte(b: Int, at62: Int, at63: Int) -> Int =
93
- if b >= 65 && b <= 90
94
- b - 65
95
- else if b >= 97 && b <= 122
96
- b - 97 + 26
97
- else if b >= 48 && b <= 57
98
- b - 48 + 52
99
- else if b == at62
100
- 62
101
- else if b == at63
102
- 63
103
- else
104
- -1
105
-
106
- fun isBase64Whitespace(b: Int) -> Bool =
107
- b == 32 || b == 9 || b == 10 || b == 13
108
-
109
- # Decode for URLs (RFC 4648).
110
- fun decodeUrl(data: Str) -> Result[Str, Base64Error] =
111
- decode(data, "-", "_", "=")
112
-
113
- # Configurable decoding. The defaults are for RFC 4648. Missing padding is
114
- # not an error. Non-base64 data, other than whitespace (which can appear at
115
- # any point), fails with `Err(InvalidBase64)`.
116
- fun decode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=") -> Result[Str, Base64Error] =
117
- at62b := at62.byteAt(0)
118
- at63b := at63.byteAt(0)
119
- hasPad := pad.length() > 0
120
- padb := if hasPad then pad.byteAt(0) else -1
121
- res := Buffer()
122
- decodeFrom(data, res, 0, 0, 0, at62b, at63b, padb)
123
-
124
- # `decode`'s loop: the bytes of `data` from `i` on, with `bits` / `nbits`
125
- # the pending bits not yet written out as a whole byte.
126
- fun decodeFrom(data: Str, res: Buffer, i: Int, bits: Int, nbits: Int, at62b: Int, at63b: Int, padb: Int) -> Result[Str, Base64Error] =
127
- if i >= data.length()
128
- Ok(res.toStr())
129
- else
130
- b := data.byteAt(i)
131
- if isBase64Whitespace(b) || b == padb
132
- decodeFrom(data, res, i + 1, bits, nbits, at62b, at63b, padb)
133
- else
134
- v := decodeByte(b, at62b, at63b)
135
- if v < 0
136
- Err(InvalidBase64)
137
- else
138
- acc := {bits << 6} | v
139
- if nbits + 6 >= 8
140
- left := nbits + 6 - 8
141
- res.writeByte(Byte({acc >> left} & 0xFF))
142
- decodeFrom(data, res, i + 1, acc, left, at62b, at63b, padb)
143
- else
144
- decodeFrom(data, res, i + 1, acc, nbits + 6, at62b, at63b, padb)
145
-
146
- test "statics are reached through the Base64 namespace and round-trip"
147
- assert decode(encodePEM("hello"))! == "hello"
148
- assert decode(encodeMIME("hi there"))! == "hi there"