plum

#treesitter#compiler#wasm

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

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


d84597d — Peter John 2026-11-09T23:01:45+05:30
std math: wasm's native float and bit instructions, in line at each call
compiler/core/src/lib.rs CHANGED
@@ -23,6 +23,7 @@ pub mod loader;
23
23
  pub mod lower;
24
24
  pub mod main_result;
25
25
  pub mod modules;
26
+ pub mod native;
26
27
  pub mod parser;
27
28
  pub mod prune;
28
29
  pub mod purity;
compiler/core/src/native.rs ADDED
@@ -0,0 +1,58 @@
1
+ //! std functions that are one native wasm instruction: declared in std with a `todo` body,
2
+ //! filled in by codegen (`plum_wasm_codegen::intrinsics`), and compiled in line at every
3
+ //! direct call. Each one computes exactly what the instruction computes (IEEE 754 for the
4
+ //! float ones), the same on every wasm host.
5
+ use crate::ast::*;
6
+
7
+ /// The native operation a std fn compiles to. The operands are the fn's parameters in order
8
+ /// (`self` first), each one wasm value.
9
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
10
+ pub enum NativeOp {
11
+ /// `f64.sqrt`: correctly rounded.
12
+ F64Sqrt,
13
+ /// `f64.abs`: clears the sign bit (`abs(-0.0)` is `+0.0`).
14
+ F64Abs,
15
+ /// `f64.floor`, `f64.ceil`, `f64.trunc`: exact, keep the sign of zero, pass NaN and
16
+ /// the infinities through.
17
+ F64Floor,
18
+ F64Ceil,
19
+ F64Trunc,
20
+ /// `i64.clz`, `i64.ctz`, `i64.popcnt` on the 64-bit two's complement pattern.
21
+ I64Clz,
22
+ I64Ctz,
23
+ I64Popcnt,
24
+ }
25
+
26
+ /// `(file, receiver type, fn name, op)`: `None` receiver is a module-level fn.
27
+ const TABLE: &[(&str, Option<&str>, &str, NativeOp)] = &[
28
+ ("std/math.plum", None, "sqrt", NativeOp::F64Sqrt),
29
+ ("std/Float.plum", Some("Float"), "sqrt", NativeOp::F64Sqrt),
30
+ ("std/Float.plum", Some("Float"), "abs", NativeOp::F64Abs),
31
+ ("std/Float.plum", Some("Float"), "floor", NativeOp::F64Floor),
32
+ ("std/Float.plum", Some("Float"), "ceil", NativeOp::F64Ceil),
33
+ ("std/Float.plum", Some("Float"), "trunc", NativeOp::F64Trunc),
34
+ ("std/Int.plum", Some("Int"), "leadingZeros", NativeOp::I64Clz),
35
+ ("std/Int.plum", Some("Int"), "trailingZeros", NativeOp::I64Ctz),
36
+ ("std/Int.plum", Some("Int"), "popCount", NativeOp::I64Popcnt),
37
+ ];
38
+
39
+ /// The native op `f` compiles to: one of std's fns in `TABLE`, under any module rename, whose
40
+ /// body is `todo`.
41
+ pub fn nativeOp(f: &Fn) -> Option<NativeOp> {
42
+ if !isTodoBody(f) {
43
+ return None;
44
+ }
45
+ let file = f.file.replace('\\', "/");
46
+ let name = crate::modules::sourceFnName(&f.name);
47
+ TABLE
48
+ .iter()
49
+ .find(|(fl, recv, n, _)| *n == name && f.type_param.as_deref() == *recv && file.ends_with(fl))
50
+ .map(|e| e.3)
51
+ }
52
+
53
+ fn isTodoBody(f: &Fn) -> bool {
54
+ match &f.body {
55
+ FnBody::Block(b) => matches!(&b.stmts[..], [Stmt { kind: StmtKind::Todo, .. }]),
56
+ _ => false,
57
+ }
58
+ }
compiler/core/src/purity.rs CHANGED
@@ -51,8 +51,9 @@ pub fn pureFns(src: &Source) -> HashSet<String> {
51
51
  }
52
52
  }
53
53
  let mut info = analyse(f, &ctors, &receivers);
54
- if crate::uniqueness::isSameFn(f) {
54
+ if crate::uniqueness::isSameFn(f) || crate::native::nativeOp(f).is_some() {
55
- // std's `ref.same`: a `todo` body the compiler fills with one `ref.eq`
55
+ // std's `ref.same` and the native math ops: a `todo` body the compiler fills
56
+ // with one instruction (`ref.eq`, `f64.sqrt`, ...)
56
57
  info.impure = false;
57
58
  }
58
59
  if reachesIo(f, &ioTypes) {
compiler/core/tests/core/purity_test.rs CHANGED
@@ -157,3 +157,20 @@ fn a_call_of_an_fn_typed_field_is_not_a_method_of_that_name() {
157
157
  assert!(!p.contains("typed") && !p.contains("untyped"), "{p:?}");
158
158
  assert!(p.contains("method"), "{p:?}");
159
159
  }
160
+
161
+ /// std's native ops (`math.sqrt`, `Float.floor`, `Int.popCount`, ...) have a `todo` body the
162
+ /// compiler fills with one instruction: they are pure, and so are their callers.
163
+ #[test]
164
+ fn std_native_ops_are_pure() {
165
+ let src = "import std/Int\nimport std/Float\nimport std/math\n\n\
166
+ fun len(x: Float, y: Float) -> Float = math.sqrt(x * x + y * y)\n\n\
167
+ fun cell(x: Float) -> Int = Int(x.floor()) + Int(x.abs().ceil())\n\n\
168
+ fun ones(n: Int) -> Int = n.popCount() + n.leadingZeros()\n";
169
+ let source = plum_test_support::load("native_pure", src).unwrap_or_else(|e| panic!("load: {e}"));
170
+ let pure = plum_core::purity::pureFns(&source);
171
+ let named = |n: &str| pure.iter().any(|k| k == n || plum_core::modules::sourceFnName(k) == n);
172
+ for n in ["len", "cell", "ones", "Float.floor", "Float.abs", "Int.popCount"] {
173
+ assert!(named(n), "{n} not pure: {pure:?}");
174
+ }
175
+ assert!(pure.iter().any(|k| plum_core::modules::sourceFnName(k) == "hypot"), "{pure:?}");
176
+ }
compiler/wasm-codegen/src/calls.rs CHANGED
@@ -59,6 +59,12 @@ pub(crate) fn emitCall(
59
59
  body: &mut Vec<u8>,
60
60
  ctx: &LocalCtx,
61
61
  ) {
62
+ if let Some(op) = withGen(|s| s.native_fns.get(&func_idx).copied()) {
63
+ // A std native op (`math.sqrt`, `Float.floor`, ...): its instruction in line, on the
64
+ // arguments already pushed; in a tail position too, like a plain `call`.
65
+ crate::intrinsics::emitNativeOp(op, body);
66
+ return;
67
+ }
62
68
  let ty = inferLocalType(result_expr, ctx);
63
69
  match tailMode(tail, Some(func_idx), &sig.ret, &ty, ctx) {
64
70
  TailMode::Plain => Instruction::Call(func_idx).encode(body),
compiler/wasm-codegen/src/context.rs CHANGED
@@ -283,6 +283,9 @@ pub(crate) struct GenState {
283
283
  pub(crate) err_info: ErrInfo,
284
284
  /// The global names of std's `ref.same` (std/ref.plum): its calls compile to one `ref.eq`.
285
285
  pub(crate) same_fns: std::collections::HashSet<String>,
286
+ /// The wasm functions of std's native ops (`plum_core::native`): a direct call of one
287
+ /// compiles to its instruction in line (see `calls::emitCall`).
288
+ pub(crate) native_fns: HashMap<u32, plum_core::native::NativeOp>,
286
289
  /// The program's traits.
287
290
  pub(crate) traits: Option<std::rc::Rc<plum_checker::traits::Traits>>,
288
291
  /// (trait object type, method) -> its dispatcher (see `traits.rs`).
compiler/wasm-codegen/src/driver.rs CHANGED
@@ -697,6 +697,9 @@ impl<'a> Setup<'a> {
697
697
  inst_funcs.insert(id, (func_idx, sig));
698
698
  }
699
699
  None => {
700
+ if let Some(op) = plum_core::native::nativeOp(u.f) {
701
+ withGen(|s| s.native_fns.insert(func_idx, op));
702
+ }
700
703
  let key = fnKey(u.f);
701
704
  func_ids.insert(key.clone(), func_idx);
702
705
  func_sigs.insert(key, sig);
compiler/wasm-codegen/src/intrinsics.rs CHANGED
@@ -17,6 +17,9 @@ pub(crate) fn compileIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<Vec<u
17
17
  if isSameFn(f) {
18
18
  return compileSameFnBody(subst);
19
19
  }
20
+ if let Some(op) = plum_core::native::nativeOp(f) {
21
+ return Some(compileNativeFnBody(f, op));
22
+ }
20
23
  if let Some(recv) = f.type_param.as_deref() {
21
24
  if isArraySpecialization(recv) {
22
25
  return compileArrayIntrinsicFnBody(f, subst);
@@ -90,6 +93,35 @@ pub(crate) fn castToEq(vt: &ValType, body: &mut Vec<u8>) {
90
93
  }
91
94
  }
92
95
 
96
+ /// The body of a std native op (`plum_core::native`), for a call that is not in line (the fn
97
+ /// passed as a value): its parameters, each one wasm local, then the instruction.
98
+ pub(crate) fn compileNativeFnBody(f: &ast::Fn, op: plum_core::native::NativeOp) -> Vec<u8> {
99
+ let mut body = vec![0u8];
100
+ let n = f.params.len() as u32 + u32::from(f.has_self);
101
+ for local in 0..n {
102
+ Instruction::LocalGet(local).encode(&mut body);
103
+ }
104
+ emitNativeOp(op, &mut body);
105
+ Instruction::End.encode(&mut body);
106
+ body
107
+ }
108
+
109
+ /// A std native op's instruction, on its operands already pushed.
110
+ pub(crate) fn emitNativeOp(op: plum_core::native::NativeOp, body: &mut Vec<u8>) {
111
+ use plum_core::native::NativeOp as N;
112
+ match op {
113
+ N::F64Sqrt => Instruction::F64Sqrt,
114
+ N::F64Abs => Instruction::F64Abs,
115
+ N::F64Floor => Instruction::F64Floor,
116
+ N::F64Ceil => Instruction::F64Ceil,
117
+ N::F64Trunc => Instruction::F64Trunc,
118
+ N::I64Clz => Instruction::I64Clz,
119
+ N::I64Ctz => Instruction::I64Ctz,
120
+ N::I64Popcnt => Instruction::I64Popcnt,
121
+ }
122
+ .encode(body);
123
+ }
124
+
93
125
  /// A function of the std module `mem` (`std/mem.plum`): its bodies are intrinsics.
94
126
  pub(crate) fn isMemFn(f: &ast::Fn) -> bool {
95
127
  f.type_param.is_none() && f.file.replace('\\', "/").ends_with("std/mem.plum")
compiler/wasm-codegen/tests/wasm_codegen/main.rs CHANGED
@@ -8,3 +8,4 @@ mod e2e_tail;
8
8
  mod e2e_types;
9
9
  mod examples_test;
10
10
  mod fusion_alloc_test;
11
+ mod native_test;
compiler/wasm-codegen/tests/wasm_codegen/native_test.rs ADDED
@@ -0,0 +1,117 @@
1
+ #![allow(non_snake_case)]
2
+ //! std's native ops (`plum_core::native`): a direct call of `math.sqrt`, `Float.sqrt`,
3
+ //! `abs`, `floor`, `ceil`, `trunc` or `Int.leadingZeros`/`trailingZeros`/`popCount` is the
4
+ //! one wasm instruction in line, not a `call` and not a loop. Checked with and without FBIP.
5
+ use std::collections::HashMap;
6
+
7
+ /// Per compiled function (by debug name): its operators' names.
8
+ fn operators(wasm: &[u8]) -> HashMap<String, Vec<String>> {
9
+ let mut names: HashMap<u32, String> = HashMap::new();
10
+ let mut imports = 0u32;
11
+ for p in wasmparser::Parser::new(0).parse_all(wasm) {
12
+ match p.unwrap() {
13
+ wasmparser::Payload::ImportSection(r) => {
14
+ imports = r.into_iter().filter(|i| matches!(i.as_ref().unwrap().ty, wasmparser::TypeRef::Func(_))).count() as u32
15
+ }
16
+ wasmparser::Payload::CustomSection(c) => {
17
+ if let wasmparser::KnownCustom::Name(r) = c.as_known() {
18
+ for n in r.flatten() {
19
+ if let wasmparser::Name::Function(m) = n {
20
+ for e in m.into_iter().flatten() {
21
+ names.insert(e.index, e.name.to_string());
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+ _ => {}
28
+ }
29
+ }
30
+ let mut out = HashMap::new();
31
+ let mut idx = imports;
32
+ for p in wasmparser::Parser::new(0).parse_all(wasm) {
33
+ if let wasmparser::Payload::CodeSectionEntry(b) = p.unwrap() {
34
+ let mut ops = Vec::new();
35
+ let mut r = b.get_operators_reader().unwrap();
36
+ while !r.eof() {
37
+ let op = format!("{:?}", r.read().unwrap());
38
+ ops.push(op.split([' ', '{', '(']).next().unwrap_or_default().to_string());
39
+ }
40
+ out.insert(names.get(&idx).cloned().unwrap_or_else(|| format!("f{idx}")), ops);
41
+ idx += 1;
42
+ }
43
+ }
44
+ out
45
+ }
46
+
47
+ fn count(ops: &[String], name: &str) -> usize {
48
+ ops.iter().filter(|o| *o == name).count()
49
+ }
50
+
51
+ fn compile(name: &str, src: &str, fbip: bool) -> Vec<u8> {
52
+ let source = plum_test_support::load(name, src).unwrap_or_else(|e| panic!("load: {e}"));
53
+ let opts = plum_wasm_codegen::CompileOptions {
54
+ passes: plum_driver::PassOptions { fbip, explain: false, ..plum_driver::PassOptions::default() },
55
+ ..Default::default()
56
+ };
57
+ let bytes = plum_wasm_codegen::compile(&source, &opts)
58
+ .map(|o| o.wasm)
59
+ .unwrap_or_else(|e| panic!("compile failed: {}", e.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n")));
60
+ wasmparser::validate(&bytes).expect("valid wasm");
61
+ bytes
62
+ }
63
+
64
+ fn runInt(wasm: &[u8]) -> i64 {
65
+ let engine = plum_test_support::engine();
66
+ let module = wasmtime::Module::new(&engine, wasm).unwrap();
67
+ let mut store = wasmtime::Store::new(&engine, ());
68
+ let mut linker = wasmtime::Linker::new(&engine);
69
+ linker.define_unknown_imports_as_default_values(&mut store, &module).unwrap();
70
+ let instance = linker.instantiate(&mut store, &module).unwrap();
71
+ let main = instance.get_typed_func::<(), i64>(&mut store, "main").unwrap();
72
+ main.call(&mut store, ()).unwrap()
73
+ }
74
+
75
+ const SRC: &str = "import std/Int
76
+ import std/Float
77
+ import std/math
78
+
79
+ fun calc(x: Float, y: Float) -> Float =
80
+ math.sqrt(x) + y.sqrt() + {-x}.abs() + x.floor() + y.ceil() + {-y}.trunc()
81
+
82
+ fun bits(n: Int) -> Int =
83
+ n.leadingZeros() * 10000 + n.trailingZeros() * 100 + n.popCount()
84
+
85
+ fun tailSqrt(x: Float) -> Float =
86
+ math.sqrt(x)
87
+
88
+ fun main() -> Int =
89
+ Int(calc(16.0, 6.25) * 100.0) * 1000000 + bits(40) + Int(tailSqrt(81.0)) * 1000000000000
90
+ ";
91
+
92
+ #[test]
93
+ fn native_ops_compile_in_line() {
94
+ for fbip in [true, false] {
95
+ let wasm = compile("native_ops", SRC, fbip);
96
+ let ops = operators(&wasm);
97
+ let f = |n: &str| ops.iter().find(|(k, _)| k.as_str() == n || k.ends_with(&format!(".{n}"))).map(|e| e.1).unwrap_or_else(|| panic!("no fn {n}: {:?}", ops.keys().collect::<Vec<_>>()));
98
+ let calc = f("calc");
99
+ assert_eq!(count(calc, "F64Sqrt"), 2, "{calc:?}");
100
+ assert_eq!(count(calc, "F64Abs"), 1, "{calc:?}");
101
+ assert_eq!(count(calc, "F64Floor"), 1, "{calc:?}");
102
+ assert_eq!(count(calc, "F64Ceil"), 1, "{calc:?}");
103
+ assert_eq!(count(calc, "F64Trunc"), 1, "{calc:?}");
104
+ assert_eq!(count(calc, "Call") + count(calc, "ReturnCall") + count(calc, "Loop"), 0, "{calc:?}");
105
+ let bits = f("bits");
106
+ assert_eq!(count(bits, "I64Clz"), 1, "{bits:?}");
107
+ assert_eq!(count(bits, "I64Ctz"), 1, "{bits:?}");
108
+ assert_eq!(count(bits, "I64Popcnt"), 1, "{bits:?}");
109
+ assert_eq!(count(bits, "Call"), 0, "{bits:?}");
110
+ // a native op in a tail position is no `return_call`
111
+ let t = f("tailSqrt");
112
+ assert_eq!(count(t, "F64Sqrt"), 1, "{t:?}");
113
+ assert_eq!(count(t, "Call") + count(t, "ReturnCall"), 0, "{t:?}");
114
+ // 4 + 2.5 + 16 + 16 + 7 - 6 = 39.5; 40 = 0b101000: 58 leading, 3 trailing, 2 ones
115
+ assert_eq!(runInt(&wasm), 9 * 1000000000000 + 3950 * 1000000 + 580302, "fbip {fbip}");
116
+ }
117
+ }
docs/std.md CHANGED
@@ -34,9 +34,11 @@ fun main() =
34
34
  d := Int.parse("42").unwrapOr(0)
35
35
  ```
36
36
 
37
- - `Int`: `abs`, `sign`, `min`, `max`, `pow`, `toStr`, `Int.parse`, `Int.Min`, `Int.Max`
37
+ - `Int`: `abs`, `sign`, `min`, `max`, `pow`, `toStr`, `Int.parse`, `Int.Min`, `Int.Max`, and on the 64-bit pattern `leadingZeros`, `trailingZeros`, `popCount` (64 for 0)
38
38
  - `Float`: `abs`, `sqrt`, `pow`, `floor`, `ceil`, `round`, `trunc`, `isNaN`, `toStr`, `Float.parse`, `Float.Pi`, `Float.Tau`, `Float.E`
39
39
  - `math`: `math.sqrt`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `ln`, `hypot`, `cbrt`
40
+
41
+ Where wasm has the operation, std uses its instruction, compiled in line at each call: `math.sqrt` and `Float.sqrt` are `f64.sqrt`, correctly rounded; `abs`, `floor`, `ceil` and `trunc` are `f64.abs`, `f64.floor`, `f64.ceil` and `f64.trunc`; `leadingZeros`, `trailingZeros` and `popCount` are `i64.clz`, `i64.ctz` and `i64.popcnt`. These are exact for every Float: NaN and the infinities pass through, a value past `Int`'s range comes back whole as it was, and a zero keeps its sign (`{-0.5}.floor()` is `-1.0`, `{-0.5}.ceil()` is `-0.0`, `{-0.0}.abs()` is `0.0`). `round` is half away from zero and exact too (`0.49999999999999994.round()` is `0.0`). `math.hypot(a, b)` is `sqrt(a * a + b * b)` unless that sum overflows or underflows, then it scales: `hypot(3e200, 4e200)` is about `5e200`, and an infinite side gives Infinity even next to a NaN. `min` and `max` stay comparisons: `x.min(y)` is `if x < y then x else y`, so with a NaN it returns `y`. `sin`, `cos`, `exp`, `ln` and the rest have no wasm instruction and are Plum code made of exact IEEE operations, so they give the same bits on every host.
40
42
  - `Bool`: `toStr`, `Bool.parse`
41
43
 
42
44
  ## Text
std/Float.plum CHANGED
@@ -73,8 +73,9 @@ primitive Float =
73
73
  value := whole + frac
74
74
  Ok(if neg then -value else value)
75
75
 
76
+ # wasm's `f64.abs`: clears the sign bit, so `{-0.0}.abs()` is `0.0`.
76
77
  fun abs(self) -> Float =
77
- if self < 0.0f then -self else self
78
+ todo
78
79
 
79
80
  # Preserves 0.0 / -0.0 / NaN, matching Go's `math.Signbit`-adjacent
80
81
  # `Copysign`/`sign` conventions loosely.
@@ -91,32 +92,27 @@ primitive Float =
91
92
  fun hash(self) -> Int =
92
93
  Int(self)
93
94
 
95
+ # `trunc`, `floor` and `ceil` are wasm's `f64.trunc`, `f64.floor` and `f64.ceil`: exact
96
+ # for every Float, a whole number (or NaN, or an infinity) comes back as it was, and the
94
- # `Int(f)` truncates toward zero (see `plum-wasm-codegen`'s `Int(x)`
97
+ # sign of a zero result is the receiver's (`{-0.5}.trunc()` is `-0.0`).
95
- # cross-type conversion) — exactly `trunc`'s definition.
96
98
  fun trunc(self) -> Float =
97
- Float(Int(self))
99
+ todo
98
100
 
99
101
  fun floor(self) -> Float =
100
- t := Float(Int(self))
101
- if self < 0.0f && t != self
102
- t - 1.0f
103
- else
102
+ todo
104
- t
105
103
 
106
104
  fun ceil(self) -> Float =
107
- t := Float(Int(self))
108
- if self > 0.0f && t != self
109
- t + 1.0f
110
- else
105
+ todo
111
- t
112
106
 
113
107
  # Round-half-away-from-zero (matching Go's `math.Round`), not
114
- # round-half-to-even.
108
+ # round-half-to-even. Exact for every Float: `0.49999999999999994.round()` is `0.0`, a
109
+ # whole number, NaN or an infinity comes back as it was, a zero result keeps the sign.
115
110
  fun round(self) -> Float =
116
- neg := self < 0.0f
111
+ t := self.trunc()
112
+ if {self - t}.abs() >= 0.5f
117
- v := if neg then -self else self
113
+ if self < 0.0f then t - 1.0f else t + 1.0f
118
- r := {v + 0.5f}.floor()
119
- if neg then -r else r
114
+ else
115
+ t
120
116
 
121
117
  fun log(self) -> Float =
122
118
  math.ln(self)
@@ -134,8 +130,9 @@ primitive Float =
134
130
  else
135
131
  {math.ln(if self < 0.0f then -self else self) * Float.Log2E}.floor()
136
132
 
133
+ # wasm's `f64.sqrt`, like `math.sqrt`.
137
134
  fun sqrt(self) -> Float =
138
- math.sqrt(self)
135
+ todo
139
136
 
140
137
  # self^y. A whole-number `y` (including negative) is computed exactly by
141
138
  # repeated squaring; a fractional `y` falls back to self^y = exp(y *
std/Int.plum CHANGED
@@ -83,14 +83,22 @@ primitive Int =
83
83
  -1.0f / 0.0f
84
84
  else
85
85
  n := if self < 0 then -self else self
86
- Float(log2Floor(n, 0))
86
+ Float(63 - n.leadingZeros())
87
87
 
88
+ # ---- bits, on the 64-bit two's complement pattern (wasm's `i64.clz`, `i64.ctz`,
89
+ # `i64.popcnt`) ----
90
+
91
+ # The zero bits above the highest one bit: 64 for 0, 0 for a negative Int.
92
+ fun leadingZeros(self) -> Int =
93
+ todo
94
+
88
- # floor(log2(n)) for n > 0, counting halvings in `k`.
95
+ # The zero bits below the lowest one bit: 64 for 0.
96
+ fun trailingZeros(self) -> Int =
97
+ todo
98
+
99
+ # The one bits: 64 for -1.
89
- fun log2Floor(n: Int, k: Int) -> Int =
100
+ fun popCount(self) -> Int =
90
- if n >= 2
91
- log2Floor(n / 2, k + 1)
92
- else
101
+ todo
93
- k
94
102
 
95
103
  fun sqrt(self) -> Float =
96
104
  math.sqrt(Float(self))
std/math.plum CHANGED
@@ -98,20 +98,10 @@ fun lnSeries(t2: Float, term: Float, sum: Float, n: Int) -> Float =
98
98
  else
99
99
  sum
100
100
 
101
+ # Square root: wasm's `f64.sqrt`, correctly rounded (IEEE 754). `sqrt(-0.0)` is `-0.0`, a
101
- # Square root via Newton's method, iterating to a fixed point.
102
+ # negative `x` or NaN gives NaN, `sqrt(Infinity)` is Infinity.
102
103
  fun sqrt(x: Float) -> Float =
103
- if x < 0.0f
104
- 0.0f / 0.0f
105
- else if x == 0.0f || x != x
106
- x
107
- else
104
+ todo
108
- sqrtFrom(x, x, 0.0f, 0)
109
-
110
- fun sqrtFrom(x: Float, guess: Float, prev: Float, i: Int) -> Float =
111
- if guess != prev && i < 100
112
- sqrtFrom(x, 0.5f * {guess + x / guess}, guess, i + 1)
113
- else
114
- guess
115
105
 
116
106
  # Reduces `x` into roughly `[-Float.Pi, Float.Pi]` by subtracting the nearest multiple of
117
107
  # `Float.Tau` — the range `sin`/`cos`'s Taylor series below actually converge
@@ -120,8 +110,8 @@ fun sqrtFrom(x: Float, guess: Float, prev: Float, i: Int) -> Float =
120
110
  # range-reduction by subtraction does; a real libm uses extended-precision
121
111
  # constants to avoid this, which isn't attempted here.
122
112
  fun reduceToPi(x: Float) -> Float =
123
- k := Int(x / Float.Tau + {if x >= 0.0f then 0.5f else -0.5f})
113
+ k := {x / Float.Tau + {if x >= 0.0f then 0.5f else -0.5f}}.trunc()
124
- x - Float(k) * Float.Tau
114
+ x - k * Float.Tau
125
115
 
126
116
  fun sin(x: Float) -> Float =
127
117
  if x != x || x > Float.Max || x < -Float.Max
@@ -203,8 +193,30 @@ fun atan2(y: Float, x: Float) -> Float =
203
193
  else
204
194
  0.0f
205
195
 
196
+ # sqrt(a^2 + b^2), without overflow or underflow on the way: exactly `sqrt(a * a + b * b)`
197
+ # when that sum is a finite number above 2^-968 (so every term that counts in it is a normal
198
+ # float), else the larger side times sqrt(1 + r^2), r the ratio of the smaller to it.
199
+ # `hypot` of an infinity is Infinity, even with a NaN.
206
200
  fun hypot(a: Float, b: Float) -> Float =
207
- sqrt(a * a + b * b)
201
+ s := a * a + b * b
202
+ if s <= Float.Max && s >= 4.008336720017946e-292
203
+ sqrt(s)
204
+ else
205
+ hypotScaled(a.abs(), b.abs())
206
+
207
+ fun hypotScaled(x: Float, y: Float) -> Float =
208
+ if x > Float.Max || y > Float.Max
209
+ 1.0f / 0.0f
210
+ else if x != x || y != y
211
+ x + y
212
+ else
213
+ big := if x > y then x else y
214
+ small := if x > y then y else x
215
+ if big == 0.0f
216
+ 0.0f
217
+ else
218
+ r := small / big
219
+ big * sqrt(1.0f + r * r)
208
220
 
209
221
  # Cube root via Newton's method (fixed iteration count, unlike `sqrt`'s
210
222
  # converge-to-a-fixed-point loop, since the cubic update step doesn't reach an
tests/core/native_math.plum ADDED
@@ -0,0 +1,154 @@
1
+ # std's native math ops (`plum_core::native`): `math.sqrt`, `Float.sqrt/abs/floor/ceil/trunc`
2
+ # and `Int.leadingZeros/trailingZeros/popCount` are one wasm instruction each; `round`,
3
+ # `hypot` and `Int.logb` are built on them. Edge cases: zeros of both signs, NaN, the
4
+ # infinities, subnormals, halves and values past 2^53 and 2^63.
5
+ import std/Float
6
+ import std/Int
7
+ import std/math
8
+ import std/Slice
9
+
10
+ Inf = 1.0f / 0.0f
11
+ NaN = 0.0f / 0.0f
12
+
13
+ # Whether `x` is a zero with the sign bit set.
14
+ fun negZero(x: Float) -> Bool =
15
+ x == 0.0f && 1.0f / x < 0.0f
16
+
17
+ fun posZero(x: Float) -> Bool =
18
+ x == 0.0f && 1.0f / x > 0.0f
19
+
20
+ # A closure over a native op.
21
+ fun apply(f: fn(Float) -> Float, x: Float) -> Float =
22
+ f(x)
23
+
24
+ test "sqrt is correctly rounded"
25
+ assert math.sqrt(16.0f) == 4.0f
26
+ assert math.sqrt(2.0f) == Float.Sqrt2
27
+ assert math.sqrt(0.5f) == Float.SqrtHalf
28
+ assert 2.25.sqrt() == 1.5f
29
+ assert 4.sqrt() == 2.0f
30
+ # the square of the result brackets x: no closer double exists
31
+ assert math.sqrt(1.0e300) == 1.0e150
32
+ assert math.sqrt(1.0e-300) == 1.0e-150
33
+
34
+ test "sqrt of zeros, NaN, infinities, negatives and subnormals"
35
+ assert posZero(math.sqrt(0.0f))
36
+ assert negZero(math.sqrt(-0.0f))
37
+ assert math.sqrt(Inf) == Inf
38
+ assert math.sqrt(-1.0f).isNaN()
39
+ assert math.sqrt(-Inf).isNaN()
40
+ assert math.sqrt(NaN).isNaN()
41
+ assert math.sqrt(Float.Min) == 2.2227587494850775e-162
42
+ assert math.sqrt(Float.Max) == 1.3407807929942596e+154
43
+
44
+ test "sqrt in a closure"
45
+ assert apply(|x| math.sqrt(x), 9.0f) == 3.0f
46
+ assert apply(|x| math.sqrt(x), -1.0f).isNaN()
47
+ assert apply(|x| x.sqrt(), Inf) == Inf
48
+
49
+ test "abs clears the sign bit"
50
+ assert {-2.5}.abs() == 2.5f
51
+ assert 2.5.abs() == 2.5f
52
+ assert posZero({-0.0f}.abs())
53
+ assert {-Inf}.abs() == Inf
54
+ assert NaN.abs().isNaN()
55
+ assert {-Float.Min}.abs() == Float.Min
56
+ assert apply(|x| x.abs(), -3.0f) == 3.0f
57
+
58
+ test "trunc, floor and ceil of ordinary values"
59
+ assert 2.7.trunc() == 2.0f
60
+ assert {-2.7}.trunc() == -2.0f
61
+ assert 2.7.floor() == 2.0f
62
+ assert {-2.7}.floor() == -3.0f
63
+ assert 2.3.ceil() == 3.0f
64
+ assert {-2.3}.ceil() == -2.0f
65
+ assert 3.0.floor() == 3.0f
66
+ assert {-3.0}.ceil() == -3.0f
67
+
68
+ test "trunc, floor and ceil keep the sign of a zero result"
69
+ assert negZero({-0.5}.trunc())
70
+ assert negZero({-0.5}.ceil())
71
+ assert negZero({-0.0f}.floor())
72
+ assert posZero(0.5.floor())
73
+ assert posZero(0.5.trunc())
74
+ assert {-0.5}.floor() == -1.0f
75
+ assert 0.5.ceil() == 1.0f
76
+
77
+ test "trunc, floor and ceil past Int's range, of NaN and the infinities"
78
+ assert 1.0e300.trunc() == 1.0e300
79
+ assert {-1.0e300}.floor() == -1.0e300
80
+ assert 1.0e19.ceil() == 1.0e19
81
+ assert 9007199254740993.0f.floor() == 9007199254740993.0f
82
+ assert Inf.floor() == Inf
83
+ assert {-Inf}.ceil() == -Inf
84
+ assert NaN.trunc().isNaN()
85
+ assert NaN.floor().isNaN()
86
+ assert NaN.ceil().isNaN()
87
+ assert posZero(Float.Min.floor())
88
+ assert Float.Min.ceil() == 1.0f
89
+ assert {-Float.Min}.floor() == -1.0f
90
+
91
+ test "round is half away from zero, exactly"
92
+ assert 2.5.round() == 3.0f
93
+ assert {-2.5}.round() == -3.0f
94
+ assert 0.5.round() == 1.0f
95
+ assert {-0.5}.round() == -1.0f
96
+ assert 1.5.round() == 2.0f
97
+ assert 2.4999.round() == 2.0f
98
+ # the largest Float below one half: adding 0.5 to it would round up to 1
99
+ assert posZero(0.49999999999999994.round())
100
+ assert negZero({-0.49999999999999994}.round())
101
+ assert negZero({-0.0f}.round())
102
+ assert negZero({-0.3}.round())
103
+ # above 2^52 every Float is whole
104
+ assert 4503599627370497.0f.round() == 4503599627370497.0f
105
+ assert 1.0e300.round() == 1.0e300
106
+ assert Inf.round() == Inf
107
+ assert NaN.round().isNaN()
108
+
109
+ test "hypot is sqrt(a^2 + b^2) without overflow or underflow"
110
+ assert math.hypot(3.0f, 4.0f) == 5.0f
111
+ assert math.hypot(-3.0f, 4.0f) == 5.0f
112
+ assert math.hypot(0.0f, 0.0f) == 0.0f
113
+ assert math.hypot(0.0f, -7.0f) == 7.0f
114
+ # (3e200 and 4e200 are not exact: the correctly rounded result is one ulp below 5e200)
115
+ assert math.hypot(3.0e200, 4.0e200) == 4.9999999999999995e+200
116
+ assert math.hypot(3.0e-200, 4.0e-200) == 5.0e-200
117
+ assert math.hypot(Float.Max, 1.0f) == Float.Max
118
+ assert math.hypot(Inf, NaN) == Inf
119
+ assert math.hypot(NaN, -Inf) == Inf
120
+ assert math.hypot(NaN, 1.0f).isNaN()
121
+ a := 0.1f
122
+ b := 0.7f
123
+ assert math.hypot(a, b) == math.sqrt(a * a + b * b)
124
+
125
+ test "leadingZeros, trailingZeros and popCount on the 64-bit pattern"
126
+ assert 0.leadingZeros() == 64
127
+ assert 1.leadingZeros() == 63
128
+ assert {-1}.leadingZeros() == 0
129
+ assert Int.Max.leadingZeros() == 1
130
+ assert 0.trailingZeros() == 64
131
+ assert 8.trailingZeros() == 3
132
+ assert Int.Min.trailingZeros() == 63
133
+ assert 0.popCount() == 0
134
+ assert 255.popCount() == 8
135
+ assert {-1}.popCount() == 64
136
+ assert Int.Min.popCount() == 1
137
+
138
+ test "Int.logb is floor(log2(|n|))"
139
+ assert 1.logb() == 0.0f
140
+ assert 2.logb() == 1.0f
141
+ assert 1023.logb() == 9.0f
142
+ assert 1024.logb() == 10.0f
143
+ assert {-8}.logb() == 3.0f
144
+ assert Int.Max.logb() == 62.0f
145
+ assert Int.Min.logb() == 63.0f
146
+ assert 0.logb() == -Inf
147
+
148
+ test "sin and cos after the range reduction"
149
+ assert math.sin(0.0f) == 0.0f
150
+ assert math.cos(0.0f) == 1.0f
151
+ assert {math.sin(Float.HalfPi) - 1.0f}.abs() < 1.0e-12
152
+ assert {math.sin(100.0f) - -0.5063656411097588f}.abs() < 1.0e-12
153
+ assert {math.cos(-100.0f) - 0.8623188722876839f}.abs() < 1.0e-12
154
+ assert math.sin(Inf).isNaN()
tests/port/game/replay.plum CHANGED
@@ -256,9 +256,11 @@ test "a bad replay says what is wrong"
256
256
  else
257
257
  assert false
258
258
 
259
- # std's maths is Plum code made of IEEE 754 double operations, which wasm defines exactly,
259
+ # std's maths is Plum code made of IEEE 754 double operations and wasm's own `f64.sqrt`,
260
- # so every browser and the native host compute the same bits.
260
+ # `f64.floor`, ..., which wasm defines exactly, so every browser and the native host compute
261
+ # the same bits. `sqrt` is correctly rounded: sqrt(2) is `Float.Sqrt2`, 0x3FF6A09E667F3BCD.
261
262
  test "std maths gives the same results on every host"
262
263
  assert replay.floatCode(math.sin(1.0)) == "3789648413623927:-52"
263
- assert replay.floatCode(math.sqrt(2.0)) == "1592262918131443:-50"
264
+ assert replay.floatCode(math.sqrt(2.0)) == "6369051672525773:-52"
265
+ assert math.sqrt(2.0) == Float.Sqrt2
264
266
  assert math.hypot(3.0, 4.0) == 5.0