plum

#treesitter#compiler#wasm

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

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


960893f — Peter John 2026-11-10T14:43:02+05:30
Linear memory: eight @mem built-ins replace std/mem
compiler/checker/tests/checker/traits_tests.rs CHANGED
@@ -441,12 +441,24 @@ fn traitStatics() {
441
441
  #[test]
442
442
  fn compileTimeBuiltins() {
443
443
  ok("fun main() =\n s: Str := @typeName(Int)\n show(s)\n");
444
- fails("fun main() =\n show(@nope(Int))\n", "unknown built-in @nope; the built-ins are @typeName, @sameRef");
444
+ fails("fun main() =\n show(@nope(Int))\n", "unknown built-in @nope; the built-ins are @typeName, @sameRef, @memSize, @memGrow, @memStoreF32, @memStoreI32, @memStoreU8, @memLoadF32, @memLoadI32, @memLoadU8");
445
445
  fails("fun main() =\n x := 1\n show(@typeName(x))\n", "@typeName takes one type, e.g. @typeName(Self)");
446
446
  fails("fun main() =\n show(@typeName(Int, Str))\n", "@typeName takes one type");
447
447
  fails("fun main() =\n n: Int := @typeName(Int)\n show(\"{n}\")\n", "type mismatch");
448
448
  }
449
449
 
450
+ /// The linear-memory built-ins take values, typed like any call's arguments.
451
+ #[test]
452
+ fn memoryBuiltins() {
453
+ ok("fun main() =\n @memStoreI32(8, 1)\n @memStoreF32(12, 1.5)\n @memStoreU8(16, 2)\n n: Int := @memLoadI32(8) + @memLoadU8(16) + @memSize() + @memGrow(1)\n x: Float := @memLoadF32(12)\n show(\"{n} {x}\")\n");
454
+ fails("fun main() =\n show(\"{@memSize(1)}\")\n", "@memSize takes no arguments, e.g. @memSize()");
455
+ fails("fun main() =\n show(\"{@memGrow()}\")\n", "@memGrow takes one value, e.g. @memGrow(pages)");
456
+ fails("fun main() =\n @memStoreI32(8)\n", "@memStoreI32 takes two values, e.g. @memStoreI32(addr, v)");
457
+ fails("fun main() =\n show(\"{@memLoadU8(List[Int])}\")\n", "@memLoadU8 takes one value, e.g. @memLoadU8(addr)");
458
+ fails("fun main() =\n @memStoreF32(8, \"x\")\n", "mismatch");
459
+ fails("fun main() =\n s: Str := @memLoadI32(8)\n show(s)\n", "type mismatch");
460
+ }
461
+
450
462
  #[test]
451
463
  fn coercionIsOfWholeValuesOnly() {
452
464
  // a `List[Orb]` is not a `List[Actor]`, nor a `fn(Orb) -> Orb` a `fn(Actor) -> Actor`
compiler/core/src/compile_builtins.rs CHANGED
@@ -26,6 +26,22 @@ pub const BUILTINS: &[(&str, Takes, &str)] = &[
26
26
  // Only for heap types (`plum_checker::identity`); a variable passed to it is never
27
27
  // updated in place (`uniqueness`).
28
28
  (SAME_REF, Takes::Values(2), "@sameRef(a, b)"),
29
+ // The program's linear memory: one growable wasm memory (16 pages of 64 KiB to start),
30
+ // exported to the host as "memory", present only in a program that uses one of these.
31
+ // Addresses are byte offsets; every access is little-endian and traps out of bounds.
32
+ // `@memSize()`: the size in bytes. `@memGrow(pages)`: adds 64 KiB pages; the old page
33
+ // count, or -1 on failure.
34
+ ("memSize", Takes::Values(0), "@memSize()"),
35
+ ("memGrow", Takes::Values(1), "@memGrow(pages)"),
36
+ // Floats are stored as f32; integers as 32 bits (`@memStoreI32` truncates,
37
+ // `@memLoadI32` sign-extends); `@memStoreU8` stores the low 8 bits and `@memLoadU8`
38
+ // gives 0..255.
39
+ ("memStoreF32", Takes::Values(2), "@memStoreF32(addr, v)"),
40
+ ("memStoreI32", Takes::Values(2), "@memStoreI32(addr, v)"),
41
+ ("memStoreU8", Takes::Values(2), "@memStoreU8(addr, v)"),
42
+ ("memLoadF32", Takes::Values(1), "@memLoadF32(addr)"),
43
+ ("memLoadI32", Takes::Values(1), "@memLoadI32(addr)"),
44
+ ("memLoadU8", Takes::Values(1), "@memLoadU8(addr)"),
29
45
  ];
30
46
 
31
47
  /// `@sameRef` without its `@`.
@@ -34,7 +50,17 @@ pub const SAME_REF: &str = "sameRef";
34
50
  pub const SAME_REF_FN: &str = "@sameRef";
35
51
 
36
52
  /// What a value built-in is declared as: `(name, type parameters, parameter types, result)`.
53
+ const DECLS: &[(&str, &[&str], &[&str], &str)] = &[
37
- const DECLS: &[(&str, &[&str], &[&str], &str)] = &[(SAME_REF_FN, &["T"], &["T", "T"], "Bool")];
54
+ (SAME_REF_FN, &["T"], &["T", "T"], "Bool"),
55
+ ("@memSize", &[], &[], "Int"),
56
+ ("@memGrow", &[], &["Int"], "Int"),
57
+ ("@memStoreF32", &[], &["Int", "Float"], "Unit"),
58
+ ("@memStoreI32", &[], &["Int", "Int"], "Unit"),
59
+ ("@memStoreU8", &[], &["Int", "Int"], "Unit"),
60
+ ("@memLoadF32", &[], &["Int"], "Float"),
61
+ ("@memLoadI32", &[], &["Int"], "Int"),
62
+ ("@memLoadU8", &[], &["Int"], "Int"),
63
+ ];
38
64
 
39
65
  /// How a built-in takes its arguments; `None` for a name that is not one.
40
66
  pub fn takes(name: &str) -> Option<Takes> {
@@ -51,6 +77,11 @@ pub fn isSameRef(f: &Fn) -> bool {
51
77
  f.type_param.is_none() && f.name == SAME_REF_FN
52
78
  }
53
79
 
80
+ /// Whether `f` is the declaration of one of the linear-memory built-ins (`@memSize`, ...).
81
+ pub fn isMem(f: &Fn) -> bool {
82
+ f.type_param.is_none() && f.name.starts_with("@mem")
83
+ }
84
+
54
85
  /// Declares each value built-in `source` calls and does not declare yet: a function named
55
86
  /// `@name` with the built-in's signature and no body of its own. Every pass then sees its
56
87
  /// calls as calls of that function; codegen supplies the instructions.
compiler/core/src/parser.rs CHANGED
@@ -2030,6 +2030,7 @@ fn isExpressionKind(kind: &str) -> bool {
2030
2030
  | "var_identifier"
2031
2031
  | "type_identifier"
2032
2032
  | "closure"
2033
+ | "builtin_call"
2033
2034
  )
2034
2035
  }
2035
2036
 
compiler/core/tests/core/traits_parse_test.rs CHANGED
@@ -220,3 +220,13 @@ fn valueBuiltinCalls() {
220
220
  let ExprKind::FnCall(c) = &e.kind else { panic!("{e:?}") };
221
221
  assert_eq!((c.args.len(), c.type_args.len()), (1, 1));
222
222
  }
223
+
224
+ /// A built-in call is a statement like any call (it used to be dropped there).
225
+ #[test]
226
+ fn builtinCallAsStatement() {
227
+ let s = plum_test_support::parseRawSource("fun f() -> Int =\n @memStoreI32(8, 1)\n @memLoadI32(8)\n");
228
+ let FnBody::Block(b) = &fnOf(&s, None, "f").body else { panic!("block body") };
229
+ assert_eq!(b.stmts.len(), 2);
230
+ let StmtKind::Expr(Expr { kind: ExprKind::FnCall(c), .. }, ..) = &b.stmts[0].kind else { panic!("{:?}", b.stmts[0]) };
231
+ assert_eq!((c.name.as_str(), c.args.len()), ("@memStoreI32", 2));
232
+ }
compiler/lsp/src/completion.rs CHANGED
@@ -73,6 +73,8 @@ pub fn topLevelItems(source: &ast::Source) -> Vec<CompletionItem> {
73
73
  let mut items = Vec::new();
74
74
  for item in &source.items {
75
75
  match item {
76
+ // A built-in's declaration (`@sameRef`) is the compiler's, not a name to offer.
77
+ ast::Item::Fn(f) if plum_core::compile_builtins::isDeclared(f) => {}
76
78
  ast::Item::Fn(f) if f.type_param.is_none() => {
77
79
  items.push(CompletionItem {
78
80
  label: plum_core::diag::sourceName(&f.name),
compiler/lsp/src/main.rs CHANGED
@@ -786,6 +786,13 @@ mod tests {
786
786
  let merged = plum_core::loadAndMergeDiag(&path, &repoRoot()).expect("loads");
787
787
  let top: Vec<String> = completion::topLevelItems(&merged).into_iter().map(|i| i.label).collect();
788
788
  assert!(top.iter().any(|l| l == "clamp") && !top.iter().any(|l| l.contains('@')), "{top:?}");
789
+ // A built-in's declaration (the compiler's own `@sameRef`) is not offered either.
790
+ let builtin = "import std/Int\nimport std/Str\n\nfun same(a: Str) -> Bool = @sameRef(a, a)\n\nfun main() =\n _ := same(\"x\")\n";
791
+ std::fs::write(&path, builtin).unwrap();
792
+ let merged = plum_core::loadAndMergeDiag(&path, &repoRoot()).expect("loads");
793
+ assert!(merged.items.iter().any(|i| matches!(i, plum_core::ast::Item::Fn(f) if f.name == "@sameRef")));
794
+ let top: Vec<String> = completion::topLevelItems(&merged).into_iter().map(|i| i.label).collect();
795
+ assert!(top.iter().any(|l| l == "same") && !top.iter().any(|l| l.contains('@')), "{top:?}");
789
796
  let _ = std::fs::remove_dir_all(&dir);
790
797
  }
791
798
 
compiler/wasm-codegen/src/emit.rs CHANGED
@@ -43,7 +43,7 @@ impl<'a> Emit<'a> {
43
43
  };
44
44
  compiled_bodies.push((idx, body));
45
45
  }
46
- if units.iter().any(|u| crate::intrinsics::isMemFn(u.f)) {
46
+ if units.iter().any(|u| plum_core::compile_builtins::isMem(u.f)) {
47
47
  module.enableMemory(16);
48
48
  }
49
49
  for (idx, body) in &compiled_bodies {
compiler/wasm-codegen/src/intrinsics.rs CHANGED
@@ -11,7 +11,7 @@ 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) {
14
+ if plum_core::compile_builtins::isMem(f) {
15
15
  return compileMemIntrinsicFnBody(f);
16
16
  }
17
17
  if plum_core::compile_builtins::isSameRef(f) {
@@ -120,12 +120,8 @@ pub(crate) fn emitNativeOp(op: plum_core::native::NativeOp, body: &mut Vec<u8>)
120
120
  .encode(body);
121
121
  }
122
122
 
123
- /// A function of the std module `mem` (`std/mem.plum`): its bodies are intrinsics.
123
+ /// The linear-memory built-ins (`@memSize`, ..., `plum_core::compile_builtins`); the
124
- pub(crate) fn isMemFn(f: &ast::Fn) -> bool {
125
- f.type_param.is_none() && f.file.replace('\\', "/").ends_with("std/mem.plum")
126
- }
127
-
128
- /// `mem`'s linear-memory primitives; the declared params start at local 0.
124
+ /// declared params start at local 0.
129
125
  /// Addresses and values are `Int`
130
126
  /// (i64) wrapped to i32; `Float` is demoted to / promoted from f32.
131
127
  pub(crate) fn compileMemIntrinsicFnBody(f: &ast::Fn) -> Option<Vec<u8>> {
@@ -139,45 +135,45 @@ pub(crate) fn compileMemIntrinsicFnBody(f: &ast::Fn) -> Option<Vec<u8>> {
139
135
  align,
140
136
  memory_index: 0,
141
137
  };
142
- match plum_core::modules::sourceFnName(&f.name) {
138
+ match f.name.strip_prefix("@mem")? {
143
- "size" => {
139
+ "Size" => {
144
140
  Instruction::MemorySize(0).encode(&mut body);
145
141
  Instruction::I64ExtendI32U.encode(&mut body);
146
142
  Instruction::I64Const(65536).encode(&mut body);
147
143
  Instruction::I64Mul.encode(&mut body);
148
144
  }
149
- "grow" => {
145
+ "Grow" => {
150
146
  arg(&mut body, 0);
151
147
  Instruction::MemoryGrow(0).encode(&mut body);
152
148
  Instruction::I64ExtendI32S.encode(&mut body);
153
149
  }
154
- "storeF32" => {
150
+ "StoreF32" => {
155
151
  arg(&mut body, 0);
156
152
  Instruction::LocalGet(1).encode(&mut body);
157
153
  Instruction::F32DemoteF64.encode(&mut body);
158
154
  Instruction::F32Store(mem(0)).encode(&mut body);
159
155
  }
160
- "storeI32" => {
156
+ "StoreI32" => {
161
157
  arg(&mut body, 0);
162
158
  arg(&mut body, 1);
163
159
  Instruction::I32Store(mem(0)).encode(&mut body);
164
160
  }
165
- "storeU8" => {
161
+ "StoreU8" => {
166
162
  arg(&mut body, 0);
167
163
  arg(&mut body, 1);
168
164
  Instruction::I32Store8(mem(0)).encode(&mut body);
169
165
  }
170
- "loadF32" => {
166
+ "LoadF32" => {
171
167
  arg(&mut body, 0);
172
168
  Instruction::F32Load(mem(0)).encode(&mut body);
173
169
  Instruction::F64PromoteF32.encode(&mut body);
174
170
  }
175
- "loadI32" => {
171
+ "LoadI32" => {
176
172
  arg(&mut body, 0);
177
173
  Instruction::I32Load(mem(0)).encode(&mut body);
178
174
  Instruction::I64ExtendI32S.encode(&mut body);
179
175
  }
180
- "loadU8" => {
176
+ "LoadU8" => {
181
177
  arg(&mut body, 0);
182
178
  Instruction::I32Load8U(mem(0)).encode(&mut body);
183
179
  Instruction::I64ExtendI32U.encode(&mut body);
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs CHANGED
@@ -2790,23 +2790,22 @@ fun main() -> Int =
2790
2790
  assert_eq!(runInt(src), 3);
2791
2791
  }
2792
2792
 
2793
- // ---- Mem: linear memory primitive ----
2793
+ // ---- The linear memory built-ins (`@memSize`, `@memLoadI32`, ...) ----
2794
2794
 
2795
2795
  #[test]
2796
2796
  fn memRoundTripsAndGrows() {
2797
2797
  let src = "\
2798
2798
  import std/Int
2799
2799
  import std/Float
2800
- import std/mem
2801
2800
 
2802
2801
  fun main() -> Int =
2803
- mem.storeI32(8, -7)
2802
+ @memStoreI32(8, -7)
2804
- mem.storeF32(12, 2.5f)
2803
+ @memStoreF32(12, 2.5f)
2805
- mem.storeU8(16, 513)
2804
+ @memStoreU8(16, 513)
2806
- ok := mem.loadI32(8) == -7 && mem.loadF32(12) == 2.5f && mem.loadU8(16) == 1
2805
+ ok := @memLoadI32(8) == -7 && @memLoadF32(12) == 2.5f && @memLoadU8(16) == 1
2807
- before := mem.size()
2806
+ before := @memSize()
2808
- old := mem.grow(2)
2807
+ old := @memGrow(2)
2809
- if ok && before == 16 * 65536 && old == 16 && mem.size() == 18 * 65536 && mem.grow(100000) == -1
2808
+ if ok && before == 16 * 65536 && old == 16 && @memSize() == 18 * 65536 && @memGrow(100000) == -1
2810
2809
  1
2811
2810
  else
2812
2811
  0
@@ -2818,10 +2817,9 @@ fun main() -> Int =
2818
2817
  fn memOutOfBoundsTraps() {
2819
2818
  let src = "\
2820
2819
  import std/Int
2821
- import std/mem
2822
2820
 
2823
2821
  fun main() -> Int =
2824
- mem.loadI32(16 * 65536)
2822
+ @memLoadI32(16 * 65536)
2825
2823
  ";
2826
2824
  let dir = plum_test_support::Scratch::at(std::env::temp_dir().join(format!("plum_mem_oob_{}", std::process::id())));
2827
2825
  let path = dir.join("main.plum");
@@ -2845,10 +2843,9 @@ fun main() -> Int =
2845
2843
  fn memoryExportedOnlyWhenMemUsed() {
2846
2844
  let with = "\
2847
2845
  import std/Int
2848
- import std/mem
2849
2846
 
2850
2847
  fun main() -> Int =
2851
- mem.size()
2848
+ @memSize()
2852
2849
  ";
2853
2850
  let without = "import std/Int\n\nfun main() -> Int =\n 1\n";
2854
2851
  let exportsMemory = |name: &str, src: &str| {
std/mem.plum DELETED
@@ -1,48 +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
- # 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
tests/core/mem_builtins.plum ADDED
@@ -0,0 +1,29 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/collections/List
5
+
6
+ # The linear-memory built-ins: one growable wasm memory (16 pages of 64 KiB to start),
7
+ # present only in a program that uses one of them. Addresses are byte offsets; integers are
8
+ # stored as 32 bits and floats as f32.
9
+
10
+ fun stored(addr: Int, v: Int) -> Int =
11
+ @memStoreI32(addr, v)
12
+ @memLoadI32(addr)
13
+
14
+ test "the memory built-ins round trip"
15
+ @memStoreI32(16, -5)
16
+ assert @memLoadI32(16) == -5
17
+ @memStoreF32(32, 1.5f)
18
+ assert @memLoadF32(32) == 1.5f
19
+ @memStoreU8(40, 300)
20
+ assert @memLoadU8(40) == 44
21
+ assert @memSize() == 1048576
22
+ assert @memGrow(1) == 16
23
+ assert @memSize() == 1114112
24
+
25
+ test "a built-in is an expression like any call"
26
+ assert stored(64, 7) + stored(68, 8) == 15
27
+ total := [1, 2, 3].fold(0, |acc, n| acc + stored(72, n))
28
+ assert total == 6
29
+ assert @memLoadU8(72) == 3 && @memLoadU8(73) == 0