diff --git a/quest/m2/ts-model/README.md b/quest/m2/ts-model/README.md index c8a697cb9..efba9d186 100644 --- a/quest/m2/ts-model/README.md +++ b/quest/m2/ts-model/README.md @@ -35,8 +35,8 @@ Decided with the maintainer on 2026-10-27, from a census of the model's 22 publi `unsafe` is bound by the consumer. These are stopgaps: decided with the maintainer on 2026-10-27, a stock crate translates with no annotations or config, so [unsafe code the translator can model](/quest/m3/ts-unsafe.md) and - [trait objects](/quest/m3/ts-dyn.md) remove them. Only true platform boundaries (clocks, - `rand`, DEFLATE) stay bound. + [trait objects](/quest/m3/ts-dyn.md) remove them. Only true platform boundaries (clocks and + DEFLATE) stay bound. - Each child measures this target by the census of `ts/moq/model.toml`, rooted at those types with the boundaries bound, which nightly reports beside the whole crate. - The end-to-end work stays here: the model's roots, its differential harness, and the @@ -49,5 +49,4 @@ Public API: the translator's output for moq-net's model. - [Shared ownership](/quest/m2/ts-shared.md) - kio's waiters are `Arc`/`Weak` with observable counts, and its atomics and locks are plain values - [Float formatting](/quest/m2/ts-model/floats.md) - `f64` formats and parses as std does - [The rest of std the model reaches](/quest/m2/ts-model/std-rest.md) - the std calls the census still refuses -- [Well-known crates without config](/quest/m2/ts-model/stock.md) - rust2-ts maps `bytes`, `rand`, and `tracing` itself, so `model.toml` stops binding and ignoring them - [Async in the TypeScript translator](/quest/m2/ts-async.md) - kio's producers and consumers are futures diff --git a/quest/m2/ts-model/stock.md b/quest/m2/ts-model/stock.md deleted file mode 100644 index f27b6f704..000000000 --- a/quest/m2/ts-model/stock.md +++ /dev/null @@ -1,26 +0,0 @@ -# [M] Well-known crates without config - -## Goal - -[rust2-ts](/ts/README.md) translates calls into `bytes`, `rand`, and `tracing` with no -binding or `ignore-macros` from the consumer, as it does std's, proven by differential -tests against native Rust. `ts/moq/model.toml` drops its entries for them. - -## Plan - -Decided with the maintainer on 2026-10-27: a stock crate translates with no annotations or -config, so a consumer's config holds only its own platform boundaries. moq's model binds -`bytes::Bytes`, `bytes::BytesMut`, and `rand::rng`, and ignores `tracing`'s macros. - -- rust2-ts ships these mappings itself, as it ships std's. Each matches the crate's - semantics exactly; where the crate depends on the platform, such as `rand`'s source of - randomness, say what the mapping uses. -- A mapping stands in only where the crate cannot translate from source: `bytes` has - `unsafe` inside. Prefer translating from source once - [unsafe code the translator can model](/quest/m3/ts-unsafe.md) covers it. -- `tracing`'s macros need a meaning without config: dropping them changes nothing - observable unless a subscriber is installed. Decide what an installed subscriber sees. -- Report the model's census before and after. - -Public API: the translator's output; `ignore-macros` and `[bind]` entries for these crates -become unnecessary. diff --git a/ts/Cargo.lock b/ts/Cargo.lock index 18f7f76ed..53980a6ae 100644 --- a/ts/Cargo.lock +++ b/ts/Cargo.lock @@ -16,15 +16,36 @@ dependencies = [ name = "bind-fixture" version = "0.0.0" dependencies = [ - "bytes", + "blob", ] +[[package]] +name = "blob" +version = "0.0.0" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + [[package]] name = "codec-fixture" version = "0.0.0" @@ -34,6 +55,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crates-dep" version = "0.0.0" @@ -57,6 +87,18 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "120339709b24832c07464b0838828361b735d793c409b8ca3147db0dae601542" +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -92,6 +134,12 @@ dependencies = [ name = "lang-fixture" version = "0.0.0" +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + [[package]] name = "memchr" version = "2.8.3" @@ -147,9 +195,35 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "reject-fixture" version = "0.0.0" +dependencies = [ + "bytes", +] [[package]] name = "rust2-driver" @@ -231,6 +305,16 @@ dependencies = [ name = "share-fixture" version = "0.0.0" +[[package]] +name = "stock-fixture" +version = "0.0.0" +dependencies = [ + "bytes", + "getrandom", + "rand", + "tracing", +] + [[package]] name = "syn" version = "2.0.119" diff --git a/ts/MIGRATE.md b/ts/MIGRATE.md index 3dbea9f58..08fb90540 100644 --- a/ts/MIGRATE.md +++ b/ts/MIGRATE.md @@ -21,6 +21,10 @@ `true`. - `rt.FromUtf8Error` holds its `rt.Utf8Error` as std's does: `e.validUpTo` and `e.errorLen` are `e.error.validUpTo` and `e.error.errorLen`. +- `ts.toml` no longer takes `ignore-macros`: `tracing`'s events are left out without it, + and no other macro is. Delete the key. +- `bytes::Bytes` and `rand::rngs::ThreadRng` can't be bound: translation maps them, a + `Bytes` as an `rt.ByteSlice`. Delete their `[bind]` entries and the files they name. - The runtime no longer exports `ownedNth`, `ownedNthBack`, `ownedSkip`, `ownedTake`, or `ownedStepBy`: `iterNth`, `iterNthBack`, `iterSkip`, `iterTake`, and `iterStepBy` take what drops an item last. `rt.Iter`'s `nthItem` and `nthBackItem` are `nth` and diff --git a/ts/README.md b/ts/README.md index a173645e3..ca28e6d0b 100644 --- a/ts/README.md +++ b/ts/README.md @@ -32,13 +32,11 @@ roots = ["coding::Decoder", "lite::Group"] # Types whose `Display` and `Debug` impls come along, whichever they have, so callers can # print them. Another crate's trait otherwise comes along only when something calls it. printable = ["coding::DecodeError"] -# Macros whose invocations are left out, such as logging. Each must evaluate to `()`. -ignore-macros = ["tracing::trace"] # Hand-written TypeScript that stands in for an item, by its path from the crate root or # else from a crate it depends on: a function, or a type and its functions. [bind] -"bytes::Bytes" = "bind/bytes.ts" +"model::flate::Encoder" = "bind/encoder.ts" "util::TaskSet" = { file = "bind/tasks.ts", drop = true } ``` @@ -109,6 +107,8 @@ crate translation reaches is refused, and so are two versions of one crate it re | `Poll`, `Waker`, `Context` | `T \| typeof rt.Pending`, refused if `T` can already be pending; `rt.Waker`, which is also the context | | `pin!(x)`, `poll_fn(f)`, `future::pending()` | `x`; `rt.PollFn`, which drops `f` with itself; `rt.NEVER` | | `Box::pin(x)`, `dyn Future` | `x`; `rt.Future`: an `async` body or std's future as it is, and another future as an `rt.DynFuture` over its `poll`, which drops it with itself unless borrowed | +| `bytes::Bytes` | `rt.ByteSlice`, as `&[u8]` is: its clones and slices share bytes that never change | +| `rand::rngs::ThreadRng` | `rt.ThreadRng`, which holds no state | `Vec` storage and `[x; N]` byte arrays up to 1 KiB share 8 KiB `ArrayBuffer`s, as Node's `Buffer` pool does, so the `buffer` behind a view holds other bytes too: read it through @@ -280,27 +280,50 @@ full type arguments. Imports name the `.ts` file, which Node, Bun, and bundlers run as is. A `tsc` build sets `rewriteRelativeImportExtensions`, or `allowImportingTsExtensions` with `noEmit`. +## Well-known crates + +rust2-ts maps a few crates itself, as it maps std, so a consumer binds and configures none +of them: + +- `bytes::Bytes` is an `rt.ByteSlice`. Its constructors, `len`, `is_empty`, `slice`, + `Clone`, `Deref`, `AsRef`, `PartialEq` with bytes, `Default`, `Debug`, and `From` + between it and `Vec`, `String`, `&'static [u8]`, and `&'static str` map to + `rt/bytes.ts`, panicking as `bytes` does. `Bytes::from_owner` reads its owner's bytes + once, as `bytes` does, and is refused for an owner that drops, which would drop with the + last clone of what it makes. +- `rand::rng()` is an `rt.ThreadRng`, whose `random` of an integer or `bool` and + `random_range` of an integer range map to `rt/rand.ts`. Each value comes from + `crypto.getRandomValues`, uniform as `rand`'s are, though no seed reproduces them, as + none reproduces `rand::rng()`'s. An empty range panics as `rand`'s does. A seeded + generator, such as `StdRng`, is refused, since its values would have to be `rand`'s. +- `tracing`'s events, `trace!` through `error!` and `event!`, are left out where they are + written. Translated code installs no subscriber, and without one an event evaluates none + of its fields and does nothing, so leaving it out is exact. Installing one, as + `tracing::subscriber::set_global_default` does, is refused as any unmapped call is. + ## Bindings A binding stands in for what the subset refuses, such as `unsafe` code or a boxed future. Its file, relative to `ts.toml`, is copied to the same path in the output, beside the -runtime. It imports `rt.ts` as the output's modules do, `../rt.ts` from `bind/bytes.ts`, +runtime. It imports `rt.ts` as the output's modules do, `../rt.ts` from `bind/blob.ts`, and may import the translated modules and npm packages too. Callers import it whole, as a -type's module, `import * as Bytes from "./bind/bytes.ts"`. +type's module, `import * as Blob from "./bind/blob.ts"`. -A bound type is the file's export of its name, `Bytes.Bytes`, with the Rust type's type +A bound type is the file's export of its name, `Blob.Blob`, with the Rust type's type parameters. A call of a bound function, or of a function that an impl for a bound type in the type's own crate defines, calls the file's export. The export is named as the translated function would be, without the type's or the function's type arguments, so one -export serves every instance and a generic one is a generic TS function. `Bytes::slice` is -`Bytes.slice`, `::eq` is `Bytes.eq$PartialEq`, and -`>>::from` is `Bytes.from$From_Vec_u8`. A trait's provided function +export serves every instance and a generic one is a generic TS function. `Blob::slice` is +`Blob.slice`, `::eq` is `Blob.eq$PartialEq`, and +`>>::from` is `Blob.from$From_Vec_u8`. A trait's provided function that the impl doesn't override, such as `ne`, and a blanket impl's, such as `ToOwned`'s, stay the trait's, as for any other type. A generic export sees a type argument only in the values it takes, so a function with a bounded type parameter that no argument holds, such as `fn zero() -> T`, or with a const parameter, can't be bound. `tsc` checks a 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 @@ -555,7 +578,11 @@ built natively for wasm32 and run beside its translation on the same inputs by also runs the scripts natively on the host (`examples/unwind.rs`), where a panic unwinds, catching and logging each step's panic and going on, so what a panic drops must match too. -- `bind` binds `bytes::Bytes`, and a function and a type of its own that read through raw +- `stock` calls `bytes`, `rand`, and `tracing` with no config, against native Rust, whose + `rand::rng()` reads the fixture's own getrandom backend on wasm32. It checks `Bytes`'s + slices and panics, how each is made and printed, that no event evaluates a field, and + that each random value is in its range, every value of a small range drawn. +- `bind` binds `blob::Blob`, a 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 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`. diff --git a/ts/fixtures/bind/Cargo.toml b/ts/fixtures/bind/Cargo.toml index 3ce1733d3..77e75fb8f 100644 --- a/ts/fixtures/bind/Cargo.toml +++ b/ts/fixtures/bind/Cargo.toml @@ -11,7 +11,7 @@ publish = false crate-type = ["lib", "cdylib"] [dependencies] -bytes = "1.12.1" +blob = { path = "blob" } [lints] workspace = true diff --git a/ts/fixtures/bind/bind/bytes.ts b/ts/fixtures/bind/bind/blob.ts similarity index 65% rename from ts/fixtures/bind/bind/bytes.ts rename to ts/fixtures/bind/bind/blob.ts index f1d3fa3ea..1404388ad 100644 --- a/ts/fixtures/bind/bind/bytes.ts +++ b/ts/fixtures/bind/bind/blob.ts @@ -1,31 +1,31 @@ -// `bytes::Bytes`, which contains `unsafe`: immutable bytes that its slices and clones +// `blob::Blob`, which contains `unsafe`: immutable bytes that its slices and clones // share, as a byte slice of them is. import * as rt from "../rt.ts"; -export type Bytes = rt.ByteSlice; +export type Blob = rt.ByteSlice; -export function copyFromSlice(data: rt.ByteSlice): Bytes { +export function copyFromSlice(data: rt.ByteSlice): Blob { return rt.byteSliceFrom(rt.byteSliceView(data).slice()); } -export function from$From_Vec_u8(vec: rt.ByteVec): Bytes { +export function from$From_Vec_u8(vec: rt.ByteVec): Blob { return rt.byteVecSlice(vec); } -export function len(self: Bytes): rt.usize { +export function len(self: Blob): rt.usize { return self.length; } -export function isEmpty(self: Bytes): boolean { +export function isEmpty(self: Blob): boolean { return self.length === 0; } /** Over each range translated code makes: `a..b`, `a..=b`, `a..`, `..b`, and `..`. */ export function slice( - self: Bytes, + self: Blob, range: rt.Range | rt.RangeInclusive | { start: rt.usize } | { end: rt.usize } | undefined, -): Bytes { +): Blob { let begin = 0; let end = self.length; if (range instanceof rt.RangeInclusive) { @@ -40,14 +40,14 @@ export function slice( return new rt.ByteSlice(self.data, self.start + begin, end - begin); } -export function clone$Clone(self: Bytes): Bytes { +export function clone$Clone(self: Blob): Blob { return self; } -export function deref$Deref(self: Bytes): rt.ByteSlice { +export function deref$Deref(self: Blob): rt.ByteSlice { return self; } -export function eq$PartialEq(self: Bytes, other: Bytes): boolean { +export function eq$PartialEq(self: Blob, other: Blob): boolean { return rt.byteSliceEq(self, other); } diff --git a/ts/fixtures/bind/blob/Cargo.toml b/ts/fixtures/bind/blob/Cargo.toml new file mode 100644 index 000000000..d39416db6 --- /dev/null +++ b/ts/fixtures/bind/blob/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "blob" +description = "Shared bytes with `unsafe` inside, which bind-fixture binds as a dependency's type" +version = "0.0.0" +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true diff --git a/ts/fixtures/bind/blob/src/lib.rs b/ts/fixtures/bind/blob/src/lib.rs new file mode 100644 index 000000000..96c047447 --- /dev/null +++ b/ts/fixtures/bind/blob/src/lib.rs @@ -0,0 +1,106 @@ +//! Immutable bytes that clones and slices share, read through `unsafe`: a dependency's +//! type that a consumer binds rather than translates. + +use std::ops::{Bound, Deref, RangeBounds}; +use std::sync::Arc; + +/// Bytes that clones and slices share. +#[derive(Clone)] +pub struct Blob { + data: Arc<[u8]>, + start: usize, + len: usize, +} + +impl Blob { + /// No bytes. + pub fn new() -> Self { + Self::copy_from_slice(&[]) + } + + /// Bytes that live for the program. + pub fn from_static(data: &'static [u8]) -> Self { + Self::copy_from_slice(data) + } + + /// A copy of `data`. + pub fn copy_from_slice(data: &[u8]) -> Self { + Self { + data: data.into(), + start: 0, + len: data.len(), + } + } + + /// The number of bytes. + pub fn len(&self) -> usize { + self.len + } + + /// Whether there are no bytes. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// The bytes in `range`, sharing these, panicking out of order or out of bounds. + pub fn slice(&self, range: impl RangeBounds) -> Self { + let begin = match range.start_bound() { + Bound::Included(&n) => n, + Bound::Excluded(&n) => n + 1, + Bound::Unbounded => 0, + }; + let end = match range.end_bound() { + Bound::Included(&n) => n + 1, + Bound::Excluded(&n) => n, + Bound::Unbounded => self.len, + }; + assert!( + begin <= end, + "range start must not be greater than end: {begin} <= {end}" + ); + assert!(end <= self.len, "range end out of bounds: {end} <= {}", self.len); + Self { + data: self.data.clone(), + start: self.start + begin, + len: end - begin, + } + } +} + +impl Default for Blob { + fn default() -> Self { + Self::new() + } +} + +impl From> for Blob { + fn from(data: Vec) -> Self { + Self::copy_from_slice(&data) + } +} + +impl Deref for Blob { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + // SAFETY: `start..start + len` is within `data`, which `slice` checked. + unsafe { self.data.get_unchecked(self.start..self.start + self.len) } + } +} + +impl PartialEq for Blob { + fn eq(&self, other: &Self) -> bool { + **self == **other + } +} + +/// Where bytes come from: a trait, which a binding can't stand in for. +pub trait Source { + /// The next bytes. + fn next(&mut self) -> Blob; +} + +/// A `Blob` of no bytes. +pub fn empty() -> Blob { + Blob::new() +} diff --git a/ts/fixtures/bind/expected/bind/bytes.ts b/ts/fixtures/bind/expected/bind/blob.ts similarity index 66% rename from ts/fixtures/bind/expected/bind/bytes.ts rename to ts/fixtures/bind/expected/bind/blob.ts index 7f8eff5ce..fa26f1b4c 100644 --- a/ts/fixtures/bind/expected/bind/bytes.ts +++ b/ts/fixtures/bind/expected/bind/blob.ts @@ -1,32 +1,32 @@ // Generated by rust2-ts. Do not edit. -// `bytes::Bytes`, which contains `unsafe`: immutable bytes that its slices and clones +// `blob::Blob`, which contains `unsafe`: immutable bytes that its slices and clones // share, as a byte slice of them is. import * as rt from "../rt.ts"; -export type Bytes = rt.ByteSlice; +export type Blob = rt.ByteSlice; -export function copyFromSlice(data: rt.ByteSlice): Bytes { +export function copyFromSlice(data: rt.ByteSlice): Blob { return rt.byteSliceFrom(rt.byteSliceView(data).slice()); } -export function from$From_Vec_u8(vec: rt.ByteVec): Bytes { +export function from$From_Vec_u8(vec: rt.ByteVec): Blob { return rt.byteVecSlice(vec); } -export function len(self: Bytes): rt.usize { +export function len(self: Blob): rt.usize { return self.length; } -export function isEmpty(self: Bytes): boolean { +export function isEmpty(self: Blob): boolean { return self.length === 0; } /** Over each range translated code makes: `a..b`, `a..=b`, `a..`, `..b`, and `..`. */ export function slice( - self: Bytes, + self: Blob, range: rt.Range | rt.RangeInclusive | { start: rt.usize } | { end: rt.usize } | undefined, -): Bytes { +): Blob { let begin = 0; let end = self.length; if (range instanceof rt.RangeInclusive) { @@ -41,14 +41,14 @@ export function slice( return new rt.ByteSlice(self.data, self.start + begin, end - begin); } -export function clone$Clone(self: Bytes): Bytes { +export function clone$Clone(self: Blob): Blob { return self; } -export function deref$Deref(self: Bytes): rt.ByteSlice { +export function deref$Deref(self: Blob): rt.ByteSlice { return self; } -export function eq$PartialEq(self: Bytes, other: Bytes): boolean { +export function eq$PartialEq(self: Blob, other: Blob): boolean { return rt.byteSliceEq(self, other); } diff --git a/ts/fixtures/bind/expected/harness.ts b/ts/fixtures/bind/expected/harness.ts index ae33dd5bc..ceb348459 100644 --- a/ts/fixtures/bind/expected/harness.ts +++ b/ts/fixtures/bind/expected/harness.ts @@ -1,13 +1,13 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import * as Bytes from "./bind/bytes.ts"; +import * as Blob from "./bind/blob.ts"; import * as checksum from "./bind/checksum.ts"; import * as skip from "./bind/skip.ts"; import * as Tally from "./bind/tally.ts"; /** - * Split the input as `Bytes`, compare and hash the parts, skip its leading zeros, and + * 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. */ export function run(input: rt.ByteSlice): rt.ByteVec { @@ -24,27 +24,27 @@ export function run(input: rt.ByteSlice): rt.ByteVec { _128 = false; _127 = false; const out: rt.ByteVec = new rt.ByteVec(); - const bytes: Bytes.Bytes = Bytes.copyFromSlice(input); - const mid: rt.usize = rt.usizeDiv(Bytes.len(bytes), 2); - const head: Bytes.Bytes = Bytes.slice(bytes, { end: mid }); - const tail: Bytes.Bytes = Bytes.slice(bytes, { start: mid }); + const bytes: Blob.Blob = Blob.copyFromSlice(input); + const mid: rt.usize = rt.usizeDiv(Blob.len(bytes), 2); + const head: Blob.Blob = Blob.slice(bytes, { end: mid }); + const tail: Blob.Blob = Blob.slice(bytes, { start: mid }); const _16: rt.Range = new rt.Range(rt.min(1, mid), mid); - const inner: Bytes.Bytes = Bytes.slice(bytes, _16); - const _20: rt.u8 = Bytes.len(head) & 0xff; + const inner: Blob.Blob = Blob.slice(bytes, _16); + const _20: rt.u8 = Blob.len(head) & 0xff; rt.byteVecPush(out, _20); - const _25: rt.u8 = Bytes.len(inner) & 0xff; + const _25: rt.u8 = Blob.len(inner) & 0xff; rt.byteVecPush(out, _25); - const _30: rt.ByteSlice = Bytes.deref$Deref(tail); + const _30: rt.ByteSlice = Blob.deref$Deref(tail); rt.byteVecExtendFromSlice(out, _30); - const _34: rt.u8 = Bytes.eq$PartialEq(head, tail) ? 1 : 0; + const _34: rt.u8 = Blob.eq$PartialEq(head, tail) ? 1 : 0; rt.byteVecPush(out, _34); - const _40: rt.u8 = Bytes.eq$PartialEq(Bytes.clone$Clone(head), head) ? 1 : 0; + const _40: rt.u8 = Blob.eq$PartialEq(Blob.clone$Clone(head), head) ? 1 : 0; rt.byteVecPush(out, _40); - const _48: rt.u8 = Bytes.eq$PartialEq(Bytes.from$From_Vec_u8(rt.byteSliceToByteVec(input)), bytes) ? 1 : 0; + const _48: rt.u8 = Blob.eq$PartialEq(Blob.from$From_Vec_u8(rt.byteSliceToByteVec(input)), bytes) ? 1 : 0; rt.byteVecPush(out, _48); - const _56: rt.u8 = Bytes.isEmpty(bytes) ? 1 : 0; + const _56: rt.u8 = Blob.isEmpty(bytes) ? 1 : 0; rt.byteVecPush(out, _56); - const sum: rt.u32 = checksum.checksum(Bytes.deref$Deref(tail)); + const sum: rt.u32 = checksum.checksum(Blob.deref$Deref(tail)); const iter: rt.Iter = rt.iterSlice([0, 8, 16, 24]); while (true) { const _65: rt.i32 | rt.Done = iter.next(); @@ -58,7 +58,7 @@ export function run(input: rt.ByteSlice): rt.ByteVec { rt.byteVecPush(out, at & 0xff); if (rt.byteSliceFirst(input) === 1) { const _88: rt.Range = new rt.Range(mid, rt.usizeSaturatingSub(mid, 1)); - Bytes.slice(bytes, _88); + Blob.slice(bytes, _88); } count = new rt.Arc(input.length as rt.u32); unwind = 69; diff --git a/ts/fixtures/bind/refused.toml b/ts/fixtures/bind/refused.toml index d51509e97..5f73489d9 100644 --- a/ts/fixtures/bind/refused.toml +++ b/ts/fixtures/bind/refused.toml @@ -7,13 +7,13 @@ roots = ["harness::run", "harness::refused"] "nowhere::Thing" = "bind/thing.ts" "std::vec::Vec" = "bind/vec.ts" "raw" = "bind/raw.ts" -"bytes::Buf" = "bind/buf.ts" +"blob::Source" = "bind/source.ts" "raw::Tally::get" = { file = "bind/get.ts", drop = true } "raw::Tally::new" = "rt/tally.ts" "raw::Held::new" = "RT/held.ts" -"bytes::BytesMut" = "../bytes.ts" -"bytes::Bytes" = "bind/bytes.ts" -"raw::Tally" = "bind/bytes.ts" +"blob::empty" = "../blob.ts" +"blob::Blob" = "bind/blob.ts" +"raw::Tally" = "bind/blob.ts" "checksum" = "bind/missing.ts" "raw::checksum" = "bind/checksum.ts" "raw::skip" = "bind/skip.ts" diff --git a/ts/fixtures/bind/refused.txt b/ts/fixtures/bind/refused.txt index 835c8c9dd..55941426a 100644 --- a/ts/fixtures/bind/refused.txt +++ b/ts/fixtures/bind/refused.txt @@ -1,13 +1,13 @@ -binding `bytes::Buf`: a binding is of a function or a type, not Trait -binding `bytes::BytesMut`: ../bytes.ts must be relative to ts.toml, inside its directory +binding `blob::Source`: a binding is of a function or a type, not Trait +binding `blob::empty`: ../blob.ts must be relative to ts.toml, inside its directory binding `nowhere::Thing`: no such item, or more than one, in the crate or a crate it depends on binding `raw`: a binding is of a function or a type, not Mod binding `raw::Held::new`: RT/held.ts would replace the runtime, rt.ts and rt/ -binding `raw::Tally`: bind/bytes.ts binds another type +binding `raw::Tally`: bind/blob.ts binds another type 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`: std's type has a representation of its own +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 unsupported type `*const u32` at fixtures/bind/src/raw.rs:36:2 `raw::Held` binds without drop, so it would never drop its `raw::Tally` at fixtures/bind/src/harness.rs:61:13 @@ -17,4 +17,4 @@ a binding of `raw::zero`, whose `T` one export for every instance can't recover 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 a raw pointer dereferenced at fixtures/bind/src/raw.rs:48:12 -an assignment through a reference to `bytes::Bytes` at fixtures/bind/src/harness.rs:68:2 +an assignment through a reference to `blob::Blob` at fixtures/bind/src/harness.rs:68:2 diff --git a/ts/fixtures/bind/src/harness.rs b/ts/fixtures/bind/src/harness.rs index f8bc3bbe8..fb7cb3216 100644 --- a/ts/fixtures/bind/src/harness.rs +++ b/ts/fixtures/bind/src/harness.rs @@ -2,15 +2,15 @@ use std::sync::Arc; -use bytes::Bytes; +use blob::Blob; use crate::raw::{Tally, checksum, skip}; -/// Split the input as `Bytes`, compare and hash the parts, skip its leading zeros, and +/// 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. pub fn run(input: &[u8]) -> Vec { let mut out = Vec::new(); - let bytes = Bytes::copy_from_slice(input); + let bytes = Blob::copy_from_slice(input); let mid = bytes.len() / 2; let head = bytes.slice(..mid); let tail = bytes.slice(mid..); @@ -20,7 +20,7 @@ pub fn run(input: &[u8]) -> Vec { out.extend_from_slice(&tail); out.push((head == tail) as u8); out.push((head.clone() == head) as u8); - out.push((Bytes::from(input.to_vec()) == bytes) as u8); + out.push((Blob::from(input.to_vec()) == bytes) as u8); out.push(bytes.is_empty() as u8); let sum = checksum(&tail); for shift in [0, 8, 16, 24] { @@ -56,14 +56,14 @@ pub fn held() -> bool { /// What `refused.toml`'s bindings can't stand in for, which `run` never reaches. pub fn refused(count: &Arc) -> u8 { - let mut bytes = Bytes::new(); - replace(&mut bytes, Bytes::from_static(b"replaced")); + let mut bytes = Blob::new(); + replace(&mut bytes, Blob::from_static(b"replaced")); let held = crate::raw::Held::new(Tally::new(count)); drop(held); let values = crate::raw::value::<1>() + crate::raw::value::<2>(); crate::raw::zero::() + bytes.len() as u8 + values as u8 } -fn replace(target: &mut Bytes, value: Bytes) { +fn replace(target: &mut Blob, value: Blob) { *target = value; } diff --git a/ts/fixtures/bind/src/lib.rs b/ts/fixtures/bind/src/lib.rs index 5a50e860e..d94cf4b46 100644 --- a/ts/fixtures/bind/src/lib.rs +++ b/ts/fixtures/bind/src/lib.rs @@ -1,4 +1,4 @@ -//! Items outside the subset, bound to hand-written TypeScript: `bytes::Bytes`, which +//! Items outside the subset, bound to hand-written TypeScript: `blob::Blob`, which //! contains `unsafe`, and the crate's own function and type that read through raw //! pointers, one of them dropping where Rust drops it. //! diff --git a/ts/fixtures/bind/ts.toml b/ts/fixtures/bind/ts.toml index 7280781b9..ab6840c05 100644 --- a/ts/fixtures/bind/ts.toml +++ b/ts/fixtures/bind/ts.toml @@ -2,7 +2,7 @@ package = "bind-fixture" roots = ["harness::run"] [bind] -"bytes::Bytes" = "bind/bytes.ts" +"blob::Blob" = "bind/blob.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.toml b/ts/fixtures/bind/wrong.toml index c1d1f212d..c30bd0031 100644 --- a/ts/fixtures/bind/wrong.toml +++ b/ts/fixtures/bind/wrong.toml @@ -4,7 +4,7 @@ package = "bind-fixture" roots = ["harness::run", "harness::held"] [bind] -"bytes::Bytes" = "wrong/bytes.ts" +"blob::Blob" = "wrong/blob.ts" "raw::checksum" = "bind/checksum.ts" "raw::skip" = "wrong/skip.ts" "raw::Tally" = { file = "wrong/tally.ts", drop = true } diff --git a/ts/fixtures/bind/wrong.txt b/ts/fixtures/bind/wrong.txt index 921a1dec5..6b7447131 100644 --- a/ts/fixtures/bind/wrong.txt +++ b/ts/fixtures/bind/wrong.txt @@ -1,10 +1,10 @@ -the binding of `bytes::Bytes::len` in wrong/bytes.ts doesn't type-check: error TS2322: Type '(self: ByteSlice) => string' is not assignable to type '(a0: ByteSlice) => usize'. +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 bytes-1.12.1/src/bytes.rs:303:5 -the binding of `bytes::Bytes::slice::>` in wrong/bytes.ts doesn't type-check: error TS2339: Property 'slice' does not exist on type 'typeof import("wrong/bytes")'. at bytes-1.12.1/src/bytes.rs:373:5 -the binding of `::eq` in wrong/bytes.ts doesn't type-check: error TS2322: Type '(self: ByteSlice, other: string) => boolean' is not assignable to type '(a0: ByteSlice, a1: ByteSlice) => boolean'. + 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 +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 bytes-1.12.1/src/bytes.rs:769:5 + Type 'ByteSlice' is not assignable to type 'string'. at fixtures/bind/blob/src/lib.rs:92: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 diff --git a/ts/fixtures/bind/wrong/blob.ts b/ts/fixtures/bind/wrong/blob.ts new file mode 100644 index 000000000..5d30b0a8a --- /dev/null +++ b/ts/fixtures/bind/wrong/blob.ts @@ -0,0 +1,34 @@ +// `blob::Blob`, bound wrong: `slice` is missing, `len` returns a string, and `eq` takes +// what no `Blob` is. + +import * as rt from "../rt.ts"; + +export type Blob = rt.ByteSlice; + +export function copyFromSlice(data: rt.ByteSlice): Blob { + return data; +} + +export function from$From_Vec_u8(vec: rt.ByteVec): Blob { + return rt.byteVecSlice(vec); +} + +export function len(self: Blob): string { + return `${self.length}`; +} + +export function isEmpty(self: Blob): boolean { + return self.length === 0; +} + +export function clone$Clone(self: Blob): Blob { + return self; +} + +export function deref$Deref(self: Blob): rt.ByteSlice { + return self; +} + +export function eq$PartialEq(self: Blob, other: string): boolean { + return self.length === other.length; +} diff --git a/ts/fixtures/bind/wrong/bytes.ts b/ts/fixtures/bind/wrong/bytes.ts deleted file mode 100644 index 030964d95..000000000 --- a/ts/fixtures/bind/wrong/bytes.ts +++ /dev/null @@ -1,34 +0,0 @@ -// `bytes::Bytes`, bound wrong: `slice` is missing, `len` returns a string, and `eq` takes -// what no `Bytes` is. - -import * as rt from "../rt.ts"; - -export type Bytes = rt.ByteSlice; - -export function copyFromSlice(data: rt.ByteSlice): Bytes { - return data; -} - -export function from$From_Vec_u8(vec: rt.ByteVec): Bytes { - return rt.byteVecSlice(vec); -} - -export function len(self: Bytes): string { - return `${self.length}`; -} - -export function isEmpty(self: Bytes): boolean { - return self.length === 0; -} - -export function clone$Clone(self: Bytes): Bytes { - return self; -} - -export function deref$Deref(self: Bytes): rt.ByteSlice { - return self; -} - -export function eq$PartialEq(self: Bytes, other: string): boolean { - return self.length === other.length; -} diff --git a/ts/fixtures/codec/ts.toml b/ts/fixtures/codec/ts.toml index 506362af1..1034519f5 100644 --- a/ts/fixtures/codec/ts.toml +++ b/ts/fixtures/codec/ts.toml @@ -1,3 +1,2 @@ package = "codec-fixture" roots = ["harness::run", "bench::run"] -ignore-macros = ["tracing::trace", "tracing::warn"] diff --git a/ts/fixtures/reject/Cargo.toml b/ts/fixtures/reject/Cargo.toml index 9925b8b6c..0d60a3ee9 100644 --- a/ts/fixtures/reject/Cargo.toml +++ b/ts/fixtures/reject/Cargo.toml @@ -6,5 +6,8 @@ edition.workspace = true license.workspace = true publish = false +[dependencies] +bytes = "1.12.1" + [lints] workspace = true diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 877c7576e..cf72bf5fc 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 73 -- Function instances: 83 +- Refusals: 74 +- Function instances: 84 - Generic functions no instance reached, lowered over their type parameters: 6 ## By construct @@ -17,12 +17,13 @@ | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | fixtures/reject/src/lib.rs:16:15 | | 2 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:41:42 | | 2 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | fixtures/reject/src/lib.rs:247:16 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:474:23 | -| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:465:40 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | fixtures/reject/src/lib.rs:479:23 | +| 2 | a coercion to `_`, which is not supported yet | fixtures/reject/src/lib.rs:470:40 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:159:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:145:23 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:139:2 | | 2 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:369:13 | +| 1 | `Bytes::from_owner` of `_`, which would drop with the last clone of what it makes, which is not supported | fixtures/reject/src/lib.rs:425:2 | | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:68:2 | | 1 | `_` is not supported yet | fixtures/reject/src/lib.rs:393:18 | | 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `None` would be `rt.None` as `_` | fixtures/reject/src/lib.rs:31:2 | @@ -31,7 +32,7 @@ | 1 | `_` through a held type's own, which is not supported yet | fixtures/reject/src/lib.rs:318:2 | | 1 | `_`, a trait object of another crate's trait, which is not supported yet | fixtures/reject/src/lib.rs:11:16 | | 1 | `_`, which is not supported yet | fixtures/reject/src/lib.rs:294:9 | -| 1 | `f64::mul_add`, which rounds once, where JS would round twice | fixtures/reject/src/lib.rs:444:4 | +| 1 | `f64::mul_add`, which rounds once, where JS would round twice | fixtures/reject/src/lib.rs:449:4 | | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | fixtures/reject/src/lib.rs:221:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:172:51 | | 1 | a cast from `_` to `_` | fixtures/reject/src/lib.rs:96:2 | @@ -42,7 +43,7 @@ | 1 | a mutable reference into a `Result`'s payload, passed on or kept | fixtures/reject/src/lib.rs:413:12 | | 1 | a printable type must implement `Display` or `Debug` | fixtures/reject/src/lib.rs:92:1 | | 1 | a scalar constant of type `_` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:491:26 | +| 1 | a trait object of `_`, which is not supported yet | fixtures/reject/src/lib.rs:496:26 | | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:62:2 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | collecting `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:36:43 | @@ -62,22 +63,22 @@ The type or module each refused type or path belongs to. | 6 | `Option` | fixtures/reject/src/lib.rs:16:15 | | 6 | `f32` | fixtures/reject/src/lib.rs:7:14 | | 4 | `Iterator` | fixtures/reject/src/lib.rs:41:42 | -| 3 | `std::sync::Arc` | fixtures/reject/src/lib.rs:101:2 | +| 4 | `std::sync::Arc` | fixtures/reject/src/lib.rs:101:2 | | 3 | `std::vec::Vec` | fixtures/reject/src/lib.rs:268:52 | | 3 | `u8` | fixtures/reject/src/lib.rs:80:2 | | 3 | `{closure}` | fixtures/reject/src/lib.rs:369:13 | | 2 | `HashMap` | fixtures/reject/src/lib.rs:263:6 | | 2 | `Meters` | fixtures/reject/src/lib.rs:85:2 | | 2 | `Poll` | fixtures/reject/src/lib.rs:105:20 | -| 2 | `Scaled` | fixtures/reject/src/lib.rs:474:23 | -| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:474:23 | +| 2 | `Scaled` | fixtures/reject/src/lib.rs:479:23 | +| 2 | `dyn Scaled` | fixtures/reject/src/lib.rs:479:23 | | 2 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:53:13 | | 2 | `std::iter::Iterator` | fixtures/reject/src/lib.rs:247:16 | | 2 | `std::iter::Map` | fixtures/reject/src/lib.rs:145:23 | | 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:180:8 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:116:2 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:21:4 | -| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:439:17 | +| 2 | `std::vec::IntoIter` | fixtures/reject/src/lib.rs:444:17 | | 1 | `Batched` | fixtures/reject/src/lib.rs:360:16 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:159:1 | | 1 | `Entry` | fixtures/reject/src/lib.rs:369:13 | @@ -86,11 +87,11 @@ The type or module each refused type or path belongs to. | 1 | `Maybe` | fixtures/reject/src/lib.rs:31:2 | | 1 | `Noisy` | fixtures/reject/src/lib.rs:53:13 | | 1 | `T \| undefined` | fixtures/reject/src/lib.rs:31:2 | -| 1 | `Tail` | fixtures/reject/src/lib.rs:501:30 | +| 1 | `Tail` | fixtures/reject/src/lib.rs:506:30 | | 1 | `[u16; 1]` | fixtures/reject/src/lib.rs:240:22 | -| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:491:26 | +| 1 | `[u8; 4]` | fixtures/reject/src/lib.rs:496:26 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:11:16 | -| 1 | `f64` | fixtures/reject/src/lib.rs:449:2 | +| 1 | `f64` | fixtures/reject/src/lib.rs:454:2 | | 1 | `into_keys` | fixtures/reject/src/lib.rs:53:13 | | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:172:51 | | 1 | `std::iter::Rev` | fixtures/reject/src/lib.rs:166:14 | @@ -98,7 +99,7 @@ The type or module each refused type or path belongs to. | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:126:11 | | 1 | `std::string::String` | fixtures/reject/src/lib.rs:74:10 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:121:2 | -| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:465:40 | +| 1 | `std::sync::Weak` | fixtures/reject/src/lib.rs:470:40 | | 1 | `str` | fixtures/reject/src/lib.rs:377:4 | | 1 | `u32` | fixtures/reject/src/lib.rs:226:13 | | 1 | `u64` | fixtures/reject/src/lib.rs:96:2 | @@ -113,10 +114,11 @@ The type or module each refused type or path belongs to. | 3 | unsupported type `_` | `f32` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:105:20 | | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | `Option` | fixtures/reject/src/lib.rs:16:15 | -| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:474:23 | +| 2 | `_`, a trait object of the generic trait `_`, which is not supported yet | `dyn Scaled`, `Scaled` | fixtures/reject/src/lib.rs:479:23 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:116:2 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:85:2 | -| 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:439:17 | +| 2 | unsupported call to `_` | `::sum` | fixtures/reject/src/lib.rs:444:17 | +| 1 | `Bytes::from_owner` of `_`, which would drop with the last clone of what it makes, which is not supported | `std::sync::Arc` | fixtures/reject/src/lib.rs:425:2 | | 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:393:18 | | 1 | `_` is not supported: its field `_` is `_`, typed `_`, whose `None` would be `rt.None` as `_` | `Maybe`, `value`, `Option`, `T \| undefined`, `Option` | fixtures/reject/src/lib.rs:31:2 | | 1 | `_` of `_` by `_`, which is not supported yet | `HashMap::contains_key`, `std::collections::HashMap`, `u8` | fixtures/reject/src/lib.rs:286:6 | @@ -132,12 +134,12 @@ The type or module each refused type or path belongs to. | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:172:51 | | 1 | a cast from `_` to `_` | `u64`, `f32` | fixtures/reject/src/lib.rs:96:2 | | 1 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:341:2 | -| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:501:30 | -| 1 | a coercion to `_`, which is not supported yet | `std::sync::Weak` | fixtures/reject/src/lib.rs:465:40 | +| 1 | a coercion to `_`, which is not supported yet | `&Tail` | fixtures/reject/src/lib.rs:506:30 | +| 1 | a coercion to `_`, which is not supported yet | `std::sync::Weak` | fixtures/reject/src/lib.rs:470:40 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:80:2 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | `u32` | fixtures/reject/src/lib.rs:226:13 | | 1 | a scalar constant of type `_` | `f32` | fixtures/reject/src/lib.rs:8:2 | -| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:491:26 | +| 1 | a trait object of `_`, which is not supported yet | `[u8; 4]` | fixtures/reject/src/lib.rs:496:26 | | 1 | a zero-sized constant of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:62:2 | | 1 | an assignment through a reference to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:101:2 | | 1 | an assignment through a reference to `_` | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:121:2 | @@ -157,7 +159,7 @@ The type or module each refused type or path belongs to. | 1 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | `{closure}`, `Iterator::for_each` | fixtures/reject/src/lib.rs:370:16 | | 1 | passing `_`, which drops, to `_`, which is not supported yet | `{closure}`, `str::contains` | fixtures/reject/src/lib.rs:377:4 | | 1 | replacing the value behind a reference to `_` | `[u16; 1]` | fixtures/reject/src/lib.rs:240:22 | -| 1 | unsupported call to `_` | `::fmt` | fixtures/reject/src/lib.rs:449:2 | +| 1 | unsupported call to `_` | `::fmt` | fixtures/reject/src/lib.rs:454:2 | | 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:394:2 | | 1 | unsupported call to `_` | `::eq` | fixtures/reject/src/lib.rs:420:2 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:126:11 | @@ -179,9 +181,9 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:351:10: unsupported call to `::hash::` - fixtures/reject/src/lib.rs:394:2: unsupported call to ` as std::ops::Deref>::deref` - fixtures/reject/src/lib.rs:420:2: unsupported call to ` as std::cmp::PartialEq>::eq` -- fixtures/reject/src/lib.rs:439:17: unsupported call to ` as std::iter::Iterator>::sum::` -- fixtures/reject/src/lib.rs:439:38: unsupported call to ` as std::iter::Iterator>::sum::` -- fixtures/reject/src/lib.rs:449:2: unsupported call to `::fmt` +- fixtures/reject/src/lib.rs:444:17: unsupported call to ` as std::iter::Iterator>::sum::` +- fixtures/reject/src/lib.rs:444:38: unsupported call to ` as std::iter::Iterator>::sum::` +- fixtures/reject/src/lib.rs:454:2: unsupported call to `::fmt` @@ -249,15 +251,15 @@ The type or module each refused type or path belongs to.
`_`, a trait object of the generic trait `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:474:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet -- fixtures/reject/src/lib.rs:475:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet +- fixtures/reject/src/lib.rs:479:23: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet +- fixtures/reject/src/lib.rs:480:4: `dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet
a coercion to `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:465:40: a coercion to `std::sync::Weak`, which is not supported yet -- fixtures/reject/src/lib.rs:501:30: a coercion to `&Tail`, which is not supported yet +- fixtures/reject/src/lib.rs:470:40: a coercion to `std::sync::Weak`, which is not supported yet +- fixtures/reject/src/lib.rs:506:30: a coercion to `&Tail`, which is not supported yet
@@ -289,6 +291,12 @@ The type or module each refused type or path belongs to. +
`Bytes::from_owner` of `_`, which would drop with the last clone of what it makes, which is not supported (1) + +- fixtures/reject/src/lib.rs:425:2: `Bytes::from_owner` of `std::sync::Arc<[u8]>`, which would drop with the last clone of what it makes, which is not supported + +
+
`Pointer` formatting, as in `{:p}`, is not supported (1) - fixtures/reject/src/lib.rs:68:2: `Pointer` formatting, as in `{:p}`, is not supported @@ -339,7 +347,7 @@ The type or module each refused type or path belongs to.
`f64::mul_add`, which rounds once, where JS would round twice (1) -- fixtures/reject/src/lib.rs:444:4: `f64::mul_add`, which rounds once, where JS would round twice +- fixtures/reject/src/lib.rs:449:4: `f64::mul_add`, which rounds once, where JS would round twice
@@ -405,7 +413,7 @@ The type or module each refused type or path belongs to.
a trait object of `_`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:491:26: a trait object of `[u8; 4]`, which is not supported yet +- fixtures/reject/src/lib.rs:496:26: a trait object of `[u8; 4]`, which is not supported yet
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index eed8a9d79..5bc147e51 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -54,17 +54,18 @@ hashing `std::vec::Vec` through `Batched`'s own `Hash::hash_slice`, whi passing `{closure@fixtures/reject/src/lib.rs:369:28: 369:35}`, a closure that owns a value that drops, to `Entry::or_insert_with`, which is not supported yet at fixtures/reject/src/lib.rs:369:13 passing `{closure@fixtures/reject/src/lib.rs:370:25: 370:33}`, a closure that owns a value that drops, to `Iterator::for_each`, which is not supported yet at fixtures/reject/src/lib.rs:370:16 passing `{closure@fixtures/reject/src/lib.rs:377:13: 377:27}`, which drops, to `str::contains`, which is not supported yet at fixtures/reject/src/lib.rs:377:4 -unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:439:17 -unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:439:38 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:444:17 +unsupported call to ` as std::iter::Iterator>::sum::` at fixtures/reject/src/lib.rs:444:38 a mutable reference into a `Result`'s payload, passed on or kept at fixtures/reject/src/lib.rs:413:12 unsupported call to ` as std::cmp::PartialEq>::eq` at fixtures/reject/src/lib.rs:420:2 -`f64::mul_add`, which rounds once, where JS would round twice at fixtures/reject/src/lib.rs:444:4 -unsupported call to `::fmt` at fixtures/reject/src/lib.rs:449:11 -a coercion to `std::sync::Weak`, which is not supported yet at fixtures/reject/src/lib.rs:465:40 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:474:23 -`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:475:4 -a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:491:26 -a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:501:30 +`Bytes::from_owner` of `std::sync::Arc<[u8]>`, which would drop with the last clone of what it makes, which is not supported at fixtures/reject/src/lib.rs:425:2 +`f64::mul_add`, which rounds once, where JS would round twice at fixtures/reject/src/lib.rs:449:4 +unsupported call to `::fmt` at fixtures/reject/src/lib.rs:454:11 +a coercion to `std::sync::Weak`, which is not supported yet at fixtures/reject/src/lib.rs:470:40 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:479:23 +`dyn Scaled`, a trait object of the generic trait `Scaled`, which is not supported yet at fixtures/reject/src/lib.rs:480:4 +a trait object of `[u8; 4]`, which is not supported yet at fixtures/reject/src/lib.rs:496:26 +a coercion to `&Tail`, which is not supported yet at fixtures/reject/src/lib.rs:506:30 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:139:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:159:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:193:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 20e169cb1..3bc400c78 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -420,6 +420,11 @@ pub fn places_equal(a: &mut u32, b: &mut u32) -> bool { Some(a) == Some(b) } +/// An owner that drops, which would drop with the last clone of the `Bytes`. +pub fn owned_bytes(owner: std::sync::Arc<[u8]>) -> usize { + bytes::Bytes::from_owner(owner).len() +} + pub struct Part(pub u64); impl std::iter::Sum for std::time::Duration { diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 8e1ec8273..65af0ff0a 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -51,6 +51,7 @@ roots = [ "parts_summed", "ok_passed", "places_equal", + "owned_bytes", "fma", "float_printed", "weak_object", diff --git a/ts/fixtures/stock/Cargo.toml b/ts/fixtures/stock/Cargo.toml new file mode 100644 index 000000000..86b84d636 --- /dev/null +++ b/ts/fixtures/stock/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "stock-fixture" +description = "Calls into bytes, rand, and tracing, which rust2-ts maps itself" +version = "0.0.0" +edition.workspace = true +license.workspace = true +publish = false + +[lib] +# The cdylib is the native side of the differential test, built for wasm32. +crate-type = ["lib", "cdylib"] + +[dependencies] +bytes = "1.12.1" +# The native side's source of randomness on wasm32, which its tests select. +getrandom = "0.4.3" +rand = "0.10.3" +tracing = "0.1.44" + +[lints] +workspace = true diff --git a/ts/fixtures/stock/expected/harness.Owner.ts b/ts/fixtures/stock/expected/harness.Owner.ts new file mode 100644 index 000000000..2c76b6fed --- /dev/null +++ b/ts/fixtures/stock/expected/harness.Owner.ts @@ -0,0 +1,16 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** An owner `Bytes::from_owner` reads once, and drops nothing JS sees. */ +export interface Owner { + data: rt.ByteVec; + skip: rt.usize; +} + +export function asRef$AsRef_u8s(self: Owner): rt.ByteSlice { + const part = rt.min(self.skip, self.data.length); + return rt.byteSliceRange(rt.byteVecSlice(self.data), part); +} + +//# sourceMappingURL=harness.Owner.ts.map diff --git a/ts/fixtures/stock/expected/harness.ts b/ts/fixtures/stock/expected/harness.ts new file mode 100644 index 000000000..63a49e94f --- /dev/null +++ b/ts/fixtures/stock/expected/harness.ts @@ -0,0 +1,236 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import * as Owner from "./harness.Owner.ts"; + +/** + * Each case, which the first byte picks modulo their count, so a case added at the end + * moves no other. + */ +export function cases(): Array<(a0: rt.ByteSlice, a1: rt.ByteVec) => void> { + return [slices, made, events, random]; +} + +/** Run one case. */ +export function run(input: rt.ByteSlice): rt.ByteVec { + const out: rt.ByteVec = new rt.ByteVec(); + if (input.length !== 0) { + const op: rt.u8 = input.data[input.start]; + const cases_: Array<(a0: rt.ByteSlice, a1: rt.ByteVec) => void> = cases(); + cases_[rt.idx(cases_, rt.usizeRem(op as rt.usize, cases_.length))](new rt.ByteSlice(input.data, input.start + 1, input.length - 1), out); + return out; + } + return out; +} + +/** + * `Bytes`'s slices by every kind of range, out of bounds included, which panic as + * `bytes` does, and what they compare equal to. + */ +export function slices(data: rt.ByteSlice, out: rt.ByteVec): void { + let part!: rt.ByteSlice; + let range!: rt.RangeInclusive; + if (data.length >= 3) { + const bytes: rt.ByteSlice = rt.bytesCopyFromSlice(new rt.ByteSlice(data.data, data.start + 3, data.length - 3)); + const past: boolean = data.data[data.start + 2] === 255; + const _14: [rt.usize, rt.usize] = [rt.usizeRem(data.data[data.start + 1] as rt.usize, rt.usizeAdd(data.length - 3, 2)), rt.usizeRem(data.data[data.start + 2] as rt.usize, rt.usizeAdd(data.length - 3, 2))]; + const a: rt.usize = _14[0]; + const b: rt.usize = _14[1]; + if ((data.data[data.start] & 128) !== 0) { + rt.bytesSlice(bytes, b); + } + const _35: rt.u8 = rt.u8Rem(data.data[data.start], 7); + if (_35 === 0) { + part = rt.bytesSlice(bytes, a, b); + } else if (_35 === 1) { + part = rt.bytesSlice(bytes, a); + } else if (_35 === 2) { + part = rt.bytesSlice(bytes, 0, b); + } else if (_35 === 3) { + part = rt.bytesSlice(bytes, 0); + } else if (_35 === 4) { + if (!past) { + const _46: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.usizeStep); + part = rt.bytesSliceInclusive(bytes, _46); + } else { + const _44: rt.RangeInclusive = new rt.RangeInclusive(a, 4294967295, rt.usizeStep); + part = rt.bytesSliceInclusive(bytes, _44); + } + } else if (_35 === 5) { + if (!past) { + part = rt.bytesSliceToInclusive(bytes, b); + } else { + part = rt.bytesSliceToInclusive(bytes, 4294967295); + } + } else { + if (!past) { + range = new rt.RangeInclusive(a, b, rt.usizeStep); + } else { + range = new rt.RangeInclusive(4294967295, 4294967295, rt.usizeStep); + } + while (rt.iterToOption(range.next()) !== undefined) { + } + part = rt.bytesSliceInclusive(bytes, range); + } + rt.byteVecPush(out, part.length & 0xff); + rt.byteVecPush(out, part.length === 0 ? 1 : 0); + rt.byteVecExtendFromSlice(out, part); + rt.byteVecPush(out, rt.byteSliceEq(part, bytes) ? 1 : 0); + rt.byteVecPush(out, rt.byteSliceEq(part, rt.byteSliceRange(part, 0)) ? 1 : 0); + rt.byteVecPush(out, rt.byteSliceEq(rt.bytesSlice(rt.bytesSlice(bytes, rt.min(a, data.length - 3)), 0, 0), rt.bytesNew()) ? 1 : 0); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.byteSliceToByteVec(part))); + } +} + +/** `Bytes` made each way, printed with `Debug`. */ +export function made(data: rt.ByteSlice, out: rt.ByteVec): void { + if (data.length !== 0) { + const skip: rt.u8 = data.data[data.start]; + const rest: rt.ByteSlice = new rt.ByteSlice(data.data, data.start + 1, data.length - 1); + const _8: rt.ByteSlice = rt.byteVecSlice(rt.byteSliceToByteVec(rest)); + const _10: rt.ByteSlice = rt.byteSliceFrom(Uint8Array.of(0, 9, 13, 10, 92, 34, 39, 126, 127, 128, 255)); + const _13: rt.ByteSlice = rt.stringAsBytes("string"); + const _15: rt.ByteSlice = rt.stringAsBytes("text"); + const _16: rt.ByteSlice = rt.byteSliceRange(rt.byteSliceFrom(Uint8Array.of(115, 116, 97, 116, 105, 99)), 0); + const _19: rt.ByteSlice = rt.bytesNew(); + const _20: rt.ByteSlice = Owner.asRef$AsRef_u8s({ data: rt.byteSliceToByteVec(rest), skip: skip as rt.usize }); + const source: rt.ByteVec = rt.byteSliceToByteVec(rest); + const copied: rt.ByteSlice = rt.bytesCopyFromSlice(rt.byteVecSlice(source)); + rt.byteVecClear(source); + rt.byteVecPush(source, 0); + const made_: rt.ByteSlice[] = [_8, _10, _13, _15, _16, _19, _20]; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(copied, f)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0]]))); + const iter: rt.Iter = rt.iterSlice(made_); + while (true) { + const _47: rt.ByteSlice | rt.Done = iter.next(); + if (_47 === rt.DONE) { + break; + } + const bytes: rt.ByteSlice = _47; + const _59: rt.usize = bytes.length; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.bytesDebug(bytes, f), (f: rt.Formatter) => rt.usizeDisplay(_59, f)]; + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args4[0], " ", args4[1], "\n"]))); + } + } +} + +/** `tracing`'s events, which evaluate nothing without a subscriber: no field marks `out`. */ +export function events(data: rt.ByteSlice, out: rt.ByteVec): void { + rt.byteVecPush(out, data.length & 0xff); +} + +/** + * `rand::rng()`'s values: each in its range, an empty range panicking as `rand`'s does, + * and every value of a small range drawn. + */ +export function random(data: rt.ByteSlice, out: rt.ByteVec): void { + let inRange!: boolean; + if (data.length >= 3) { + const kind: rt.u8 = data.data[data.start]; + const a: rt.u8 = data.data[data.start + 1]; + const b: rt.u8 = data.data[data.start + 2]; + rt.randRng(); + b1: { + const _10: rt.u8 = rt.u8Rem(kind, 10); + if (_10 === 0) { + const range4 = new rt.Range(a, b); + const x: rt.u8 = rt.randRange(range4.start, range4.end, 8, false) as rt.u8; + if (!(a <= x)) { + inRange = false; + } else { + inRange = x < b; + } + } else if (_10 === 1) { + const x2: rt.u8 = rt.randRangeInclusive(new rt.RangeInclusive(a, b, rt.u8Step), 8, false) as rt.u8; + if (!(a <= x2)) { + inRange = false; + } else { + inRange = x2 <= b; + } + } else if (_10 === 2) { + const _22: [rt.i32, rt.i32] = [rt.i32Mul((a << 24) >> 24 as rt.i32, 1000), rt.i32Mul((b << 24) >> 24 as rt.i32, 1000)]; + const lo: rt.i32 = _22[0]; + const hi: rt.i32 = _22[1]; + const range3 = new rt.Range(lo, hi); + const x3: rt.i32 = rt.randRange(range3.start, range3.end, 32, true) as rt.i32; + if (!(lo <= x3)) { + inRange = false; + } else { + inRange = x3 < hi; + } + } else if (_10 === 3) { + const lo2: rt.u64 = rt.u64Sub({ hi: 0xffffffff, lo: 0xffffffff } as rt.u64, rt.u64Mul(a as rt.u64, 1099511627776)); + inRange = rt.u64Le(lo2, rt.randRangeInclusive(new rt.RangeInclusive(lo2, { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, rt.u64Step), 64, false) as rt.u64); + } else if (_10 === 4) { + const _48: [rt.i128, rt.i128] = [rt.i128Shl((a << 24) >> 24 as rt.i128, 100), rt.i128Shl((b << 24) >> 24 as rt.i128, 100)]; + const lo3: rt.i128 = _48[0]; + const hi2: rt.i128 = _48[1]; + const range2 = new rt.Range(lo3, hi2, rt.i128Step); + const x5: rt.i128 = rt.randRange(range2.start, range2.end, 128, true) as rt.i128; + if (!rt.i128Le(lo3, x5)) { + inRange = false; + } else { + inRange = rt.i128Lt(x5, hi2); + } + } else if (_10 === 5) { + const lo4: rt.u64 = rt.u64Add({ hi: 0x10000000, lo: 0 } as rt.u64, a as rt.u64); + const seen: boolean[] = Array.from({ length: 4 }, (): boolean => { + return false; + }); + let iterStart: rt.i32 = 0; + const iterEnd: rt.i32 = 256; + while (iterStart++ < iterEnd) { + const range = new rt.Range(lo4, rt.u64Add(lo4, 4), rt.u64Step); + const _76: rt.usize = rt.u64Low(rt.u64Sub(rt.randRange(range.start, range.end, 64, false) as rt.u64, lo4)); + if (!(_76 < 4)) { + rt.panic("index out of bounds: the len is " + 4 + " but the index is " + _76); + } + seen[_76] = true; + } + inRange = rt.iterAll(rt.iterSlice(seen), (_2: boolean): boolean => { + return _2; + }); + } else if (_10 === 6) { + const _91: [rt.i64, rt.i64] = [rt.i64Add({ hi: -0x80000000, lo: 0 } as rt.i64, a as rt.i64), rt.i64Sub({ hi: 0x7fffffff, lo: 0xffffffff } as rt.i64, b as rt.i64)]; + const lo5: rt.i64 = _91[0]; + const hi3: rt.i64 = _91[1]; + const x6: rt.i64 = rt.randRangeInclusive(new rt.RangeInclusive(lo5, hi3, rt.i64Step), 64, true) as rt.i64; + if (!rt.i64Le(lo5, x6)) { + inRange = false; + } else { + inRange = rt.i64Le(x6, hi3); + } + } else if (_10 === 7) { + inRange = ((rt.randRange(0, { end: b }.end, 8, false) as rt.u8)) < b; + } else if (_10 === 8) { + const hi4: rt.u64 = rt.u64Sub({ hi: 0xffffffff, lo: 0xffffffff } as rt.u64, a as rt.u64); + if (!(((rt.randRangeToInclusive({ end: b, inclusive: true }.end, 8) as rt.u8)) <= b)) { + inRange = false; + } else { + inRange = rt.u64Le(rt.randRangeToInclusive({ end: hi4, inclusive: true }.end, 64) as rt.u64, hi4); + } + } else { + const _117: [rt.u64, rt.i16] = [rt.randInt(64, false) as rt.u64, rt.randInt(16, true) as rt.i16]; + const x7: rt.u64 = _117[0]; + const y: rt.i16 = _117[1]; + rt.randRng(); + const flag: boolean = rt.randBool(); + if (rt.u64Eq(x7, x7)) { + if (y === y) { + if (!flag) { + inRange = !flag; + break b1; + } + inRange = true; + break b1; + } + } + inRange = false; + } + } + rt.byteVecPush(out, inRange ? 1 : 0); + } +} + +//# sourceMappingURL=harness.ts.map diff --git a/ts/fixtures/stock/src/harness.rs b/ts/fixtures/stock/src/harness.rs new file mode 100644 index 000000000..9f5957914 --- /dev/null +++ b/ts/fixtures/stock/src/harness.rs @@ -0,0 +1,182 @@ +//! The entry point both sides of the differential test run. The first byte picks a +//! case and the rest is its input. + +use bytes::Bytes; +use rand::RngExt; + +/// What a case runs on the rest of the input. +type Case = fn(&[u8], &mut Vec); + +/// Each case, which the first byte picks modulo their count, so a case added at the end +/// moves no other. +fn cases() -> Vec { + vec![slices, made, events, random] +} + +/// Run one case. +pub fn run(input: &[u8]) -> Vec { + let mut out = Vec::new(); + let Some((&op, data)) = input.split_first() else { + return out; + }; + let cases = cases(); + cases[usize::from(op) % cases.len()](data, &mut out); + out +} + +/// `Bytes`'s slices by every kind of range, out of bounds included, which panic as +/// `bytes` does, and what they compare equal to. +fn slices(data: &[u8], out: &mut Vec) { + let [kind, a, b, rest @ ..] = data else { + return; + }; + let bytes = Bytes::copy_from_slice(rest); + // One past `usize::MAX`, which an inclusive range can't end at. + let past = *b == 0xff; + let (a, b) = (*a as usize % (rest.len() + 2), *b as usize % (rest.len() + 2)); + if kind & 0x80 != 0 { + // Unused, but still checked: past the end, it panics. + let _ = bytes.slice(b..); + } + let part = match kind % 7 { + 0 => bytes.slice(a..b), + 1 => bytes.slice(a..), + 2 => bytes.slice(..b), + 3 => bytes.slice(..), + 4 if past => bytes.slice(a..=usize::MAX), + 4 => bytes.slice(a..=b), + 5 if past => bytes.slice(..=usize::MAX), + 5 => bytes.slice(..=b), + _ => { + // Drained: `start` moves past `end`, or at `usize::MAX` the range is exhausted. + let mut range = if past { usize::MAX..=usize::MAX } else { a..=b }; + while range.next().is_some() {} + bytes.slice(range) + } + }; + out.push(part.len() as u8); + out.push(part.is_empty() as u8); + out.extend_from_slice(&part); + out.push((part == bytes) as u8); + out.push((part.clone() == part[..]) as u8); + out.push((bytes.slice(a.min(rest.len())..).slice(..0) == Bytes::new()) as u8); + let vec: Vec = part.into(); + out.extend_from_slice(&vec); +} + +/// An owner `Bytes::from_owner` reads once, and drops nothing JS sees. +struct Owner { + data: Vec, + skip: usize, +} + +impl AsRef<[u8]> for Owner { + fn as_ref(&self) -> &[u8] { + &self.data[self.skip.min(self.data.len())..] + } +} + +/// `Bytes` made each way, printed with `Debug`. +fn made(data: &[u8], out: &mut Vec) { + let Some((&skip, rest)) = data.split_first() else { + return; + }; + let made = [ + Bytes::from(rest.to_vec()), + Bytes::from_static(b"\0\t\r\n\\\"'~\x7f\x80\xff"), + Bytes::from(String::from("string")), + Bytes::from("text"), + Bytes::from(&b"static"[..]), + Bytes::default(), + Bytes::from_owner(Owner { + data: rest.to_vec(), + skip: skip as usize, + }), + ]; + let mut source = rest.to_vec(); + let copied = Bytes::copy_from_slice(&source); + // Written in place, where a `Bytes` that shared it would see the write. + source.clear(); + source.push(0); + out.extend_from_slice(format!("{copied:?}").as_bytes()); + for bytes in made { + out.extend_from_slice(format!("{bytes:?} {}\n", bytes.len()).as_bytes()); + } +} + +/// `tracing`'s events, which evaluate nothing without a subscriber: no field marks `out`. +fn events(data: &[u8], out: &mut Vec) { + tracing::trace!(n = mark(out, 1), "trace"); + tracing::debug!(?data, n = mark(out, 2)); + tracing::info!(n = %mark(out, 3), "info {}", data.len()); + tracing::warn!(target: "stock", "warn {}", mark(out, 4)); + tracing::error!(n = mark(out, 5)); + tracing::event!(tracing::Level::INFO, n = mark(out, 6), "event"); + out.push(data.len() as u8); +} + +/// Push `n`, and return it. +fn mark(out: &mut Vec, n: u8) -> u8 { + out.push(n); + n +} + +/// `rand::rng()`'s values: each in its range, an empty range panicking as `rand`'s does, +/// and every value of a small range drawn. +fn random(data: &[u8], out: &mut Vec) { + let [kind, a, b, ..] = *data else { + return; + }; + let mut rng = rand::rng(); + let in_range = match kind % 10 { + 0 => { + let x = rng.random_range(a..b); + a <= x && x < b + } + 1 => { + let x = rng.random_range(a..=b); + a <= x && x <= b + } + 2 => { + let (lo, hi) = (i32::from(a as i8) * 1000, i32::from(b as i8) * 1000); + let x = rng.random_range(lo..hi); + lo <= x && x < hi + } + 3 => { + let lo = u64::MAX - u64::from(a) * (1 << 40); + let x = rng.random_range(lo..=u64::MAX); + lo <= x + } + 4 => { + let (lo, hi) = (i128::from(a as i8) << 100, i128::from(b as i8) << 100); + let x = rng.random_range(lo..hi); + lo <= x && x < hi + } + 5 => { + // Each of the four values, past 2^53, within 256 draws. + let lo = (1u64 << 60) + u64::from(a); + let mut seen = [false; 4]; + for _ in 0..256 { + seen[(rng.random_range(lo..lo + 4) - lo) as usize] = true; + } + seen.iter().all(|&s| s) + } + 6 => { + let (lo, hi) = (i64::MIN + i64::from(a), i64::MAX - i64::from(b)); + let x = rng.random_range(lo..=hi); + lo <= x && x <= hi + } + 7 => rng.random_range(..b) < b, + 8 => { + // Up to each type's maximum, as `b` of 255 is. + let hi = u64::MAX - u64::from(a); + rng.random_range(..=b) <= b && rng.random_range(..=hi) <= hi + } + _ => { + let (x, y): (u64, i16) = (rng.random(), rng.random()); + let flag: bool = rand::rng().random(); + x == x && y == y && (flag || !flag) + } + }; + out.push(in_range as u8); +} diff --git a/ts/fixtures/stock/src/lib.rs b/ts/fixtures/stock/src/lib.rs new file mode 100644 index 000000000..906dd577c --- /dev/null +++ b/ts/fixtures/stock/src/lib.rs @@ -0,0 +1,34 @@ +//! Calls into `bytes`, `rand`, and `tracing`, which translation maps itself, so this +//! config binds and leaves out nothing. +//! +//! `harness::run` is the entry point both sides of the differential test run. + +pub mod harness; +#[cfg(target_arch = "wasm32")] +#[path = "../../wasm.rs"] +mod wasm; +#[cfg(target_arch = "wasm32")] +use harness::run as entry; + +/// The native side's source for `rand::rng()` on wasm32, which has no OS to seed from: +/// xorshift64*, so a failure reproduces. The translated side reads `crypto` instead. +/// +/// # Safety +/// +/// `dest` is valid for writes of `len` bytes, as getrandom's custom backend promises. +#[cfg(target_arch = "wasm32")] +#[unsafe(no_mangle)] +unsafe extern "Rust" fn __getrandom_v03_custom(dest: *mut u8, len: usize) -> Result<(), getrandom::Error> { + use std::sync::atomic::{AtomicU64, Ordering}; + static STATE: AtomicU64 = AtomicU64::new(0x9e37_79b9_7f4a_7c15); + for i in 0..len { + let mut x = STATE.load(Ordering::Relaxed); + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + STATE.store(x, Ordering::Relaxed); + // SAFETY: `i < len`, within what the caller gave. + unsafe { dest.add(i).write((x.wrapping_mul(0x2545_f491_4f6c_dd1d) >> 56) as u8) }; + } + Ok(()) +} diff --git a/ts/fixtures/stock/ts.toml b/ts/fixtures/stock/ts.toml new file mode 100644 index 000000000..dfa8bacfd --- /dev/null +++ b/ts/fixtures/stock/ts.toml @@ -0,0 +1,2 @@ +package = "stock-fixture" +roots = ["harness::run"] diff --git a/ts/moq/model.toml b/ts/moq/model.toml index 042528810..88d1e7631 100644 --- a/ts/moq/model.toml +++ b/ts/moq/model.toml @@ -18,15 +18,11 @@ roots = [ "model::broadcast::listing::Tracks", "model::time::Timestamp", ] -ignore-macros = ["tracing::trace", "tracing::debug", "tracing::info", "tracing::warn", "tracing::error"] [bind] -# `unsafe` inside. -"bytes::Bytes" = "bind/bytes.ts" +# `unsafe` inside, which translation doesn't map yet. "bytes::BytesMut" = "bind/bytes-mut.ts" -# Randomness, DEFLATE, and the clock, which JS has its own of. -"rand::rng" = "bind/rand.ts" -"rand::rngs::ThreadRng" = "bind/rand.ts" +# DEFLATE and the clock, which JS has its own of. "model::flate::Encoder" = "bind/encoder.ts" "model::flate::Decoder" = "bind/decoder.ts" "model::clock::now" = "bind/clock.ts" diff --git a/ts/moq/net.toml b/ts/moq/net.toml index e81cece7d..dddc64644 100644 --- a/ts/moq/net.toml +++ b/ts/moq/net.toml @@ -1,4 +1,3 @@ # moq-net whole, for the census: it names no roots, so every item is one. package = "moq-net" roots = [] -ignore-macros = ["tracing::trace", "tracing::debug", "tracing::info", "tracing::warn", "tracing::error"] diff --git a/ts/moq/ts.toml b/ts/moq/ts.toml index 5c1bf9d52..2129eaa29 100644 --- a/ts/moq/ts.toml +++ b/ts/moq/ts.toml @@ -10,4 +10,3 @@ roots = [ ] # The errors the roots return, which moq's callers print. printable = ["coding::DecodeError", "coding::EncodeError", "coding::BoundsExceeded"] -ignore-macros = ["tracing::trace", "tracing::debug", "tracing::info", "tracing::warn", "tracing::error"] diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 0efdec340..b49ad2727 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -10,10 +10,12 @@ import { type char, type TryFromIntError, type u32, type usize, u8Debug, usizeDe import type { Pending } from "./rt/task.ts"; import { AtIndex } from "./rt/collections.ts"; +export * from "./rt/bytes.ts"; export * from "./rt/collections.ts"; export * from "./rt/float.ts"; export * from "./rt/int.ts"; export * from "./rt/iter.ts"; +export * from "./rt/rand.ts"; export * from "./rt/str.ts"; export * from "./rt/task.ts"; export * from "./rt/time.ts"; diff --git a/ts/runtime/rt/bytes.ts b/ts/runtime/rt/bytes.ts new file mode 100644 index 000000000..b95b7e8a1 --- /dev/null +++ b/ts/runtime/rt/bytes.ts @@ -0,0 +1,63 @@ +// `bytes::Bytes`, for rust2-ts output: immutable bytes that its clones and slices share, +// as a `&[u8]` shares them, so a `Bytes` is an `rt.ByteSlice`. `rt.ts` re-exports all of it. + +import { ByteSlice, type FmtResult, type Formatter, fmtWriteStr, panic, type RangeInclusive } from "../rt.ts"; +import type { usize } from "./int.ts"; + +/** `bytes::Bytes`. */ +export type Bytes = ByteSlice; + +/** `Bytes::new`. Its bytes are made each time, as a bundler keeps a constant object. */ +export function bytesNew(): Bytes { + return new ByteSlice(new Uint8Array(0), 0, 0); +} + +/** `Bytes::copy_from_slice`: a copy, which later writes to `data` don't change. */ +export function bytesCopyFromSlice(data: ByteSlice): Bytes { + return new ByteSlice(data.data.slice(data.start, data.start + data.length), 0, data.length); +} + +/** `Bytes::slice` of `begin..end`, `end` defaulting to the length, panicking as `bytes` does. */ +export function bytesSlice(b: Bytes, begin: usize, end: usize = b.length as usize): Bytes { + if (begin > end) panic(`range start must not be greater than end: ${begin} <= ${end}`); + if (end > b.length) panic(`range end out of bounds: ${end} <= ${b.length}`); + return new ByteSlice(b.data, b.start + begin, end - begin); +} + +/** `Bytes::slice` of `a..=b`; one exhausted by overflowing is empty, ending before its start. */ +export function bytesSliceInclusive(b: Bytes, range: RangeInclusive): Bytes { + if (range.exhausted) return bytesSlice(b, range.lo, range.lo); + if (range.hi === 0xffffffff) panic("out of range"); + return bytesSlice(b, range.lo, (range.hi + 1) as usize); +} + +/** `Bytes::slice` of `..=end`, which can't end past `usize::MAX`. */ +export function bytesSliceToInclusive(b: Bytes, end: usize): Bytes { + if (end === 0xffffffff) panic("out of range"); + return bytesSlice(b, 0 as usize, (end + 1) as usize); +} + +/** `Debug`: a byte string literal, `b"\x00ab"`, written a piece at a time as `bytes` does. */ +export function bytesDebug(b: Bytes, f: Formatter): FmtResult { + let r = fmtWriteStr(f, 'b"'); + for (let i = 0; i < b.length && r.ok; i++) r = fmtWriteStr(f, escape(b.data[b.start + i])); + return r.ok ? fmtWriteStr(f, '"') : r; +} + +function escape(byte: number): string { + switch (byte) { + case 0x0a: + return "\\n"; + case 0x0d: + return "\\r"; + case 0x09: + return "\\t"; + case 0x5c: + case 0x22: + return `\\${String.fromCharCode(byte)}`; + case 0: + return "\\0"; + } + if (byte >= 0x20 && byte < 0x7f) return String.fromCharCode(byte); + return `\\x${byte.toString(16).padStart(2, "0")}`; +} diff --git a/ts/runtime/rt/int.ts b/ts/runtime/rt/int.ts index 87e504909..91ae16a69 100644 --- a/ts/runtime/rt/int.ts +++ b/ts/runtime/rt/int.ts @@ -1304,6 +1304,16 @@ function of(value: number | bigint, bits: number, signed: boolean): Wide { return one(box(value, bits, signed)); } +/** An integer of `bits` from a bigint in its range: a number up to 32 bits, else as `of` makes it. */ +export function intFromBig(value: bigint, bits: number, signed: boolean): number | Limbs { + return bits <= 32 ? Number(value) : of(value, bits, signed); +} + +/** Any integer's exact value. */ +export function intToBig(value: number | Limbs): bigint { + return typeof value === "number" ? BigInt(value) : exact(value); +} + /** `value as T`, from any integer: its low bits, read in the type's sign. */ function cast(value: number | Limbs, bits: number, signed: boolean): Wide { if (typeof value === "number") return fits(value, signed) ? value : one(limbs(value, bits, signed)); diff --git a/ts/runtime/rt/rand.ts b/ts/runtime/rt/rand.ts new file mode 100644 index 000000000..005b64083 --- /dev/null +++ b/ts/runtime/rt/rand.ts @@ -0,0 +1,62 @@ +// `rand`'s thread-local generator, for rust2-ts output: each value comes from the +// platform's cryptographic source, `crypto.getRandomValues`, as `rand::rng()` seeds from +// the OS's. The values are uniform as `rand`'s are, but not its stream: no seed reproduces +// them on either side. `rt.ts` re-exports all of it. + +import { panic, type RangeInclusive } from "../rt.ts"; +import { intFromBig, intToBig, type Limbs } from "./int.ts"; + +/** `rand::rngs::ThreadRng`: a handle to the platform's source, which holds no state. */ +export class ThreadRng {} + +/** `rand::rng()`. A handle is made each time, as a bundler keeps a constant object. */ +export function randRng(): ThreadRng { + return new ThreadRng(); +} + +/** `bits` uniform random bits, as a nonnegative bigint. */ +function randomBits(bits: number): bigint { + const words = crypto.getRandomValues(new Uint32Array(Math.ceil(bits / 32))); + let v = 0n; + for (const word of words) v = (v << 32n) | BigInt(word); + return v & ((1n << BigInt(bits)) - 1n); +} + +/** A uniform value below `span`, which is positive: the fewest bits that hold it, redrawn past it. */ +function below(span: bigint): bigint { + const bits = (span - 1n).toString(2).length; + for (;;) { + const v = randomBits(bits); + if (v < span) return v; + } +} + +/** `random::()` of an integer type of `bits`, signed or not: each value equally likely. */ +export function randInt(bits: number, signed: boolean): number | Limbs { + const v = randomBits(bits); + return intFromBig(signed && v >> BigInt(bits - 1) ? v - (1n << BigInt(bits)) : v, bits, signed); +} + +/** `random::()`. */ +export function randBool(): boolean { + return randomBits(1) === 1n; +} + +/** `random_range(lo..hi)` of an integer type of `bits`, panicking on an empty range as `rand` does. */ +export function randRange(lo: number | Limbs, hi: number | Limbs, bits: number, signed: boolean): number | Limbs { + const [l, h] = [intToBig(lo), intToBig(hi)]; + if (l >= h) panic("cannot sample empty range"); + return intFromBig(l + below(h - l), bits, signed); +} + +/** `random_range(lo..=hi)`, from its bounds alone, as `rand` reads even an exhausted range. */ +export function randRangeInclusive(range: RangeInclusive, bits: number, signed: boolean): number | Limbs { + const [l, h] = [intToBig(range.lo), intToBig(range.hi)]; + if (l > h) panic("cannot sample empty range"); + return intFromBig(l + below(h - l + 1n), bits, signed); +} + +/** `random_range(..=hi)` of an unsigned integer type of `bits`, which is never empty. */ +export function randRangeToInclusive(hi: number | Limbs, bits: number): number | Limbs { + return intFromBig(below(intToBig(hi) + 1n), bits, false); +} diff --git a/ts/runtime/tsconfig.json b/ts/runtime/tsconfig.json index bb7621503..94478cae0 100644 --- a/ts/runtime/tsconfig.json +++ b/ts/runtime/tsconfig.json @@ -12,5 +12,5 @@ "verbatimModuleSyntax": true, "erasableSyntaxOnly": true }, - "files": ["rt.ts", "rt/collections.ts", "rt/int.ts", "rt/iter.ts", "rt/str.ts", "rt/task.ts", "rt/time.ts"] + "files": ["rt.ts", "rt/bytes.ts", "rt/collections.ts", "rt/int.ts", "rt/iter.ts", "rt/rand.ts", "rt/str.ts", "rt/task.ts", "rt/time.ts"] } diff --git a/ts/src/census.rs b/ts/src/census.rs index 330384cfb..cf774b566 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -141,6 +141,7 @@ const VERBATIM: &[&str] = &[ ".await", "?", "Binary", + "Bytes::from_owner", "Copy", "Debug", "DebugList::entries", diff --git a/ts/src/config.rs b/ts/src/config.rs index 5330c9bab..7301019c1 100644 --- a/ts/src/config.rs +++ b/ts/src/config.rs @@ -18,10 +18,6 @@ pub struct Config { /// so callers can print them as Rust does. #[serde(default)] pub printable: Vec, - /// Macros, by path, whose invocations are left out, such as logging. Each must - /// evaluate to `()`. - #[serde(default)] - pub ignore_macros: Vec, /// Hand-written TypeScript that stands in for a Rust item, by the item's path: from /// the crate root, or else from a crate it depends on. #[serde(default)] diff --git a/ts/src/lower/bind.rs b/ts/src/lower/bind.rs index 8ea5e9f36..50f472458 100644 --- a/ts/src/lower/bind.rs +++ b/ts/src/lower/bind.rs @@ -84,7 +84,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } DefKind::Struct | DefKind::Enum | DefKind::Union => { if super::library::Std::of(tcx, def_id).is_some() { - fail(self, "std's type has a representation of its own".into()); + fail(self, "the type has a representation of its own".into()); continue; } Kind::Type { drop: bind.drop } diff --git a/ts/src/lower/fmt.rs b/ts/src/lower/fmt.rs index d7b5446e3..40bef7247 100644 --- a/ts/src/lower/fmt.rs +++ b/ts/src/lower/fmt.rs @@ -296,6 +296,7 @@ pub fn std_impl<'tcx>( (Std::Utf8Error, Trait::Debug) => rt("utf8ErrorDebug", vec![value, f]), (Std::Utf8Error, Trait::Display) => rt("utf8ErrorDisplay", vec![value, f]), (Std::Duration, Trait::Debug) => Expr::rt("durationDebug", vec![value, f]), + (Std::Bytes, Trait::Debug) => Expr::rt("bytesDebug", vec![value, f]), _ => return None, }, _ => return None, diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index d351244d4..35c5b61fb 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -16,7 +16,8 @@ use super::fmt; use super::num::{self, Int, Operand}; use crate::ts::{Expr, Stmt}; -/// A standard library type with its own representation. +/// A type with a representation of its own: std's, or a well-known crate's that +/// [`super::stock`] maps. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Std { /// `T | undefined`. @@ -118,12 +119,16 @@ pub enum Std { Hasher, /// `rt.Duration`: its seconds and nanoseconds, never changed once made. Duration, + /// `bytes::Bytes`: an `rt.ByteSlice`, as `&[u8]` is. + Bytes, + /// `rand::rngs::ThreadRng`: `rt.ThreadRng`, which holds no state. + ThreadRng, } impl Std { pub fn of(tcx: TyCtxt<'_>, did: DefId) -> Option { if !is_std(tcx, did) { - return None; + return super::stock::of(tcx, did); } use rustc_span::sym; if tcx.is_diagnostic_item(sym::Option, did) { @@ -772,6 +777,10 @@ pub fn key(tcx: TyCtxt<'_>, def_id: DefId) -> Option<(String, String)> { pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec, out: &mut Vec) -> Option { let tcx = b.t.tcx; + let args = match super::stock::call(b, call, args, out) { + Ok(e) => return e, + Err(args) => args, + }; if !is_std(tcx, call.def_id) { return None; } diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 317ba8abb..5b2a325fd 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -417,7 +417,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { out: &mut Vec, ) -> Option> { let tcx = self.tcx; - if library::std_path(tcx, def_id).is_empty() { + let bytes = library::inherent_std(tcx, def_id) == Some(Std::Bytes); + if library::std_path(tcx, def_id).is_empty() && !bytes { return None; } // A box's own `Drop` frees its memory, once drop elaboration dropped or moved out @@ -570,6 +571,26 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { self.slots[local] = Slot::Alias(Some(place)); Some(None) } + // A `Bytes`'s slice by a range's bounds, read where the range is made. Its bounds + // check panics, so it runs even if the slice goes unused. + ("Bytes", "slice") + if bytes && let Some((start, end)) = self.range_bounds(&args[1].node, targ(0)?, span, out) => + { + let b = self.operand(&args[0].node, span, out); + done( + Expr::rt("bytesSlice", std::iter::once(b).chain([start]).chain(end).collect()), + true, + ) + } + ("Bytes", "slice") + if bytes + && let ty::Adt(adt, _) = targ(0)?.kind() + && Std::of(tcx, adt.did()) == Some(Std::RangeToInclusive) => + { + let end = self.range_fields(&args[1].node, *adt, span, out).pop()?; + let b = self.operand(&args[0].node, span, out); + done(Expr::rt("bytesSliceToInclusive", vec![b, end]), true) + } // Of bytes only: JS's `copyWithin` would share a `Copy` aggregate Rust copies. ("slice", "copy_within") if targ(0).is_some_and(|t| matches!(t.kind(), ty::Uint(ty::UintTy::U8))) => { let s = self.operand(&args[0].node, span, out); @@ -1088,19 +1109,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { "Range" | "RangeTo" | "RangeFrom" => {} _ => return None, } - let fields: Vec = match self.take_parts(op) { - Some(parts) => parts, - None => { - let range = self.operand(op, span, out); - let range = self.path(range, "range", out); - adt.non_enum_variant() - .fields - .iter() - .map(|f| range.clone().member(f.name.as_str())) - .collect() - } - }; - let mut fields = fields.into_iter(); + let mut fields = self.range_fields(op, *adt, span, out).into_iter(); match name.as_str() { "Range" => Some((fields.next()?, Some(fields.next()?))), "RangeTo" => Some((Expr::lit("0"), fields.next())), @@ -1108,6 +1117,26 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// A std range's fields, in declaration order, read where the range is made if it is. + fn range_fields( + &mut self, + op: &Operand<'tcx>, + adt: ty::AdtDef<'tcx>, + span: Span, + out: &mut Vec, + ) -> Vec { + if let Some(parts) = self.take_parts(op) { + return parts; + } + let range = self.operand(op, span, out); + let range = self.path(range, "range", out); + adt.non_enum_variant() + .fields + .iter() + .map(|f| range.clone().member(f.name.as_str())) + .collect() + } + /// What a `DebugList` iterates, as an iterable JS value, which drops nothing it reads. fn items(&mut self, value: Expr, ty: Ty<'tcx>, span: Span) -> Option { let tcx = self.tcx; diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 98c011eb1..0558378b6 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -414,8 +414,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { { self.unreachable.insert(bb); } + // A left-out macro's code reads nothing, so a parameter only it reads is unused. for (i, stmt) in data.statements.iter().enumerate() { - if self.noops.contains(&(bb, i)) { + if self.noops.contains(&(bb, i)) || self.in_ignored(stmt.source_info.span) { continue; } match &stmt.kind { @@ -454,6 +455,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } let term = data.terminator(); + if !data.is_cleanup && self.in_ignored(term.source_info.span) { + continue; + } match &term.kind { TerminatorKind::SwitchInt { discr, .. } => self.operand_use(discr), TerminatorKind::Return => { @@ -638,7 +642,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let mut pure = IndexVec::from_elem_n(true, mir.local_decls.len()); for (bb, data) in mir.basic_blocks.iter_enumerated() { for (i, stmt) in data.statements.iter().enumerate() { - if self.noops.contains(&(bb, i)) { + if self.noops.contains(&(bb, i)) || self.in_ignored(stmt.source_info.span) { continue; } if let StatementKind::Assign(assign) = &stmt.kind diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index ada9e1754..ef2a42cda 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -19,6 +19,7 @@ mod iter; mod library; mod mir; mod num; +mod stock; mod task; mod time; @@ -221,8 +222,8 @@ pub struct Translator<'a, 'tcx> { } /// The crates that translate as one program: the package, and every crate it depends on -/// but std's. What the roots reach of them translates; any function of std's is its -/// mapping, a binding, or refused. +/// but std's and those [`stock`] maps. What the roots reach of them translates; any +/// function of the others is its mapping, a binding, or refused. pub struct Crates(rustc_data_structures::fx::FxHashSet); impl Crates { @@ -231,7 +232,11 @@ impl Crates { tcx.crates(()) .iter() .copied() - .filter(|&krate| !tcx.crate_dep_kind(krate).macros_only() && !of_std(tcx, krate)) + .filter(|&krate| { + !tcx.crate_dep_kind(krate).macros_only() + && !of_std(tcx, krate) + && !stock::is_stock_crate(tcx, krate) + }) .collect(), ) } @@ -1103,7 +1108,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { | library::Std::BTreeSet | library::Std::VecDeque | library::Std::Entry - | library::Std::Hasher, + | library::Std::Hasher + | library::Std::ThreadRng, ) => Some(ObjectKind::Class), Some(_) => None, None if adt.is_struct() => Some(ObjectKind::Class), @@ -1426,6 +1432,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { library::Std::Ordering => Type::Rt("Ordering", vec![]), library::Std::Hasher => Type::Rt("Hasher", vec![]), library::Std::Duration => Type::Rt("Duration", vec![]), + library::Std::Bytes => Type::Rt("ByteSlice", vec![]), + library::Std::ThreadRng => Type::Rt("ThreadRng", vec![]), library::Std::ControlFlow => { if let Some(msg) = self.erasure_conflict(Ty::new_adt(tcx, adt, args)) { self.err(span, msg); @@ -1642,18 +1650,25 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { (!doc.trim().is_empty()).then_some(doc) } - /// Where the invocation of a left-out macro that made `span` is written, if one did. + /// Where the invocation of a left-out macro that made `span` is written, if one did: + /// the outermost of `tracing`'s events, which expand to one another. Translated code + /// installs no subscriber, and without one an event evaluates none of its fields and + /// does nothing, so leaving it out is exact. pub fn ignored_site(&self, mut span: Span) -> Option { + let mut site = None; while span.from_expansion() { let data = span.ctxt().outer_expn_data(); if let Some(def_id) = data.macro_def_id - && self.config.ignore_macros.contains(&self.tcx.def_path_str(def_id)) - { - return Some(data.call_site); + && self.tcx.crate_name(def_id.krate).as_str() == "tracing" + && matches!( + self.tcx.item_name(def_id).as_str(), + "event" | "trace" | "debug" | "info" | "warn" | "error" + ) { + site = Some(data.call_site); } span = data.call_site; } - None + site } } diff --git a/ts/src/lower/stock.rs b/ts/src/lower/stock.rs new file mode 100644 index 000000000..9bce159b3 --- /dev/null +++ b/ts/src/lower/stock.rs @@ -0,0 +1,207 @@ +//! Well-known crates that translation maps itself, as it maps std, so a consumer binds +//! none of them: `bytes::Bytes`, which is the `rt.ByteSlice` a `&[u8]` is, and `rand`'s +//! thread-local generator, which draws from the platform's cryptographic source. +//! `tracing`'s events are left out where they are written, by +//! [`super::Translator::ignored_site`]. + +use rustc_hir::def::DefKind; +use rustc_hir::def_id::{CrateNum, DefId}; +use rustc_middle::ty::{self, Ty, TyCtxt}; + +use super::body::Body; +use super::library::{Call, Std, key, string, targ}; +use super::num::Int; +use crate::ts::{Expr, Stmt}; + +/// The type `did` is, if it is one of these crates' that has a representation of its own. +pub fn of(tcx: TyCtxt<'_>, did: DefId) -> Option { + if !is_stock(tcx, did) { + return None; + } + match (tcx.crate_name(did.krate).as_str(), tcx.opt_item_name(did)?.as_str()) { + ("bytes", "Bytes") => Some(Std::Bytes), + ("rand", "ThreadRng") => Some(Std::ThreadRng), + _ => None, + } +} + +/// Whether `did` is an item of one of these crates, rather than of the crate translated, +/// whatever its name. +pub fn is_stock(tcx: TyCtxt<'_>, did: DefId) -> bool { + !did.is_local() && is_stock_crate(tcx, did.krate) +} + +/// Whether `krate`, a dependency, is one of these crates, which maps rather than translates. +pub fn is_stock_crate(tcx: TyCtxt<'_>, krate: CrateNum) -> bool { + matches!(tcx.crate_name(krate).as_str(), "bytes" | "rand") +} + +/// A call of one of these crates' functions, or of a std trait's on one of their types: +/// its mapping, `None` if it has none, or its arguments back if it is no such call. +pub fn call<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + args: Vec, + out: &mut Vec, +) -> Result, Vec> { + let tcx = b.t.tcx; + let Some((owner, name)) = key(tcx, call.def_id) else { + return Err(args); + }; + let self_std = call.args.types().next().and_then(|t| b.t.std_of(t.peel_refs())); + if is_stock(tcx, call.def_id) { + return Ok(match tcx.crate_name(call.def_id.krate).as_str() { + "bytes" => bytes(b, call, &name, args, out), + _ => rand(b, call, &owner, &name, args, out), + }); + } + match (owner.as_str(), name.as_str(), self_std) { + // A clone of either shares what it holds, and a `Bytes` is the slice it derefs to. + ("Clone", "clone", Some(Std::Bytes | Std::ThreadRng)) + | ("Deref", "deref", Some(Std::Bytes)) + | ("AsRef", "as_ref", Some(Std::Bytes)) + | ("Borrow", "borrow", Some(Std::Bytes)) => Ok(args.into_iter().next()), + ("Default", "default", Some(Std::Bytes)) => Ok(Some(Expr::rt("bytesNew", vec![]))), + ("Default", "default", Some(Std::ThreadRng)) => Ok(Some(Expr::rt("randRng", vec![]))), + ("PartialEq", "eq", Some(Std::Bytes)) => { + let other = targ(call.args, 1).peel_refs(); + let bytes = b.t.std_of(other) == Some(Std::Bytes) + || matches!(other.kind(), ty::Slice(e) if matches!(e.kind(), ty::Uint(ty::UintTy::U8))); + Ok(bytes.then(|| Expr::rt("byteSliceEq", args))) + } + ("From", "from", _) => from(b, call, args), + _ => Err(args), + } +} + +/// `From::from` into or out of a `Bytes`. +fn from<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec) -> Result, Vec> { + let tcx = b.t.tcx; + let (to, from) = (targ(call.args, 0), targ(call.args, 1)); + let byte_vec = |t: Ty<'tcx>| b.t.std_of(t) == Some(Std::Vec) && targ_is_u8(t); + let f = match (b.t.std_of(to), b.t.std_of(from)) { + (Some(Std::Bytes), _) if byte_vec(from) => "byteVecSlice", + (Some(Std::Bytes), _) if string(tcx, from.peel_refs()) => "stringAsBytes", + (Some(Std::Bytes), _) if is_bytes_ref(from) => return Ok(args.into_iter().next()), + (Some(Std::Bytes), _) => return Ok(None), + (_, Some(Std::Bytes)) if byte_vec(to) => "byteSliceToByteVec", + (_, Some(Std::Bytes)) => return Ok(None), + _ => return Err(args), + }; + Ok(Some(Expr::rt(f, args))) +} + +/// A function of `bytes`: `Bytes`'s own. +fn bytes<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + name: &str, + args: Vec, + out: &mut Vec, +) -> Option { + let tcx = b.t.tcx; + if super::library::inherent_std(tcx, call.def_id) != Some(Std::Bytes) { + return None; + } + let mut args = args.into_iter(); + Some(match name { + "new" => Expr::rt("bytesNew", vec![]), + // A `&'static [u8]` never changes, so the slice is the `Bytes`. + "from_static" => args.next()?, + "copy_from_slice" => Expr::rt("bytesCopyFromSlice", vec![args.next()?]), + "len" => args.next()?.member("length"), + "is_empty" => args.next()?.member("length").binary("===", Expr::lit("0")), + // The other ranges' bounds are read where the range is made, by the body's lowering. + "slice" if b.t.std_of(targ(call.args, 0)) == Some(Std::RangeInclusive) => { + Expr::rt("bytesSliceInclusive", vec![args.next()?, args.next()?]) + } + // The owner is read once, as `bytes` reads it, and would drop with the last `Bytes` + // that shares it, which no value here tracks. + "from_owner" => { + let owner = targ(call.args, 0); + if b.t.drops(owner) { + let msg = format!( + "`Bytes::from_owner` of `{owner}`, which would drop with the last clone of what it makes, which is not supported" + ); + return Some(b.err(call.span, msg)); + } + let as_ref = trait_fn(tcx, rustc_span::sym::AsRef)?; + let slice = Ty::new_slice(tcx, tcx.types.u8); + b.call_def( + as_ref, + tcx.mk_args(&[owner.into(), slice.into()]), + vec![args.next()?], + call.span, + out, + ) + } + _ => return None, + }) +} + +/// A function of `rand`: `rng`, or a method of its `Rng` or `RngExt` on a `ThreadRng`. +fn rand<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + owner: &str, + name: &str, + args: Vec, + out: &mut Vec, +) -> Option { + let tcx = b.t.tcx; + if tcx.def_kind(call.def_id) == DefKind::Fn && matches!(name, "rng" | "thread_rng") { + return Some(Expr::rt("randRng", vec![])); + } + if !matches!(owner, "Rng" | "RngExt") || b.t.std_of(targ(call.args, 0).peel_refs()) != Some(Std::ThreadRng) { + return None; + } + // The generator holds no state, so only the arguments after it are read. + let mut args = args.into_iter().skip(1); + let ty = targ(call.args, 1); + let width = |int: Int| (Expr::lit(int.bits.to_string()), Expr::lit(int.signed.to_string())); + Some(match name { + "random" if ty.is_bool() => Expr::rt("randBool", vec![]), + "random" => { + let int = Int::of(ty)?; + let (bits, signed) = width(int); + Expr::As(Box::new(Expr::rt("randInt", vec![bits, signed])), int.ty()) + } + "random_range" => { + let int = Int::of(ty)?; + let (bits, signed) = width(int); + let range = args.next()?; + let value = match b.t.std_of(targ(call.args, 2))? { + Std::Range => { + let range = b.spill(range, "range", out); + let (start, end) = (range.clone().member("start"), range.member("end")); + Expr::rt("randRange", vec![start, end, bits, signed]) + } + Std::RangeTo => Expr::rt("randRange", vec![int.lit(0), range.member("end"), bits, signed]), + Std::RangeInclusive => Expr::rt("randRangeInclusive", vec![range, bits, signed]), + // `rand` samples `..=b` only of unsigned integers. + Std::RangeToInclusive => Expr::rt("randRangeToInclusive", vec![range.member("end"), bits]), + _ => return None, + }; + Expr::As(Box::new(value), int.ty()) + } + _ => return None, + }) +} + +/// The one function of the trait `item` names, such as `AsRef::as_ref`. +fn trait_fn(tcx: TyCtxt<'_>, item: rustc_span::Symbol) -> Option { + let tr = tcx.get_diagnostic_item(item)?; + tcx.associated_items(tr) + .in_definition_order() + .find(|i| i.is_fn()) + .map(|i| i.def_id) +} + +fn targ_is_u8(ty: Ty<'_>) -> bool { + matches!(ty.kind(), ty::Adt(_, args) if args.types().next().is_some_and(|t| matches!(t.kind(), ty::Uint(ty::UintTy::U8)))) +} + +/// Whether `ty` is `&[u8]`. +fn is_bytes_ref(ty: Ty<'_>) -> bool { + matches!(ty.kind(), ty::Ref(_, inner, _) if matches!(inner.kind(), ty::Slice(e) if matches!(e.kind(), ty::Uint(ty::UintTy::U8)))) +} diff --git a/ts/src/program.rs b/ts/src/program.rs index 70b813a67..75f989708 100644 --- a/ts/src/program.rs +++ b/ts/src/program.rs @@ -10,10 +10,12 @@ use crate::ts::{self, FieldId, Function, Item, SymId}; /// file's path from there, and its text. pub const RUNTIME: &[(&str, &str)] = &[ ("rt.ts", include_str!("../runtime/rt.ts")), + ("rt/bytes.ts", include_str!("../runtime/rt/bytes.ts")), ("rt/collections.ts", include_str!("../runtime/rt/collections.ts")), ("rt/float.ts", include_str!("../runtime/rt/float.ts")), ("rt/int.ts", include_str!("../runtime/rt/int.ts")), ("rt/iter.ts", include_str!("../runtime/rt/iter.ts")), + ("rt/rand.ts", include_str!("../runtime/rt/rand.ts")), ("rt/str.ts", include_str!("../runtime/rt/str.ts")), ("rt/task.ts", include_str!("../runtime/rt/task.ts")), ("rt/time.ts", include_str!("../runtime/rt/time.ts")), diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 196ca04ca..fdb6e13e8 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -149,8 +149,9 @@ fn typecheck(out: &Path) { } /// Run the harness natively, as wasm32, and translated, on the same inputs: the -/// translated side through `entry`, a module in `out`. `features` are the package's. -fn differential(package: &str, features: &[&str], out: &Path, entry: &str, cases: u32) { +/// translated side through `entry`, a module in `out`. `build` are the native build's +/// arguments, such as `--features`. +fn differential(package: &str, build: &[&str], out: &Path, entry: &str, cases: u32) { let target_dir = scratch().join("wasm"); let status = cargo() .args([ @@ -163,7 +164,8 @@ fn differential(package: &str, features: &[&str], out: &Path, entry: &str, cases "--target-dir", ]) .arg(&target_dir) - .args(features.iter().flat_map(|f| ["--features", f])) + .args(build) + .env("CARGO_UNSTABLE_PROFILE_RUSTFLAGS", "true") .arg("--manifest-path") .arg(manifest_dir().join("Cargo.toml")) .status() @@ -396,7 +398,7 @@ fn share() { String::from_utf8_lossy(&output.stderr) ); typecheck(&out); - differential("share-fixture", &[feature], &out, "harness.ts", 1_000); + differential("share-fixture", &["--features", feature], &out, "harness.ts", 1_000); } } @@ -492,7 +494,7 @@ fn bind() { let toml = fixture("bind").join(format!("{config}.toml")); let output = driver("bind", &toml, &["--out".as_ref(), out.as_ref()], "build"); assert!( - !out.join("bind/bytes.ts").exists(), + !out.join("bind/blob.ts").exists(), "a failed translation left a binding's file" ); rejected(&out, &output, &fixture("bind").join(format!("{config}.txt"))); @@ -604,3 +606,30 @@ fn census() { diff(&want, &got) ); } + +/// Selects the fixture's own getrandom backend, which `rand::rng()` seeds from natively: +/// wasm32 has no OS to read. Only getrandom's flags change, so nothing else rebuilds. +const GETRANDOM: &str = r#"profile.dev.package.getrandom.rustflags=["--cfg", 'getrandom_backend="custom"']"#; + +/// `bytes`, `rand`, and `tracing`, which translation maps without a binding or config. +#[test] +fn stock() { + let out = scratch().join("stock").join("out"); + let config = fixture("stock").join("ts.toml"); + let args: [&std::ffi::OsStr; 5] = [ + "--out".as_ref(), + out.as_ref(), + "--".as_ref(), + "--config".as_ref(), + GETRANDOM.as_ref(), + ]; + let output = driver("stock", &config, &args, "build"); + assert!( + output.status.success(), + "translating stock failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + snapshot("stock", &out); + typecheck(&out); + differential("stock-fixture", &["--config", GETRANDOM], &out, "harness.ts", 5_000); +}