diff --git a/quest/m2/README.md b/quest/m2/README.md index d8214313b..df3547796 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -34,7 +34,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values - [Copy what a container stores](/quest/m2/ts-store-alias.md) - `push` and other stores of a `Copy` aggregate copy it instead of sharing it -- [str and String methods over char](/quest/m2/ts-str-char.md) - `chars`, `char` patterns, and `String::push` translate, unblocking `ietf/namespace.rs` - [Share a held-back read across a call](/quest/m2/ts-shared-read.md) - `leading-ones` decode recovers what #83's copy fix cost - [Output tsc accepts for writes through Result and Poll compares](/quest/m2/ts-tsc-shapes.md) - two shapes whose output fails `tsc` type-check - [Translate moq-net's model to TypeScript](/quest/m2/ts-model.md) - the driver grows from moq-net's codec to its model, for moq to compare against WASM diff --git a/quest/m2/ts-str-char.md b/quest/m2/ts-str-char.md deleted file mode 100644 index b888a906e..000000000 --- a/quest/m2/ts-str-char.md +++ /dev/null @@ -1,18 +0,0 @@ -# [S] str and String methods over char - -## Goal - -rust2-ts translates `str::chars`, the `str` methods that take a `char` pattern, -`char::is_ascii_digit`, and `String::push` through `&mut String`, so moq-net's -`ietf/namespace.rs` translates, proven by differential tests against native Rust. - -## Plan - -Found by [#86](https://github.com/kixelated/rust2/pull/86)'s census on 2026-10-26, -after `char` values themselves translate. `String::push` through `&mut String` is the -one that blocks `ietf/namespace.rs`. - -- Cover multi-byte and surrogate-boundary characters in the differential tests. -- Report moq-net's census before and after. - -Public API: the translator's output. diff --git a/ts/README.md b/ts/README.md index 0f0149df6..67d8eee9f 100644 --- a/ts/README.md +++ b/ts/README.md @@ -50,8 +50,9 @@ Each Rust module with translated items becomes a file (`lib.ts`, `coding/varint. and each type a module of its own beside it, holding the type and its functions (`coding/decode.Decoder.ts`), each with a `.ts.map` source map into the Rust it came from. `rt.ts` beside them is the -runtime: what std does that JS does not, with iterators in `rt/iter.ts`, collections in -`rt/collections.ts`, and ownership and async in `rt/task.ts`. +runtime: what std does that JS does not, with iterators in `rt/iter.ts`, `str`'s searches +in `rt/str.ts`, collections in `rt/collections.ts`, and ownership and async in +`rt/task.ts`. | Rust | TypeScript | | --- | --- | @@ -123,6 +124,13 @@ range's bounds, with no `rt.Iter` made. The crate's own `impl Iterator` returns std's adaptors through `rt.iterFrom`. A caller calls `next()` for one item, or iterates an `rt.Iter` with `for ... of`. +A `str` is a JS string, which is UTF-16: `chars` steps by code point, and a search by a +`char` or a predicate, as in `rt.strSplit(s, "/")`, takes the char's text or the closure, +which it calls on each char it reads, in the order std reads them. An offset it returns, +from `rfind` or `match_indices`, counts UTF-8 bytes, as Rust's does. A JS string can't +change in place, so `String::push` assigns a longer one to the local or field the `&mut` +borrows. + Functions and members are camelCase. Functions are monomorphized: each instance is its own function, suffixed after a `$` by its trait, then by its type's type arguments and its own, as in `roundtripLite$Group`, `Wrap.get$Wrap_Pair`, `Pair.fmt$Debug`, and @@ -303,7 +311,8 @@ holds that JS copies kept other than to read and write it, `Hasher::write` of by without a mapping in `src/lower/iter.rs` (such as `cycle`, `unzip`, and `partition`), an own `impl Iterator` with `next_back`, `len`, or another provided method of its own, other format specs (a precision, `+`, `{:b}`, `{:x?}`, and widths from arguments), writing to a -`String` with `write!`, a copy of a closure that changes what it captured, `mem::swap`, +`String` with `write!` or pushing to one through a parameter, a `str` pattern other than a +`char` or a predicate, a copy of a closure that changes what it captured, `mem::swap`, `replace`, or `take` of a reference's whole pointee, assigning an `Arc`, a waker, a `MutexGuard`, a pinned reference, or a future through a reference, a switch on or a field of another crate's type without a mapping, and std functions without a mapping in diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 5816022d6..3013a5c5f 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -9,6 +9,7 @@ import { u8Op, u16Op, u32Op, u64Op, u128Op, usizeOp, i8Op, i16Op, i32Op, i64Op, import { adaptors, consumers, ranges, options, own, values } from "./iters.ts"; import { keys } from "./keys.ts"; import { copies, order, discriminants, loops, patterns, closures, library, flows } from "./shapes.ts"; +import { strs } from "./strs.ts"; /** Run one case. */ export function run(input: Uint8Array): rt.ByteVec { @@ -19,7 +20,7 @@ export function run(input: Uint8Array): rt.ByteVec { const _10: [rt.u8, rt.u8] = [input[0], input[1]]; const op: rt.u8 = _10[0]; const kind: rt.u8 = _10[1]; - const _14: rt.u8 = rt.u8Rem(op, 42); + const _14: rt.u8 = rt.u8Rem(op, 43); if (_14 === 0) { u8Op(kind, input.subarray(2, input.length - 0), out); } else if (_14 === 1) { @@ -120,6 +121,8 @@ export function run(input: Uint8Array): rt.ByteVec { keys(kind, input.subarray(2, input.length - 0), out); } else if (_14 === 40) { chars(kind, input.subarray(2, input.length - 0), out); + } else if (_14 === 41) { + strs(kind, input.subarray(2, input.length - 0), out); } else { vecs(input.subarray(2, input.length - 0), out); } diff --git a/ts/fixtures/lang/expected/strs.Named.ts b/ts/fixtures/lang/expected/strs.Named.ts new file mode 100644 index 000000000..6d8315873 --- /dev/null +++ b/ts/fixtures/lang/expected/strs.Named.ts @@ -0,0 +1,13 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +export interface Named { + name: string; +} + +export function add(self: Named, c: rt.char): void { + self.name = self.name + String.fromCodePoint(c); +} + +//# sourceMappingURL=strs.Named.ts.map diff --git a/ts/fixtures/lang/expected/strs.ts b/ts/fixtures/lang/expected/strs.ts new file mode 100644 index 000000000..039300678 --- /dev/null +++ b/ts/fixtures/lang/expected/strs.ts @@ -0,0 +1,353 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { put } from "./fmt.ts"; +import * as Named from "./strs.Named.ts"; + +/** A char of the alphabet for each byte, by its low bits. */ +export function text(data: Uint8Array): string { + let s: string = ""; + const iterS: Uint8Array = data; + let iterI: number = 0; + while (true) { + const _5: rt.u8 | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_5 === rt.DONE) { + return s; + } + const _13: rt.usize = rt.u8Rem(_5, 16) as rt.usize; + if (!(_13 < 16)) { + rt.panic("index out of bounds: the len is " + 16 + " but the index is " + _13); + } + s = s + String.fromCodePoint([47, 92, 97, 48, 57, 127, 128, 233, 2047, 2048, 55295, 57344, 65535, 65536, 128512, 1114111][_13]); + } +} + +/** Whether the `i`th step reads from the back: by the byte's high bit. */ +export function fromBack(data: Uint8Array, i: rt.usize): boolean { + const _3: rt.u8 | undefined = rt.sliceGet(data, i); + if (_3 !== undefined) { + if ((_3 & 128) !== 0) { + return true; + } + } + return false; +} + +export function putChar(out: rt.ByteVec, c: rt.char | undefined): void { + if (c === undefined) { + rt.byteVecPush(out, 255); + } else { + rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(c as rt.u32)); + } +} + +export function putOffset(out: rt.ByteVec, i: rt.usize | undefined): void { + if (i === undefined) { + rt.byteVecPush(out, 254); + } else { + rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(i as rt.u32)); + } +} + +/** What a predicate saw, then where it stopped. */ +export function putSeen(out: rt.ByteVec, seen: rt.char[]): void { + const iterS: rt.char[] = seen; + let iterI: number = 0; + while (true) { + const _5: rt.char | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_5 === rt.DONE) { + break; + } + putChar(out, _5); + } + rt.byteVecPush(out, 253); +} + +export function strs(kind: rt.u8, data: Uint8Array, out: rt.ByteVec): void { + let c!: rt.char | undefined; + let part!: string | undefined; + let part3!: string | undefined; + let item!: [rt.usize, string] | undefined; + let _237!: rt.char; + const s: string = text(data); + const _7: rt.usize = rt.u8Rem(rt.u8Div(kind, 8), 16) as rt.usize; + if (!(_7 < 16)) { + rt.panic("index out of bounds: the len is " + 16 + " but the index is " + _7); + } + const sep: rt.char = [47, 92, 97, 48, 57, 127, 128, 233, 2047, 2048, 55295, 57344, 65535, 65536, 128512, 1114111][_7]; + b0: { + const _13: rt.u8 = rt.u8Rem(kind, 8); + if (_13 === 0) { + const it: rt.Iter = rt.strChars(s); + let i: rt.usize = 0; + while (true) { + if (!fromBack(data, i)) { + c = rt.iterToOption(it.next()); + } else { + c = rt.iterToOption(it.nextBack()); + } + putChar(out, c); + if (!((c === undefined))) { + i = rt.usizeAdd(i, 1); + } else { + rt.byteVecPush(out, rt.iterCount(rt.strChars(s)) & 0xff); + const iter: rt.Iter = rt.iterRev(rt.strChars(s)); + while (true) { + const _41: rt.char | rt.Done = iter.next(); + if (_41 === rt.DONE) { + break; + } + rt.byteVecPush(out, rt.charIsAsciiDigit(_41) ? 1 : 0); + } + rt.byteVecPush(out, s.length === 0 ? 1 : 0); + rt.byteVecPush(out, s.length === 0 ? 1 : 0); + break b0; + } + } + } + if (_13 === 1) { + const parts: rt.Iter = rt.strSplit(s, String.fromCodePoint(sep)); + let i2: rt.usize = 0; + while (true) { + if (!fromBack(data, i2)) { + part = rt.iterToOption(parts.next()); + } else { + part = rt.iterToOption(parts.nextBack()); + } + if (part !== undefined) { + const part2: string = part; + put(out, part2); + rt.byteVecPush(out, rt.stringLen(part2) & 0xff); + i2 = rt.usizeAdd(i2, 1); + } else { + rt.byteVecPush(out, i2 & 0xff); + const _81: rt.Iter = rt.strSplit(s, String.fromCodePoint(sep)); + put(out, rt.optionUnwrapOr(rt.iterToOption(_81.next()), "none")); + break b0; + } + } + } + if (_13 === 2) { + const seen: rt.char[] = []; + const parts2: rt.Iter = rt.strSplit(s, (c9: rt.char): boolean => { + seen.push(c9); + if (!(c9 === sep)) { + return rt.charIsAsciiDigit(c9); + } + return true; + }); + let i3: rt.usize = 0; + while (true) { + if (!fromBack(data, i3)) { + part3 = rt.iterToOption(parts2.next()); + } else { + part3 = rt.iterToOption(parts2.nextBack()); + } + if (part3 !== undefined) { + put(out, part3); + i3 = rt.usizeAdd(i3, 1); + } else { + putSeen(out, seen); + break b0; + } + } + } + if (_13 === 3) { + put(out, rt.strTrimStartMatches(s, String.fromCodePoint(sep))); + put(out, rt.strTrimEndMatches(s, String.fromCodePoint(sep))); + put(out, rt.strTrimEndMatches(rt.strTrimStartMatches(s, String.fromCodePoint(sep)), String.fromCodePoint(sep))); + rt.byteVecPush(out, rt.strStartsWith(s, String.fromCodePoint(sep)) ? 1 : 0); + putOffset(out, rt.strRfind(s, String.fromCodePoint(sep))); + } else if (_13 === 4) { + const seen2: rt.char[] = []; + put(out, rt.strTrimStartMatches(s, (c5: rt.char): boolean => { + seen2.push(c5); + return c5 === sep; + })); + putSeen(out, seen2); + put(out, rt.strTrimEndMatches(s, (c6: rt.char): boolean => { + seen2.push(c6); + return c6 !== sep; + })); + putSeen(out, seen2); + rt.byteVecPush(out, rt.strStartsWith(s, (c7: rt.char): boolean => { + return rt.charIsAsciiDigit(c7); + }) ? 1 : 0); + put(out, rt.strTrimStartMatches(s, digit)); + putOffset(out, rt.strRfind(s, (c8: rt.char): boolean => { + seen2.push(c8); + return c8 === sep; + })); + putSeen(out, seen2); + } else { + if (_13 === 5) { + const found2: rt.Iter<[rt.usize, string]> = rt.strMatchIndices(s, String.fromCodePoint(sep)); + let i4: rt.usize = 0; + while (true) { + if (!fromBack(data, i4)) { + item = rt.iterToOption(found2.next()); + } else { + item = rt.iterToOption(found2.nextBack()); + } + if (item !== undefined) { + const at: rt.usize = item[0]; + const matched: string = item[1]; + putOffset(out, at); + put(out, matched); + i4 = rt.usizeAdd(i4, 1); + } else { + const iterS: rt.usize[] = rt.iterToArray(rt.iterMap(rt.strMatchIndices(s, "/"), (_2: [rt.usize, string]): rt.usize => { + return _2[0]; + })); + let iterI: number = 0; + while (true) { + const _190: rt.usize | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_190 === rt.DONE) { + break; + } + putOffset(out, _190); + } + break b0; + } + } + } + if (_13 === 6) { + const parts3: string[] = unescape(s); + const iterS2: string[] = parts3; + let iterI2: number = 0; + while (true) { + const _202: string | rt.Done = iterI2 < iterS2.length ? iterS2[iterI2++] : rt.DONE; + if (_202 === rt.DONE) { + break; + } + put(out, _202); + } + put(out, escape(parts3)); + } else { + let built: string = ""; + const named: Named.Named = { name: "" }; + const each: string[] = ["", ""]; + const iter4: rt.Iter<[rt.usize, rt.char]> = rt.iterEnumerate(rt.strChars(s)); + while (true) { + const _228: [rt.usize, rt.char] | rt.Done = iter4.next(); + if (_228 === rt.DONE) { + break; + } + const i5: rt.usize = _228[0]; + const c3: rt.char = _228[1]; + built = built + String.fromCodePoint(c3); + if (!(rt.usizeRem(i5, 2) === 0)) { + _237 = sep; + } else { + _237 = c3; + } + named.name = named.name + String.fromCodePoint(_237); + Named.add(named, c3); + const _246: rt.usize = rt.usizeRem(i5, 2); + const at2 = rt.idx(each, _246); + each[at2] = each[at2] + String.fromCodePoint(c3); + const _248: rt.char | undefined = rt.charFromU32(rt.u32Add(c3 as rt.u32, 1)); + if (_248 !== undefined) { + built = built + String.fromCodePoint(_248); + } + } + named.name = named.name + "􏿿"; + put(out, built); + put(out, named.name); + const at3 = rt.idx(each, 0); + put(out, each[at3]); + const at4 = rt.idx(each, 1); + put(out, each[at4]); + const before: string = built; + const len: rt.usize = rt.stringLen(built); + const empty: boolean = built.length === 0; + built = built + String.fromCodePoint(sep); + put(out, before); + rt.byteVecPush(out, len & 0xff); + rt.byteVecPush(out, empty ? 1 : 0); + const taken2 = built; + built = ""; + put(out, taken2); + rt.byteVecPush(out, built.length === 0 ? 1 : 0); + } + } + } +} + +/** A predicate that is a function, not a closure. */ +export function digit(c: rt.char): boolean { + return rt.charIsAsciiDigit(c); +} + +/** `/` separates parts, and `\` escapes a `/` or `\` within one. */ +export function unescape(path: string): string[] { + if (!((path.length === 0))) { + const parts: string[] = []; + let part: string = ""; + const chars: rt.Iter = rt.strChars(path); + while (true) { + const _7: rt.char | rt.Done = chars.next(); + if (_7 !== rt.DONE) { + const ch: rt.char = _7; + if (ch === 47) { + const taken = part; + part = ""; + const _12: string = taken; + parts.push(_12); + } else if (ch === 92) { + const _14: rt.char | rt.Done = chars.next(); + if (_14 === rt.DONE) { + part = part + "\\"; + } else if (_14 === 47 || _14 === 92) { + part = part + String.fromCodePoint(_14); + } else { + const next2: rt.char = _14; + part = part + "\\"; + part = part + String.fromCodePoint(next2); + } + } else { + part = part + String.fromCodePoint(ch); + } + } else { + break; + } + } + parts.push(part); + return parts; + } + return []; +} + +export function escape(parts: string[]): string { + let _23!: boolean; + let path: string = ""; + const iter: rt.Iter<[rt.usize, string]> = rt.iterEnumerate(rt.iterSlice(parts)); + l1: while (true) { + const _7: [rt.usize, string] | rt.Done = iter.next(); + if (_7 === rt.DONE) { + return path; + } + if (_7[0] > 0) { + path = path + "/"; + } + const iter2: rt.Iter = rt.strChars(_7[1]); + while (true) { + const _19: rt.char | rt.Done = iter2.next(); + if (_19 === rt.DONE) { + continue l1; + } + const ch: rt.char = _19; + if (ch === 47 || ch === 92) { + _23 = true; + } else { + _23 = false; + } + if (_23) { + path = path + "\\"; + } + path = path + String.fromCodePoint(ch); + } + } +} + +//# sourceMappingURL=strs.ts.map diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 39c51e2e7..7ad220513 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -1,7 +1,7 @@ //! The entry point both sides of the differential test run. The first byte picks a //! case and the rest is its input. -use crate::{chars, collections, fmt, generics, ints, iters, keys, shapes}; +use crate::{chars, collections, fmt, generics, ints, iters, keys, shapes, strs}; /// The native side's entry: [`run`], except that a case starting with 0xff prints a /// [`fmt::Fault`], which the translated side prints from TypeScript in `caller.ts`. @@ -19,7 +19,7 @@ pub fn run(input: &[u8]) -> Vec { return out; }; let (op, kind) = (*op, *kind); - match op % 42 { + match op % 43 { 0 => ints::u8_op(kind, data, &mut out), 1 => ints::u16_op(kind, data, &mut out), 2 => ints::u32_op(kind, data, &mut out), @@ -71,6 +71,7 @@ pub fn run(input: &[u8]) -> Vec { 38 => shapes::flows(data, &mut out), 39 => keys::keys(kind, data, &mut out), 40 => chars::chars(kind, data, &mut out), + 41 => strs::strs(kind, data, &mut out), _ => collections::vecs(data, &mut out), } out diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index e87d789aa..af8569eda 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -1,7 +1,7 @@ //! The language the driver translates, exercised against native Rust: every integer -//! width's arithmetic and casts, `char`s, control flow, patterns, `Copy` aggregates, -//! closures, traits, generic types, formatting, collections, and the standard library -//! calls it maps. +//! width's arithmetic and casts, `char`s and the `str` methods over them, control flow, +//! patterns, `Copy` aggregates, closures, traits, generic types, formatting, collections, +//! and the standard library calls it maps. //! //! `harness::run` is the entry point both sides of the differential test run, and //! `fmt::Fault` an error only `caller.ts` prints. @@ -15,6 +15,7 @@ mod ints; mod iters; mod keys; mod shapes; +mod strs; #[cfg(target_arch = "wasm32")] #[path = "../../wasm.rs"] mod wasm; diff --git a/ts/fixtures/lang/src/strs.rs b/ts/fixtures/lang/src/strs.rs new file mode 100644 index 000000000..48a5c1c34 --- /dev/null +++ b/ts/fixtures/lang/src/strs.rs @@ -0,0 +1,283 @@ +//! `str` and `String` over `char`: iterated from both ends, searched by a `char` or a +//! predicate, trimmed, split, and built a char at a time. Text is made of chars of every +//! UTF-8 width and those next to UTF-16's surrogates, so byte offsets and code units part. +//! Predicates log each char they are called with, so where a search stops is output too. + +use crate::fmt::put; + +/// Separators, digits, and chars where a UTF-8 or UTF-16 length changes. +const ALPHABET: [char; 16] = [ + '/', + '\\', + 'a', + '0', + '9', + '\u{7f}', + '\u{80}', + 'é', + '\u{7ff}', + '\u{800}', + '\u{d7ff}', + '\u{e000}', + '\u{ffff}', + '\u{10000}', + '😀', + '\u{10ffff}', +]; + +/// A char of the alphabet for each byte, by its low bits. +fn text(data: &[u8]) -> String { + let mut s = String::new(); + for &b in data { + s.push(ALPHABET[(b % 16) as usize]); + } + s +} + +/// Whether the `i`th step reads from the back: by the byte's high bit. +fn from_back(data: &[u8], i: usize) -> bool { + matches!(data.get(i), Some(&b) if b & 0x80 != 0) +} + +fn put_char(out: &mut Vec, c: Option) { + match c { + Some(c) => out.extend_from_slice(&u32::from(c).to_be_bytes()), + None => out.push(0xff), + } +} + +fn put_offset(out: &mut Vec, i: Option) { + match i { + Some(i) => out.extend_from_slice(&(i as u32).to_be_bytes()), + None => out.push(0xfe), + } +} + +/// What a predicate saw, then where it stopped. +fn put_seen(out: &mut Vec, seen: &[char]) { + for &c in seen { + put_char(out, Some(c)); + } + out.push(0xfd); +} + +pub fn strs(kind: u8, data: &[u8], out: &mut Vec) { + let s = text(data); + // The pattern: a char of the alphabet, by the kind's high bits. + let sep = ALPHABET[(kind / 8 % 16) as usize]; + match kind % 8 { + 0 => { + // `chars` from both ends, until they meet. + let mut it = s.chars(); + let mut i = 0; + loop { + let c = match from_back(data, i) { + true => it.next_back(), + false => it.next(), + }; + put_char(out, c); + if c.is_none() { + break; + } + i += 1; + } + out.push(s.chars().count() as u8); + for c in s.chars().rev() { + out.push(c.is_ascii_digit() as u8); + } + out.push(s.is_empty() as u8); + out.push(s.as_str().is_empty() as u8); + } + 1 => { + // `split` by a char, from both ends. + let mut parts = s.split(sep); + let mut i = 0; + loop { + let part = match from_back(data, i) { + true => parts.next_back(), + false => parts.next(), + }; + let Some(part) = part else { + break; + }; + put(out, part); + out.push(part.len() as u8); + i += 1; + } + out.push(i as u8); + put(out, s.split(sep).next().unwrap_or("none")); + } + 2 => { + // `split` by a predicate, which sees each char once, in the order it is read. + let mut seen = Vec::new(); + let mut parts = s.split(|c: char| { + seen.push(c); + c == sep || c.is_ascii_digit() + }); + let mut i = 0; + loop { + let part = match from_back(data, i) { + true => parts.next_back(), + false => parts.next(), + }; + let Some(part) = part else { + break; + }; + put(out, part); + i += 1; + } + put_seen(out, &seen); + } + 3 => { + // Trimmed, tested, and found by a char. + put(out, s.trim_start_matches(sep)); + put(out, s.trim_end_matches(sep)); + put(out, s.trim_start_matches(sep).trim_end_matches(sep)); + out.push(s.starts_with(sep) as u8); + put_offset(out, s.rfind(sep)); + } + 4 => { + // Trimmed, tested, and found by a predicate. + let mut seen = Vec::new(); + let trimmed = s.trim_start_matches(|c: char| { + seen.push(c); + c == sep + }); + put(out, trimmed); + put_seen(out, &seen); + let trimmed = s.trim_end_matches(|c: char| { + seen.push(c); + c != sep + }); + put(out, trimmed); + put_seen(out, &seen); + out.push(s.starts_with(|c: char| c.is_ascii_digit()) as u8); + put(out, s.trim_start_matches(digit)); + let found = s.rfind(|c: char| { + seen.push(c); + c == sep + }); + put_offset(out, found); + put_seen(out, &seen); + } + 5 => { + // `match_indices` by a char, from both ends: byte offsets, not code units. + let mut found = s.match_indices(sep); + let mut i = 0; + loop { + let item = match from_back(data, i) { + true => found.next_back(), + false => found.next(), + }; + let Some((at, matched)) = item else { + break; + }; + put_offset(out, Some(at)); + put(out, matched); + i += 1; + } + let ends: Vec = s.match_indices('/').map(|(i, _)| i).collect(); + for end in ends { + put_offset(out, Some(end)); + } + } + 6 => { + // A path's parts, unescaped and escaped again, as moq's namespaces are. + let parts = unescape(&s); + for part in &parts { + put(out, part); + } + put(out, &escape(&parts)); + } + _ => { + // `push` through a `&mut String`: to a borrowed local, a field, a field through a + // `&mut self`, and an element, of a char made at run time. + let mut built = String::new(); + let mut named = Named { name: String::new() }; + let mut each = vec![String::new(), String::new()]; + for (i, c) in s.chars().enumerate() { + let target = &mut built; + target.push(c); + named.name.push(if i % 2 == 0 { c } else { sep }); + named.add(c); + each[i % 2].push(c); + if let Some(c) = char::from_u32(u32::from(c) + 1) { + built.push(c); + } + } + named.name.push('\u{10ffff}'); + put(out, &built); + put(out, &named.name); + put(out, &each[0]); + put(out, &each[1]); + // Reads from before a push, which must not see it. + let before = built.clone(); + let len = built.len(); + let empty = built.is_empty(); + built.push(sep); + put(out, &before); + out.push(len as u8); + out.push(empty as u8); + let taken = std::mem::take(&mut built); + put(out, &taken); + out.push(built.is_empty() as u8); + } + } +} + +/// A predicate that is a function, not a closure. +fn digit(c: char) -> bool { + c.is_ascii_digit() +} + +struct Named { + name: String, +} + +impl Named { + fn add(&mut self, c: char) { + self.name.push(c); + } +} + +/// `/` separates parts, and `\` escapes a `/` or `\` within one. +fn unescape(path: &str) -> Vec { + if path.is_empty() { + return Vec::new(); + } + let mut parts = Vec::new(); + let mut part = String::new(); + let mut chars = path.chars(); + while let Some(ch) = chars.next() { + match ch { + '/' => parts.push(std::mem::take(&mut part)), + '\\' => match chars.next() { + Some(next @ ('/' | '\\')) => part.push(next), + Some(next) => { + part.push('\\'); + part.push(next); + } + None => part.push('\\'), + }, + _ => part.push(ch), + } + } + parts.push(part); + parts +} + +fn escape(parts: &[String]) -> String { + let mut path = String::new(); + for (i, part) in parts.iter().enumerate() { + if i > 0 { + path.push('/'); + } + for ch in part.chars() { + if matches!(ch, '/' | '\\') { + path.push('\\'); + } + path.push(ch); + } + } + path +} diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index c7a4a6ebb..d3a7f38f9 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 69 -- Function instances: 57 +- Refusals: 72 +- Function instances: 59 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -10,11 +10,11 @@ | ---: | --- | --- | | 7 | an assignment through a reference to `_` | fixtures/reject/src/lib.rs:16:2 | | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:27:15 | -| 5 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:15:13 | -| 5 | unsupported call to `_` | fixtures/reject/src/lib.rs:32:4 | +| 6 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:15:13 | +| 6 | unsupported call to `_` | fixtures/reject/src/lib.rs:32:4 | +| 4 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:107:2 | | 4 | unsupported type `_` | fixtures/reject/src/lib.rs:6:14 | | 3 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:55:2 | -| 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:107:2 | | 2 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:127:20 | | 2 | a field of `_` | fixtures/reject/src/lib.rs:289:7 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:186:1 | @@ -56,6 +56,7 @@ The type or module each refused type or path belongs to. | 6 | `Option` | fixtures/reject/src/lib.rs:27:15 | | 6 | `f64` | fixtures/reject/src/lib.rs:6:14 | | 6 | `u8` | fixtures/reject/src/lib.rs:64:10 | +| 4 | `std::string::String` | fixtures/reject/src/lib.rs:94:16 | | 4 | `std::vec::Vec` | fixtures/reject/src/lib.rs:55:2 | | 4 | `u32` | fixtures/reject/src/lib.rs:15:13 | | 2 | `Iterator` | fixtures/reject/src/lib.rs:166:2 | @@ -64,7 +65,6 @@ The type or module each refused type or path belongs to. | 2 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:294:6 | | 2 | `std::option::Option` | fixtures/reject/src/lib.rs:294:6 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:143:2 | -| 2 | `std::string::String` | fixtures/reject/src/lib.rs:94:16 | | 2 | `std::sync::Arc` | fixtures/reject/src/lib.rs:123:2 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:186:1 | | 1 | `FusedIterator` | fixtures/reject/src/lib.rs:240:1 | @@ -83,6 +83,7 @@ The type or module each refused type or path belongs to. | 1 | `std::ops::Range` | fixtures/reject/src/lib.rs:207:8 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:153:11 | | 1 | `std::slice` | fixtures/reject/src/lib.rs:32:4 | +| 1 | `std::str` | fixtures/reject/src/lib.rs:372:4 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:148:2 | | 1 | `u64` | fixtures/reject/src/lib.rs:118:2 | | 1 | `{async closure}` | fixtures/reject/src/lib.rs:74:2 | @@ -94,6 +95,7 @@ The type or module each refused type or path belongs to. | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:27:15 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:14 | | 2 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:127:20 | +| 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:94:16 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:15:13 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u8`, `u8` | fixtures/reject/src/lib.rs:64:10 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:143:2 | @@ -105,7 +107,6 @@ The type or module each refused type or path belongs to. | 1 | `_` through a held type's own, which is not supported yet | `::ne` | fixtures/reject/src/lib.rs:349:2 | | 1 | `_`, a mutable reference to a value a map holds, kept other than to read and write it | `std::option::Option` | fixtures/reject/src/lib.rs:359:6 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:325:9 | -| 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:94:16 | | 1 | a `_` cast from `_` to `_` | `IntToFloat`, `u64`, `f64` | fixtures/reject/src/lib.rs:118:2 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:199:51 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:102:2 | @@ -128,11 +129,13 @@ The type or module each refused type or path belongs to. | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::fold` | fixtures/reject/src/lib.rs:166:2 | | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:220:2 | | 1 | replacing the value behind a reference to `_` | `[u8; 1]` | fixtures/reject/src/lib.rs:272:22 | +| 1 | replacing the value behind a reference to `_` | `std::string::String` | fixtures/reject/src/lib.rs:367:4 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:153:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:96:10 | | 1 | unsupported call to `_` | `std::mem::size_of_val` | fixtures/reject/src/lib.rs:48:18 | | 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:207:8 | | 1 | unsupported call to `_` | `std::slice::sort` | fixtures/reject/src/lib.rs:32:4 | +| 1 | unsupported call to `_` | `std::str::split` | fixtures/reject/src/lib.rs:372:4 | | 1 | unsupported type `_` | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:10:16 | ## Spans @@ -160,23 +163,34 @@ The type or module each refused type or path belongs to. -
`_`: a JS value of `_` is a copy, so a reference can't change it (5) +
`_`: a JS value of `_` is a copy, so a reference can't change it (6) - fixtures/reject/src/lib.rs:15:13: `&mut u32`: a JS value of `u32` is a copy, so a reference can't change it - fixtures/reject/src/lib.rs:21:2: `&mut u32`: a JS value of `u32` is a copy, so a reference can't change it - fixtures/reject/src/lib.rs:64:10: `&mut u8`: a JS value of `u8` is a copy, so a reference can't change it - fixtures/reject/src/lib.rs:94:16: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it - fixtures/reject/src/lib.rs:359:29: `&mut u8`: a JS value of `u8` is a copy, so a reference can't change it +- fixtures/reject/src/lib.rs:366:15: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it
-
unsupported call to `_` (5) +
unsupported call to `_` (6) - fixtures/reject/src/lib.rs:32:4: unsupported call to `std::slice::::sort` - fixtures/reject/src/lib.rs:48:18: unsupported call to `std::mem::size_of_val::` - fixtures/reject/src/lib.rs:96:10: unsupported call to `::write_fmt` - fixtures/reject/src/lib.rs:153:11: unsupported call to ` as std::iter::Iterator>::cycle` - fixtures/reject/src/lib.rs:207:8: unsupported call to `std::ops::Range::::contains::` +- fixtures/reject/src/lib.rs:372:4: unsupported call to `core::str::::split::<&str>` + +
+ +
replacing the value behind a reference to `_` (4) + +- fixtures/reject/src/lib.rs:107:2: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:111:2: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:272:22: replacing the value behind a reference to `[u8; 1]` +- fixtures/reject/src/lib.rs:367:4: replacing the value behind a reference to `std::string::String`
@@ -197,14 +211,6 @@ The type or module each refused type or path belongs to.
-
replacing the value behind a reference to `_` (3) - -- fixtures/reject/src/lib.rs:107:2: replacing the value behind a reference to `Meters` -- fixtures/reject/src/lib.rs:111:2: replacing the value behind a reference to `Meters` -- fixtures/reject/src/lib.rs:272:22: replacing the value behind a reference to `[u8; 1]` - -
-
`_` is not supported: it would be pending two ways with one value (2) - fixtures/reject/src/lib.rs:127:20: `Poll>>` is not supported: it would be pending two ways with one value diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 93c2a4da5..b6a68c922 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -59,6 +59,9 @@ a field of `std::ops::RangeFrom` at fixtures/reject/src/lib.rs:289:48 hashing `std::vec::Vec` as a key, which is not supported yet at fixtures/reject/src/lib.rs:299:52 comparing `std::vec::Vec` as a key, which is not supported yet at fixtures/reject/src/lib.rs:299:52 `HashMap::contains_key` of `std::collections::HashMap` by `u8`, which is not supported yet at fixtures/reject/src/lib.rs:317:6 +`&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:366:15 +replacing the value behind a reference to `std::string::String` at fixtures/reject/src/lib.rs:367:4 +unsupported call to `core::str::::split::<&str>` at fixtures/reject/src/lib.rs:372:4 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:166:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:186:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:220:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index f103c13df..b1a225835 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -361,3 +361,13 @@ pub fn passed(map: &mut std::collections::HashMap) -> u8 { *v }) } + +/// A `String` pushed to through a parameter, whose JS value is the caller's copy. +pub fn pushed(s: &mut String) { + s.push('a'); +} + +/// A `str` pattern, where only a `char` and a predicate are supported. +pub fn split_str(s: &str) -> usize { + s.split("ab").count() +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 7aa37b14c..06dae69ed 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -42,6 +42,8 @@ roots = [ "byte_keys", "borrowed", "raw_keys", + "pushed", + "split_str", "missing", ] printable = ["Meters"] diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index e4ce35cf3..5486fe8f6 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -10,6 +10,7 @@ import { type char, type TryFromIntError, type u32, u8Display, usizeDisplay } fr export * from "./rt/collections.ts"; export * from "./rt/int.ts"; export * from "./rt/iter.ts"; +export * from "./rt/str.ts"; export * from "./rt/task.ts"; /** A Rust panic. */ @@ -439,6 +440,11 @@ export function charFromU32(n: u32): char | undefined { return n > 0x10ffff || (n >= 0xd800 && n <= 0xdfff) ? undefined : (n as char); } +/** `char::is_ascii_digit`. */ +export function charIsAsciiDigit(c: char): boolean { + return c >= 0x30 && c <= 0x39; +} + // Formatting, as `core::fmt` does it: the same output byte for byte. /** `core::fmt::Error`. */ diff --git a/ts/runtime/rt/str.ts b/ts/runtime/rt/str.ts new file mode 100644 index 000000000..d5f78ec10 --- /dev/null +++ b/ts/runtime/rt/str.ts @@ -0,0 +1,254 @@ +// `str`'s iterators and searches over `char`, for rust2-ts output. `rt.ts` re-exports all +// of it. +// +// A JS string is UTF-16 where a `str` is UTF-8: these step by code point, and an offset +// they return counts UTF-8 bytes, as Rust's does. A string from translated code is well +// formed, so a char's text never matches across a surrogate pair. + +import type { char, usize } from "./int.ts"; +import { DONE, type Done, Iter } from "./iter.ts"; + +/** A pattern: a `char`, as its text, or a `FnMut(char) -> bool`. */ +export type Pattern = string | ((c: char) => boolean); + +/** The UTF-8 length of the code units of `s` from `from` to `to`. */ +function utf8Len(s: string, from: number, to: number): number { + let n = to - from; + for (let i = from; i < to; i++) { + const u = s.charCodeAt(i); + // Each half of a surrogate pair is two of its four bytes. + if (u >= 0x80) n += u < 0x800 || (u >= 0xd800 && u <= 0xdfff) ? 1 : 2; + } + return n; +} + +/** Where the char that ends at `end` starts. */ +function before(s: string, end: number): number { + const u = s.charCodeAt(end - 1); + return u >= 0xdc00 && u <= 0xdfff ? end - 2 : end - 1; +} + +/** `str::chars`. */ +export function strChars(s: string): Iter { + return new Chars(s); +} + +class Chars extends Iter { + readonly #s: string; + #front = 0; + #back: number; + + constructor(s: string) { + super(); + this.#s = s; + this.#back = s.length; + } + + next(): char | Done { + if (this.#front >= this.#back) return DONE; + const c = this.#s.codePointAt(this.#front) as number; + this.#front += c > 0xffff ? 2 : 1; + return c as char; + } + + override nextBack(): char | Done { + if (this.#front >= this.#back) return DONE; + this.#back = before(this.#s, this.#back); + return this.#s.codePointAt(this.#back) as char; + } +} + +/** + * std's searcher of a pattern in `s` between `front` and `back`, in code units. Each step + * finds the next match from one end, `start` to `end`, and moves that end past it. + */ +class Searcher { + readonly s: string; + readonly #p: Pattern; + #front = 0; + #back: number; + start = 0; + end = 0; + + constructor(s: string, p: Pattern) { + this.s = s; + this.#p = p; + this.#back = s.length; + } + + nextMatch(): boolean { + const { s } = this; + const p = this.#p; + if (typeof p === "string") { + const i = s.indexOf(p, this.#front); + if (i < 0 || i + p.length > this.#back) { + this.#front = this.#back; + return false; + } + this.start = i; + this.end = this.#front = i + p.length; + return true; + } + while (this.#front < this.#back) { + const i = this.#front; + const c = s.codePointAt(i) as number; + this.#front += c > 0xffff ? 2 : 1; + if (p(c as char)) { + this.start = i; + this.end = this.#front; + return true; + } + } + return false; + } + + nextMatchBack(): boolean { + const { s } = this; + const p = this.#p; + if (typeof p === "string") { + const from = this.#back - p.length; + const i = from < this.#front ? -1 : s.lastIndexOf(p, from); + if (i < this.#front) { + this.#back = this.#front; + return false; + } + this.start = this.#back = i; + this.end = i + p.length; + return true; + } + while (this.#back > this.#front) { + const end = this.#back; + this.#back = before(s, end); + if (p(s.codePointAt(this.#back) as char)) { + this.start = this.#back; + this.end = end; + return true; + } + } + return false; + } +} + +/** `str::split`. */ +export function strSplit(s: string, p: Pattern): Iter { + return new Split(new Searcher(s, p)); +} + +class Split extends Iter { + readonly #m: Searcher; + #start = 0; + #end: number; + #finished = false; + + constructor(m: Searcher) { + super(); + this.#m = m; + this.#end = m.s.length; + } + + next(): string | Done { + if (this.#finished) return DONE; + const m = this.#m; + if (m.nextMatch()) { + const part = m.s.slice(this.#start, m.start); + this.#start = m.end; + return part; + } + this.#finished = true; + return m.s.slice(this.#start, this.#end); + } + + override nextBack(): string | Done { + if (this.#finished) return DONE; + const m = this.#m; + if (m.nextMatchBack()) { + const part = m.s.slice(m.end, this.#end); + this.#end = m.start; + return part; + } + this.#finished = true; + return m.s.slice(this.#start, this.#end); + } +} + +/** `str::match_indices`: each match, after its offset in UTF-8 bytes. */ +export function strMatchIndices(s: string, p: Pattern): Iter<[usize, string]> { + return new MatchIndices(new Searcher(s, p)); +} + +class MatchIndices extends Iter<[usize, string]> { + readonly #m: Searcher; + // Where the last match from each end starts, in code units and in bytes. The back's + // bytes are counted once it first moves. + #front = 0; + #frontBytes = 0; + #back = -1; + #backBytes = 0; + + constructor(m: Searcher) { + super(); + this.#m = m; + } + + next(): [usize, string] | Done { + const m = this.#m; + if (!m.nextMatch()) return DONE; + this.#frontBytes += utf8Len(m.s, this.#front, m.start); + this.#front = m.start; + return [this.#frontBytes as usize, m.s.slice(m.start, m.end)]; + } + + override nextBack(): [usize, string] | Done { + const m = this.#m; + if (!m.nextMatchBack()) return DONE; + if (this.#back < 0) { + this.#back = m.s.length; + this.#backBytes = this.#frontBytes + utf8Len(m.s, this.#front, this.#back); + } + this.#backBytes -= utf8Len(m.s, m.start, this.#back); + this.#back = m.start; + return [this.#backBytes as usize, m.s.slice(m.start, m.end)]; + } +} + +/** `str::starts_with`. */ +export function strStartsWith(s: string, p: Pattern): boolean { + if (typeof p === "string") return s.startsWith(p); + return s.length > 0 && p(s.codePointAt(0) as char); +} + +/** `str::trim_start_matches`. */ +export function strTrimStartMatches(s: string, p: Pattern): string { + let i = 0; + if (typeof p === "string") { + while (s.startsWith(p, i)) i += p.length; + } else { + while (i < s.length) { + const c = s.codePointAt(i) as number; + if (!p(c as char)) break; + i += c > 0xffff ? 2 : 1; + } + } + return s.slice(i); +} + +/** `str::trim_end_matches`. */ +export function strTrimEndMatches(s: string, p: Pattern): string { + let end = s.length; + if (typeof p === "string") { + while (end >= p.length && s.startsWith(p, end - p.length)) end -= p.length; + } else { + while (end > 0) { + const i = before(s, end); + if (!p(s.codePointAt(i) as char)) break; + end = i; + } + } + return s.slice(0, end); +} + +/** `str::rfind`: the last match's offset in UTF-8 bytes. */ +export function strRfind(s: string, p: Pattern): usize | undefined { + const m = new Searcher(s, p); + return m.nextMatchBack() ? (utf8Len(s, 0, m.start) as usize) : undefined; +} diff --git a/ts/runtime/tsconfig.json b/ts/runtime/tsconfig.json index 00be8fac0..c7aa3a644 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/task.ts"] + "files": ["rt.ts", "rt/collections.ts", "rt/int.ts", "rt/iter.ts", "rt/str.ts", "rt/task.ts"] } diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index d6e6fb934..1445589da 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -739,6 +739,22 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec ("String" | "str", "len") => Expr::rt("stringLen", args), ("String", "as_str") => args.pop()?, ("String", "new") => Expr::Str(String::new()), + ("String" | "str", "is_empty") => args.pop()?.member("length").binary("===", Expr::lit("0")), + ("str", "chars") => Expr::rt("strChars", args), + // Searches by a pattern. + ("str", "split" | "match_indices" | "starts_with" | "trim_start_matches" | "trim_end_matches" | "rfind") => { + let f = match name.as_str() { + "split" => "strSplit", + "match_indices" => "strMatchIndices", + "starts_with" => "strStartsWith", + "trim_start_matches" => "strTrimStartMatches", + "trim_end_matches" => "strTrimEndMatches", + _ => "strRfind", + }; + let [s, p] = <[Expr; 2]>::try_from(args).ok()?; + Expr::rt(f, vec![s, pattern(targ(gargs, 0), p)?]) + } + ("char", "is_ascii_digit") => Expr::rt("charIsAsciiDigit", args), ("ToString", "to_string") | ("ToOwned", "to_owned") if matches!(self_ty()?.peel_refs().kind(), ty::Str) => { args.pop()? } @@ -915,6 +931,26 @@ fn owned<'tcx>(b: &mut Body<'_, '_, 'tcx>, value: Expr, ty: Ty<'tcx>, span: Span } } +/// A `str` method's pattern as the runtime takes it, an `rt.Pattern`: a `char`'s text, +/// or a predicate as it is. `None` for any other pattern. +fn pattern(ty: Ty<'_>, p: Expr) -> Option { + match ty.kind() { + ty::Char => Some(char_text(p)), + ty::Closure(..) | ty::FnDef(..) => Some(p), + _ => None, + } +} + +/// A `char`'s text: a literal for a constant, or `String.fromCodePoint(c)`. +pub fn char_text(c: Expr) -> Expr { + if let Expr::Lit(n) = &c + && let Some(c) = n.parse().ok().and_then(char::from_u32) + { + return Expr::Str(c.to_string()); + } + Expr::ident("String").member("fromCodePoint").call(vec![c]) +} + /// `rt.(args)`. fn rt2(args: Vec, of: &str, name: &str) -> Expr { Expr::rt_of(of, name).call(args) diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index dd1bec09a..f23c9c420 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -279,6 +279,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ); done(next, true) } + // A JS string can't change in place, so what the `&mut` borrows gets a longer one. + ("String", "push") => { + let place = self.borrowed_place(&args[0].node, span)?; + let c = self.operand(&args[1].node, span, out); + let pushed = place.clone().binary("+", library::char_text(c)); + out.push(StmtKind::Expr(place.assign(pushed)).at(None)); + done(Expr::undefined(), false) + } ("Option", "take") => { let place = self.borrowed_place(&args[0].node, span)?; done(self.swap_out(place, Expr::undefined(), "taken", out), true) diff --git a/ts/src/program.rs b/ts/src/program.rs index f861d7bde..ce7b32077 100644 --- a/ts/src/program.rs +++ b/ts/src/program.rs @@ -13,6 +13,7 @@ pub const RUNTIME: &[(&str, &str)] = &[ ("rt/collections.ts", include_str!("../runtime/rt/collections.ts")), ("rt/int.ts", include_str!("../runtime/rt/int.ts")), ("rt/iter.ts", include_str!("../runtime/rt/iter.ts")), + ("rt/str.ts", include_str!("../runtime/rt/str.ts")), ("rt/task.ts", include_str!("../runtime/rt/task.ts")), ];