diff --git a/quest/m3/README.md b/quest/m3/README.md index 51216e681..cea1dee97 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -24,7 +24,6 @@ generic std gap is planned here even when moq never calls it. - [Placeholders written to a crate's own fmt::Write](/quest/m3/ts-fmt-calls.md) - `write!` with placeholders into a crate's own writer translates, its `write_str` seeing each call std makes - [Waiting: type-check in process with tsrs](/quest/m3/ts-tsrs.md) - rust2-ts checks bindings through tsrs instead of `tsc` once it is a stable library - [An inclusive range folded through an adaptor](/quest/m3/ts-range-fold.md) - a `RangeInclusive` folded through `map`, `filter`, or `rev` ends in core's state, and `by_ref` of one type-checks -- [Binding gaps](/quest/m3/ts-bind-gaps.md) - bound types as keys, unit returns checked, renamed dependencies - [A B-tree's drop order](/quest/m3/ts-btree-drop.md) - dropping a whole `BTreeMap` or `BTreeSet` drops its entries node by node, as std's does - [Drop order in std's folds and iterators](/quest/m3/ts-drop-order.md) - the values that drop still refused in std's folds, zips, flattens, and collects drop as std's do - [Set operations](/quest/m3/ts-set-ops.md) - `union`, `intersection`, `difference`, and `symmetric_difference` of hash and B-tree sets translate diff --git a/quest/m3/ts-bind-gaps.md b/quest/m3/ts-bind-gaps.md deleted file mode 100644 index b2c4a259c..000000000 --- a/quest/m3/ts-bind-gaps.md +++ /dev/null @@ -1,14 +0,0 @@ -# [S] Binding gaps - -## Goal - -rust2-ts's [bindings](/ts/README.md) cover a bound type as a collection key, through its -binding's `Hash`, `Eq`, and `Ord`, which [#127](https://github.com/moq-dev/rust2/pull/127) -refuses. - -## Plan - -Found by #127 on 2026-10-27. Keying a collection by a bound type fails with the Rust -item's span today. - -Public API: `ts.toml`'s bindings. diff --git a/ts/README.md b/ts/README.md index e5a573271..a715d5387 100644 --- a/ts/README.md +++ b/ts/README.md @@ -442,8 +442,7 @@ generic bound type's value at each of its instantiations translation reaches. A type with a representation of its own, std's or a well-known crate's, can't be bound. Translation can't see into a bound type, so a field, variant, or constructor of one is -refused, as are iterating one, keying a collection by one, and assigning a whole one -through a `&mut`. Its value is never `undefined` or `rt.Pending`, which `None` and +refused, as are iterating one and assigning a whole one through a `&mut`. Its value is never `undefined` or `rt.Pending`, which `None` and `Poll::Pending` are, and is an object unless the Rust type is `Copy`. A `&mut` to one passes that object, which the binding's functions change in place. Where the type is `Copy`, such a `&mut` is refused, since JS shares the value where Rust copies it, and a @@ -459,6 +458,15 @@ translation at the Rust item's span, and the output is removed. Only the binding another only where translation reaches both. A binding inside the output is refused, since a translation replaces it. +A bound type keys a collection, alone or in a tuple, `Option`, or `Arc`, by the exports of +its Rust impls: `hash$Hash(self, state: rt.Hasher): undefined` and `eq$PartialEq` for a +`HashMap` or `HashSet`, `cmp$Ord` for a `BTreeMap` or `BTreeSet`, and +`partialCmp$PartialOrd` too for a B-tree's `range`. A derived impl's are the same exports. +Each must agree with the Rust impl: `hash` writes what it writes, through `rt.hash8` to +`rt.hash128`, `rt.hashStr`, and `rt.hashBytes`, so values `eq` finds equal hash alike, and +`cmp` orders as it does. A collection finds even a bound value that is a JS primitive by +these, never by `===`. A missing one fails at its impl, as any missing export does. + A bound type with `drop = true` drops where Rust drops it, through its `[Symbol.dispose]`, which `tsc` checks it has. Without it, dropping one does nothing JS sees, `tsc` checks it has no `[Symbol.dispose]`, and a type argument that drops is refused. @@ -712,7 +720,9 @@ built natively for wasm32 and run beside its translation on the same inputs by its own included. `caller.ts` names the inputs that reserve at the edges of `BytesMut`'s 512 MiB limit. - `bind` binds `buf::Blob`, a renamed dependency's type with `unsafe` inside, and a function and a type of its own that read through raw - pointers, the type dropping an `Arc` where Rust drops it, to the TS in `bind/`. Its + pointers, the type dropping an `Arc` where Rust drops it, to the TS in `bind/`. It keys + hash and B-tree collections by `Blob` and by `key::Nibble`, a JS number equal to another + by its low bits alone, through their bindings' `Hash`, `Eq`, and `Ord`. Its differential test runs them against native Rust. `wrong.toml` binds TS that doesn't match the Rust signatures, which `tsc` refuses at each item, with the errors in `wrong.txt`. `refused.toml` holds bindings the config can't make, with the errors in `refused.txt`. diff --git a/ts/fixtures/bind/bind/blob.ts b/ts/fixtures/bind/bind/blob.ts index 1404388ad..de27fb913 100644 --- a/ts/fixtures/bind/bind/blob.ts +++ b/ts/fixtures/bind/bind/blob.ts @@ -51,3 +51,16 @@ export function deref$Deref(self: Blob): rt.ByteSlice { export function eq$PartialEq(self: Blob, other: Blob): boolean { return rt.byteSliceEq(self, other); } + +export function hash$Hash(self: Blob, state: rt.Hasher): undefined { + rt.hashBytes(self, state); + return undefined; +} + +export function partialCmp$PartialOrd(self: Blob, other: Blob): rt.Ordering { + return rt.cmpBytes(self, other); +} + +export function cmp$Ord(self: Blob, other: Blob): rt.Ordering { + return rt.cmpBytes(self, other); +} diff --git a/ts/fixtures/bind/bind/nibble.ts b/ts/fixtures/bind/bind/nibble.ts new file mode 100644 index 000000000..6b6d2702f --- /dev/null +++ b/ts/fixtures/bind/bind/nibble.ts @@ -0,0 +1,32 @@ +// `key::Nibble`, a byte that compares, hashes, and orders by its low four bits, which the +// `===` of its number would not. + +import * as rt from "../rt.ts"; + +export type Nibble = rt.u8; + +function make(byte: rt.u8): Nibble { + return byte; +} +export { make as new }; + +export function get(self: Nibble): rt.u8 { + return self; +} + +export function eq$PartialEq(self: Nibble, other: Nibble): boolean { + return (self & 0xf) === (other & 0xf); +} + +export function hash$Hash(self: Nibble, state: rt.Hasher): undefined { + rt.hash8(self & 0xf, state); + return undefined; +} + +export function partialCmp$PartialOrd(self: Nibble, other: Nibble): rt.Ordering { + return cmp$Ord(self, other); +} + +export function cmp$Ord(self: Nibble, other: Nibble): rt.Ordering { + return rt.cmp(self & 0xf, other & 0xf); +} diff --git a/ts/fixtures/bind/blob/src/lib.rs b/ts/fixtures/bind/blob/src/lib.rs index 96c047447..f89046449 100644 --- a/ts/fixtures/bind/blob/src/lib.rs +++ b/ts/fixtures/bind/blob/src/lib.rs @@ -1,6 +1,8 @@ //! Immutable bytes that clones and slices share, read through `unsafe`: a dependency's //! type that a consumer binds rather than translates. +use std::cmp::Ordering; +use std::hash::{Hash, Hasher}; use std::ops::{Bound, Deref, RangeBounds}; use std::sync::Arc; @@ -94,6 +96,26 @@ impl PartialEq for Blob { } } +impl Eq for Blob {} + +impl Hash for Blob { + fn hash(&self, state: &mut H) { + (**self).hash(state); + } +} + +impl PartialOrd for Blob { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Blob { + fn cmp(&self, other: &Self) -> Ordering { + (**self).cmp(&**other) + } +} + /// Where bytes come from: a trait, which a binding can't stand in for. pub trait Source { /// The next bytes. diff --git a/ts/fixtures/bind/expected/bind/blob.ts b/ts/fixtures/bind/expected/bind/blob.ts index fa26f1b4c..b6eef5386 100644 --- a/ts/fixtures/bind/expected/bind/blob.ts +++ b/ts/fixtures/bind/expected/bind/blob.ts @@ -52,3 +52,16 @@ export function deref$Deref(self: Blob): rt.ByteSlice { export function eq$PartialEq(self: Blob, other: Blob): boolean { return rt.byteSliceEq(self, other); } + +export function hash$Hash(self: Blob, state: rt.Hasher): undefined { + rt.hashBytes(self, state); + return undefined; +} + +export function partialCmp$PartialOrd(self: Blob, other: Blob): rt.Ordering { + return rt.cmpBytes(self, other); +} + +export function cmp$Ord(self: Blob, other: Blob): rt.Ordering { + return rt.cmpBytes(self, other); +} diff --git a/ts/fixtures/bind/expected/bind/nibble.ts b/ts/fixtures/bind/expected/bind/nibble.ts new file mode 100644 index 000000000..c014bd755 --- /dev/null +++ b/ts/fixtures/bind/expected/bind/nibble.ts @@ -0,0 +1,33 @@ +// Generated by rust2-ts. Do not edit. +// `key::Nibble`, a byte that compares, hashes, and orders by its low four bits, which the +// `===` of its number would not. + +import * as rt from "../rt.ts"; + +export type Nibble = rt.u8; + +function make(byte: rt.u8): Nibble { + return byte; +} +export { make as new }; + +export function get(self: Nibble): rt.u8 { + return self; +} + +export function eq$PartialEq(self: Nibble, other: Nibble): boolean { + return (self & 0xf) === (other & 0xf); +} + +export function hash$Hash(self: Nibble, state: rt.Hasher): undefined { + rt.hash8(self & 0xf, state); + return undefined; +} + +export function partialCmp$PartialOrd(self: Nibble, other: Nibble): rt.Ordering { + return cmp$Ord(self, other); +} + +export function cmp$Ord(self: Nibble, other: Nibble): rt.Ordering { + return rt.cmp(self & 0xf, other & 0xf); +} diff --git a/ts/fixtures/bind/expected/core/option.ts b/ts/fixtures/bind/expected/core/option.ts new file mode 100644 index 000000000..500671a60 --- /dev/null +++ b/ts/fixtures/bind/expected/core/option.ts @@ -0,0 +1,27 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import type * as Nibble from "../bind/nibble.ts"; + +export function unwrapOr$0r2bmpr(self: rt.u8 | undefined, default_: rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$1rbuegs(self: rt.ByteSlice | undefined, default_: rt.ByteSlice): rt.ByteSlice { + if (self === undefined) { + return default_; + } + return self; +} + +export function mapOr$174crag(self: Nibble.Nibble | undefined, default_: rt.u8, f: (a0: Nibble.Nibble) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +//# sourceMappingURL=option.ts.map diff --git a/ts/fixtures/bind/expected/harness.ts b/ts/fixtures/bind/expected/harness.ts index b48b86e20..f9dd684c4 100644 --- a/ts/fixtures/bind/expected/harness.ts +++ b/ts/fixtures/bind/expected/harness.ts @@ -3,15 +3,18 @@ import * as rt from "./rt.ts"; import * as Blob from "./bind/blob.ts"; import * as checksum from "./bind/checksum.ts"; +import * as Nibble from "./bind/nibble.ts"; import * as skip from "./bind/skip.ts"; import * as Tally from "./bind/tally.ts"; +import { unwrapOr$0r2bmpr, unwrapOr$1rbuegs, mapOr$174crag } from "./core/option.ts"; /** * Split the input as `Blob`, compare and hash the parts, skip its leading zeros, and - * count tallies down as they drop. A first byte of 1 slices out of order, which panics. + * count tallies down as they drop, then key collections by bound types. A first byte of + * 1 slices out of order, which panics. */ export function run(input: rt.ByteSlice): rt.ByteVec { - let _125: boolean = false; + let _128: boolean = false; const out: rt.ByteVec = new rt.ByteVec(); const bytes: Blob.Blob = Blob.copyFromSlice(input); const mid: rt.usize = rt.usizeDiv(Blob.len(bytes), 2); @@ -57,20 +60,104 @@ export function run(input: rt.ByteSlice): rt.ByteVec { rt.byteVecPush(out, count.strong & 0xff); const _110: rt.u8 = Tally.get(b) & 0xff; rt.byteVecPush(out, _110); - _125 = true; + _128 = true; const held: Tally.Tally | undefined = b; if (rt.byteSliceFirst(input) === 2) { - _125 = false; + _128 = false; rt.drop(held); } rt.byteVecPush(out, count.strong & 0xff); + keys(input, bytes, out); const _0: rt.ByteVec = out; - if (_125) { + if (_128) { rt.drop(held); } - _125 = false; + _128 = false; count[Symbol.dispose](); return _0; } +/** + * Collections keyed by `Blob`s, equal by their bytes wherever they are sliced from, and by + * `Nibble`s, equal by their low bits: what each finds, keeps, and orders. + */ +export function keys(input: rt.ByteSlice, bytes: Blob.Blob, out: rt.ByteVec): void { + let _12!: rt.usize; + let _143!: rt.u8; + const seen: rt.HashSet = rt.hashNew(rt.hashing(Blob.hash$Hash, Blob.eq$PartialEq, true)) as rt.HashSet; + const counts: rt.HashMap = rt.hashNew(rt.hashing(Blob.hash$Hash, Blob.eq$PartialEq, true)) as rt.HashMap; + const sorted: rt.BTreeSet = rt.btreeNew(Blob.cmp$Ord) as rt.BTreeSet; + const firsts: rt.BTreeMap = rt.btreeNew(Blob.cmp$Ord) as rt.BTreeMap; + const _10: rt.usize = Blob.len(bytes); + let iterStart: rt.usize = 0; + const iterEnd: rt.usize = _10; + while ((_12 = iterStart++) < iterEnd) { + const at: rt.usize = _12; + const part: Blob.Blob = Blob.slice(bytes, new rt.Range(at, rt.min(rt.usizeAdd(at, 2), Blob.len(bytes)))); + const _26: Blob.Blob = Blob.clone$Clone(part); + rt.byteVecPush(out, rt.hashAdd(seen, _26) ? 1 : 0); + const _31: Blob.Blob = Blob.clone$Clone(part); + const _28: rt.Place = rt.entryOrInsertMut(rt.entry(counts, _31), 0); + _28.v = rt.u8Add(_28.v, 1); + const _36: Blob.Blob = Blob.clone$Clone(part); + rt.btreeAdd(sorted, _36); + rt.entryOrInsertMut(rt.entry(firsts, part), at & 0xff); + } + rt.byteVecPush(out, rt.hashLen(seen) & 0xff); + rt.byteVecPush(out, rt.hashLen(counts) & 0xff); + const probe: Blob.Blob = Blob.copyFromSlice(unwrapOr$1rbuegs(rt.byteSliceGetRange(input, 0, 2), input)); + rt.byteVecPush(out, rt.hashContains(seen, probe) ? 1 : 0); + rt.byteVecPush(out, unwrapOr$0r2bmpr(rt.hashGet(counts, probe), 0)); + rt.byteVecPush(out, rt.btreeContains(sorted, probe) ? 1 : 0); + rt.byteVecPush(out, unwrapOr$0r2bmpr(rt.btreeGet(firsts, probe), 255)); + const _81: { start: Blob.Blob } = { start: Blob.clone$Clone(probe) }; + rt.byteVecPush(out, rt.iterCount(rt.btreeRangeKeys(sorted, _81, Blob.eq$PartialEq, rt.cmpGt(Blob.partialCmp$PartialOrd))) & 0xff); + const iter2: rt.Iter<[Blob.Blob, rt.u8]> = rt.btreeIter(firsts); + while (true) { + const _87: [Blob.Blob, rt.u8] | rt.Done = iter2.next(); + if (_87 === rt.DONE) { + break; + } + rt.byteVecPush(out, Blob.len(_87[0]) & 0xff); + rt.byteVecExtendFromSlice(out, Blob.deref$Deref(_87[0])); + rt.byteVecPush(out, _87[1]); + } + rt.byteVecPush(out, rt.hashDelete(seen, probe) ? 1 : 0); + rt.byteVecPush(out, rt.btreeDelete(sorted, probe) ? 1 : 0); + rt.byteVecPush(out, rt.hashLen(seen) & 0xff); + const nibbles: rt.HashSet = rt.hashNew(rt.hashing(Nibble.hash$Hash, Nibble.eq$PartialEq, true)) as rt.HashSet; + const lasts: rt.HashMap = rt.hashNew(rt.hashing(Nibble.hash$Hash, Nibble.eq$PartialEq, true)) as rt.HashMap; + const ordered: rt.BTreeSet = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeSet; + const values: rt.BTreeMap = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeMap; + for (const byte of rt.byteSliceView(input)) { + const key: Nibble.Nibble = Nibble.new(byte); + rt.byteVecPush(out, rt.hashAdd(nibbles, key) ? 1 : 0); + rt.byteVecPush(out, unwrapOr$0r2bmpr(rt.hashInsert(lasts, key, byte), 255)); + rt.btreeAdd(ordered, key); + rt.btreeInsert(values, key, byte); + } + rt.byteVecPush(out, rt.hashLen(nibbles) & 0xff); + let iterStart2: rt.u8 = 0; + const iterEnd2: rt.u8 = 16; + while ((_143 = iterStart2++) < iterEnd2) { + const key3: Nibble.Nibble = Nibble.new(rt.u8Mul(_143, 17)); + rt.byteVecPush(out, mapOr$174crag(rt.hashKey(nibbles, key3), 255, (n: Nibble.Nibble): rt.u8 => { + return Nibble.get(n); + })); + rt.byteVecPush(out, unwrapOr$0r2bmpr(rt.hashGet(lasts, key3), 255)); + } + const iter5: rt.Iter<[Nibble.Nibble, rt.u8]> = rt.btreeIter(values); + while (true) { + const _164: [Nibble.Nibble, rt.u8] | rt.Done = iter5.next(); + if (_164 === rt.DONE) { + break; + } + rt.byteVecPush(out, Nibble.get(_164[0])); + rt.byteVecPush(out, _164[1]); + } + rt.iterExtendBytes(out, rt.iterMap(rt.btreeKeys(ordered), (n2: Nibble.Nibble): rt.u8 => { + return Nibble.get(n2); + })); +} + //# sourceMappingURL=harness.ts.map diff --git a/ts/fixtures/bind/refused.txt b/ts/fixtures/bind/refused.txt index 3527835d7..e46876b88 100644 --- a/ts/fixtures/bind/refused.txt +++ b/ts/fixtures/bind/refused.txt @@ -9,11 +9,11 @@ binding `raw::Tally::get`: only a type's value drops binding `raw::Tally::new`: rt/tally.ts would replace the runtime, rt.ts and rt/ binding `raw::checksum`: `checksum` binds the same item binding `std::vec::Vec`: the type has a representation of its own -reading bind/missing.ts: No such file or directory (os error 2) at fixtures/bind/src/harness.rs:25:12 -`raw::Held` binds without drop, so it would never drop its `raw::Tally` at fixtures/bind/src/harness.rs:61:13 +reading bind/missing.ts: No such file or directory (os error 2) at fixtures/bind/src/harness.rs:28:12 +`raw::Held` binds without drop, so it would never drop its `raw::Tally` at fixtures/bind/src/harness.rs:121:13 a binding of `raw::value`, whose `N` one export for every instance can't recover from its arguments at fixtures/bind/src/raw.rs:65:1 a binding of `raw::zero`, whose `T` one export for every instance can't recover from its arguments at fixtures/bind/src/raw.rs:60:1 -`raw::Held` binds without drop, so it would never drop its `raw::Tally` at fixtures/bind/src/harness.rs:61:6 +`raw::Held` binds without drop, so it would never drop its `raw::Tally` at fixtures/bind/src/harness.rs:121:6 unsupported call to `std::sync::Arc::::from_raw` at fixtures/bind/src/raw.rs:55:17 unsupported call to `std::sync::Arc::::into_raw` at fixtures/bind/src/raw.rs:42:11 -an assignment through a reference to `blob::Blob` at fixtures/bind/src/harness.rs:68:2 +an assignment through a reference to `blob::Blob` at fixtures/bind/src/harness.rs:128:2 diff --git a/ts/fixtures/bind/src/harness.rs b/ts/fixtures/bind/src/harness.rs index 85fef507a..e42575b1c 100644 --- a/ts/fixtures/bind/src/harness.rs +++ b/ts/fixtures/bind/src/harness.rs @@ -1,13 +1,16 @@ //! The entry point both sides of the differential test run. +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::sync::Arc; use buf::Blob; +use crate::key::Nibble; use crate::raw::{Tally, checksum, skip}; /// Split the input as `Blob`, compare and hash the parts, skip its leading zeros, and -/// count tallies down as they drop. A first byte of 1 slices out of order, which panics. +/// count tallies down as they drop, then key collections by bound types. A first byte of +/// 1 slices out of order, which panics. pub fn run(input: &[u8]) -> Vec { let mut out = Vec::new(); let bytes = Blob::copy_from_slice(input); @@ -45,9 +48,66 @@ pub fn run(input: &[u8]) -> Vec { drop(held); } out.push(Arc::strong_count(&count) as u8); + keys(input, &bytes, &mut out); out } +/// Collections keyed by `Blob`s, equal by their bytes wherever they are sliced from, and by +/// `Nibble`s, equal by their low bits: what each finds, keeps, and orders. +fn keys(input: &[u8], bytes: &Blob, out: &mut Vec) { + let mut seen = HashSet::new(); + let mut counts = HashMap::new(); + let mut sorted = BTreeSet::new(); + let mut firsts = BTreeMap::new(); + for at in 0..bytes.len() { + let part = bytes.slice(at..(at + 2).min(bytes.len())); + out.push(seen.insert(part.clone()) as u8); + *counts.entry(part.clone()).or_insert(0u8) += 1; + sorted.insert(part.clone()); + firsts.entry(part).or_insert(at as u8); + } + out.push(seen.len() as u8); + out.push(counts.len() as u8); + // A copy of the bytes, which no part shares, finds the part equal to it. + let probe = Blob::copy_from_slice(input.get(..2).unwrap_or(input)); + out.push(seen.contains(&probe) as u8); + out.push(counts.get(&probe).copied().unwrap_or(0)); + out.push(sorted.contains(&probe) as u8); + out.push(firsts.get(&probe).copied().unwrap_or(0xff)); + out.push(sorted.range(probe.clone()..).count() as u8); + for (part, first) in &firsts { + out.push(part.len() as u8); + out.extend_from_slice(part); + out.push(*first); + } + out.push(seen.remove(&probe) as u8); + out.push(sorted.remove(&probe) as u8); + out.push(seen.len() as u8); + + let mut nibbles = HashSet::new(); + let mut lasts = HashMap::new(); + let mut ordered = BTreeSet::new(); + let mut values = BTreeMap::new(); + for &byte in input { + let key = Nibble::new(byte); + out.push(nibbles.insert(key) as u8); + out.push(lasts.insert(key, byte).unwrap_or(0xff)); + ordered.insert(key); + values.insert(key, byte); + } + out.push(nibbles.len() as u8); + for key in 0..16 { + let key = Nibble::new(key * 17); + out.push(nibbles.get(&key).map_or(0xff, |n| n.get())); + out.push(lasts.get(&key).copied().unwrap_or(0xff)); + } + for (key, value) in &values { + out.push(key.get()); + out.push(*value); + } + out.extend(ordered.iter().map(|n| n.get())); +} + /// A `Held` of `None`, which `wrong.toml`'s binding would make `undefined`, as the outer /// `None` is. pub fn held() -> bool { diff --git a/ts/fixtures/bind/src/key.rs b/ts/fixtures/bind/src/key.rs new file mode 100644 index 000000000..e58617e5f --- /dev/null +++ b/ts/fixtures/bind/src/key.rs @@ -0,0 +1,46 @@ +//! A key bound to TypeScript as a JS number, which compares, hashes, and orders by its own +//! impls where `===` would tell apart values it finds equal. + +use std::cmp::Ordering; +use std::hash::{Hash, Hasher}; + +/// A byte that compares, hashes, and orders by its low four bits alone. +#[derive(Clone, Copy)] +pub struct Nibble(u8); + +impl Nibble { + pub fn new(byte: u8) -> Self { + Self(byte) + } + + /// The whole byte, which tells which of equal keys a collection kept. + pub fn get(self) -> u8 { + self.0 + } +} + +impl PartialEq for Nibble { + fn eq(&self, other: &Self) -> bool { + self.0 & 0xf == other.0 & 0xf + } +} + +impl Eq for Nibble {} + +impl Hash for Nibble { + fn hash(&self, state: &mut H) { + (self.0 & 0xf).hash(state); + } +} + +impl PartialOrd for Nibble { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Nibble { + fn cmp(&self, other: &Self) -> Ordering { + (self.0 & 0xf).cmp(&(other.0 & 0xf)) + } +} diff --git a/ts/fixtures/bind/src/lib.rs b/ts/fixtures/bind/src/lib.rs index 2214b1ed3..9707a1bc3 100644 --- a/ts/fixtures/bind/src/lib.rs +++ b/ts/fixtures/bind/src/lib.rs @@ -1,10 +1,12 @@ //! Items outside the subset, bound to hand-written TypeScript: `buf::Blob`, a renamed //! dependency's type that contains `unsafe`, and the crate's own function and type that -//! read through raw pointers, one of them dropping where Rust drops it. +//! read through raw pointers, one of them dropping where Rust drops it, and a key whose own +//! `Hash`, `Eq`, and `Ord` a JS number's `===` would break. //! //! `harness::run` is the entry point both sides of the differential test run. pub mod harness; +pub mod key; pub mod raw; /// A second path to the function, which a binding can't also name. pub use raw::checksum; diff --git a/ts/fixtures/bind/ts.toml b/ts/fixtures/bind/ts.toml index fe86d3bd9..cd284c80a 100644 --- a/ts/fixtures/bind/ts.toml +++ b/ts/fixtures/bind/ts.toml @@ -3,6 +3,7 @@ roots = ["harness::run"] [bind] "buf::Blob" = "bind/blob.ts" +"key::Nibble" = "bind/nibble.ts" "raw::checksum" = "bind/checksum.ts" "raw::skip" = "bind/skip.ts" "raw::Tally" = { file = "bind/tally.ts", drop = true } diff --git a/ts/fixtures/bind/wrong.txt b/ts/fixtures/bind/wrong.txt index 6b7447131..9e6014576 100644 --- a/ts/fixtures/bind/wrong.txt +++ b/ts/fixtures/bind/wrong.txt @@ -1,12 +1,15 @@ the binding of `blob::Blob::len` in wrong/blob.ts doesn't type-check: error TS2322: Type '(self: ByteSlice) => string' is not assignable to type '(a0: ByteSlice) => usize'. Type 'string' is not assignable to type 'usize'. - Type 'string' is not assignable to type 'number'. at fixtures/bind/blob/src/lib.rs:36:2 -the binding of `blob::Blob::slice::>` in wrong/blob.ts doesn't type-check: error TS2339: Property 'slice' does not exist on type 'typeof import("wrong/blob")'. at fixtures/bind/blob/src/lib.rs:46:2 + Type 'string' is not assignable to type 'number'. at fixtures/bind/blob/src/lib.rs:38:2 +the binding of `blob::Blob::slice::>` in wrong/blob.ts doesn't type-check: error TS2339: Property 'slice' does not exist on type 'typeof import("wrong/blob")'. at fixtures/bind/blob/src/lib.rs:48:2 the binding of `::eq` in wrong/blob.ts doesn't type-check: error TS2322: Type '(self: ByteSlice, other: string) => boolean' is not assignable to type '(a0: ByteSlice, a1: ByteSlice) => boolean'. Types of parameters 'other' and 'a1' are incompatible. - Type 'ByteSlice' is not assignable to type 'string'. at fixtures/bind/blob/src/lib.rs:92:2 + Type 'ByteSlice' is not assignable to type 'string'. at fixtures/bind/blob/src/lib.rs:94:2 the binding of `raw::skip` in wrong/skip.ts doesn't type-check: error TS2322: Type '(bytes: ByteSlice, at: Place) => usize' is not assignable to type '(a0: ByteSlice, a1: Place) => undefined'. Type 'usize' is not assignable to type 'undefined'. at fixtures/bind/src/raw.rs:26:1 the binding of `raw::Tally` in wrong/tally.ts doesn't type-check: error TS2322: Type 'Tally' is not assignable to type '"a bound value that drops must have a [Symbol.dispose]"'. at fixtures/bind/src/raw.rs:35:1 the binding of `raw::Held>` in wrong/held.ts doesn't type-check: error TS2322: Type 'u8 | undefined' is not assignable to type '"a bound value can't be undefined, which None is"'. Type 'undefined' is not assignable to type '"a bound value can't be undefined, which None is"'. at fixtures/bind/src/raw.rs:70:1 +the binding of `::hash::` in wrong/blob.ts doesn't type-check: error TS2339: Property 'hash$Hash' does not exist on type 'typeof import("wrong/blob")'. at fixtures/bind/blob/src/lib.rs:102:2 +the binding of `::cmp` in wrong/blob.ts doesn't type-check: error TS2339: Property 'cmp$Ord' does not exist on type 'typeof import("wrong/blob")'. at fixtures/bind/blob/src/lib.rs:114:2 +the binding of `::partial_cmp` in wrong/blob.ts doesn't type-check: error TS2339: Property 'partialCmp$PartialOrd' does not exist on type 'typeof import("wrong/blob")'. at fixtures/bind/blob/src/lib.rs:108:2 diff --git a/ts/fixtures/bind/wrong/blob.ts b/ts/fixtures/bind/wrong/blob.ts index 5d30b0a8a..1ba653aab 100644 --- a/ts/fixtures/bind/wrong/blob.ts +++ b/ts/fixtures/bind/wrong/blob.ts @@ -1,5 +1,5 @@ -// `blob::Blob`, bound wrong: `slice` is missing, `len` returns a string, and `eq` takes -// what no `Blob` is. +// `blob::Blob`, bound wrong: `slice` and the key's `hash`, `cmp`, and `partial_cmp` are +// missing, `len` returns a string, and `eq` takes what no `Blob` is. import * as rt from "../rt.ts"; diff --git a/ts/src/lower/collections.rs b/ts/src/lower/collections.rs index ac1671e84..c75ed2909 100644 --- a/ts/src/lower/collections.rs +++ b/ts/src/lower/collections.rs @@ -3,9 +3,9 @@ //! //! A hash collection holds a key that is a JS primitive as its own JS map key, which JS //! compares as Rust's `Eq` does for numbers, strings, and booleans, and finds any other -//! key through its translated `Hash` and `Eq`, which `rt.hashing` makes it carry. A -//! B-tree orders every key by its translated `Ord`. Each value a collection stores is its -//! own copy, as in Rust. +//! key through its translated or bound `Hash` and `Eq`, which `rt.hashing` makes it carry. +//! A B-tree orders every key by its translated or bound `Ord`. Each value a collection +//! stores is its own copy, as in Rust. use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, GenericArgsRef, Instance, Ty}; @@ -712,13 +712,14 @@ fn hashing<'tcx>(b: &mut Body<'_, '_, 'tcx>, coll: Ty<'tcx>, key: Ty<'tcx>, span return None; }; let mut values = vec![hash_fn(b, key, hasher, span), eq_fn(b, key, span)]; - // A fieldless enum is a JS string, which its own `Eq` may tell apart where JS can't, - // as is the `Some` of an `Option` of one, and a `Reverse` of one. + // A fieldless enum is a JS string, and a bound value may be any primitive, which its + // own `Eq` may tell apart where JS can't, as is the `Some` of an `Option` of one, and a + // `Reverse` of one. let mut held = key; while let Some(inner) = option_of(b, held).or_else(|| reverse_of(b, held)) { held = peel(b, inner); } - if matches!(held.kind(), ty::Adt(adt, _) if fieldless(*adt)) { + if matches!(held.kind(), ty::Adt(adt, _) if fieldless(*adt) || b.t.bound_drops(adt.did()).is_some()) { values.push(Expr::lit("true")); } Some(Some(Expr::rt("hashing", values))) @@ -728,6 +729,12 @@ fn fieldless(adt: ty::AdtDef<'_>) -> bool { adt.is_enum() && adt.variants().iter().all(|v| v.fields.is_empty()) } +/// Whether `ty` compares, orders, and hashes by its own impls, which translate or which its +/// binding's exports stand in for, rather than as the runtime does std's. +fn local<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { + matches!(ty.kind(), ty::Adt(adt, _) if b.t.own(adt.did()) || b.t.bound_drops(adt.did()).is_some()) +} + /// Whether `ty`'s `ne` reaches the crate's own `ne` of a type it holds: through tuples, /// `Arc`s, `Reverse`s, and the elements of slices, but not an `Option`, whose `ne` is /// `!eq`. @@ -738,7 +745,7 @@ fn own_ne<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { ty::Tuple(tys) => tys.iter().any(|t| own_ne(b, t)), _ if let Some(elem) = elements_of(b, ty) => own_ne(b, elem), ty::Adt(..) if let Some(inner) = arc_of(b, ty).or_else(|| reverse_of(b, ty)) => own_ne(b, inner), - ty::Adt(adt, _) if b.t.own(adt.did()) => { + _ if local(b, ty) => { let ne = trait_fn(tcx, "PartialEq", "ne"); Instance::try_resolve(tcx, b.t.typing_env_pub(), ne, tcx.mk_args(&[ty.into(), ty.into()])) .ok() @@ -758,7 +765,7 @@ fn own_test<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>, test: &str) -> bool { match ty.kind() { ty::Tuple(tys) => tys.last().is_some_and(|&t| own_test(b, t, test)), ty::Adt(..) if let Some(inner) = arc_of(b, ty).or_else(|| reverse_of(b, ty)) => own_test(b, inner, test), - ty::Adt(adt, _) if b.t.own(adt.did()) => { + _ if local(b, ty) => { let f = trait_fn(tcx, "PartialOrd", test); Instance::try_resolve(tcx, b.t.typing_env_pub(), f, tcx.mk_args(&[ty.into(), ty.into()])) .ok() @@ -858,11 +865,10 @@ fn btree<'tcx>( let range = values.pop()?; values.push(bounds(b, call, range)); // std checks the ends by `==` and `>`, which a key of std's alone does as its `Ord` - // does, and one holding the crate's own type by that type's `PartialEq` and - // `PartialOrd`. + // does, and one holding the crate's own or a bound type by that type's `PartialEq` + // and `PartialOrd`. let target = range_input(b, call).1; - let own = |t: Ty<'tcx>| matches!(t.kind(), ty::Adt(adt, _) if b.t.own(adt.did())); - if target.walk().filter_map(|arg| arg.as_type()).any(own) { + if target.walk().filter_map(|arg| arg.as_type()).any(|t| local(b, t)) { values.push(eq_fn(b, target, span)); values.push(test_fn(b, target, "gt", span)); } @@ -999,6 +1005,8 @@ fn own_ord<'tcx>( match ty.kind() { ty::Tuple(tys) => tys.iter().any(|t| own_ord(b, t, seen)), ty::Adt(..) if let Some(inner) = option_of(b, ty).or_else(|| arc_of(b, ty)) => own_ord(b, inner, seen), + // A binding's, hand-written even where the Rust impl is derived. + ty::Adt(adt, _) if b.t.bound_drops(adt.did()).is_some() => true, ty::Adt(adt, args) if b.t.own(adt.did()) => { let derived = |tr: &str, item: &str, args: &[ty::GenericArg<'tcx>]| { let f = trait_fn(tcx, tr, item); @@ -1424,7 +1432,7 @@ fn std_key<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { // What a std type holds may be the crate's, which compares and hashes by its own impls. let held = |t: Ty<'tcx>| { let t = peel(b, t); - std_key(b, t) || b.t.deferred(t) || matches!(t.kind(), ty::Adt(adt, _) if b.t.own(adt.did())) + std_key(b, t) || b.t.deferred(t) || local(b, t) }; match ty.kind() { // A float is no key, but its `PartialEq` and `PartialOrd` are the runtime's. @@ -1575,11 +1583,11 @@ pub fn cmp_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, partial: bool, spa _ if let Some(elem) = elements_of(b, ty) => Expr::rt("cmpSlice", vec![cmp_fn(b, elem, partial, span)]), // Whichever form it has, as the key it is or the operand a reference passes. _ if bytes(b, ty) => Expr::Rt("cmpBytes".into()), - ty::Adt(adt, _) if b.t.own(adt.did()) && partial => { + _ if local(b, ty) && partial => { let cmp = trait_fn(tcx, "PartialOrd", "partial_cmp"); b.fn_value(cmp, tcx.mk_args(&[ty.into(), ty.into()]), span) } - ty::Adt(adt, _) if b.t.own(adt.did()) => { + _ if local(b, ty) => { let cmp = trait_fn(tcx, "Ord", "cmp"); b.fn_value(cmp, tcx.mk_args(&[ty.into()]), span) } @@ -1637,9 +1645,7 @@ pub fn eq_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Expr } Expr::rt("eqArc", values) } - ty::Adt(adt, _) - if b.t.own(adt.did()) || b.t.std_of(ty).is_some_and(|std| std == Std::Result || std.error()) => - { + ty::Adt(..) if local(b, ty) || b.t.std_of(ty).is_some_and(|std| std == Std::Result || std.error()) => { let eq = trait_fn(tcx, "PartialEq", "eq"); b.fn_value(eq, tcx.mk_args(&[ty.into(), ty.into()]), span) } @@ -1683,7 +1689,7 @@ fn hash_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, hasher: Ty<'tcx>, spa } // Its length, then its bytes, whichever form it is: a `[u8; N]` hashes as a slice. _ if bytes(b, ty) => Expr::Rt("hashBytes".into()), - ty::Adt(adt, _) if b.t.own(adt.did()) => { + _ if local(b, ty) => { let hash = trait_fn(tcx, "Hash", "hash"); b.fn_value(hash, tcx.mk_args(&[ty.into(), hasher.into()]), span) } @@ -1697,11 +1703,8 @@ fn hash_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, hasher: Ty<'tcx>, spa fn own_hash_slice<'tcx>(b: &Body<'_, '_, 'tcx>, elem: Ty<'tcx>, hasher: Ty<'tcx>) -> bool { let tcx = b.t.tcx; let elem = peel(b, elem); - let ty::Adt(adt, _) = elem.kind() else { - return false; - }; let f = trait_fn(tcx, "Hash", "hash_slice"); - b.t.own(adt.did()) + local(b, elem) && Instance::try_resolve(tcx, b.t.typing_env_pub(), f, tcx.mk_args(&[elem.into(), hasher.into()])) .ok() .flatten()