plum

#treesitter#compiler#wasm

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

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


7152cc2 — Peter John 2026-11-11T02:41:59+05:30
std: native Int/Byte/Bool/Float compare, copied into their callers
compiler/core/src/native.rs CHANGED
@@ -5,9 +5,10 @@
5
5
  //! static, `module.name` for a module-level function, `@name` for a built-in. One the
6
6
  //! compiler has no implementation for is an error (`unimplemented`).
7
7
  //!
8
- //! The ones that are one wasm instruction (`NativeOp`) are compiled in line at every direct
8
+ //! The ones that are a few wasm instructions (`NativeOp`) are compiled in line at every direct
9
+ //! call when they read each operand once (`NativeOp::inLine`); the `compare`s read each twice and
10
+ //! are small functions that the wasm post-pass copies into their callers. Each computes exactly
9
- //! call. Each computes exactly what the instruction computes (IEEE 754 for the float ones),
11
+ //! what its instructions compute (IEEE 754 for the float ones), the same on every wasm host.
10
- //! the same on every wasm host.
11
12
  use crate::ast::*;
12
13
  use crate::diag::{DiagKind, Diagnostic};
13
14
 
@@ -33,6 +34,22 @@ pub enum NativeOp {
33
34
  I64ReinterpretF64,
34
35
  /// `f64.reinterpret_i64`: the Float whose bits are the Int's 64-bit pattern.
35
36
  F64ReinterpretI64,
37
+ /// `Int.compare`: -1, 0 or 1, `(a > b) - (a < b)` widened to an Int.
38
+ I64Compare,
39
+ /// `Byte.compare`: the same on two unsigned 8-bit values.
40
+ U32Compare,
41
+ /// `Bool.compare`: `a - b` (false before true) widened to an Int.
42
+ BoolCompare,
43
+ /// `Float.compare`: `(a > b) - (a < b)`, plus `(a != a) - (b != b)` so that every NaN is one
44
+ /// value after `Infinity`; `-0.0` and `0.0` compare equal.
45
+ F64Compare,
46
+ }
47
+
48
+ impl NativeOp {
49
+ /// Compiled in line at a call, on the arguments the call pushed: each is read once.
50
+ pub fn inLine(self) -> bool {
51
+ !matches!(self, NativeOp::I64Compare | NativeOp::U32Compare | NativeOp::F64Compare)
52
+ }
36
53
  }
37
54
 
38
55
  /// What the compiler supplies for a `@native` function.
@@ -64,6 +81,10 @@ const TABLE: &[(&str, Native)] = &[
64
81
  ("Int.popCount", Native::Op(NativeOp::I64Popcnt)),
65
82
  ("Float.toBits", Native::Op(NativeOp::I64ReinterpretF64)),
66
83
  ("Float.fromBits", Native::Op(NativeOp::F64ReinterpretI64)),
84
+ ("Int.compare", Native::Op(NativeOp::I64Compare)),
85
+ ("Byte.compare", Native::Op(NativeOp::U32Compare)),
86
+ ("Bool.compare", Native::Op(NativeOp::BoolCompare)),
87
+ ("Float.compare", Native::Op(NativeOp::F64Compare)),
67
88
  ("Array.init", Native::Array),
68
89
  ("Array.at", Native::Array),
69
90
  ("Array.set", Native::Array),
compiler/wasm-codegen/src/driver.rs CHANGED
@@ -703,7 +703,7 @@ impl<'a> Setup<'a> {
703
703
  inst_funcs.insert(id, (func_idx, sig));
704
704
  }
705
705
  None => {
706
- if let Some(op) = plum_core::native::nativeOp(u.f) {
706
+ if let Some(op) = plum_core::native::nativeOp(u.f).filter(|op| op.inLine()) {
707
707
  withGen(|s| s.native_fns.insert(func_idx, op));
708
708
  }
709
709
  let key = fnKey(u.f);
compiler/wasm-codegen/src/intrinsics.rs CHANGED
@@ -82,13 +82,45 @@ pub(crate) fn castToEq(vt: &ValType, body: &mut Vec<u8>) {
82
82
  /// one in a type (`Float.fromBits`) still has the type's leading self slot (one local: the
83
83
  /// receivers are `Int` and `Float`), which it skips.
84
84
  pub(crate) fn compileNativeFnBody(f: &ast::Fn, op: plum_core::native::NativeOp) -> Vec<u8> {
85
+ use plum_core::native::NativeOp as N;
85
86
  let mut body = vec![0u8];
87
+ let get = |l: u32, body: &mut Vec<u8>| Instruction::LocalGet(l).encode(body);
88
+ // The `compare`s read `self` (local 0) and `o` (local 1) twice each, with no branch: small
89
+ // enough for `optimize::inlineLeaves` to copy into each caller.
90
+ let ordered = |gt: Instruction, lt: Instruction, body: &mut Vec<u8>| {
91
+ get(0, body);
92
+ get(1, body);
93
+ gt.encode(body);
94
+ get(0, body);
95
+ get(1, body);
96
+ lt.encode(body);
97
+ Instruction::I32Sub.encode(body);
98
+ };
99
+ match op {
100
+ N::I64Compare => ordered(Instruction::I64GtS, Instruction::I64LtS, &mut body),
101
+ N::U32Compare => ordered(Instruction::I32GtU, Instruction::I32LtU, &mut body),
102
+ N::F64Compare => {
103
+ ordered(Instruction::F64Gt, Instruction::F64Lt, &mut body);
104
+ for l in 0..2 {
105
+ get(l, &mut body);
106
+ get(l, &mut body);
107
+ Instruction::F64Ne.encode(&mut body);
108
+ }
109
+ Instruction::I32Sub.encode(&mut body);
110
+ Instruction::I32Add.encode(&mut body);
111
+ }
112
+ _ => {
86
- let skip = u32::from(f.type_param.is_some() && !f.has_self);
113
+ let skip = u32::from(f.type_param.is_some() && !f.has_self);
87
- let n = f.params.len() as u32 + u32::from(f.has_self);
114
+ let n = f.params.len() as u32 + u32::from(f.has_self);
88
- for local in skip..skip + n {
115
+ for local in skip..skip + n {
116
+ get(local, &mut body);
117
+ }
118
+ emitNativeOp(op, &mut body);
89
- Instruction::LocalGet(local).encode(&mut body);
119
+ Instruction::End.encode(&mut body);
120
+ return body;
121
+ }
90
122
  }
91
- emitNativeOp(op, &mut body);
123
+ Instruction::I64ExtendI32S.encode(&mut body);
92
124
  Instruction::End.encode(&mut body);
93
125
  body
94
126
  }
@@ -107,6 +139,11 @@ pub(crate) fn emitNativeOp(op: plum_core::native::NativeOp, body: &mut Vec<u8>)
107
139
  N::I64Popcnt => Instruction::I64Popcnt,
108
140
  N::I64ReinterpretF64 => Instruction::I64ReinterpretF64,
109
141
  N::F64ReinterpretI64 => Instruction::F64ReinterpretI64,
142
+ N::BoolCompare => {
143
+ Instruction::I32Sub.encode(body);
144
+ Instruction::I64ExtendI32S
145
+ }
146
+ N::I64Compare | N::U32Compare | N::F64Compare => unreachable!("a `compare` is not compiled in line: NativeOp::inLine"),
110
147
  }
111
148
  .encode(body);
112
149
  }
compiler/wasm-codegen/src/module.rs CHANGED
@@ -202,6 +202,8 @@ impl WasmModule {
202
202
  }
203
203
  let saved = (self.functions.clone(), self.exports.clone(), self.start_function, self.table_elements.clone(), self.func_names.clone());
204
204
  let r = crate::optimize::removeRedundantCasts(self)
205
+ .and_then(|_| crate::optimize::inlineLeaves(self))
206
+ // Again, for the calls inside what the first round copied (`Int.compare` in a small fn).
205
207
  .and_then(|_| crate::optimize::inlineLeaves(self))
206
208
  .and_then(|_| crate::optimize::removeRedundantCasts(self))
207
209
  .and_then(|_| if keepDeadFns { Ok(0) } else { crate::optimize::removeDeadFunctions(self) })
compiler/wasm-codegen/src/optimize.rs CHANGED
@@ -215,13 +215,67 @@ pub(crate) fn removeDeadFunctions(module: &mut WasmModule) -> Result<usize, Stri
215
215
  /// Largest body (in bytes, after its parameter loads) `inlineLeaves` copies into a caller.
216
216
  pub(crate) const INLINE_LIMIT: usize = 20;
217
217
 
218
+ /// Largest body `inlineLeaves` copies into a caller when it reads its (number) parameters out of
219
+ /// order or more than once (`Int.compare`): the caller stores the arguments in locals of its own.
220
+ pub(crate) const SPILL_INLINE_LIMIT: usize = 32;
221
+
222
+ /// The one-byte encoding of a number value type, the only kind a spilled parameter may have
223
+ /// (a local of it needs no initialiser).
224
+ fn numberValType(t: wasmparser::ValType) -> Option<u8> {
225
+ match t {
226
+ wasmparser::ValType::I32 => Some(0x7F),
227
+ wasmparser::ValType::I64 => Some(0x7E),
228
+ wasmparser::ValType::F32 => Some(0x7D),
229
+ wasmparser::ValType::F64 => Some(0x7C),
230
+ _ => None,
231
+ }
232
+ }
233
+
234
+ /// `body` with `extra` more locals declared after its own, one group per local.
235
+ fn addLocals(body: &[u8], extra: &[u8]) -> Result<Vec<u8>, String> {
236
+ let mut r = wasmparser::BinaryReader::new(body, 0);
237
+ let groups = r.read_var_u32().map_err(|e| e.to_string())?;
238
+ let from = r.original_position();
239
+ for _ in 0..groups {
240
+ r.read_var_u32().map_err(|e| e.to_string())?;
241
+ r.read::<wasmparser::ValType>().map_err(|e| e.to_string())?;
242
+ }
243
+ let to = r.original_position();
244
+ let mut out = Vec::with_capacity(body.len() + 2 * extra.len() + 5);
245
+ leb(groups + extra.len() as u32, &mut out);
246
+ out.extend_from_slice(&body[from..to]);
247
+ for t in extra {
248
+ out.push(1);
249
+ out.push(*t);
250
+ }
251
+ out.extend_from_slice(&body[to..]);
252
+ Ok(out)
253
+ }
254
+
255
+ fn leb(mut v: u32, out: &mut Vec<u8>) {
256
+ loop {
257
+ let b = (v & 0x7F) as u8;
258
+ v >>= 7;
259
+ if v == 0 {
260
+ out.push(b);
261
+ return;
262
+ }
263
+ out.push(b | 0x80);
264
+ }
265
+ }
266
+
218
267
  /// Copies the body of every small straight-line function into each place that calls it.
219
268
  /// A candidate declares no locals, starts by loading its parameters in order
220
269
  /// (`local.get 0 .. local.get n-1`, exactly what its caller has just pushed), then runs at
221
270
  /// most `INLINE_LIMIT` bytes that touch no local and hold no block, branch or return: so
222
271
  /// the bytes after the loads, put where the `call` was, do the same work on the same
223
272
  /// stack (a `return_call` becomes those bytes and a `return`). Accessors such as
224
- /// `Str.length` or `Array.at` go this way. Returns the number of call sites inlined.
273
+ /// `Str.length` or `Array.at` go this way. A body whose number parameters are read in
274
+ /// another order or more than once (`Int.compare` reads both twice), of at most
275
+ /// `SPILL_INLINE_LIMIT` bytes, is copied too: the caller first stores the arguments in
276
+ /// locals it adds for that callee's parameter types (one set per caller and signature, as
277
+ /// each copy uses them up at once), and the copy reads those. Returns the number of call
278
+ /// sites inlined.
225
279
  pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
226
280
  let bytes = module.encode();
227
281
  let imports = module.func_import_count;
@@ -232,8 +286,18 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
232
286
  rest: Option<usize>,
233
287
  end: Option<usize>,
234
288
  ok: bool,
289
+ /// The spilling form: every parameter a number, no other local touched, no control.
290
+ spill: bool,
291
+ tys: Vec<u8>,
292
+ first: Option<usize>,
293
+ /// `(start, end, parameter)` of each `local.get`.
294
+ gets: Vec<(usize, usize, u32)>,
235
295
  }
296
+ let mut scans: Vec<Scan> = (0..n)
236
- let mut scans: Vec<Scan> = (0..n).map(|_| Scan { params: 0, loaded: 0, rest: None, end: None, ok: false }).collect();
297
+ .map(|_| Scan { params: 0, loaded: 0, rest: None, end: None, ok: false, spill: false, tys: vec![], first: None, gets: vec![] })
298
+ .collect();
299
+ // Every local a function has (parameters included), for the locals a spilled copy adds.
300
+ let mut localCount: Vec<u32> = vec![0; n];
237
301
  // Per defined function: (callee, op start, op end, is a return_call).
238
302
  let mut calls: Vec<Vec<(u32, usize, usize, bool)>> = vec![Vec::new(); n];
239
303
  let mut cur = usize::MAX;
@@ -246,11 +310,59 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
246
310
  let sc = &mut scans[fn_i];
247
311
  if cur != fn_i {
248
312
  cur = fn_i;
313
+ localCount[fn_i] = v.len_locals();
249
314
  // No declared locals: the body bytes start with a zero count of local groups.
250
315
  sc.ok = module.functions[fn_i].1.first() == Some(&0);
251
316
  sc.params = v.len_locals();
317
+ sc.spill = sc.ok;
318
+ sc.first = Some(start);
319
+ for k in 0..sc.params {
320
+ match v.get_local_type(k).and_then(numberValType) {
321
+ Some(t) => sc.tys.push(t),
322
+ None => sc.spill = false,
323
+ }
324
+ }
252
325
  }
253
- if !sc.ok || sc.end.is_some() {
326
+ if sc.end.is_some() {
327
+ return;
328
+ }
329
+ let control = matches!(
330
+ op,
331
+ Operator::LocalSet { .. }
332
+ | Operator::LocalTee { .. }
333
+ | Operator::Block { .. }
334
+ | Operator::Loop { .. }
335
+ | Operator::If { .. }
336
+ | Operator::Else
337
+ | Operator::Try { .. }
338
+ | Operator::TryTable { .. }
339
+ | Operator::Catch { .. }
340
+ | Operator::CatchAll
341
+ | Operator::Delegate { .. }
342
+ | Operator::Rethrow { .. }
343
+ | Operator::Br { .. }
344
+ | Operator::BrIf { .. }
345
+ | Operator::BrTable { .. }
346
+ | Operator::BrOnNull { .. }
347
+ | Operator::BrOnNonNull { .. }
348
+ | Operator::BrOnCast { .. }
349
+ | Operator::BrOnCastFail { .. }
350
+ | Operator::Return
351
+ | Operator::ReturnCall { .. }
352
+ | Operator::ReturnCallIndirect { .. }
353
+ | Operator::ReturnCallRef { .. }
354
+ );
355
+ match op {
356
+ Operator::End => {
357
+ sc.end = Some(start);
358
+ return;
359
+ }
360
+ Operator::LocalGet { local_index } if *local_index < sc.params => sc.gets.push((start, end, *local_index)),
361
+ Operator::LocalGet { .. } => sc.spill = false,
362
+ _ if control => sc.spill = false,
363
+ _ => {}
364
+ }
365
+ if !sc.ok {
254
366
  return;
255
367
  }
256
368
  if sc.rest.is_none() {
@@ -263,57 +375,74 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
263
375
  }
264
376
  sc.rest = Some(start);
265
377
  }
266
- match op {
267
- Operator::End => sc.end = Some(start),
268
- Operator::LocalGet { .. }
269
- | Operator::LocalSet { .. }
378
+ if control || matches!(op, Operator::LocalGet { .. }) {
270
- | Operator::LocalTee { .. }
271
- | Operator::Block { .. }
272
- | Operator::Loop { .. }
273
- | Operator::If { .. }
274
- | Operator::Else
379
+ sc.ok = false;
275
- | Operator::Try { .. }
276
- | Operator::TryTable { .. }
277
- | Operator::Catch { .. }
278
- | Operator::CatchAll
279
- | Operator::Delegate { .. }
280
- | Operator::Rethrow { .. }
281
- | Operator::Br { .. }
282
- | Operator::BrIf { .. }
283
- | Operator::BrTable { .. }
284
- | Operator::BrOnNull { .. }
285
- | Operator::BrOnNonNull { .. }
286
- | Operator::BrOnCast { .. }
287
- | Operator::BrOnCastFail { .. }
288
- | Operator::Return
289
- | Operator::ReturnCall { .. }
290
- | Operator::ReturnCallIndirect { .. }
291
- | Operator::ReturnCallRef { .. } => sc.ok = false,
292
- _ => {}
293
380
  }
294
381
  })?;
382
+ /// A copy: its bytes with each parameter read as `(start, end, parameter)` within them, and
383
+ /// the parameter types to store the arguments in (empty: they stay on the stack).
384
+ struct Copy {
385
+ code: Vec<u8>,
386
+ gets: Vec<(usize, usize, u32)>,
387
+ tys: Vec<u8>,
388
+ }
295
- let inline: Vec<Option<Vec<u8>>> = scans
389
+ let inline: Vec<Option<Copy>> = scans
296
390
  .iter()
297
391
  .enumerate()
298
- .map(|(d, sc)| match (sc.ok, sc.rest, sc.end) {
392
+ .map(|(d, sc)| match (sc.ok, sc.rest, sc.end, sc.spill, sc.first) {
299
- (true, Some(r), Some(e)) if e - r <= INLINE_LIMIT => Some(module.functions[d].1[r..e].to_vec()),
393
+ (true, Some(r), Some(e), _, _) if e - r <= INLINE_LIMIT => {
394
+ Some(Copy { code: module.functions[d].1[r..e].to_vec(), gets: vec![], tys: vec![] })
395
+ }
396
+ (_, _, Some(e), true, Some(f)) if e - f <= SPILL_INLINE_LIMIT && sc.params > 0 => Some(Copy {
397
+ code: module.functions[d].1[f..e].to_vec(),
398
+ gets: sc.gets.iter().map(|&(s, t, k)| (s - f, t - f, k)).collect(),
399
+ tys: sc.tys.clone(),
400
+ }),
300
401
  _ => None,
301
402
  })
302
403
  .collect();
303
404
  let mut edits: Vec<Vec<Edit>> = (0..n).map(|_| Vec::new()).collect();
405
+ // Per caller: the locals it adds, and the first of them for each signature spilled.
406
+ let mut added: Vec<Vec<u8>> = vec![Vec::new(); n];
407
+ let mut spillBase: Vec<std::collections::BTreeMap<Vec<u8>, u32>> = vec![Default::default(); n];
304
408
  for (d, cs) in calls.iter().enumerate() {
305
409
  for &(f, start, end, tail) in cs {
306
410
  let Some(callee) = f.checked_sub(imports).map(|c| c as usize) else { continue };
307
- let Some(Some(code)) = inline.get(callee) else { continue };
411
+ let Some(Some(copy)) = inline.get(callee) else { continue };
308
412
  if callee == d {
309
413
  continue;
310
414
  }
311
- let mut with = code.clone();
415
+ let mut with = Vec::new();
416
+ if copy.tys.is_empty() {
417
+ with.extend_from_slice(&copy.code);
418
+ } else {
419
+ let base = *spillBase[d].entry(copy.tys.clone()).or_insert_with(|| {
420
+ let b = localCount[d] + added[d].len() as u32;
421
+ added[d].extend_from_slice(&copy.tys);
422
+ b
423
+ });
424
+ for k in (0..copy.tys.len() as u32).rev() {
425
+ wasm_encoder::Encode::encode(&wasm_encoder::Instruction::LocalSet(base + k), &mut with);
426
+ }
427
+ let mut at = 0;
428
+ for &(s, t, k) in &copy.gets {
429
+ with.extend_from_slice(&copy.code[at..s]);
430
+ wasm_encoder::Encode::encode(&wasm_encoder::Instruction::LocalGet(base + k), &mut with);
431
+ at = t;
432
+ }
433
+ with.extend_from_slice(&copy.code[at..]);
434
+ }
312
435
  if tail {
313
436
  with.push(0x0F);
314
437
  }
315
438
  edits[d].push(Edit { start, end, with });
316
439
  }
317
440
  }
318
- Ok(applyAll(module, edits))
441
+ let count = applyAll(module, edits);
442
+ for (d, extra) in added.iter().enumerate() {
443
+ if !extra.is_empty() {
444
+ module.functions[d].1 = addLocals(&module.functions[d].1, extra)?;
445
+ }
446
+ }
447
+ Ok(count)
319
448
  }
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs CHANGED
@@ -158,6 +158,28 @@ fun main() -> Int =
158
158
  assert_eq!(runInt("inline", src), 15);
159
159
  }
160
160
 
161
+ /// `Int.compare` reads both operands twice, so each caller stores its arguments in locals it
162
+ /// adds and copies the comparison in: no call is left, and the results are the same. `rank` is
163
+ /// small enough to be copied into `main` too; the second round copies the comparisons it held.
164
+ #[test]
165
+ fn compareIsCopiedIntoItsCallers() {
166
+ let src = "\
167
+ import std/Int
168
+
169
+ fun rank(a: Int, b: Int) -> Int = a.compare(b) * 10 + b.compare(a)
170
+
171
+ fun main() -> Int =
172
+ rank(1, 2) * 100 + rank(3, 3) * 10 + rank(9, -9)
173
+ ";
174
+ let all = bodies(&compile("cmp", src));
175
+ let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
176
+ assert!(!names.contains(&"Int.compare") && !names.contains(&"rank"), "{names:?}");
177
+ let main = body(&all, "main");
178
+ assert!(!main.iter().any(|op| op.starts_with("Call")), "{main:?}");
179
+ assert_eq!(main.iter().filter(|op| op.starts_with("I64GtS")).count(), 6, "{main:?}");
180
+ assert_eq!(runInt("cmp", src), (-10 + 1) * 100 + (10 - 1));
181
+ }
182
+
161
183
  /// A fn's closures get distinct names: `f.closure`, `f.closure2`.
162
184
  #[test]
163
185
  fn closuresOfOneFnHaveDistinctNames() {
std/Bool.plum CHANGED
@@ -15,9 +15,8 @@ primitive Bool =
15
15
  fun toStr(self) -> Str =
16
16
  if self then "true" else "false"
17
17
 
18
- # `false` before `true`: the order of `Map` keys.
18
+ # `false` before `true`: the order of `Map` keys. Native: `self - o` as Ints.
19
- fun compare(self, o: Bool) -> Int =
19
+ fun compare(self, o: Bool) -> Int = @native
20
- if self == o then 0 else if self then 1 else -1
21
20
 
22
21
  # Parses exactly `"true"` or `"false"`.
23
22
  fun parse(s: Str) -> Result<Bool, BoolError> =
std/Byte.plum CHANGED
@@ -18,6 +18,6 @@ primitive Byte =
18
18
  fun toStr(self) -> Str =
19
19
  Int(self).toStr()
20
20
 
21
- # -1, 0 or 1 as `self` is below, equal to or above `o`: the order of `Map` keys.
21
+ # -1, 0 or 1 as `self` is below, equal to or above `o`: the order of `Map` keys (native,
22
+ # like `Int.compare`).
22
- fun compare(self, o: Byte) -> Int =
23
+ fun compare(self, o: Byte) -> Int = @native
23
- Int(self).compare(Int(o))
std/Float.plum CHANGED
@@ -62,18 +62,8 @@ primitive Float =
62
62
 
63
63
  # A total order for `Map` keys: -1, 0 or 1 as `self` is below, equal to or above `o`.
64
64
  # `-0.0` and `0.0` compare equal, and every NaN equals every other NaN and comes after
65
- # `Infinity`.
65
+ # `Infinity`. Native, with no branch: `(self > o) - (self < o) + (self != self) - (o != o)`.
66
- fun compare(self, o: Float) -> Int =
66
+ fun compare(self, o: Float) -> Int = @native
67
- if self < o
68
- -1
69
- else if self > o
70
- 1
71
- else if self == o
72
- 0
73
- else if self != self
74
- if o != o then 0 else 1
75
- else
76
- -1
77
67
 
78
68
  # The bits (`toBits`), so `0.1` and `0.2` hash apart; `Hamt` avalanches them as it does
79
69
  # an Int's. Floats that are `==` hash the same: `0.0` and `-0.0` both hash to 0. Every NaN
std/Int.plum CHANGED
@@ -61,9 +61,9 @@ primitive Int =
61
61
  fun hash(self) -> Int =
62
62
  self
63
63
 
64
- # -1, 0 or 1 as `self` is below, equal to or above `o`: the order of `Map` keys.
64
+ # -1, 0 or 1 as `self` is below, equal to or above `o`: the order of `Map` keys. Native:
65
+ # `(self > o) - (self < o)`, no branch, copied into each caller.
65
- fun compare(self, o: Int) -> Int =
66
+ fun compare(self, o: Int) -> Int = @native
66
- if self < o then -1 else if self > o then 1 else 0
67
67
 
68
68
  # An Int is always already whole, so trunc/floor/ceil/round are all just
69
69
  # the value itself widened to Float.
tests/std/native_compare.plum ADDED
@@ -0,0 +1,17 @@
1
+ # `Int`, `Byte`, `Bool` and `Float` `compare` are native, with no branch: the same -1, 0 or 1 as
2
+ # the comparisons they replace, NaN after `Infinity` and `-0.0` equal to `0.0` included.
3
+ import std/Int
4
+ import std/Float
5
+ import std/Byte
6
+ import std/Bool
7
+ import std/Str
8
+
9
+ test "compare of Int, Byte, Bool and Float"
10
+ assert 1.compare(2) == -1 && 2.compare(1) == 1 && 5.compare(5) == 0
11
+ assert {-9223372036854775807 - 1}.compare(1) == -1 && 9223372036854775807.compare(-1) == 1
12
+ assert Byte(3).compare(Byte(200)) == -1 && Byte(255).compare(Byte(0)) == 1 && Byte(7).compare(Byte(7)) == 0
13
+ assert false.compare(true) == -1 && true.compare(false) == 1 && true.compare(true) == 0 && false.compare(false) == 0
14
+ nan := 0.0 / 0.0
15
+ inf := 1.0 / 0.0
16
+ assert 1.5.compare(2.5) == -1 && 2.5.compare(1.5) == 1 && 0.0.compare(-0.0) == 0
17
+ assert nan.compare(inf) == 1 && inf.compare(nan) == -1 && nan.compare(nan) == 0 && nan.compare(1.0) == 1 && {-inf}.compare(nan) == -1