plum

#treesitter#compiler#wasm

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

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


3dac004 — Peter John 2026-11-10T14:46:36+05:30
@native: the body of a function the compiler supplies
Files changed (39) hide show
  1. compiler/checker/src/stmt.rs +1 -1
  2. compiler/core/src/ast.rs +3 -0
  3. compiler/core/src/blocks.rs +2 -2
  4. compiler/core/src/builtin_usage.rs +1 -1
  5. compiler/core/src/closure_escape.rs +1 -1
  6. compiler/core/src/compile_builtins.rs +2 -12
  7. compiler/core/src/drive.rs +1 -1
  8. compiler/core/src/enum_checks.rs +1 -1
  9. compiler/core/src/loader.rs +24 -0
  10. compiler/core/src/lower.rs +4 -0
  11. compiler/core/src/native.rs +123 -31
  12. compiler/core/src/parser.rs +13 -1
  13. compiler/core/src/purity.rs +7 -10
  14. compiler/core/src/tail.rs +1 -1
  15. compiler/core/src/trmc.rs +1 -1
  16. compiler/core/src/uniqueness.rs +4 -4
  17. compiler/core/src/visit.rs +2 -2
  18. compiler/core/tests/core/main.rs +1 -0
  19. compiler/core/tests/core/native_test.rs +172 -0
  20. compiler/core/tests/core/purity_test.rs +1 -1
  21. compiler/tooling/tree-sitter-plum/grammar.js +6 -0
  22. compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm +6 -0
  23. compiler/tooling/tree-sitter-plum/src/grammar.json +0 -0
  24. compiler/tooling/tree-sitter-plum/src/node-types.json +0 -0
  25. compiler/tooling/tree-sitter-plum/src/parser.c +0 -0
  26. compiler/tooling/tree-sitter-plum/test/corpus/function.txt +36 -0
  27. compiler/tooling/tree-sitter-plum/test/highlight/sample.plum +9 -0
  28. compiler/tooling/vscode-plum/syntaxes/plum.tmLanguage.json +8 -0
  29. compiler/wasm-codegen/src/closures.rs +1 -1
  30. compiler/wasm-codegen/src/emit.rs +1 -1
  31. compiler/wasm-codegen/src/fnbody.rs +1 -1
  32. compiler/wasm-codegen/src/gctypes.rs +1 -1
  33. compiler/wasm-codegen/src/intrinsics.rs +15 -24
  34. compiler/wasm-codegen/src/stmts.rs +2 -2
  35. std/Array.plum +8 -16
  36. std/Float.plum +7 -14
  37. std/Int.plum +3 -6
  38. std/Str.plum +1 -2
  39. std/math/math.plum +1 -2
compiler/checker/src/stmt.rs CHANGED
@@ -560,7 +560,7 @@ pub(crate) fn checkStmtInner(
560
560
  withCheck(|s| { let c = &s.match_tail; *c.borrow_mut() = tail.clone() });
561
561
  errors.append(&mut checkMatch(m, env, declared_ret, fn_name, fn_pos, ctx));
562
562
  }
563
- ast::StmtKind::Todo => {}
563
+ ast::StmtKind::Todo | ast::StmtKind::Native => {}
564
564
  ast::StmtKind::Crash(e) => match inferExpr(e, env, ctx) {
565
565
  Ok(t) => {
566
566
  if let Err(msg) = unify(&types::strType(), &t, ctx) {
compiler/core/src/ast.rs CHANGED
@@ -74,6 +74,7 @@ impl Stmt {
74
74
  Stmt { id: NodeId(0), span: Span::default(), kind }
75
75
  }
76
76
  pub fn Assign(a: Assign) -> Stmt { Stmt::new(StmtKind::Assign(a)) }
77
+ pub const Native: Stmt = Stmt { id: NodeId(0), span: Span { startLine: 0, startColumn: 0, endLine: 0, endColumn: 0 }, kind: StmtKind::Native };
77
78
  pub const Todo: Stmt = Stmt { id: NodeId(0), span: Span { startLine: 0, startColumn: 0, endLine: 0, endColumn: 0 }, kind: StmtKind::Todo };
78
79
  pub fn Assert(c: Check) -> Stmt { Stmt::new(StmtKind::Assert(c)) }
79
80
  pub fn While(w: While) -> Stmt { Stmt::new(StmtKind::While(w)) }
@@ -764,6 +765,8 @@ pub enum StmtKind {
764
765
  Match(Match),
765
766
  Return(Option<Expr>),
766
767
  Todo,
768
+ /// `@native`, a function's whole body: the compiler supplies it (`native`).
769
+ Native,
767
770
  /// `crash expr` — stops the program with the `Str` message `expr`.
768
771
  Crash(Expr),
769
772
  /// A bare expression statement — including a block's tail expression
compiler/core/src/blocks.rs CHANGED
@@ -53,7 +53,7 @@ impl Pass {
53
53
  self.tail(&c.body.stmts, last.span);
54
54
  }
55
55
  }
56
- StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo => {}
56
+ StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo | StmtKind::Native => {}
57
57
  _ => self.error(last.span, "the last line of a block used as a value must be a value, an 'if' or a 'match'"),
58
58
  }
59
59
  }
@@ -200,7 +200,7 @@ impl Scoper<'_> {
200
200
  }
201
201
  }
202
202
  // A `While` is only ever built by TRMC, after this pass.
203
- StmtKind::While(_) | StmtKind::Todo => {}
203
+ StmtKind::While(_) | StmtKind::Todo | StmtKind::Native => {}
204
204
  }
205
205
  }
206
206
 
compiler/core/src/builtin_usage.rs CHANGED
@@ -143,7 +143,7 @@ fn walkStmt(stmt: &Stmt, names: &mut Acc) {
143
143
  }
144
144
  }
145
145
  // A `While` is only ever built by TRMC, after this pass.
146
- StmtKind::While(_) | StmtKind::Todo => {}
146
+ StmtKind::While(_) | StmtKind::Todo | StmtKind::Native => {}
147
147
  StmtKind::Crash(e) => walkExpr(e, names),
148
148
  StmtKind::Assert(check) => walkExpr(&check.cond, names),
149
149
  StmtKind::If(i) => {
compiler/core/src/closure_escape.rs CHANGED
@@ -110,7 +110,7 @@ impl<'a> Cx<'a> {
110
110
  AssignTarget::Field(o, _) => self.expr(o, cl),
111
111
  }) || a.values.iter().any(|v| self.expr(v, cl))
112
112
  }
113
- StmtKind::Todo => false,
113
+ StmtKind::Todo | StmtKind::Native => false,
114
114
  StmtKind::Assert(c) => self.expr(&c.cond, cl),
115
115
  StmtKind::While(w) => self.expr(&w.condition, cl) || self.block(&w.body, cl),
116
116
  StmtKind::If(i) => {
compiler/core/src/compile_builtins.rs CHANGED
@@ -72,18 +72,8 @@ pub fn isDeclared(f: &Fn) -> bool {
72
72
  f.type_param.is_none() && f.name.starts_with('@')
73
73
  }
74
74
 
75
- /// Whether `f` is the declaration of `@sameRef`.
76
- pub fn isSameRef(f: &Fn) -> bool {
77
- f.type_param.is_none() && f.name == SAME_REF_FN
78
- }
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
-
85
75
  /// Declares each value built-in `source` calls and does not declare yet: a function named
86
- /// `@name` with the built-in's signature and no body of its own. Every pass then sees its
76
+ /// `@name` with the built-in's signature and the body `@native`. Every pass then sees its
87
77
  /// calls as calls of that function; codegen supplies the instructions.
88
78
  pub fn declare(source: &mut Source) {
89
79
  let mut used: Vec<&'static str> = Vec::new();
@@ -135,7 +125,7 @@ pub fn declare(source: &mut Source) {
135
125
  .map(|(i, t)| Param { name: ["a", "b"][i].to_string(), ty: ParamType::Type(ty(t)), default: None })
136
126
  .collect(),
137
127
  returns: (*ret != "Unit").then(|| ty(ret)),
138
- body: FnBody::Block(Block { stmts: vec![Stmt::Todo] }),
128
+ body: FnBody::Block(Block { stmts: vec![Stmt::Native] }),
139
129
  }));
140
130
  }
141
131
  }
compiler/core/src/drive.rs CHANGED
@@ -2233,7 +2233,7 @@ impl Driver {
2233
2233
  fn quietStmt(&self, s: &Stmt) -> bool {
2234
2234
  match &s.kind {
2235
2235
  StmtKind::Assign(a) if a.targets.iter().any(|t| matches!(t, AssignTarget::Field(..))) => false,
2236
- StmtKind::Todo => false,
2236
+ StmtKind::Todo | StmtKind::Native => false,
2237
2237
  _ => {
2238
2238
  stmtBlockRefs(s).into_iter().all(|b| b.stmts.iter().all(|s| self.quietStmt(s)))
2239
2239
  && stmtExprRefs(s).into_iter().all(|e| {
compiler/core/src/enum_checks.rs CHANGED
@@ -259,7 +259,7 @@ impl TypeWalk<'_> {
259
259
  }
260
260
  a.values.iter().for_each(|v| self.expr(v));
261
261
  }
262
- StmtKind::Todo => {}
262
+ StmtKind::Todo | StmtKind::Native => {}
263
263
  StmtKind::Crash(e) => self.expr(e),
264
264
  StmtKind::Assert(c) => self.expr(&c.cond),
265
265
  StmtKind::While(w) => {
compiler/core/src/loader.rs CHANGED
@@ -62,6 +62,7 @@ pub fn loadAndMergeWithOverridesDiag(
62
62
  collectImport(import, lib_path, overrides, &mut visited, &mut files)?;
63
63
  }
64
64
  shadowStdTypes(&mut files, lib_path)?;
65
+ nativeOnlyInStd(&files, lib_path)?;
65
66
  resolveFileModules(&mut files, lib_path)?;
66
67
  for f in &files {
67
68
  mergeItems(&f.path, &f.source, &mut items, &mut names, &mut prims)?;
@@ -172,6 +173,29 @@ fn collectImport(
172
173
  Ok(())
173
174
  }
174
175
 
176
+ /// `@native` is std's: a function outside std with that body is an error at the function.
177
+ fn nativeOnlyInStd(files: &[Loaded], lib_path: &Path) -> Loaded_<()> {
178
+ for f in files.iter().filter(|f| !isStdFile(&f.path, lib_path)) {
179
+ for item in &f.source.items {
180
+ if let Item::Fn(func) = item {
181
+ if crate::native::isNative(func) {
182
+ return Err(vec![Diagnostic::new(
183
+ DiagKind::Type,
184
+ displayPath(&f.path),
185
+ func.line,
186
+ func.column,
187
+ format!(
188
+ "`{}` is declared `@native`, which only std may do: the compiler supplies the body of std's own functions; write its body",
189
+ func.name
190
+ ),
191
+ )]);
192
+ }
193
+ }
194
+ }
195
+ }
196
+ Ok(())
197
+ }
198
+
175
199
  /// Gives each file's `import a/b` the name `b` for that module's functions and constants
176
200
  /// (see `modules`), renaming the ones several files define.
177
201
  fn resolveFileModules(files: &mut [Loaded], lib_path: &Path) -> Loaded_<()> {
compiler/core/src/lower.rs CHANGED
@@ -26,6 +26,10 @@ pub fn perFileDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
26
26
  pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
27
27
  crate::session::begin();
28
28
  crate::compile_builtins::declare(source);
29
+ let nativeErrors = crate::native::unimplemented(source);
30
+ if !nativeErrors.is_empty() {
31
+ return Err(nativeErrors);
32
+ }
29
33
  let pathErrors = crate::spread_paths::lowerSpreadPaths(source);
30
34
  if !pathErrors.is_empty() {
31
35
  return Err(pathErrors);
compiler/core/src/native.rs CHANGED
@@ -1,8 +1,15 @@
1
- //! std functions that are one native wasm instruction: declared in std with a `todo` body,
1
+ //! `@native` functions: declared with the body `@native` (in std, or by the compiler itself
2
+ //! for a value built-in such as `@sameRef`: `compile_builtins::declare`) and supplied by
2
- //! filled in by codegen (`plum_wasm_codegen::intrinsics`), and compiled in line at every
3
+ //! codegen (`plum_wasm_codegen::intrinsics`). The compiler knows each one by its qualified
4
+ //! name (`qualifiedName`), never by the path of its file: `Type.name` for a method or a
5
+ //! static, `module.name` for a module-level function, `@name` for a built-in. One the
6
+ //! compiler has no implementation for is an error (`unimplemented`).
7
+ //!
8
+ //! The ones that are one wasm instruction (`NativeOp`) are compiled in line at every direct
3
- //! direct call. Each one computes exactly what the instruction computes (IEEE 754 for the
9
+ //! call. Each computes exactly what the instruction computes (IEEE 754 for the float ones),
4
- //! float ones), the same on every wasm host.
10
+ //! the same on every wasm host.
5
11
  use crate::ast::*;
12
+ use crate::diag::{DiagKind, Diagnostic};
6
13
 
7
14
  /// The native operation a std fn compiles to. The operands are the fn's parameters in order
8
15
  /// (`self` first), each one wasm value.
@@ -28,38 +35,123 @@ pub enum NativeOp {
28
35
  F64ReinterpretI64,
29
36
  }
30
37
 
38
+ /// What the compiler supplies for a `@native` function.
39
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
40
+ pub enum Native {
41
+ /// One wasm instruction.
42
+ Op(NativeOp),
43
+ /// A method or static of `Array[T]` (`init`, `get`, `set`, ...): wasm-gc array
44
+ /// instructions.
45
+ Array,
46
+ /// `str.typeName[T]()`: the name of the type `T`, a string literal per instantiation.
47
+ TypeName,
48
+ /// `@sameRef(a, b)`: one `ref.eq`.
49
+ SameRef,
50
+ /// A linear-memory built-in (`@memSize`, `@memLoadI32`, ...).
51
+ Mem,
52
+ }
53
+
31
- /// `(file, receiver type, fn name, op)`: `None` receiver is a module-level fn.
54
+ /// Every `@native` function the compiler implements, by qualified name.
32
- const TABLE: &[(&str, Option<&str>, &str, NativeOp)] = &[
55
+ const TABLE: &[(&str, Native)] = &[
33
- ("std/math/math.plum", None, "sqrt", NativeOp::F64Sqrt),
56
+ ("math.sqrt", Native::Op(NativeOp::F64Sqrt)),
34
- ("std/Float.plum", Some("Float"), "sqrt", NativeOp::F64Sqrt),
57
+ ("Float.sqrt", Native::Op(NativeOp::F64Sqrt)),
35
- ("std/Float.plum", Some("Float"), "abs", NativeOp::F64Abs),
58
+ ("Float.abs", Native::Op(NativeOp::F64Abs)),
36
- ("std/Float.plum", Some("Float"), "floor", NativeOp::F64Floor),
59
+ ("Float.floor", Native::Op(NativeOp::F64Floor)),
37
- ("std/Float.plum", Some("Float"), "ceil", NativeOp::F64Ceil),
60
+ ("Float.ceil", Native::Op(NativeOp::F64Ceil)),
38
- ("std/Float.plum", Some("Float"), "trunc", NativeOp::F64Trunc),
61
+ ("Float.trunc", Native::Op(NativeOp::F64Trunc)),
39
- ("std/Int.plum", Some("Int"), "leadingZeros", NativeOp::I64Clz),
62
+ ("Int.leadingZeros", Native::Op(NativeOp::I64Clz)),
40
- ("std/Int.plum", Some("Int"), "trailingZeros", NativeOp::I64Ctz),
63
+ ("Int.trailingZeros", Native::Op(NativeOp::I64Ctz)),
41
- ("std/Int.plum", Some("Int"), "popCount", NativeOp::I64Popcnt),
64
+ ("Int.popCount", Native::Op(NativeOp::I64Popcnt)),
42
- ("std/Float.plum", Some("Float"), "toBits", NativeOp::I64ReinterpretF64),
65
+ ("Float.toBits", Native::Op(NativeOp::I64ReinterpretF64)),
43
- ("std/Float.plum", Some("Float"), "fromBits", NativeOp::F64ReinterpretI64),
66
+ ("Float.fromBits", Native::Op(NativeOp::F64ReinterpretI64)),
67
+ ("Array.init", Native::Array),
68
+ ("Array.get", Native::Array),
69
+ ("Array.set", Native::Array),
70
+ ("Array.length", Native::Array),
71
+ ("Array.push", Native::Array),
72
+ ("Array.resize", Native::Array),
73
+ ("Array.copy", Native::Array),
74
+ ("Array.equal", Native::Array),
75
+ ("str.typeName", Native::TypeName),
76
+ ("@sameRef", Native::SameRef),
77
+ ("@memSize", Native::Mem),
78
+ ("@memGrow", Native::Mem),
79
+ ("@memStoreF32", Native::Mem),
80
+ ("@memStoreI32", Native::Mem),
81
+ ("@memStoreU8", Native::Mem),
82
+ ("@memLoadF32", Native::Mem),
83
+ ("@memLoadI32", Native::Mem),
84
+ ("@memLoadU8", Native::Mem),
44
85
  ];
45
86
 
46
- /// The native op `f` compiles to: one of std's fns in `TABLE`, under any module rename, whose
47
- /// body is `todo`.
87
+ /// Whether `f`'s whole body is `@native`.
48
- pub fn nativeOp(f: &Fn) -> Option<NativeOp> {
88
+ pub fn isNative(f: &Fn) -> bool {
49
- if !isTodoBody(f) {
89
+ match &f.body {
90
+ FnBody::Block(b) => matches!(&b.stmts[..], [Stmt { kind: StmtKind::Native, .. }]),
91
+ _ => false,
92
+ }
93
+ }
94
+
95
+ /// The name the compiler knows `f` by: `Type.name` for a method or a static, `@name` for a
96
+ /// built-in's declaration, and `module.name` for a module-level function. The module is the
97
+ /// one an import of the file names (`modules::moduleAlias`): the file's own name without
98
+ /// its folders, lower-cased, so `std/math/math.plum`'s `sqrt` is `math.sqrt` wherever the
99
+ /// file is. A function of no file (an in-memory source) is just `name`.
100
+ pub fn qualifiedName(f: &Fn) -> String {
101
+ // A built-in's is not the module mark of a renamed function ().
102
+ if f.type_param.is_none() && f.name.starts_with('@') {
50
- return None;
103
+ return f.name.clone();
51
104
  }
52
- let file = f.file.replace('\\', "/");
53
105
  let name = crate::modules::sourceFnName(&f.name);
54
- TABLE
106
+ if let Some(t) = &f.type_param {
55
- .iter()
107
+ return format!("{t}.{name}");
108
+ }
109
+ let file = f.file.replace('\\', "/");
110
+ let stem = file.rsplit('/').next().unwrap_or("");
56
- .find(|(fl, recv, n, _)| *n == name && f.type_param.as_deref() == *recv && file.ends_with(fl))
111
+ let module = stem.strip_suffix(".plum").unwrap_or(stem).to_lowercase();
112
+ if module.is_empty() {
57
- .map(|e| e.3)
113
+ name.to_string()
114
+ } else {
115
+ format!("{module}.{name}")
116
+ }
58
117
  }
59
118
 
119
+ /// What the compiler supplies for `f`: `None` when its body is not `@native`, or when the
120
+ /// compiler has no implementation under its name (the error `unimplemented` reports).
60
- fn isTodoBody(f: &Fn) -> bool {
121
+ pub fn native(f: &Fn) -> Option<Native> {
122
+ if !isNative(f) {
123
+ return None;
124
+ }
125
+ let q = qualifiedName(f);
126
+ TABLE.iter().find(|(n, _)| *n == q).map(|e| e.1)
127
+ }
128
+
129
+ /// The one instruction `f` compiles to, when it is such a `@native` function.
130
+ pub fn nativeOp(f: &Fn) -> Option<NativeOp> {
61
- match &f.body {
131
+ match native(f) {
62
- FnBody::Block(b) => matches!(&b.stmts[..], [Stmt { kind: StmtKind::Todo, .. }]),
132
+ Some(Native::Op(op)) => Some(op),
63
- _ => false,
133
+ _ => None,
134
+ }
135
+ }
136
+
137
+ /// An error for each `@native` function the compiler has no implementation for, at the
138
+ /// function.
139
+ pub fn unimplemented(source: &Source) -> Vec<Diagnostic> {
140
+ let mut out = Vec::new();
141
+ for item in &source.items {
142
+ let Item::Fn(f) = item else { continue };
143
+ if isNative(f) && native(f).is_none() {
144
+ out.push(Diagnostic::new(
145
+ DiagKind::Type,
146
+ &f.file,
147
+ f.line,
148
+ f.column,
149
+ format!(
150
+ "`{}` is declared `@native`, but the compiler has no implementation for it; write its body",
151
+ qualifiedName(f)
152
+ ),
153
+ ));
154
+ }
64
155
  }
156
+ out
65
157
  }
compiler/core/src/parser.rs CHANGED
@@ -519,12 +519,18 @@ impl<'a> AstParser<'a> {
519
519
  match last.kind() {
520
520
  // Skip non-body trailing nodes
521
521
  "fn_identifier" | "type" | "fn_value_type" | "param" | "self" => None,
522
+ // `=` then `@native` alone on the next line: the same whole body.
523
+ "body" if matches!(&self.namedChildren(*last)[..], [only] if self.unwrapExprNode(*only).kind() == "native") => {
524
+ Some(FnBody::Block(Block { stmts: vec![Stmt::Native] }))
525
+ }
522
526
  "body" => Some(FnBody::Block(self.parseBlock(*last))),
523
527
  // `fun f(..) = match x` + indented arms: same AST as the
524
528
  // indented `=\n match x` form.
525
529
  _ => {
526
530
  let unwrapped = self.unwrapExprNode(*last);
527
531
  match unwrapped.kind() {
532
+ // `fun f(..) = @native`: the compiler supplies the body.
533
+ "native" => Some(FnBody::Block(Block { stmts: vec![Stmt::Native] })),
528
534
  // `fun f(..) = match x` + indented arms (or a block `if`): same AST
529
535
  // as the indented `=\n match x` form.
530
536
  "match" | "if" => Some(FnBody::Block(self.inlineBody(unwrapped))),
@@ -1197,7 +1203,7 @@ impl<'a> AstParser<'a> {
1197
1203
  .all(|b| Self::valueTail(&b.stmts))
1198
1204
  }
1199
1205
  Some(StmtKind::Match(m)) => m.cases.iter().all(|c| Self::valueTail(&c.body.stmts)),
1200
- Some(StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo) => true,
1206
+ Some(StmtKind::Return(_) | StmtKind::Crash(_) | StmtKind::Todo | StmtKind::Native) => true,
1201
1207
  _ => false,
1202
1208
  }
1203
1209
  }
@@ -1299,6 +1305,11 @@ impl<'a> AstParser<'a> {
1299
1305
  }
1300
1306
  "fn_call" => Expr::FnCall(self.parseFnCall(node)),
1301
1307
  "builtin_call" => self.parseBuiltinCall(node),
1308
+ // Anywhere but as a function's whole body (`parseFn` takes that one).
1309
+ "native" => {
1310
+ self.removed(node, "`@native` is only valid as a function's whole body (`fun f(..) = @native`): it says the compiler supplies the body");
1311
+ Expr::Int(0)
1312
+ }
1302
1313
  "class_call" => Expr::ClassCall(self.parseClassCall(node)),
1303
1314
  "list_literal" => self.parseListLiteral(node),
1304
1315
  "parenthesized_expression" => {
@@ -2031,6 +2042,7 @@ fn isExpressionKind(kind: &str) -> bool {
2031
2042
  | "type_identifier"
2032
2043
  | "closure"
2033
2044
  | "builtin_call"
2045
+ | "native"
2034
2046
  )
2035
2047
  }
2036
2048
 
compiler/core/src/purity.rs CHANGED
@@ -51,8 +51,8 @@ pub fn pureFns(src: &Source) -> HashSet<String> {
51
51
  }
52
52
  }
53
53
  let mut info = analyse(f, &ctors, &receivers);
54
- if crate::compile_builtins::isSameRef(f) || crate::native::nativeOp(f).is_some() {
54
+ if matches!(crate::native::native(f), Some(crate::native::Native::SameRef | crate::native::Native::Op(_))) {
55
- // `@sameRef` and std's native math ops: a `todo` body the compiler fills
55
+ // `@sameRef` and std's native math ops: a `@native` body the compiler fills
56
56
  // with one instruction (`ref.eq`, `f64.sqrt`, ...)
57
57
  info.impure = false;
58
58
  }
@@ -132,7 +132,7 @@ fn reachesIo(f: &Fn, io: &HashSet<String>) -> bool {
132
132
  /// Keys of the read-only fns: running one may stop the program or call the host, but never
133
133
  /// writes to an object the caller can see. Like `pureFns`, except `crash`/`!`/`assert`
134
134
  /// are allowed and an extern counts as read-only when every parameter is a value type
135
- /// (a scalar, `Str` or a `struct`), so it cannot be handed a mutable object. A `todo`
135
+ /// (a scalar, `Str` or a `struct`), so it cannot be handed a mutable object. A `@native`
136
136
  /// body (a builtin, e.g. `Array.set`) and a call of a fn-typed parameter are not.
137
137
  /// A pure value can move past a call of a read-only fn.
138
138
  pub fn readOnlyFns(src: &Source) -> HashSet<String> {
@@ -191,12 +191,9 @@ pub fn readOnlyFns(src: &Source) -> HashSet<String> {
191
191
  solve(keys, infos, &free, &methods)
192
192
  }
193
193
 
194
- /// A builtin: a body that is just `todo` (the compiler provides it).
194
+ /// A builtin: a body that is just `@native` (the compiler provides it).
195
195
  fn isBuiltin(f: &Fn) -> bool {
196
- match &f.body {
196
+ crate::native::isNative(f)
197
- FnBody::Block(b) => matches!(&b.stmts[..], [Stmt { kind: StmtKind::Todo, .. }]),
198
- _ => false,
199
- }
200
197
  }
201
198
 
202
199
  /// Greatest fixpoint: a fn stays in the set while it is not marked and every callee is in it.
@@ -241,7 +238,7 @@ enum Call {
241
238
 
242
239
  struct Info {
243
240
  impure: bool,
244
- /// writes a field of a non-fresh object, runs a `todo` builtin or calls a fn-typed param
241
+ /// writes a field of a non-fresh object, runs a `@native` builtin or calls a fn-typed param
245
242
  mutates: bool,
246
243
  calls: Vec<Call>,
247
244
  }
@@ -385,7 +382,7 @@ impl<'a> Walker<'a> {
385
382
  self.expr(v);
386
383
  }
387
384
  }
388
- StmtKind::Todo => {
385
+ StmtKind::Todo | StmtKind::Native => {
389
386
  self.impure = true;
390
387
  self.mutates = true;
391
388
  }
compiler/core/src/tail.rs CHANGED
@@ -82,7 +82,7 @@ fn stmt(cx: &mut Ctx, s: &mut Stmt, tail: bool, ret: bool) {
82
82
  expr(cx, v, false);
83
83
  }
84
84
  }
85
- StmtKind::Todo => {}
85
+ StmtKind::Todo | StmtKind::Native => {}
86
86
  StmtKind::Assert(c) => expr(cx, &mut c.cond, false),
87
87
  StmtKind::While(w) => {
88
88
  expr(cx, &mut w.condition, false);
compiler/core/src/trmc.rs CHANGED
@@ -193,7 +193,7 @@ fn bannedExpr(e: &Expr) -> bool {
193
193
  }
194
194
 
195
195
  fn bannedStmt(s: &Stmt) -> bool {
196
- matches!(&s.kind, StmtKind::Return(_) | StmtKind::Todo | StmtKind::Crash(_))
196
+ matches!(&s.kind, StmtKind::Return(_) | StmtKind::Todo | StmtKind::Native | StmtKind::Crash(_))
197
197
  || crate::visit::stmtExprRefs(s).into_iter().any(bannedExpr)
198
198
  || crate::visit::stmtBlockRefs(s).into_iter().any(bannedBlock)
199
199
  }
compiler/core/src/uniqueness.rs CHANGED
@@ -130,7 +130,7 @@ pub(crate) fn walkStmt<'a>(s: &'a Stmt, f: Visit<'a, '_>) {
130
130
  }
131
131
  }
132
132
  StmtKind::Return(Some(e)) | StmtKind::Crash(e) | StmtKind::Expr(e, _, _) => walkExpr(e, f),
133
- StmtKind::Return(None) | StmtKind::Todo => {}
133
+ StmtKind::Return(None) | StmtKind::Todo | StmtKind::Native => {}
134
134
  }
135
135
  }
136
136
 
@@ -253,7 +253,7 @@ fn mutStmt(s: &mut Stmt, f: &mut dyn FnMut(&mut Expr)) {
253
253
  }
254
254
  }
255
255
  StmtKind::Return(Some(e)) | StmtKind::Crash(e) | StmtKind::Expr(e, _, _) => mutExpr(e, f),
256
- StmtKind::Return(None) | StmtKind::Todo => {}
256
+ StmtKind::Return(None) | StmtKind::Todo | StmtKind::Native => {}
257
257
  }
258
258
  }
259
259
 
@@ -1086,7 +1086,7 @@ impl<'a> Scan<'a> {
1086
1086
  || m.cases.iter().any(|c| c.guard.as_ref().is_some_and(|g| self.mentions(g)) || self.mentionsStmts(&c.body.stmts))
1087
1087
  }
1088
1088
  StmtKind::Return(Some(e)) | StmtKind::Crash(e) | StmtKind::Expr(e, _, _) => self.mentions(e),
1089
- StmtKind::Return(None) | StmtKind::Todo => false,
1089
+ StmtKind::Return(None) | StmtKind::Todo | StmtKind::Native => false,
1090
1090
  };
1091
1091
  self.mentioned.borrow_mut().insert(key, m);
1092
1092
  m
@@ -1301,7 +1301,7 @@ impl<'a> Scan<'a> {
1301
1301
  self.block(&c.body, tail, live, depth + 1);
1302
1302
  }
1303
1303
  }
1304
- StmtKind::Return(None) | StmtKind::Todo => {}
1304
+ StmtKind::Return(None) | StmtKind::Todo | StmtKind::Native => {}
1305
1305
  }
1306
1306
  }
1307
1307
 
compiler/core/src/visit.rs CHANGED
@@ -131,7 +131,7 @@ pub fn stmtExprs(s: &mut Stmt) -> Vec<&mut Expr> {
131
131
  v.extend(m.cases.iter_mut().filter_map(|c| c.guard.as_mut()));
132
132
  v
133
133
  }
134
- StmtKind::Todo => vec![],
134
+ StmtKind::Todo | StmtKind::Native => vec![],
135
135
  }
136
136
  }
137
137
 
@@ -229,7 +229,7 @@ pub fn stmtExprRefs(s: &Stmt) -> Vec<&Expr> {
229
229
  v.extend(m.cases.iter().filter_map(|c| c.guard.as_ref()));
230
230
  v
231
231
  }
232
- StmtKind::Todo => vec![],
232
+ StmtKind::Todo | StmtKind::Native => vec![],
233
233
  }
234
234
  }
235
235
 
compiler/core/tests/core/main.rs CHANGED
@@ -13,6 +13,7 @@ mod list_literal_test;
13
13
  mod loader_test;
14
14
  mod lower_test;
15
15
  mod match_body_parse_test;
16
+ mod native_test;
16
17
  mod parser_test;
17
18
  mod purity_test;
18
19
  mod question_parse_test;
compiler/core/tests/core/native_test.rs ADDED
@@ -0,0 +1,172 @@
1
+ #![allow(non_snake_case)]
2
+ //! `@native`: a function's whole body, std's only, and an error when the compiler has no
3
+ //! implementation for the function.
4
+ use plum_core::ast::*;
5
+ use plum_core::loadAndMergeDiag;
6
+ use plum_core::native::{native, qualifiedName, unimplemented, Native, NativeOp};
7
+ use std::fs;
8
+ use tempfile::TempDir;
9
+
10
+ fn fnOf<'a>(s: &'a Source, name: &str) -> &'a Fn {
11
+ s.items
12
+ .iter()
13
+ .find_map(|i| match i {
14
+ Item::Fn(f) if f.name == name => Some(f),
15
+ _ => None,
16
+ })
17
+ .unwrap_or_else(|| panic!("no fn {name}"))
18
+ }
19
+
20
+ fn errText(ds: Vec<plum_core::Diagnostic>) -> String {
21
+ ds.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n")
22
+ }
23
+
24
+ /// A temp lib folder holding `std/<name>.plum` files, and the load of its `main.plum`.
25
+ fn loadWithStd(stdFiles: &[(&str, &str)], main: &str) -> Result<Source, String> {
26
+ let dir = TempDir::new().unwrap();
27
+ for (name, text) in stdFiles {
28
+ let path = dir.path().join(format!("std/{name}.plum"));
29
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
30
+ fs::write(&path, text).unwrap();
31
+ }
32
+ let entry = dir.path().join("main.plum");
33
+ fs::write(&entry, main).unwrap();
34
+ loadAndMergeDiag(&entry, dir.path()).map_err(errText)
35
+ }
36
+
37
+ /// `= @native` on the line or alone on the next one is the whole body; nothing else is.
38
+ #[test]
39
+ fn nativeIsAWholeBody() {
40
+ let s = plum_test_support::parseRawSource(
41
+ "fun a(u: Unit) -> Unit = @native\n\nfun b(u: Unit) -> Unit =\n @native\n\nfun c(u: Unit) -> Unit =\n # the compiler's\n @native\n\nfun d(u: Unit) -> Unit = u\n",
42
+ );
43
+ for n in ["a", "b", "c"] {
44
+ let f = fnOf(&s, n);
45
+ assert!(plum_core::native::isNative(f), "{n}: {:?}", f.body);
46
+ assert!(matches!(&f.body, FnBody::Block(b) if matches!(&b.stmts[..], [Stmt { kind: StmtKind::Native, .. }])));
47
+ }
48
+ assert!(!plum_core::native::isNative(fnOf(&s, "d")));
49
+ }
50
+
51
+ /// Anywhere else `@native` is an error at the `@native` itself.
52
+ #[test]
53
+ fn nativeAnywhereElseIsAnError() {
54
+ for (src, at) in [
55
+ ("fun f(u: Unit) -> Unit =\n x := @native\n x\n", ":2:8:"),
56
+ ("fun f(u: Unit) -> Unit =\n @native\n u\n", ":2:3:"),
57
+ ("fun f(u: Unit) -> Unit =\n u\n @native\n", ":3:3:"),
58
+ ("fun g(u: Unit) -> Unit = u\n\nfun f(u: Unit) -> Unit = g(@native)\n", ":3:28:"),
59
+ ("fun f(u: Unit) -> fn(Unit) -> Unit = |v| @native\n", ":1:42:"),
60
+ ("fun f(b: Bool, u: Unit) -> Unit = if b then @native else u\n", ":1:45:"),
61
+ ("fun f(b: Bool, u: Unit) -> Unit =\n if b\n @native\n else\n u\n", ":3:5:"),
62
+ ("Limit = @native\n", ":1:9:"),
63
+ ("test \"t\"\n @native\n", ":2:3:"),
64
+ ] {
65
+ let err = loadWithStd(&[], src).unwrap_err();
66
+ assert!(err.contains("`@native` is only valid as a function's whole body"), "{src}: {err}");
67
+ assert!(err.contains(at), "{src}: expected {at} in {err}");
68
+ }
69
+ }
70
+
71
+ /// Only std declares `@native` functions: one in a program's own file is an error naming it.
72
+ #[test]
73
+ fn nativeOutsideStdIsAnError() {
74
+ let err = loadWithStd(&[], "fun ok(u: Unit) -> Unit = u\n\nfun sqrt(u: Unit) -> Unit = @native\n").unwrap_err();
75
+ assert!(err.contains("main.plum:3:1:") && err.contains("`sqrt` is declared `@native`, which only std may do"), "{err}");
76
+ // A program's own folder named `std` is not the std.
77
+ let dir = TempDir::new().unwrap();
78
+ let lib = dir.path().join("lib");
79
+ fs::create_dir_all(dir.path().join("app/std")).unwrap();
80
+ fs::create_dir_all(&lib).unwrap();
81
+ let entry = dir.path().join("app/std/Float.plum");
82
+ fs::write(&entry, "fun sqrt(u: Unit) -> Unit = @native\n").unwrap();
83
+ let err = errText(loadAndMergeDiag(&entry, &lib).unwrap_err());
84
+ assert!(err.contains("which only std may do"), "{err}");
85
+ }
86
+
87
+ /// A `@native` function the compiler has no implementation for is an error naming the
88
+ /// function and where it is declared (it used to compile, and trap when called).
89
+ #[test]
90
+ fn nativeWithoutAnImplementationIsAnError() {
91
+ let std = "module std\n\nfun known(u: Unit) -> Unit = u\n\nfun cbrt(u: Unit) -> Unit = @native\n";
92
+ let err = loadWithStd(&[("math/math", std)], "import std/math/math\n\nfun main(u: Unit) -> Unit = math.known(u)\n").unwrap_err();
93
+ assert!(err.contains("math.plum:5:1:"), "{err}");
94
+ assert!(err.contains("`math.cbrt` is declared `@native`, but the compiler has no implementation for it"), "{err}");
95
+ // A method is named with its type.
96
+ let prim = "module std\n\nprimitive Byte =\n fun twice(self) -> Byte =\n @native\n";
97
+ let err = loadWithStd(&[("Byte", prim)], "import std/Byte\n\nfun main(b: Byte) -> Byte = b\n").unwrap_err();
98
+ assert!(err.contains("Byte.plum:4:3:") && err.contains("`Byte.twice` is declared `@native`"), "{err}");
99
+ // In an in-memory source too, with the fn's own position.
100
+ let s = plum_test_support::parseRawSource("fun fine(u: Unit) -> Unit = u\n\nfun gone(u: Unit) -> Unit = @native\n");
101
+ let errs = unimplemented(&s);
102
+ assert_eq!(errs.len(), 1, "{errs:?}");
103
+ assert_eq!((errs[0].line, errs[0].column), (3, 1));
104
+ assert!(errs[0].message.contains("`gone` is declared `@native`"), "{}", errs[0].message);
105
+ }
106
+
107
+ /// The compiler knows a `@native` function by its qualified name, not by the path of its
108
+ /// file: the type for a method, the module (the file's name) for a module-level function.
109
+ #[test]
110
+ fn nativesAreKnownByQualifiedName() {
111
+ let s = plum_test_support::parseRawSource(
112
+ "primitive Float =\n fun sqrt(self) -> Float = @native\n fun own(self) -> Float = self\n\nfun sqrt(x: Float) -> Float = @native\n\nfun typeName[T]() -> Str = @native\n",
113
+ );
114
+ let method = s.items.iter().find_map(|i| match i {
115
+ Item::Fn(f) if f.type_param.as_deref() == Some("Float") && f.name == "sqrt" => Some(f.clone()),
116
+ _ => None,
117
+ });
118
+ let mut method = method.expect("Float.sqrt");
119
+ // A method: any file, any folder.
120
+ for file in ["", "lib/std/Float.plum", "lib/std/math/Numbers.plum", "elsewhere/x.plum"] {
121
+ method.file = file.to_string();
122
+ assert_eq!(qualifiedName(&method), "Float.sqrt");
123
+ assert_eq!(native(&method), Some(Native::Op(NativeOp::F64Sqrt)), "{file}");
124
+ }
125
+ // A module-level function: the module is the file's name, whatever its folder.
126
+ let free = s.items.iter().find_map(|i| match i {
127
+ Item::Fn(f) if f.type_param.is_none() && f.name == "sqrt" => Some(f.clone()),
128
+ _ => None,
129
+ });
130
+ let mut free = free.expect("sqrt");
131
+ for (file, known) in [("lib/std/math/math.plum", true), ("lib/std/math.plum", true), ("moved/Math.plum", true), ("lib/std/math/trig.plum", false), ("", false)] {
132
+ free.file = file.to_string();
133
+ assert_eq!(native(&free).is_some(), known, "{file}: {}", qualifiedName(&free));
134
+ }
135
+ // A renamed one (`sqrt@math`, when another module has a `sqrt`) is the same function.
136
+ free.file = "lib/std/math/math.plum".to_string();
137
+ free.name = "sqrt@math".to_string();
138
+ assert_eq!(qualifiedName(&free), "math.sqrt");
139
+ assert_eq!(native(&free), Some(Native::Op(NativeOp::F64Sqrt)));
140
+ let mut tn = fnOf(&s, "typeName").clone();
141
+ tn.file = "lib/std/Str.plum".to_string();
142
+ assert_eq!(native(&tn), Some(Native::TypeName));
143
+ // A body that is not `@native` is never one, whatever its name.
144
+ let own = s.items.iter().find_map(|i| match i {
145
+ Item::Fn(f) if f.name == "own" => Some(f),
146
+ _ => None,
147
+ });
148
+ assert_eq!(native(own.unwrap()), None);
149
+ let src = "primitive Float =\n fun sqrt(self) -> Float = self\n";
150
+ let s = plum_test_support::parseRawSource(src);
151
+ assert_eq!(native(fnOf(&s, "sqrt")), None);
152
+ }
153
+
154
+ /// The built-ins' own declarations are `@native` functions the compiler implements.
155
+ #[test]
156
+ fn builtinDeclarationsAreNative() {
157
+ let mut s = plum_test_support::parseRawSource(
158
+ "fun f(a: Str) -> Bool =\n @memStoreI32(0, 1)\n @sameRef(a, a) && @memLoadI32(0) == @memSize()\n",
159
+ );
160
+ plum_core::compile_builtins::declare(&mut s);
161
+ assert!(unimplemented(&s).is_empty());
162
+ assert_eq!(native(fnOf(&s, "@sameRef")), Some(Native::SameRef));
163
+ for n in ["@memStoreI32", "@memLoadI32", "@memSize"] {
164
+ assert_eq!(native(fnOf(&s, n)), Some(Native::Mem), "{n}");
165
+ }
166
+ // Only the ones the program calls are declared, and each once.
167
+ let count = s.items.iter().filter(|i| matches!(i, Item::Fn(f) if f.name.starts_with('@'))).count();
168
+ assert_eq!(count, 4);
169
+ plum_core::compile_builtins::declare(&mut s);
170
+ let again = s.items.iter().filter(|i| matches!(i, Item::Fn(f) if f.name.starts_with('@'))).count();
171
+ assert_eq!(again, 4);
172
+ }
compiler/core/tests/core/purity_test.rs CHANGED
@@ -158,7 +158,7 @@ fn a_call_of_an_fn_typed_field_is_not_a_method_of_that_name() {
158
158
  assert!(p.contains("method"), "{p:?}");
159
159
  }
160
160
 
161
- /// std's native ops (`math.sqrt`, `Float.floor`, `Int.popCount`, ...) have a `todo` body the
161
+ /// std's native ops (`math.sqrt`, `Float.floor`, `Int.popCount`, ...) have a `@native` body the
162
162
  /// compiler fills with one instruction: they are pure, and so are their callers.
163
163
  #[test]
164
164
  fn std_native_ops_are_pure() {
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -531,8 +531,14 @@ module.exports = grammar({
531
531
  $.list_literal,
532
532
  $.parenthesized_expression,
533
533
  $.builtin_call,
534
+ $.native,
534
535
  ),
535
536
 
537
+ // `@native`: a function's whole body, `fun get(self, i: Int) -> T = @native`: the
538
+ // compiler supplies it. It parses as an expression so that the compiler can say what
539
+ // is wrong with one written anywhere else.
540
+ native: (_) => "@native",
541
+
536
542
  // `@typeName(Self)`: a compile-time built-in. Each argument is a type or an
537
543
  // expression; each built-in says which it takes (a name that reads as both, like
538
544
  // `Self` or `Orb`, is a type).
compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm CHANGED
@@ -131,6 +131,12 @@
131
131
 
132
132
  (todo) @keyword.control.exception
133
133
 
134
+ (native) @keyword
135
+
136
+ (builtin_call
137
+ "@" @function.builtin
138
+ name: (var_identifier) @function.builtin)
139
+
134
140
  "crash" @keyword.control.exception
135
141
 
136
142
  "match" @keyword
compiler/tooling/tree-sitter-plum/src/grammar.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/node-types.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/parser.c CHANGED
Binary file
compiler/tooling/tree-sitter-plum/test/corpus/function.txt CHANGED
@@ -552,3 +552,39 @@ fun adder(n: Int) -> fn(Int) -> Int =
552
552
  (expression
553
553
  (primary_expression
554
554
  (var_identifier))))))))
555
+
556
+ ==================
557
+ function - @native body
558
+ ==================
559
+
560
+ primitive Int =
561
+ fun popCount(self) -> Int = @native
562
+
563
+ fun sqrt(x: Float) -> Float =
564
+ @native
565
+
566
+ ---
567
+
568
+ (source
569
+ (primitive
570
+ (type_identifier)
571
+ (fn
572
+ (fn_identifier)
573
+ (self)
574
+ (type
575
+ (type_identifier))
576
+ (expression
577
+ (primary_expression
578
+ (native)))))
579
+ (fn
580
+ (fn_identifier)
581
+ (param
582
+ (var_identifier)
583
+ (type
584
+ (type_identifier)))
585
+ (type
586
+ (type_identifier))
587
+ (body
588
+ (expression
589
+ (primary_expression
590
+ (native))))))
compiler/tooling/tree-sitter-plum/test/highlight/sample.plum CHANGED
@@ -26,3 +26,12 @@ fun main() =
26
26
  crash "one"
27
27
  # <- keyword.control.exception
28
28
  printLn("Hello world")
29
+
30
+ primitive Int =
31
+ fun popCount(self) -> Int = @native
32
+ # ^ keyword
33
+
34
+ fun same(a: Str) -> Bool = @sameRef(a, a)
35
+ # ^ function.builtin
36
+ # ^ function.builtin
37
+ # ^ variable
compiler/tooling/vscode-plum/syntaxes/plum.tmLanguage.json CHANGED
@@ -42,6 +42,14 @@
42
42
  "match": "\\b(module|struct|enum|trait|primitive|fun|fn|extern|export|fip|mut|self|test)(?![A-Za-z0-9_])",
43
43
  "name": "keyword.const.plum"
44
44
  },
45
+ {
46
+ "name": "keyword.other.native.plum",
47
+ "match": "@native(?![A-Za-z0-9_])"
48
+ },
49
+ {
50
+ "name": "support.function.builtin.plum",
51
+ "match": "@[a-z][A-Za-z0-9_]*"
52
+ },
45
53
  {
46
54
  "name": "keyword.control.plum",
47
55
  "match": "\\b(import|return|continue|break|match|when|if|then|else|while|for|range|assert|todo|crash|is|as)\\b"
compiler/wasm-codegen/src/closures.rs CHANGED
@@ -171,7 +171,7 @@ impl<'a, 't> ClosureWalker<'a, 't> {
171
171
  self.walkBlock(&case.body);
172
172
  }
173
173
  }
174
- ast::Stmt { kind: ast::StmtKind::Todo, .. } => {}
174
+ ast::Stmt { kind: ast::StmtKind::Todo | ast::StmtKind::Native, .. } => {}
175
175
  ast::Stmt { kind: ast::StmtKind::Crash(e), .. } => self.walkExpr(e),
176
176
  }
177
177
  }
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| plum_core::compile_builtins::isMem(u.f)) {
46
+ if units.iter().any(|u| plum_core::native::native(u.f) == Some(plum_core::native::Native::Mem)) {
47
47
  module.enableMemory(16);
48
48
  }
49
49
  for (idx, body) in &compiled_bodies {
compiler/wasm-codegen/src/fnbody.rs CHANGED
@@ -168,7 +168,7 @@ impl<'a> Collector<'a> {
168
168
  self.walkBlock(&case.body);
169
169
  }
170
170
  }
171
- ast::Stmt { kind: ast::StmtKind::Todo, .. } => {}
171
+ ast::Stmt { kind: ast::StmtKind::Todo | ast::StmtKind::Native, .. } => {}
172
172
  ast::Stmt { kind: ast::StmtKind::Crash(e), .. } => self.walkExpr(e),
173
173
  }
174
174
  }
compiler/wasm-codegen/src/gctypes.rs CHANGED
@@ -179,7 +179,7 @@ impl GcTypeRegistry {
179
179
  /// Whether `name` is the `Array` intrinsic — it is backed by one
180
180
  /// physical wasm-gc array type (`GcTypeRegistry::array_type_idx`) instead of
181
181
  /// a struct type, and its `init`/`get`/`set`/`length` methods are
182
- /// compiler intrinsics rather than compiled `todo` bodies (see
182
+ /// compiler intrinsics (`@native` bodies) (see
183
183
  /// `compileIntrinsicFnBody`).
184
184
  pub(crate) fn isArraySpecialization(name: &str) -> bool {
185
185
  name == "Array"
compiler/wasm-codegen/src/intrinsics.rs CHANGED
@@ -2,36 +2,27 @@
2
2
 
3
3
  use crate::*;
4
4
 
5
- /// Hand-written bodies for a handful of `libs/std/str.plum` primitives that can't
5
+ /// Hand-written bodies for the `@native` functions (`plum_core::native`): std's primitives
6
- /// be expressed in Plum source at all (byte-level array access, building a new
6
+ /// that can't be expressed in Plum source at all (array access, one wasm instruction), and
7
- /// one-element array) — these three are the whole reason every other `Str` method
8
- /// (case conversion, trim, split, ...) can now be written in pure Plum on top of
9
- /// them. Declared normally in `str.plum` (with `= todo` bodies so the checker
7
+ /// the value built-ins. Each is declared normally (with the body `@native`, so the checker
10
- /// registers their real signature and validates call sites), then intercepted
8
+ /// registers its real signature and validates call sites) and recognised here by its
11
- /// here — by `fnKey` — instead of compiling their `todo` body to `unreachable`.
12
- /// Returns `None` for any other function, meaning "compile it normally."
9
+ /// qualified name. Returns `None` for any other function, meaning "compile it normally."
13
10
  pub(crate) fn compileIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<Vec<u8>> {
11
+ use plum_core::native::Native;
14
- if plum_core::compile_builtins::isMem(f) {
12
+ match plum_core::native::native(f)? {
15
- return compileMemIntrinsicFnBody(f);
13
+ Native::Mem => compileMemIntrinsicFnBody(f),
14
+ Native::SameRef => compileSameFnBody(subst),
15
+ Native::Op(op) => Some(compileNativeFnBody(f, op)),
16
+ Native::Array => compileArrayIntrinsicFnBody(f, subst),
17
+ // `emit::compileUnitBodies` compiles its body as a string literal.
18
+ Native::TypeName => None,
16
19
  }
17
- if plum_core::compile_builtins::isSameRef(f) {
18
- return compileSameFnBody(subst);
19
- }
20
- if let Some(op) = plum_core::native::nativeOp(f) {
21
- return Some(compileNativeFnBody(f, op));
22
- }
23
- if let Some(recv) = f.type_param.as_deref() {
24
- if isArraySpecialization(recv) {
25
- return compileArrayIntrinsicFnBody(f, subst);
26
- }
27
- }
28
- None
29
20
  }
30
21
 
31
- /// `str.typeName[T]()` (std/Str.plum): its body is the name of the type `T` its
22
+ /// `str.typeName[T]()` (std's module `str`): its body is the name of the type `T` its
32
23
  /// instantiation has, without type arguments.
33
24
  pub(crate) fn isTypeNameFn(f: &ast::Fn) -> bool {
34
- f.type_param.is_none() && f.name == "typeName" && f.file.replace('\\', "/").ends_with("std/Str.plum")
25
+ plum_core::native::native(f) == Some(plum_core::native::Native::TypeName)
35
26
  }
36
27
 
37
28
  /// The body of `typeName[T]` with `T` as `subst` has it: the bare name as a string
compiler/wasm-codegen/src/stmts.rs CHANGED
@@ -65,7 +65,7 @@ pub(crate) fn compileStmtInValuePosition(
65
65
  match stmt {
66
66
  ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. } => compileExpr(e, body, ctx, state),
67
67
  ast::Stmt { kind: ast::StmtKind::Return(_), .. }
68
- | ast::Stmt { kind: ast::StmtKind::Todo, .. }
68
+ | ast::Stmt { kind: ast::StmtKind::Todo | ast::StmtKind::Native, .. }
69
69
  | ast::Stmt { kind: ast::StmtKind::Crash(_), .. } => {
70
70
  compileStmt(stmt, body, ctx, state)
71
71
  }
@@ -465,7 +465,7 @@ fn compileStmtNode(
465
465
  Instruction::Call(crash_idx).encode(body);
466
466
  Instruction::Unreachable.encode(body);
467
467
  }
468
- ast::Stmt { kind: ast::StmtKind::Todo, .. } => {
468
+ ast::Stmt { kind: ast::StmtKind::Todo | ast::StmtKind::Native, .. } => {
469
469
  // Marks an unimplemented body — trap rather than silently continuing.
470
470
  Instruction::Unreachable.encode(body);
471
471
  }
std/Array.plum CHANGED
@@ -41,37 +41,31 @@ import std/Byte
41
41
  # never-`set` index traps), zero for a value `T` (`Int`/`Float`/`Bool`/`Byte`).
42
42
  primitive Array[T] =
43
43
  # A new, empty array.
44
- fun init() -> Array[T] =
44
+ fun init() -> Array[T] = @native
45
- todo
46
45
 
47
46
  # The element at index `i`. Traps if `i` is out of range (or, for a reference `T`, was never `set`).
48
- fun get(self, i: Int) -> T =
47
+ fun get(self, i: Int) -> T = @native
49
- todo
50
48
 
51
49
  # Same as `get`: the `for x := range array` iteration protocol is `length()` + `at(i)`.
52
50
  fun at(self, i: Int) -> T =
53
51
  self.get(i)
54
52
 
55
53
  # Overwrites the element at index `i` with `v`. Traps if `i` is out of range.
56
- fun set(self, i: Int, v: T) -> Unit =
54
+ fun set(self, i: Int, v: T) -> Unit = @native
57
- todo
58
55
 
59
56
  # Number of slots in the array.
60
- fun length(self) -> Int =
57
+ fun length(self) -> Int = @native
61
- todo
62
58
 
63
59
  # Returns a NEW array, one longer than `self`, with `v` appended at the end
64
60
  # — `self` itself is left untouched (this allocates and copies, it does not
65
61
  # mutate in place). Callers grow in a loop by reassigning: `arr =
66
62
  # arr.push(v)`.
67
- fun push(self, v: T) -> Array[T] =
63
+ fun push(self, v: T) -> Array[T] = @native
68
- todo
69
64
 
70
65
  # Returns a NEW array of length `n` holding `self`'s first `min(length, n)`
71
66
  # elements (the remaining slots null-shaped, like `init`/`push`). `Slice`
72
67
  # grows by doubling through this.
73
- fun resize(self, n: Int) -> Array[T] =
68
+ fun resize(self, n: Int) -> Array[T] = @native
74
- todo
75
69
 
76
70
  # A new array of length `n` with every slot set to `v`:
77
71
  # `Array[Int].filled(100, 0)`. Ordinary Plum on top of the intrinsics; for
@@ -85,14 +79,12 @@ primitive Array[T] =
85
79
 
86
80
  # Copies `n` elements of `src` from `srcStart` into `dst` at `dstStart`
87
81
  # (`array.copy`: overlapping ranges are fine). Traps if a range is out of bounds.
88
- fun copy(dst: Array[T], dstStart: Int, src: Array[T], srcStart: Int, n: Int) =
82
+ fun copy(dst: Array[T], dstStart: Int, src: Array[T], srcStart: Int, n: Int) = @native
89
- todo
90
83
 
91
84
  # True when `a[aStart..aStart+n]` and `b[bStart..bStart+n]` hold the same
92
85
  # elements (the memcmp analog; `n == 0` is always true). Scalar `T` only:
93
86
  # `Byte`, `Bool`, `Int` and `Float`.
94
- fun equal(a: Array[T], aStart: Int, b: Array[T], bStart: Int, n: Int) -> Bool =
87
+ fun equal(a: Array[T], aStart: Int, b: Array[T], bStart: Int, n: Int) -> Bool = @native
95
- todo
96
88
 
97
89
  test "Array is a primitive with working generic methods"
98
90
  a := Array[Str]().push("x").push("y")
std/Float.plum CHANGED
@@ -41,17 +41,14 @@ primitive Float =
41
41
  # The 64 IEEE 754 bits of `self` as an Int (wasm's `i64.reinterpret_f64`): the sign bit is
42
42
  # bit 63, then 11 exponent bits, then 52 fraction bits. `{-0.0}.toBits()` is `Int.Min`, a
43
43
  # NaN keeps its payload.
44
- fun toBits(self) -> Int =
44
+ fun toBits(self) -> Int = @native
45
- todo
46
45
 
47
46
  # The Float whose 64 IEEE 754 bits are `bits` (wasm's `f64.reinterpret_i64`), the inverse of
48
47
  # `toBits`: `Float.fromBits(x.toBits())` has the same bits as `x`, NaNs included.
49
- fun fromBits(bits: Int) -> Float =
48
+ fun fromBits(bits: Int) -> Float = @native
50
- todo
51
49
 
52
50
  # wasm's `f64.abs`: clears the sign bit, so `{-0.0}.abs()` is `0.0`.
53
- fun abs(self) -> Float =
51
+ fun abs(self) -> Float = @native
54
- todo
55
52
 
56
53
  # Preserves 0.0 / -0.0 / NaN, matching Go's `math.Signbit`-adjacent
57
54
  # `Copysign`/`sign` conventions loosely.
@@ -93,14 +90,11 @@ primitive Float =
93
90
  # `trunc`, `floor` and `ceil` are wasm's `f64.trunc`, `f64.floor` and `f64.ceil`: exact
94
91
  # for every Float, a whole number (or NaN, or an infinity) comes back as it was, and the
95
92
  # sign of a zero result is the receiver's (`{-0.5}.trunc()` is `-0.0`).
96
- fun trunc(self) -> Float =
93
+ fun trunc(self) -> Float = @native
97
- todo
98
94
 
99
- fun floor(self) -> Float =
95
+ fun floor(self) -> Float = @native
100
- todo
101
96
 
102
- fun ceil(self) -> Float =
97
+ fun ceil(self) -> Float = @native
103
- todo
104
98
 
105
99
  # Round-half-away-from-zero (matching Go's `math.Round`), not
106
100
  # round-half-to-even. Exact for every Float: `0.49999999999999994.round()` is `0.0`, a
@@ -139,8 +133,7 @@ primitive Float =
139
133
  Float(e - 1023)
140
134
 
141
135
  # wasm's `f64.sqrt`, like `math.sqrt`.
142
- fun sqrt(self) -> Float =
136
+ fun sqrt(self) -> Float = @native
143
- todo
144
137
 
145
138
  # self^y. A whole-number `y` (including negative) is computed exactly by
146
139
  # repeated squaring; a fractional `y` falls back to self^y = exp(y *
std/Int.plum CHANGED
@@ -101,16 +101,13 @@ primitive Int =
101
101
  # `i64.popcnt`) ----
102
102
 
103
103
  # The zero bits above the highest one bit: 64 for 0, 0 for a negative Int.
104
- fun leadingZeros(self) -> Int =
104
+ fun leadingZeros(self) -> Int = @native
105
- todo
106
105
 
107
106
  # The zero bits below the lowest one bit: 64 for 0.
108
- fun trailingZeros(self) -> Int =
107
+ fun trailingZeros(self) -> Int = @native
109
- todo
110
108
 
111
109
  # The one bits: 64 for -1.
112
- fun popCount(self) -> Int =
110
+ fun popCount(self) -> Int = @native
113
- todo
114
111
 
115
112
  fun sqrt(self) -> Float =
116
113
  math.sqrt(Float(self))
std/Str.plum CHANGED
@@ -732,8 +732,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
732
732
  # The name of the type `T`, without its type arguments (`Button[Msg]` gives "Button"):
733
733
  # a compiler intrinsic, resolved once `T` is a concrete type (see `wasm-codegen`'s
734
734
  # intrinsics). `typeName[Self]()` in a trait's default gives each implementer's own name.
735
- fun typeName[T]() -> Str =
735
+ fun typeName[T]() -> Str = @native
736
- todo
737
736
 
738
737
  test "split divides on every occurrence of the separator"
739
738
  parts := "a,b,c".split(",", 0)
std/math/math.plum CHANGED
@@ -150,8 +150,7 @@ fun lnSeries(t2: Float, t: Float) -> Float =
150
150
 
151
151
  # Square root: wasm's `f64.sqrt`, correctly rounded (IEEE 754). `sqrt(-0.0)` is `-0.0`, a
152
152
  # negative `x` or NaN gives NaN, `sqrt(Infinity)` is Infinity.
153
- fun sqrt(x: Float) -> Float =
153
+ fun sqrt(x: Float) -> Float = @native
154
- todo
155
154
 
156
155
  # Sine, fdlibm's `s_sin.c` (FreeBSD's, under 1 ulp): `|x| <= Pi/4` goes straight to the
157
156
  # kernel, anything bigger is first reduced to `x - n * Pi/2` (see `trigReduce`) and the kernel