From 047213dc1efcdf60b26a00c3f7ab71b8fed42cea Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 01:31:55 -0800 Subject: [PATCH 01/28] chore(quest): claim quest/m1/ffi-rules/transcript.md Quest-Claim: 8e229d4f0a4f4903 From e88806feee52f2685e97c152da9feafeaeb6b737 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 02:09:54 -0800 Subject: [PATCH 02/28] wip: transcript as a typed Rust subset, parsed against api.json --- ffi/Cargo.lock | 22 +- ffi/Cargo.toml | 2 + ffi/fixtures/api/examples/transcript.rs | 603 +++++---- ffi/tests/fixtures.rs | 12 + ffi/tests/fixtures/transcript/ir.rs | 285 +++++ ffi/tests/fixtures/transcript/mod.rs | 1478 +++++++++++++++++++++++ ffi/tests/fixtures/transcript/python.rs | 1 + 7 files changed, 2145 insertions(+), 258 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/ir.rs create mode 100644 ffi/tests/fixtures/transcript/mod.rs create mode 100644 ffi/tests/fixtures/transcript/python.rs diff --git a/ffi/Cargo.lock b/ffi/Cargo.lock index 7af119daf..d2c5ed12c 100644 --- a/ffi/Cargo.lock +++ b/ffi/Cargo.lock @@ -81,7 +81,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -481,9 +481,11 @@ name = "rust2-ffi" version = "0.0.0" dependencies = [ "loom", + "proc-macro2", "rust2-driver", "serde", "serde_json", + "syn 3.0.10", "toml", "wasmparser", ] @@ -551,7 +553,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -638,9 +640,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -655,7 +657,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -675,7 +677,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -860,7 +862,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] @@ -1007,7 +1009,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -1028,7 +1030,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -1062,7 +1064,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] diff --git a/ffi/Cargo.toml b/ffi/Cargo.toml index 6ee07cb45..d255635be 100644 --- a/ffi/Cargo.toml +++ b/ffi/Cargo.toml @@ -30,6 +30,8 @@ wasmparser = { version = "0.263.0", default-features = false, features = ["std"] [dev-dependencies] loom = "0.7.3" +proc-macro2 = { version = "1.0.107", features = ["span-locations"] } +syn = { version = "3.0.10", default-features = false, features = ["clone-impls", "full", "parsing", "printing"] } [lints] workspace = true diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index f273b57c1..77fae4fc6 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -1,5 +1,10 @@ -//! The script `tests/api.c` runs through the C ABI, run natively: the two transcripts -//! must match line for line. +//! The script every language's test runs through its binding, run natively: each +//! transcript must match this one line for line. +//! +//! `main` is data as well as Rust: `tests/fixtures/transcript` reads it, in the subset its +//! module docs name, and writes it as each language's script. Each function defined here is +//! a language's own, hand-written beside its script under the same name: what tests its +//! idiom, such as futures and readers, or prints a value no two bindings shape alike. use std::future::Future; use std::ops::Bound; @@ -14,7 +19,10 @@ use api::{ }; use bytes::Bytes; -/// Keeps even levels, as `tests/api.c`'s implementation does. +/// One static, so Rust lends one string, as interning lends a binding's equal ones. +static LIT: &str = "lit"; + +/// Keeps even levels, as each language's implementation does. struct Print; impl Log for Print { @@ -30,14 +38,6 @@ impl Drop for Print { } } -struct Count(AtomicUsize); - -impl Wake for Count { - fn wake(self: Arc) { - self.0.fetch_add(1, Ordering::Relaxed); - } -} - fn main() { println!("limit {LIMIT}"); @@ -108,22 +108,32 @@ fn main() { } } let rows = api::rows(&[Point { x: 1, y: 2 }, Point { x: 3, y: 3 }]); - let rows: Vec = (rows.iter()) - .map(|(name, shape, p)| format!("{name} {shape:?} {} {}", p.x, p.y)) - .collect(); - println!("rows {}", rows.join(", ")); + println!( + "rows {}", + rows.iter() + .map(|(name, shape, p)| format!("{name} {shape:?} {} {}", p.x, p.y)) + .collect::>() + .join(", ") + ); + // Each handle in a tuple moves in, as one taken by value does. let board = api::Board::new(vec![ ("low".to_string(), Counter::new("l", 1)), ("high".to_string(), Counter::new("h", 9)), ]); // The counters a board returns build another, each handle moved back in. let board = api::Board::new(board.into_counters()); - let ranked: Vec = (board.ranked()) - .map(|(name, counter)| format!("{name} {} {}", counter.name(), counter.get())) - .collect(); - println!("ranked {}", ranked.join(", ")); + println!( + "ranked {}", + board + .ranked() + .map(|(name, counter)| format!("{name} {} {}", counter.name(), counter.get())) + .collect::>() + .join(", ") + ); let best: Counter = board.best().into(); println!("best {} {}", best.name(), best.get()); + // A map crosses as its pairs and a set as its items, which Rust collects in order, each + // key once, the last kept. let atlas = api::Atlas { points: [("b", 1, 1), ("ab", 2, 3), ("b", 4, 4)] .into_iter() @@ -132,11 +142,17 @@ fn main() { ids: [3, 1, 3].into_iter().collect(), } .with("c", Point { x: 5, y: 6 }); - let points: Vec = (atlas.points.iter()) - .map(|(name, p)| format!("{name} {} {}", p.x, p.y)) - .collect(); - let ids: Vec = atlas.ids.iter().map(u32::to_string).collect(); - println!("atlas {}; ids {}", points.join(", "), ids.join(" ")); + println!( + "atlas {}; ids {}", + atlas + .points + .iter() + .map(|(name, p)| format!("{name} {} {}", p.x, p.y)) + .collect::>() + .join(", "), + atlas.ids.iter().map(|id| format!("{id}")).collect::>().join(" ") + ); + // Another crate's error crosses as its message. for text in ["80", "x"] { match api::port(text) { Ok(port) => println!("port {port}"), @@ -154,10 +170,12 @@ fn main() { for value in [None, Some((None,)), Some((Some(3),))] { println!("doubled {:?}", api::doubled(value)); } - let lent = (vec![1, 2],); + // A borrowed or boxed tuple of one is a tuple, not its element. + let lent: (Vec,) = (vec![1, 2],); let (lent,) = api::lent_back(&lent); let (boxed,) = *api::boxed_tuple(vec![3]); println!("lent back {lent:?} boxed {boxed:?}"); + // A borrowed string and an owned one share a tuple struct. println!( "title {:?} {:?} named {:?}", api::title(true), @@ -197,8 +215,6 @@ fn main() { let long = api::longer(joined, &Name::owned("dd".to_string())); println!("longer {}", long.as_str()); println!("unnamed [{}]", api::unnamed().as_str()); - // One static, so Rust lends one string, as interning lends a binding's equal ones. - static LIT: &str = "lit"; let (lit, again) = (Name::borrowed(LIT), Name::borrowed(LIT)); let other = Name::borrowed("other"); println!( @@ -210,12 +226,11 @@ fn main() { println!("total {}", api::total(2..5)); println!("reach {}", api::reach(2, (), 5)); - let scaled = |v, by| api::scaled(v, by).map_or("none".to_string(), |v| format!("{v:032x}")); println!( "scaled {} {} {}", - scaled(u128::MAX, 1), - scaled((1 << 64) + 1, 1 << 63), - scaled(1 << 127, 2) + api::scaled(u128::MAX, 1).map_or("none".to_string(), |v| format!("{v:032x}")), + api::scaled((1 << 64) + 1, 1 << 63).map_or("none".to_string(), |v| format!("{v:032x}")), + api::scaled(1 << 127, 2).map_or("none".to_string(), |v| format!("{v:032x}")) ); let mut digest = api::Digest::new(); digest.sum = api::fingerprint("deadbeef").unwrap(); @@ -226,12 +241,21 @@ fn main() { api::fingerprint("zz").unwrap_err() ); let mut batch: api::Batch = api::Batch::new(); - let accepted = (1..=5).filter(|&v| batch.push(v)).count(); let mut batch2 = api::pair(); - let paired = (1..=3).filter(|&v| batch2.push(v)).count(); + println!( + "pushed {} {} {} {} {} paired {} {} {}", + batch.push(1), + batch.push(2), + batch.push(3), + batch.push(4), + batch.push(5), + batch2.push(1), + batch2.push(2), + batch2.push(3) + ); let emptied = api::drain(&mut batch); println!( - "batch {} {accepted} {emptied} {} {} {paired} {}", + "batch {} {emptied} {} {} {}", batch.capacity(), api::drain(&mut batch), batch2.capacity(), @@ -296,6 +320,7 @@ fn main() { println!("{}", api::describe(&event)); } + // A `Copy` handle passed by value is copied, so it stays usable. let stamp = Stamp::from_millis(2500); println!("secs {}", stamp.secs()); println!("later {}", Stamp::from_millis(3000).later(stamp)); @@ -366,7 +391,7 @@ fn main() { let mut extent = api::Extent::new(5, 3); let start = extent; let old = extent.slide(10); - extent.start += 1; + extent.start = extent.start + 1; println!( "extent {old} {} {} {} {}", extent.start, @@ -387,8 +412,14 @@ fn main() { mark, payload: Bytes::from_static(b"abc"), }; - let moved = (Counter::new("w", 1), Bytes::from_static(b"abcd")); - println!("heft {}", api::heft((mark, Bytes::from_static(b"ab")), &parcel, moved)); + println!( + "heft {}", + api::heft( + (mark, Bytes::from_static(b"ab")), + &parcel, + (Counter::new("w", 1), Bytes::from_static(b"abcd")) + ) + ); // A value's `&mut self` beside a checked handle. let mut noted = api::Score::of(2); let before = noted.note(&api::Mark::of(5)); @@ -405,82 +436,7 @@ fn main() { }); println!("filtered {kept}"); - let channel = Channel::new(); - let count = Arc::new(Count(AtomicUsize::new(0))); - let waker = Waker::from(count.clone()); - let mut cx = Context::from_waker(&waker); - { - let mut recv = pin!(channel.recv()); - let first = recv.as_mut().poll(&mut cx); - println!("recv pending {}", first.is_pending()); - channel.send(Bytes::from_static(b"hi")); - println!("woken {}", count.0.load(Ordering::Relaxed)); - if let Poll::Ready(payload) = recv.as_mut().poll(&mut cx) { - println!("recv {}", String::from_utf8_lossy(&payload)); - } - } - channel.send(Bytes::new()); - let mut recv = pin!(channel.recv_nonempty()); - match recv.as_mut().poll(&mut cx) { - Poll::Ready(Ok(payload)) => println!("nonempty {}", payload.len()), - Poll::Ready(Err(e)) => println!("nonempty err {e}"), - Poll::Pending => println!("nonempty pending"), - } - let mut filled: Vec = Vec::new(); - let mut fill4: api::Batch = api::Batch::new(); - if let Poll::Ready(v) = pin!(api::fill(&mut fill4, 9)).poll(&mut cx) { - filled.extend(v.iter().map(u32::to_string)); - } - let mut fill2 = api::pair(); - if let Poll::Ready(v) = pin!(api::fill(&mut fill2, 1)).poll(&mut cx) { - filled.extend(v.iter().map(u32::to_string)); - } - println!("fill {}", filled.join(" ")); - - // The send happens at the call: the future is dropped unpolled. - drop(channel.send_later(Bytes::from_static(b"eager"))); - let mut recv = pin!(channel.recv()); - if let Poll::Ready(payload) = recv.as_mut().poll(&mut cx) { - println!("recv {}", String::from_utf8_lossy(&payload)); - } - // The send happens at the call, and the future borrows the channel and the tag. - let mut tagged = pin!(channel.tagged("tag")); - if let Poll::Ready(text) = tagged.as_mut().poll(&mut cx) { - println!("tagged {text}"); - } - // So does a future borrowing an optional slice, which the export owns while it is pending. - let items = [1u32, 2, 3]; - let mut itemized = pin!(channel.itemized(Some(&items))); - if let Poll::Ready(count) = itemized.as_mut().poll(&mut cx) { - println!("itemized {count}"); - } - // Another crate's future borrowing its bytes, which the export owns while it is pending. - let bytes = *b"abc"; - if let Poll::Ready(len) = pin!(api::byte_len(&bytes)).poll(&mut cx) { - println!("byte_len {len}"); - } - channel.send(Bytes::from_static(b"sized")); - let mut sized = pin!(channel.recv_sized()); - if let Poll::Ready((payload, len)) = sized.as_mut().poll(&mut cx) { - println!("sized {} {len}", String::from_utf8_lossy(&payload)); - } - channel.notify(waker.clone()); - channel.send(Bytes::from_static(b"rung")); - println!("woken {}", count.0.load(Ordering::Relaxed)); - if let Poll::Ready(payload) = channel.poll_take(&Waiter::new(waker.clone())) { - println!("take {}", String::from_utf8_lossy(&payload)); - } - channel.send(Bytes::from_static(b"measured")); - if let Poll::Ready(Ok(len)) = channel.clone().poll_measure(&mut cx, 2) { - println!("measure {len}"); - } - channel.listen((), &cx); - channel.send(Bytes::from_static(b"heard")); - println!("woken {}", count.0.load(Ordering::Relaxed)); - let waiter = Waiter::new(waker.clone()); - waiter.waker().clone().wake(); - waiter.context().waker().clone().wake(); - println!("woken {}", count.0.load(Ordering::Relaxed)); + channel(); let list = Node { value: 1, @@ -498,6 +454,7 @@ fn main() { let size = area.size(); println!("area {} {} {}", size.width, size.height, area.pixels()); + // Generic types, each at the instances it infers, named by their arguments. let pair = Pair { left: 2u32, right: 5 }; let swapped = pair.swap(); println!( @@ -508,22 +465,23 @@ fn main() { pair == swapped ); println!("even {} {}", pair.even(), Pair { left: 7u32, right: 7 }.even()); + // An instance renamed alone, beside another of `Pair` that keeps its name. let sized = api::tag(Size { width: 1, height: 2 }, 3); let flipped = sized.swap(); println!("sized {} {} {flipped:?}", flipped.left, flipped.right.width); let beside = Pair { left: 258u32, right: 9 }.beside(sized.left); println!("beside {} {beside:?}", beside.left); let mut stack = Stack::new(); - for (i, name) in ["a", "b"].into_iter().enumerate() { - stack.push(Counter::new(name, i as u64 + 1)); - } - let top = stack.pop().map(|c| c.get()); + stack.push(Counter::new("a", 1)); + stack.push(Counter::new("b", 2)); + let top = stack.pop().unwrap().get(); println!( - "stack {} {top:?} {} {}", + "stack {} {top} {} {}", stack.depth(), stack.pop().is_some(), stack.pop().is_none() ); + // Generic functions and methods, at each implementation of the trait bounding them. let from_point = Counter::seeded("p", Point { x: -3, y: 4 }); let from_size = Counter::seeded("s", Size { width: 5, height: 6 }); let from_counter = Counter::seeded("c", &from_point); @@ -538,6 +496,7 @@ fn main() { api::seeds::(&Size { width: 2, height: 3 }) ); + // A trait implemented for `Point` and `&Point` apart: one instance. println!("weigh {}", api::weigh(Point { x: -1, y: 2 })); // A function named as the type it returns, and one named as a type it does not. let polar = api::polar::point(2).expect("a point off the origin"); @@ -547,6 +506,7 @@ fn main() { api::polar::point(0).is_none(), api::area(Size { width: 2, height: 3 }) ); + // Two types whose paths join alike, the second kept apart where its path splits. println!( "wind {}", api::wind(api::PolarTurn { whole: 2 }, api::polar::Turn { part: 3 }) @@ -567,6 +527,7 @@ fn main() { api::clash::audio_encoder::finish(), api::clash::nested(Some(((1, 2), 3)), Some(((1, 2, 3),))) ); + // Instances that name each other, and one made only by an impl of it. let left = api::Left { value: api::Right { value: 1u8 }, }; @@ -574,6 +535,7 @@ fn main() { value: api::Left { value: 2u8 }, }; println!("cross {} outer {}", api::cross(left, right), api::Outer::new(4).get()); + // A bound that outlives the call takes a value, and an instance only a constant names. println!("kept {} boxed {}", api::kept(Point { x: 1, y: -2 }), api::BOXED.value); println!("keep {}", api::keep(Point { x: 1, y: -2 })); let five = Point { x: 5, y: 2 }; @@ -583,23 +545,25 @@ fn main() { api::kept_or::(None), api::keeper(five) ); + // Inferred instances taking a lent closure and a foreign implementation, and one only + // its impl of a trait names. let sides = Pair { left: 2u32, right: 5 }; println!("apply {}", api::apply(sides, |side| side * 3)); println!("report {}", api::report(sides, Print)); println!("wrapped {}", api::kept(api::Wrap { value: 4u32 })); println!("keeps {}", api::keeps(Print).value); + // Its Drop runs when its last reference goes, not before. let token = api::Token::new(7); println!("token {} dropped {}", token.id, api::dropped()); drop(token); println!("dropped {}", api::dropped()); + // A field and the method of its name, each its own member. let mut retry = api::Retry::new(Some(5)); - let limit = retry.limit; println!( - "retry {} {} {} {}", - u8::from(limit.is_some()), - limit.unwrap_or(0), + "retry {:?} {} {}", + retry.limit, retry.limit(), retry.delay() ); @@ -629,22 +593,25 @@ fn main() { .next("c"); println!("peer {peer:?} {:?}", peer.aliases()); let file = api::file(std::path::Path::new("dir"), "f\\'\"\t"); - println!("file {}", file.as_os_str().as_encoded_bytes().escape_ascii()); - let parents = api::parents(vec![file, std::path::PathBuf::from("/")]); - let parents: Vec = (parents.iter()) - .map(|p| match p { - Some(p) => p.as_os_str().as_encoded_bytes().escape_ascii().to_string(), - None => "none".to_string(), - }) - .collect(); - println!("parents {}", parents.join(" ")); + println!("file {}", escaped(&file)); + println!( + "parents {}", + api::parents(vec![file, std::path::PathBuf::from("/")]) + .iter() + .map(|p| p.as_ref().map_or("none".to_string(), |p| escaped(p))) + .collect::>() + .join(" ") + ); let words = api::words(" one two three "); println!("words {} {words:?}", words.len()); println!("sentence {} {}", api::sentence(Some(words)), api::sentence(None)); println!("sentence {}|", api::sentence(Some(Vec::new()))); println!("either {} {}", api::either(Some("abc")), api::either(None)); - let prefixed = |prefix: Option<&[u8]>| String::from_utf8(api::prefixed(b"cd", prefix)).unwrap(); - println!("prefixed {} {}", prefixed(Some(b"ab")), prefixed(None)); + println!( + "prefixed {} {}", + String::from_utf8(api::prefixed(b"cd", Some(b"ab"))).unwrap(), + String::from_utf8(api::prefixed(b"cd", None)).unwrap() + ); println!( "coordinates {} {}", api::coordinates(Some(&Point { x: 2, y: 3 })), @@ -658,18 +625,18 @@ fn main() { two.add_to(None), three.get() ); - let mut buf = b"0,".to_vec(); + let mut buf: Vec = b"0,".to_vec(); api::put_number(1, &mut buf); api::put_number(23, &mut buf); println!("put_number {}", String::from_utf8(buf).unwrap()); - let mut entry = (b"ab".to_vec(), 1); + let mut entry: (Vec, u32) = (b"ab".to_vec(), 1); let count = api::push_counted(&mut entry, b'c'); println!( "push_counted {count} {} {}", String::from_utf8(entry.0).unwrap(), entry.1 ); - let mut buf = bytes::Bytes::from_static(b"7x9"); + let mut buf: Bytes = Bytes::from_static(b"7x9"); let first = api::digit(&mut buf).unwrap(); let skipped = api::digit(&mut buf).is_err(); println!( @@ -683,21 +650,17 @@ fn main() { let config = api::secure("h3"); println!("secure {} {}", api::alpn_lent(&config), api::alpn(config.clone())); let cert = api::certify(b"der"); - let chain = vec![api::certify(b"a"), api::certify(b"bc")]; println!( "cert {} {} {}", api::cert_len(&cert), String::from_utf8_lossy(&api::cert_der(cert)), - api::chain_len(chain) + api::chain_len(vec![api::certify(b"a"), api::certify(b"bc")]) ); // Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. - let resolver = api::resolver("r1"); - println!("resolver {}", api::resolved(resolver)); + println!("resolver {}", api::resolved(api::resolver("r1"))); let mut codecs = api::Codecs::new(); println!("codecs {}", codecs.ids()); - let mut list = codecs.list.clone(); - list.reverse(); - codecs.list = list; + codecs.list = reversed(codecs.list.clone()); println!("codecs reversed {}", codecs.ids()); // A standard library value no type maps, in a handle. let failure = api::failure("boom"); @@ -775,13 +738,18 @@ fn main() { ledger.seal(); println!("sealed {}", ledger.edit().err().unwrap()); println!("chunks {:?}", api::chunks(b"abcde", 2)); - let mut counters = api::counters(vec!["x".to_string(), "y".to_string()]); - let names: Vec = counters.iter().map(|c| format!("{} {}", c.name(), c.get())).collect(); - println!("counters {}", names.join(", ")); - let boxed = counters.split_off(1); + let counters = api::counters(vec!["x".to_string(), "y".to_string()]); + println!( + "counters {}", + counters + .iter() + .map(|c| format!("{} {}", c.name(), c.get())) + .collect::>() + .join(", ") + ); println!( "worth {} {}", - api::worth(Some(counters), Box::new(boxed)), + api::worth(Some(counters), Box::new(api::counters(vec!["z".to_string()]))), api::worth(None, Box::default()) ); println!( @@ -798,10 +766,9 @@ fn main() { ); println!("less {}", api::less(5, 2)); println!("sums {:?}", api::sums(vec![vec![1, 2], Vec::new(), vec![3]])); - let least = api::least(vec![[3, 1].into(), Default::default(), [2].into()]); println!( "least {}", - least + api::least(vec![[3, 1].into(), Default::default(), [2].into()]) .iter() .map(|set| format!("{:?}", set.iter().collect::>())) .collect::>() @@ -814,10 +781,10 @@ fn main() { println!( "float equal {} {} {} {} {}", // Each value against itself, which a NaN it holds makes unequal. - PartialEq::eq(&edges, &edges), + edges == edges, edges == api::Numbers::edges(), api::Numbers::zero(true) == api::Numbers::zero(false), - PartialEq::eq(&nan, &nan), + nan == nan, api::Measure::new(-0.0, true) == api::Measure::new(0.0, false) ); println!( @@ -826,10 +793,9 @@ fn main() { api::sum_u32(&[u32::MAX, u32::MAX, 2]) ); println!("doubled i64 {:?}", api::doubled_i64(&[i64::MIN, -1, 0, i64::MAX])); - let floats = api::boxed_floats(Box::new([-0.0, f64::from_bits(0x7ff8_0000_0000_0001)])); println!( "boxed floats {:?}", - floats.iter().map(|f| f.to_bits()).collect::>() + f64_bits(&api::boxed_floats(Box::new([-0.0, f64::from_bits(0x7ff8_0000_0000_0001)]))) ); let summed = api::summed([Point { x: 1, y: 2 }, Point { x: -4, y: 6 }]); let none = api::summed([]); @@ -839,7 +805,7 @@ fn main() { api::longest(["a".to_string(), "abc".to_string()]), api::longest([]) ); - let words = ["a".to_string(), "b".to_string()]; + let words: [String; 2] = ["a".to_string(), "b".to_string()]; println!("first of {:?} {:?}", api::first_of(&words), api::first_of(&[])); let limits = api::byte_limits(Bytes::from_static(b"a"), Bytes::from_static(b"bc")); let waits = api::Limits { @@ -850,28 +816,33 @@ fn main() { "limits {} {} breadth {}", String::from_utf8_lossy(&limits.low), String::from_utf8_lossy(&limits.high), - api::breadth(waits).as_millis() + millis(api::breadth(waits)) ); - let parts = [Bytes::from_static(b"ab"), Bytes::new(), Bytes::from_static(b"c")]; + let parts: [Bytes; 3] = [Bytes::from_static(b"ab"), Bytes::new(), Bytes::from_static(b"c")]; println!( "joined {} {} read {}", String::from_utf8_lossy(&api::joined(&parts)), api::joined(&[]).len(), api::read_len(&b"hello"[..]) ); - let doc: serde_json::Value = r#"{"b": [1, 2.5, null], "a": "\u00e9"}"#.parse().expect("a JSON document"); + let doc: serde_json::Value = r#"{"b": [1, 2.5, null], "a": "\u00e9"}"#.parse().unwrap(); println!("json {}", api::encode(&doc)); println!("timed text {}", api::timed_text(&doc)); println!("tagged {}", api::tagged(doc, "t")); - let entries = api::entries( - [("b", "[1]"), ("a", "2")] - .into_iter() - .map(|(key, text)| (key.to_string(), text.parse().expect("a JSON document"))) - .collect(), - "t", + println!( + "entries {}", + api::entries( + [("b", "[1]"), ("a", "2")] + .into_iter() + .map(|(key, text)| (key.to_string(), text.parse().unwrap())) + .collect(), + "t", + ) + .iter() + .map(|(key, value)| format!("{key} {value}")) + .collect::>() + .join(", ") ); - let entries: Vec = entries.iter().map(|(key, value)| format!("{key} {value}")).collect(); - println!("entries {}", entries.join(", ")); match "{\"a\":".parse::() { Ok(doc) => println!("json parse {doc}"), Err(err) => println!("json parse err {err}"), @@ -901,44 +872,43 @@ fn main() { trail.labels() ); // A filter, collected at the call. - let beyond: Vec = trail.beyond(1).map(|p| format!("{} {}", p.x, p.y)).collect(); - println!("beyond {}", beyond.join(", ")); - let numbered: Vec = api::numbered(vec!["p".to_string(), "q".to_string()]) - .map(|c| format!("{} {}", c.name(), c.get())) - .collect(); - println!("numbered {}", numbered.join(", ")); + println!( + "beyond {}", + trail.beyond(1).map(|p| format!("{} {}", p.x, p.y)).collect::>().join(", ") + ); + println!( + "numbered {}", + api::numbered(vec!["p".to_string(), "q".to_string()]) + .map(|c| format!("{} {}", c.name(), c.get())) + .collect::>() + .join(", ") + ); let (v4, v6) = api::nexts("127.0.0.1:8080".parse().unwrap(), "[::1%3]:443".parse().unwrap()); - println!("nexts {} {} {} {}", v4.ip(), v4.port(), v6.port(), v6.scope_id()); + println!("nexts {} {}", socket_hex(v4.into()), socket_hex(v6.into())); // IP addresses of each family, printed as their bytes in hex, so their length shows their // family: an IPv4-mapped IPv6 stays IPv6 through each binding, and comes back as IPv4 // only when Rust flips it. let (v4, v6) = api::next_ips("10.0.0.255".parse().unwrap(), "::ffff".parse().unwrap()); - let mapped = api::flip(std::net::Ipv4Addr::new(127, 0, 0, 1).into()); + let mapped = api::flip("127.0.0.1".parse().unwrap()); let back = api::flip(mapped); - let other = api::flip(std::net::Ipv6Addr::LOCALHOST.into()); + let other = api::flip("::1".parse().unwrap()); println!( "ips {} {} {} {} {}", - hex(&v4.octets()), - hex(&v6.octets()), + ip_hex(v4.into()), + ip_hex(v6.into()), ip_hex(mapped), ip_hex(back), ip_hex(other) ); // Lossless round trips: each type's edge values, passed through Rust and back. - let durations: Vec = [ - std::time::Duration::ZERO, - std::time::Duration::from_nanos(1), - std::time::Duration::from_nanos(i64::MAX as u64 + 1), - std::time::Duration::MAX, - ] - .into_iter() - .map(|d| { - let d = api::same_duration(d); - format!("{}.{:09}", d.as_secs(), d.subsec_nanos()) - }) - .collect(); - println!("lossless duration {}", durations.join(" ")); + println!( + "lossless duration {} {} {} {}", + seconds(api::same_duration(std::time::Duration::ZERO)), + seconds(api::same_duration(std::time::Duration::from_nanos(1))), + seconds(api::same_duration(std::time::Duration::from_nanos(i64::MAX as u64 + 1))), + seconds(api::same_duration(std::time::Duration::MAX)) + ); println!( "lossless u64 {} {} {}", api::same_u64(0), @@ -957,16 +927,18 @@ fn main() { api::same_u128(1 << 64), api::same_u128(u128::MAX) ); - let chars: Vec = ['\0', '\u{d7ff}', '\u{e000}', char::MAX] - .into_iter() - .map(|c| format!("{:x}", u32::from(api::same_char(c)))) - .collect(); - println!("lossless char {}", chars.join(" ")); - let paths: Vec = [std::path::PathBuf::from("a/é"), unspelled()] - .into_iter() - .map(|p| hex(api::same_path(p).as_os_str().as_encoded_bytes())) - .collect(); - println!("lossless path {}", paths.join(" ")); + println!( + "lossless char {:x} {:x} {:x} {:x}", + code(api::same_char('\0')), + code(api::same_char('\u{d7ff}')), + code(api::same_char('\u{e000}')), + code(api::same_char(char::MAX)) + ); + println!( + "lossless path {} {}", + path_hex(api::same_path(std::path::PathBuf::from("a/é"))), + path_hex(api::same_path(unspelled())) + ); let v4 = api::same_socket_addr_v4(std::net::SocketAddrV4::new(std::net::Ipv4Addr::BROADCAST, u16::MAX)); let v6 = api::same_socket_addr_v6(std::net::SocketAddrV6::new( std::net::Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0, 2), @@ -974,15 +946,12 @@ fn main() { u32::MAX, u32::MAX, )); - let addrs: Vec = [v4.into(), v6.into()] - .into_iter() - .map(|a| socket_hex(api::same_socket_addr(a))) - .collect(); println!( - "lossless socket {} {} {}", + "lossless socket {} {} {} {}", socket_hex(v4.into()), socket_hex(v6.into()), - addrs.join(" ") + socket_hex(api::same_socket_addr(v4.into())), + socket_hex(api::same_socket_addr(v6.into())) ); // A key hashes by Rust's `Hash`: equal keys alike, and these two apart. let (a, b) = (api::Key::new("a"), api::Key::new("b")); @@ -993,29 +962,30 @@ fn main() { ); println!( "lossless ip {} {}", - ip_hex(api::same_ip_addr(std::net::Ipv4Addr::BROADCAST.into())), - ip_hex(api::same_ip_addr( - std::net::Ipv6Addr::new(0xffff, 0, 0, 0, 0, 0, 0, 1).into() - )) + ip_hex(api::same_ip_addr("255.255.255.255".parse().unwrap())), + ip_hex(api::same_ip_addr("ffff::1".parse().unwrap())) ); // Standard and common types: serde_json's map iterator, std's instant, and tracing's // level and its filter. - let sections: Vec = api::sections( - [("b", "[1]"), ("a", "2")] - .into_iter() - .map(|(key, text)| (key.to_string(), text.parse().expect("a JSON document"))) - .collect(), - ) - .map(|(key, value)| format!("{key} {value}")) - .collect(); - println!("sections {}", sections.join(", ")); + println!( + "sections {}", + api::sections( + [("b", "[1]"), ("a", "2")] + .into_iter() + .map(|(key, text)| (key.to_string(), text.parse().unwrap())) + .collect(), + ) + .map(|(key, value)| format!("{key} {value}")) + .collect::>() + .join(", ") + ); let start = api::now(); let end = api::later(start, std::time::Duration::from_millis(1500)); println!( "instants {} {} {} {}", - api::since(end, start).as_millis(), - api::since(start, end).as_millis(), + millis(api::since(end, start)), + millis(api::since(start, end)), start == api::later(start, std::time::Duration::ZERO), start == end ); @@ -1050,9 +1020,123 @@ fn main() { let nines = api::Mark::of(9); let (front, back) = (api::seat(nines, 1), api::seat(nines, 2)); println!("seat {front:?} {} {}", front == front.clone(), front == back); - // A kept closure, called on another thread after the call that took it returned, is - // each native language's own check, since wasm32 has no thread to call it on. - // A kept closure: called again at the instant it asks for, then once its waiter wakes. + drive(); + readers(); + println!("non zeros {}", api::describe_non_zeros(api::non_zeros())); + println!( + "hop {:?} {:?} {:?}", + api::next_hop(None), + api::next_hop(Some(std::num::NonZero::new(1).unwrap())), + api::next_hop(Some(std::num::NonZero::new(u64::MAX).unwrap())) + ); + println!( + "farther hop {}", + api::farther_hop(Pair { + left: std::num::NonZero::new(3u16).unwrap(), + right: std::num::NonZero::new(u16::MAX).unwrap(), + }) + ); + // A value that is not `Send`, all on this thread: a handle to a local's count, and a + // local made from none. + let local = api::Local::new(); + let shared = api::local_or_new(Some(&local)); + let bumped = local.bump(); + println!("local {bumped} {}", shared.bump()); + println!("local fresh {}", api::local_or_new(None).bump()); + println!("local either {}", api::bump_either(None, &shared)); + local_later(&local); +} + +struct Count(AtomicUsize); + +impl Wake for Count { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::Relaxed); + } +} + +/// A channel's futures, polled by hand: what each language says with its own futures. +fn channel() { + let channel = Channel::new(); + let count = Arc::new(Count(AtomicUsize::new(0))); + let waker = Waker::from(count.clone()); + let mut cx = Context::from_waker(&waker); + { + let mut recv = pin!(channel.recv()); + let first = recv.as_mut().poll(&mut cx); + println!("recv pending {}", first.is_pending()); + channel.send(Bytes::from_static(b"hi")); + println!("woken {}", count.0.load(Ordering::Relaxed)); + if let Poll::Ready(payload) = recv.as_mut().poll(&mut cx) { + println!("recv {}", String::from_utf8_lossy(&payload)); + } + } + channel.send(Bytes::new()); + let mut recv = pin!(channel.recv_nonempty()); + match recv.as_mut().poll(&mut cx) { + Poll::Ready(Ok(payload)) => println!("nonempty {}", payload.len()), + Poll::Ready(Err(e)) => println!("nonempty err {e}"), + Poll::Pending => println!("nonempty pending"), + } + let mut filled: Vec = Vec::new(); + let mut fill4: api::Batch = api::Batch::new(); + if let Poll::Ready(v) = pin!(api::fill(&mut fill4, 9)).poll(&mut cx) { + filled.extend(v.iter().map(u32::to_string)); + } + let mut fill2 = api::pair(); + if let Poll::Ready(v) = pin!(api::fill(&mut fill2, 1)).poll(&mut cx) { + filled.extend(v.iter().map(u32::to_string)); + } + println!("fill {}", filled.join(" ")); + + // The send happens at the call: the future is dropped unpolled. + drop(channel.send_later(Bytes::from_static(b"eager"))); + let mut recv = pin!(channel.recv()); + if let Poll::Ready(payload) = recv.as_mut().poll(&mut cx) { + println!("recv {}", String::from_utf8_lossy(&payload)); + } + // The send happens at the call, and the future borrows the channel and the tag. + let mut tagged = pin!(channel.tagged("tag")); + if let Poll::Ready(text) = tagged.as_mut().poll(&mut cx) { + println!("tagged {text}"); + } + // So does a future borrowing an optional slice, which the export owns while it is pending. + let items = [1u32, 2, 3]; + let mut itemized = pin!(channel.itemized(Some(&items))); + if let Poll::Ready(count) = itemized.as_mut().poll(&mut cx) { + println!("itemized {count}"); + } + // Another crate's future borrowing its bytes, which the export owns while it is pending. + let bytes = *b"abc"; + if let Poll::Ready(len) = pin!(api::byte_len(&bytes)).poll(&mut cx) { + println!("byte_len {len}"); + } + channel.send(Bytes::from_static(b"sized")); + let mut sized = pin!(channel.recv_sized()); + if let Poll::Ready((payload, len)) = sized.as_mut().poll(&mut cx) { + println!("sized {} {len}", String::from_utf8_lossy(&payload)); + } + channel.notify(waker.clone()); + channel.send(Bytes::from_static(b"rung")); + println!("woken {}", count.0.load(Ordering::Relaxed)); + if let Poll::Ready(payload) = channel.poll_take(&Waiter::new(waker.clone())) { + println!("take {}", String::from_utf8_lossy(&payload)); + } + channel.send(Bytes::from_static(b"measured")); + if let Poll::Ready(Ok(len)) = channel.clone().poll_measure(&mut cx, 2) { + println!("measure {len}"); + } + channel.listen((), &cx); + channel.send(Bytes::from_static(b"heard")); + println!("woken {}", count.0.load(Ordering::Relaxed)); + let waiter = Waiter::new(waker.clone()); + waiter.waker().clone().wake(); + waiter.context().waker().clone().wake(); + println!("woken {}", count.0.load(Ordering::Relaxed)); +} + +/// A kept closure: called again at the instant it asks for, then once its waiter wakes. +fn drive() { let start = api::Moment::new(0, 1000).unwrap(); let mut calls = 0; let mut drive = pin!(api::drive(start, |now: api::Moment, waiter: &Waiter| { @@ -1075,6 +1159,11 @@ fn main() { } }; println!("drive {stopped}"); +} + +/// Readers each language implements: one over bytes, one whose reads fail, and a seek +/// from the start past `i64::MAX`, which reaches the reader whole, as `Cursor` takes one. +fn readers() { match api::tail(&mut std::io::Cursor::new(b"hello world"), 5) { Ok((tail, at)) => println!("tail {} {at}", String::from_utf8_lossy(&tail)), Err(err) => println!("tail error {err}"), @@ -1083,33 +1172,15 @@ fn main() { Ok((tail, at)) => println!("tail {} {at}", String::from_utf8_lossy(&tail)), Err(err) => println!("tail error {err}"), } - // A seek from the start reaches the reader whole, past `i64::MAX`, as `Cursor` takes one. match api::seek_to(&mut std::io::Cursor::new(Vec::::new()), u64::MAX) { Ok(at) => println!("sought {at}"), Err(err) => println!("sought error {err}"), } - println!("non zeros {}", api::describe_non_zeros(api::non_zeros())); - for hop in [None, Some(1), Some(u64::MAX)] { - println!( - "hop {:?}", - api::next_hop(hop.and_then(std::num::NonZero::new)).map(|h| h.get()) - ); - } - let near = std::num::NonZero::new(3u16).unwrap(); - let far = std::num::NonZero::new(u16::MAX).unwrap(); - println!( - "farther hop {}", - api::farther_hop(Pair { left: near, right: far }).get() - ); - // A value that is not `Send`, all on this thread: a handle to a local's count, and a - // local made from none. - let local = api::Local::new(); - let shared = api::local_or_new(Some(&local)); - let bumped = local.bump(); - println!("local {bumped} {}", shared.bump()); - println!("local fresh {}", api::local_or_new(None).bump()); - println!("local either {}", api::bump_either(None, &shared)); - println!("local later {}", finish(api::local_or_new_later(Some(&local))).bump()); +} + +/// Futures of a value that is not `Send`, polled on this thread until each is ready. +fn local_later(local: &api::Local) { + println!("local later {}", finish(api::local_or_new_later(Some(local))).bump()); println!("local later fresh {}", finish(api::local_or_new_later(None)).bump()); } @@ -1143,6 +1214,42 @@ fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } +/// A path's bytes as `escape_ascii` prints them. +fn escaped(path: &std::path::Path) -> String { + path.as_os_str().as_encoded_bytes().escape_ascii().to_string() +} + +/// A path's bytes in hex. +fn path_hex(path: std::path::PathBuf) -> String { + hex(path.as_os_str().as_encoded_bytes()) +} + +/// A duration as its seconds and nine digits of nanoseconds. +fn seconds(d: std::time::Duration) -> String { + format!("{}.{:09}", d.as_secs(), d.subsec_nanos()) +} + +/// A duration in whole milliseconds. +fn millis(d: std::time::Duration) -> u64 { + d.as_millis() as u64 +} + +/// A char's code point. +fn code(c: char) -> u32 { + c.into() +} + +/// The list reversed. +fn reversed(mut list: Vec<&'static dyn tls::held::Codec>) -> Vec<&'static dyn tls::held::Codec> { + list.reverse(); + list +} + +/// Each float's bits. +fn f64_bits(floats: &[f64]) -> Vec { + floats.iter().map(|f| f.to_bits()).collect() +} + /// A socket address as its IP's bytes in hex, its port, flow label, and scope, each /// IPv6's alone, apart by colons. fn socket_hex(addr: std::net::SocketAddr) -> String { @@ -1186,7 +1293,7 @@ fn numbers(what: &str, numbers: &api::Numbers) { println!("{what} some {:?}", numbers.some); } -/// A reader whose reads fail, as `tests/api.c`'s broken one does: each seek lands at 0. +/// A reader whose reads fail, as each language's broken one does: each seek lands at 0. struct Broken; impl std::io::Read for Broken { diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index bbb48737d..893445b53 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -10,6 +10,8 @@ mod shapes; #[path = "fixtures/step.rs"] mod step; +#[path = "fixtures/transcript/mod.rs"] +mod transcript; use std::env::consts::EXE_SUFFIX; use std::ffi::OsString; @@ -3849,3 +3851,13 @@ fn profiled() { "{stderr}" ); } + +#[test] +fn transcript_parses() { + let api = api(); + let t = transcript::Transcript::load( + &api.out.join("api.json"), + &manifest_dir().join("fixtures/api/examples/transcript.rs"), + ); + assert!(!t.steps.is_empty()); +} diff --git a/ffi/tests/fixtures/transcript/ir.rs b/ffi/tests/fixtures/transcript/ir.rs new file mode 100644 index 000000000..88406d380 --- /dev/null +++ b/ffi/tests/fixtures/transcript/ir.rs @@ -0,0 +1,285 @@ +//! The export's `api.json`, as far as the transcript reads it: the exporter's IR and each +//! language's name for every item. Fields the transcript does not read are skipped, so the +//! IR may grow without touching this; a change to what it reads fails to parse, loudly. + +use std::collections::BTreeMap; + +/// The export's `api.json`. +#[derive(serde::Deserialize)] +pub(crate) struct Lock { + /// Each language's name for each item, by the item's key, such as `fn api::divide`. + pub(crate) names: BTreeMap>, + pub(crate) api: Api, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Api { + pub(crate) records: Vec, + pub(crate) enums: Vec, + pub(crate) objects: Vec, + pub(crate) callbacks: Vec, + pub(crate) functions: Vec, + pub(crate) constants: Vec, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Record { + pub(crate) path: Vec, + pub(crate) args: Vec, + pub(crate) fields: Vec, + pub(crate) tuple: bool, + pub(crate) methods: Vec, + pub(crate) traits: Traits, + pub(crate) opaque: Option, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Field { + pub(crate) name: String, + pub(crate) ty: Type, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Enum { + pub(crate) path: Vec, + pub(crate) args: Vec, + pub(crate) variants: Vec, + pub(crate) methods: Vec, + pub(crate) traits: Traits, + pub(crate) foreign: bool, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Variant { + pub(crate) name: String, + pub(crate) fields: Vec, + pub(crate) tuple: bool, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Object { + pub(crate) path: Vec, + pub(crate) args: Vec, + #[serde(default = "yes")] + pub(crate) send: bool, + pub(crate) copy: bool, + pub(crate) shared: bool, + pub(crate) methods: Vec, + pub(crate) traits: Traits, + pub(crate) foreign: bool, +} + +fn yes() -> bool { + true +} + +#[derive(serde::Deserialize)] +pub(crate) struct Callback { + pub(crate) path: Vec, + pub(crate) methods: Vec, +} + +#[derive(Clone, Copy, Default, serde::Deserialize)] +pub(crate) struct Traits { + pub(crate) clone: bool, + pub(crate) eq: bool, + pub(crate) display: bool, + pub(crate) debug: bool, + pub(crate) default: bool, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Function { + pub(crate) path: Vec, + pub(crate) receiver: Option, + pub(crate) params: Vec, + pub(crate) ok: Type, + pub(crate) err: Option, + pub(crate) future: bool, + pub(crate) collect: bool, + pub(crate) lends: bool, + #[serde(default)] + pub(crate) lends_mut: bool, + pub(crate) access: Access, + pub(crate) instance: Option, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Instance { + pub(crate) named: Vec, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Access { + Call, + Field { shared: bool, set: bool }, + Const, + Parse, + Text, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Receiver { + Ref, + Mut, + Owned, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Param { + pub(crate) name: String, + pub(crate) ty: Type, +} + +#[derive(serde::Deserialize)] +pub(crate) struct Constant { + pub(crate) path: Vec, + pub(crate) value: Literal, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Literal { + Bool(bool), + Int(Int, i128), +} + +/// The IR's `Type`, and a `Result` besides, which the IR keeps apart as a function's `err`. +#[derive(Clone, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Type { + Unit, + Bool, + Int(Int), + NonZero(Int), + U128, + F32, + F64, + Char, + Str, + String, + Slice, + Vec, + Bytes, + Duration, + Array(usize), + Path, + PathBuf, + SocketAddr(Family), + IpAddr(Family), + List(Collection, Box), + Waker, + Future, + Reader, + Jni(serde_json::Value), + Option(Box), + Box(Box), + Ref(Mutability, Box), + Record(usize), + Enum(usize), + Object(usize), + Callback(usize, Dyn), + Closure(Box), + Range(Int), + Bound(Int), + Bounds(Int), + Tuple(Vec), + Const(Literal), + /// A call's value or its error: the transcript's own, never the IR's. + #[serde(skip)] + Result(Box, Box), +} + +#[derive(Clone, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) struct Closure { + pub(crate) params: Vec, + pub(crate) ok: Type, + pub(crate) err: Option, + pub(crate) kept: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Collection { + Vec, + Slice, + Box, + BTreeSet, + BTreeMap, + JsonMap, + Array(usize), + Iter, + IterRef, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Family { + Any, + V4, + V6, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Mutability { + Not, + Mut, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Dyn { + Impl, + Box, + Arc, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +pub(crate) enum Int { + U8, + U16, + U32, + U64, + Usize, + I8, + I16, + I32, + I64, + Isize, +} + +impl Int { + pub(crate) fn rust(self) -> &'static str { + match self { + Int::U8 => "u8", + Int::U16 => "u16", + Int::U32 => "u32", + Int::U64 => "u64", + Int::Usize => "usize", + Int::I8 => "i8", + Int::I16 => "i16", + Int::I32 => "i32", + Int::I64 => "i64", + Int::Isize => "isize", + } + } + + pub(crate) fn signed(self) -> bool { + matches!(self, Int::I8 | Int::I16 | Int::I32 | Int::I64 | Int::Isize) + } + + /// Its width in bits, a pointer's taken as 64. + pub(crate) fn bits(self) -> u32 { + match self { + Int::U8 | Int::I8 => 8, + Int::U16 | Int::I16 => 16, + Int::U32 | Int::I32 => 32, + _ => 64, + } + } +} + +impl Type { + /// The type behind any references and boxes. + pub(crate) fn base(&self) -> &Type { + match self { + Type::Ref(_, inner) | Type::Box(inner) => inner.base(), + ty => ty, + } + } +} diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs new file mode 100644 index 000000000..1805d2666 --- /dev/null +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -0,0 +1,1478 @@ +//! The api fixture's transcript as data: `fixtures/api/examples/transcript.rs`'s `main`, +//! a typed subset of Rust, parsed and resolved against the export's `api.json`, then +//! written as each language's script, whose output must match the native one line for line. +//! +//! The subset is what every binding can say alike: `let`, `println!`, calls of the API's +//! functions and methods, field reads and writes, `match` on a `Result` or an `Option`, +//! `for` over a literal array, which unrolls, closures, and literals of the API's types. +//! A call of a function `transcript.rs` defines itself is each language's own, hand-written +//! beside its script under the same name: what tests a language's idiom, such as its +//! futures, or prints a value no binding shapes alike, such as `hex`. Anything else is an +//! error naming its line. + +pub(crate) mod ir; +pub(crate) mod python; + +use std::collections::BTreeMap; +use std::path::Path; + +use ir::{Access, Collection, Function, Int, Mutability, Type}; +use syn::spanned::Spanned; + +/// The transcript, resolved against an export. +pub(crate) struct Transcript { + pub(crate) api: ir::Api, + names: BTreeMap>, + pub(crate) steps: Vec, + /// The functions `transcript.rs` defines, each a language's own: what each returns. + pub(crate) locals: BTreeMap, +} + +/// A statement of the script. +#[derive(Clone)] +pub(crate) enum Step { + Let(Pat, Expr), + Print(Vec), + /// An expression whose value is dropped, such as a call made for its effect. + Do(Expr), + /// `drop(name)`: the local's value drops here, not at the end of the script. + Drop(String), + /// `place.field = value`: a field's setter. + Set(Expr, Expr), + /// A `match` on a `Result` or an `Option`, `ok` on `Ok` or `Some`. + Match { + value: Expr, + ok: Arm, + err: Arm, + }, +} + +/// A `match` arm: the pattern binding the payload, if any, and the steps it runs. +#[derive(Clone)] +pub(crate) struct Arm { + pub(crate) pat: Option, + pub(crate) steps: Vec, +} + +/// What a `let`, an arm, or a closure's parameter binds. +#[derive(Clone)] +pub(crate) enum Pat { + Name(String, Type), + Tuple(Vec), + Ignore(Type), +} + +/// A piece of a `println!`. +#[derive(Clone)] +pub(crate) enum Piece { + Text(String), + Value(Expr, Spec), +} + +/// How a value prints. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Spec { + Display, + Debug, + /// `{:0Nx}`: lowercase hex, zero-padded to `N` digits. + Hex(usize), + /// `{:0N}`: decimal, zero-padded to `N` digits. + Padded(usize), +} + +/// A typed expression. +#[derive(Clone)] +pub(crate) struct Expr { + pub(crate) kind: Kind, + pub(crate) ty: Type, +} + +/// An integer literal of any width: its magnitude, and whether it is negative. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct Num { + pub(crate) negative: bool, + pub(crate) magnitude: u128, +} + +impl Num { + /// Its two's complement bits, truncated to 64. + pub(crate) fn bits(self) -> u64 { + let v = self.magnitude as u64; + if self.negative { v.wrapping_neg() } else { v } + } +} + +impl std::fmt::Display for Num { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self.negative { + true => write!(f, "-{}", self.magnitude), + false => write!(f, "{}", self.magnitude), + } + } +} + +/// What owns a function: nothing, or the type whose method it is. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Owner { + Free, + Record(usize), + Enum(usize), + Object(usize), +} + +/// A function of the API: its owner and its index there. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct FnId { + pub(crate) owner: Owner, + pub(crate) index: usize, +} + +/// A binary operator. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Op { + Eq, + Ne, + Lt, + Gt, + Add, + Sub, + Mul, + Rem, + And, +} + +#[derive(Clone)] +pub(crate) enum Kind { + Unit, + Bool(bool), + Int(Num), + /// A float's bits, an `f32`'s widened. + Float(f64), + Char(char), + Str(String), + Bytes(Vec), + None, + Some(Box), + Tuple(Vec), + /// The items of a collection, a map's as tuples of a key and its value. + List(Vec), + /// A record built from its fields, in its order. + Record(usize, Vec), + /// An enum's variant, from its fields. + Variant(usize, usize, Vec), + /// A record's `Default`, or an object's. + Default, + Var(String), + /// A constant of the IR's `constants`. + Const(usize), + /// A call: the receiver of a method taking `self`, then its arguments. + Call(FnId, Option>, Vec), + /// A record's field, by index. + Field(Box, usize), + /// A tuple's element. + Element(Box, usize), + /// `Clone::clone`. + Clone(Box), + /// `.unwrap()` of an `Option` or a `Result`, or `.expect(..)`. + Unwrap(Box), + /// `.unwrap_err()` or `.err().unwrap()` of a `Result`. + UnwrapErr(Box), + IsSome(Box), + IsNone(Box), + IsErr(Box), + Binary(Op, Box, Box), + /// A closure: its parameters, the steps it runs, and what it returns. + Closure(Vec, Vec, Box), + /// A call of a function `transcript.rs` defines, or a value of a unit struct it does, + /// each a language's own. + Local(String, Vec), +} + +impl Expr { + fn new(kind: Kind, ty: Type) -> Expr { + Expr { kind, ty } + } +} + +impl Transcript { + /// The transcript of `source`, resolved against the export's `api.json`. + pub(crate) fn load(lock: &Path, source: &Path) -> Transcript { + let lock: ir::Lock = serde_json::from_str(&std::fs::read_to_string(lock).unwrap()).unwrap(); + let text = std::fs::read_to_string(source).unwrap(); + let file = syn::parse_file(&text).unwrap_or_else(|e| panic!("{}: {e}", at(e.span()))); + let mut transcript = Transcript { + api: lock.api, + names: lock.names, + steps: Vec::new(), + locals: BTreeMap::new(), + }; + let mut main = None; + let mut units = Vec::new(); + for item in &file.items { + match item { + syn::Item::Fn(f) if f.sig.ident == "main" => main = Some(f), + syn::Item::Fn(f) => { + let ty = match &f.sig.output { + syn::ReturnType::Default => Type::Unit, + syn::ReturnType::Type(_, ty) => local_type(ty), + }; + transcript.locals.insert(f.sig.ident.to_string(), ty); + } + syn::Item::Struct(s) if matches!(s.fields, syn::Fields::Unit) => units.push(s.ident.to_string()), + _ => {} + } + } + let main = main.expect("transcript.rs has a main"); + let mut scope = Scope { + t: &transcript, + vars: Vec::new(), + units, + }; + let steps = scope.block(&main.block.stmts); + transcript.steps = steps; + transcript + } + + /// The function `id` names. + pub(crate) fn function(&self, id: FnId) -> &Function { + match id.owner { + Owner::Free => &self.api.functions[id.index], + Owner::Record(i) => &self.api.records[i].methods[id.index], + Owner::Enum(i) => &self.api.enums[i].methods[id.index], + Owner::Object(i) => &self.api.objects[i].methods[id.index], + } + } + + /// The Rust path of a type, with its arguments, as `api.json`'s names key it. + pub(crate) fn rust(&self, ty: &Type) -> String { + let named = |path: &[String], args: &[Type]| match args { + [] => path.join("::"), + args => { + let args: Vec = args.iter().map(|a| self.rust(a)).collect(); + format!("{}<{}>", path.join("::"), args.join(", ")) + } + }; + match ty { + Type::Unit => "()".to_string(), + Type::Bool => "bool".to_string(), + Type::Int(int) => int.rust().to_string(), + Type::NonZero(int) => format!("std::num::NonZero<{}>", int.rust()), + Type::F32 => "f32".to_string(), + Type::F64 => "f64".to_string(), + Type::Char => "char".to_string(), + Type::String => "String".to_string(), + Type::Bytes => "bytes::Bytes".to_string(), + Type::Duration => "std::time::Duration".to_string(), + Type::Record(i) => named(&self.api.records[*i].path, &self.api.records[*i].args), + Type::Enum(i) => named(&self.api.enums[*i].path, &self.api.enums[*i].args), + Type::Object(i) => named(&self.api.objects[*i].path, &self.api.objects[*i].args), + Type::Const(ir::Literal::Int(_, v)) => v.to_string(), + Type::Const(ir::Literal::Bool(v)) => v.to_string(), + other => panic!("no type argument is {other:?}"), + } + } + + /// The key `api.json`'s names give `id`, such as `fn api::Counter::new`. + pub(crate) fn key(&self, id: FnId) -> String { + let f = self.function(id); + let owner = match id.owner { + Owner::Free => None, + Owner::Record(i) => Some(self.rust(&Type::Record(i))), + Owner::Enum(i) => Some(self.rust(&Type::Enum(i))), + Owner::Object(i) => Some(self.rust(&Type::Object(i))), + }; + let name = f.path.last().unwrap(); + let mut path = match owner { + Some(owner) => format!("{owner}::{name}"), + None => f.path.join("::"), + }; + if let Some(instance) = &f.instance + && !instance.named.is_empty() + { + let args: Vec = instance.named.iter().map(|a| self.rust(a)).collect(); + path = format!("{path}<{}>", args.join(", ")); + } + let kind = match f.access { + Access::Field { set: false, .. } => "get", + Access::Field { set: true, .. } => "set", + _ => "fn", + }; + format!("{kind} {path}") + } + + /// `language`'s name for `id`. + pub(crate) fn name(&self, language: &str, id: FnId) -> &str { + self.named(language, &self.key(id)) + } + + /// `language`'s name for the type `ty`. + pub(crate) fn type_name(&self, language: &str, ty: &Type) -> &str { + self.named(language, &format!("type {}", self.rust(ty))) + } + + /// `language`'s name for the item `key` names, such as `const api::LIMIT`. + pub(crate) fn named(&self, language: &str, key: &str) -> &str { + let names = &self.names[language]; + if let Some(name) = names.get(key) { + return name; + } + // Swift keys an overload by its labels after the path. + let prefix = format!("{key} / "); + match names.range(prefix.clone()..).next() { + Some((k, name)) if k.starts_with(&prefix) => name, + _ => panic!("{language} names no {key}"), + } + } +} + +/// `file:line:column` of a span in `transcript.rs`. +fn at(span: proc_macro2::Span) -> String { + let start = span.start(); + format!("transcript.rs:{}:{}", start.line, start.column + 1) +} + +/// Fail at `node`'s span: a construct the subset lacks, or one the API does not have. +fn fail(node: &dyn Spanned, message: impl std::fmt::Display) -> ! { + panic!("{}: {message}", at(node.span())) +} + +/// The type of a local function's return, which only names the standard library's. +fn local_type(ty: &syn::Type) -> Type { + let syn::Type::Path(path) = ty else { + fail(ty, "a local function returns a named type") + }; + let name = path.path.segments.last().unwrap().ident.to_string(); + match name.as_str() { + "String" => Type::String, + "bool" => Type::Bool, + "u8" => Type::Int(Int::U8), + "u32" => Type::Int(Int::U32), + "u64" => Type::Int(Int::U64), + "usize" => Type::Int(Int::Usize), + "i64" => Type::Int(Int::I64), + // What a hook makes is the API's, typed where it is used. + _ => fail(ty, format!("a local function returning {name}")), + } +} + +/// A local in scope: its type, or a loop's literal, typed at each use. +enum Var { + Typed(String, Type), + Alias(String, syn::Expr), +} + +struct Scope<'t> { + t: &'t Transcript, + vars: Vec, + /// The unit structs `transcript.rs` defines: each language's own implementation. + units: Vec, +} + +impl Scope<'_> { + fn block(&mut self, stmts: &[syn::Stmt]) -> Vec { + let depth = self.vars.len(); + let mut steps = Vec::new(); + for stmt in stmts { + self.stmt(stmt, &mut steps); + } + self.vars.truncate(depth); + steps + } + + fn lookup(&self, name: &str) -> Option<&Var> { + self.vars.iter().rev().find(|v| match v { + Var::Typed(n, _) | Var::Alias(n, _) => n == name, + }) + } + + fn stmt(&mut self, stmt: &syn::Stmt, steps: &mut Vec) { + match stmt { + syn::Stmt::Local(local) => { + let Some(init) = &local.init else { + fail(local, "a let without a value") + }; + if init.diverge.is_some() { + fail(local, "a let-else"); + } + let expected = match &local.pat { + syn::Pat::Type(typed) => Some(self.annotated(&typed.ty)), + _ => None, + }; + let value = match &expected { + Some(ty) => self.check(&init.expr, ty), + None => self.infer(&init.expr), + }; + let pat = self.bind(&local.pat, &value.ty); + steps.push(Step::Let(pat, value)); + } + syn::Stmt::Macro(m) => steps.push(self.mac(&m.mac)), + syn::Stmt::Expr(expr, _) => self.expr_stmt(expr, steps), + syn::Stmt::Item(item) => fail(item, "an item inside main"), + } + } + + fn expr_stmt(&mut self, expr: &syn::Expr, steps: &mut Vec) { + match expr { + syn::Expr::Macro(m) => steps.push(self.mac(&m.mac)), + syn::Expr::ForLoop(f) => { + let syn::Expr::Array(items) = &*f.expr else { + fail(&f.expr, "a for loop over anything but an array literal") + }; + let syn::Pat::Ident(name) = &*f.pat else { + fail(&f.pat, "a for loop binding anything but a name") + }; + for item in &items.elems { + self.vars.push(Var::Alias(name.ident.to_string(), item.clone())); + let body = self.block(&f.body.stmts); + self.vars.pop(); + steps.extend(body); + } + } + syn::Expr::Match(m) => steps.push(self.matched(m)), + syn::Expr::Assign(a) => { + let place = self.infer(&a.left); + let value = self.check(&a.right, &place.ty); + steps.push(Step::Set(place, value)); + } + syn::Expr::Call(call) if path_is(&call.func, "drop") => { + let [arg] = call.args.iter().collect::>()[..] else { + fail(call, "drop of one local") + }; + let syn::Expr::Path(p) = arg else { + fail(arg, "drop of anything but a local") + }; + let name = p.path.get_ident().unwrap().to_string(); + let Some(Var::Typed(..)) = self.lookup(&name) else { + fail(arg, format!("drop of {name}, which is no local")) + }; + steps.push(Step::Drop(name)); + } + expr => steps.push(Step::Do(self.infer(expr))), + } + } + + /// A `let`'s pattern, binding its names to the parts of `ty`. + fn bind(&mut self, pat: &syn::Pat, ty: &Type) -> Pat { + match pat { + syn::Pat::Type(typed) => self.bind(&typed.pat, ty), + syn::Pat::Ident(ident) => { + let name = ident.ident.to_string(); + self.vars.push(Var::Typed(name.clone(), ty.clone())); + Pat::Name(name, ty.clone()) + } + syn::Pat::Wild(_) => Pat::Ignore(ty.clone()), + syn::Pat::Tuple(tuple) => { + let Type::Tuple(elements) = unref(ty) else { + fail(pat, format!("a tuple pattern of {ty:?}")) + }; + if elements.len() != tuple.elems.len() { + fail(pat, "a tuple pattern of another length"); + } + let elements = elements.clone(); + Pat::Tuple(tuple.elems.iter().zip(&elements).map(|(p, ty)| self.bind(p, ty)).collect()) + } + pat => fail(pat, "a pattern other than a name, `_`, or a tuple"), + } + } + + /// The type an annotation on a `let` names. + fn annotated(&self, ty: &syn::Type) -> Type { + let syn::Type::Path(path) = ty else { + fail(ty, "an annotation other than a path") + }; + let last = path.path.segments.last().unwrap(); + match last.ident.to_string().as_str() { + "Vec" if matches!(&last.arguments, syn::PathArguments::AngleBracketed(args) if matches!(args.args.first(), Some(syn::GenericArgument::Type(syn::Type::Path(p))) if p.path.is_ident("String"))) => { + Type::List(Collection::Vec, Box::new(Type::String)) + } + _ => self.type_of_path(&path.path).unwrap_or_else(|| fail(ty, "an annotation of a type the API lacks")), + } + } + + /// The API's type a path names, such as `api::Batch` or `std::net::SocketAddr`. + fn type_of_path(&self, path: &syn::Path) -> Option { + let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); + let last = names.last()?.as_str(); + let api = &self.t.api; + let matches = |p: &[String]| p.last().map(String::as_str) == Some(last) && suffix(p, &names); + let found: Vec = (api.records.iter().enumerate()) + .filter(|(_, r)| matches(&r.path)) + .map(|(i, _)| Type::Record(i)) + .chain((api.enums.iter().enumerate()).filter(|(_, e)| matches(&e.path)).map(|(i, _)| Type::Enum(i))) + .chain((api.objects.iter().enumerate()).filter(|(_, o)| matches(&o.path)).map(|(i, _)| Type::Object(i))) + .collect(); + match (found.as_slice(), last) { + ([one], _) => Some(one.clone()), + // A generic type at its default, or its one instance. + ([first, ..], _) if found.iter().all(|t| self.t.rust(t).split('<').next() == self.t.rust(first).split('<').next()) => { + let plain = found.iter().find(|t| !self.t.rust(t).contains('<')); + Some(plain.unwrap_or(first).clone()) + } + (_, "SocketAddr") => Some(Type::SocketAddr(ir::Family::Any)), + (_, "Duration") => Some(Type::Duration), + (_, "Bytes") => Some(Type::Bytes), + _ => None, + } + } + + fn mac(&mut self, mac: &syn::Macro) -> Step { + if !mac.path.is_ident("println") { + fail(mac, "a macro other than println!"); + } + let args = mac + .parse_body_with(syn::punctuated::Punctuated::::parse_terminated) + .unwrap_or_else(|e| fail(mac, e)); + let mut args = args.into_iter(); + let Some(syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(format), + .. + })) = args.next() + else { + fail(mac, "println! without a format string") + }; + let args: Vec = args.collect(); + // The arguments are parsed out of the macro's tokens, so they live as long as the + // transcript does by leaking: a test process parses one file once. + let args: &[syn::Expr] = Box::leak(args.into_boxed_slice()); + let pieces = self.format(&format, args); + Step::Print(pieces) + } + + /// The pieces of a format string and its arguments. + fn format(&mut self, lit: &syn::LitStr, args: &[syn::Expr]) -> Vec { + let text = lit.value(); + let mut pieces = Vec::new(); + let mut literal = String::new(); + let mut next = 0; + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '{' if chars.peek() == Some(&'{') => { + chars.next(); + literal.push('{'); + } + '}' if chars.peek() == Some(&'}') => { + chars.next(); + literal.push('}'); + } + '{' => { + let mut inner = String::new(); + for c in chars.by_ref() { + if c == '}' { + break; + } + inner.push(c); + } + let (name, spec) = inner.split_once(':').unwrap_or((&inner, "")); + let spec = match spec { + "" => Spec::Display, + "?" => Spec::Debug, + s if s.starts_with('0') && s.ends_with('x') => Spec::Hex(s[1..s.len() - 1].parse().unwrap()), + s if s.starts_with('0') => Spec::Padded(s[1..].parse().unwrap()), + s => fail(lit, format!("the format {s}")), + }; + let value = if name.is_empty() { + let arg = args.get(next).unwrap_or_else(|| fail(lit, "too few arguments")); + next += 1; + self.infer(arg) + } else { + let expr: &syn::Expr = Box::leak(Box::new(syn::parse_str::(name).unwrap())); + self.infer_at(expr, lit) + }; + if !literal.is_empty() { + pieces.push(Piece::Text(std::mem::take(&mut literal))); + } + pieces.push(Piece::Value(value, spec)); + } + c => literal.push(c), + } + } + if next != args.len() { + fail(lit, "too many arguments"); + } + if !literal.is_empty() { + pieces.push(Piece::Text(literal)); + } + pieces + } + + /// `infer`, failing at `at`'s span, for an expression parsed from a format string. + fn infer_at(&mut self, expr: &syn::Expr, at: &dyn Spanned) -> Expr { + let syn::Expr::Path(p) = expr else { fail(at, "an inline format argument other than a name") }; + let name = p.path.segments.last().unwrap().ident.to_string(); + if self.lookup(&name).is_none() && self.constant(&p.path).is_none() { + fail(at, format!("{name} is no local or constant")); + } + self.infer(expr) + } + + fn matched(&mut self, m: &syn::ExprMatch) -> Step { + let value = self.infer(&m.expr); + let (ok_ty, err_ty, option) = match &value.ty { + Type::Result(ok, err) => ((**ok).clone(), Some((**err).clone()), false), + Type::Option(inner) => ((**inner).clone(), None, true), + ty => fail(&m.expr, format!("a match on {ty:?}")), + }; + let mut ok = None; + let mut err = None; + for arm in &m.arms { + let (variant, inner) = match &arm.pat { + syn::Pat::TupleStruct(ts) => { + let name = ts.path.segments.last().unwrap().ident.to_string(); + let [inner] = ts.elems.iter().collect::>()[..] else { + fail(ts, "a variant of one field") + }; + (name, Some(inner)) + } + syn::Pat::Ident(i) if i.ident == "None" => ("None".to_string(), None), + syn::Pat::Path(p) if p.path.is_ident("None") => ("None".to_string(), None), + pat => fail(pat, "an arm other than Ok, Err, Some, or None"), + }; + let depth = self.vars.len(); + let (slot, ty) = match (variant.as_str(), option) { + ("Ok", false) | ("Some", true) => (&mut ok, Some(&ok_ty)), + ("Err", false) => (&mut err, err_ty.as_ref()), + ("None", true) => (&mut err, None), + _ => fail(&arm.pat, format!("{variant} in a match on {:?}", value.ty)), + }; + let pat = inner.map(|p| self.bind(p, ty.unwrap())); + let mut steps = Vec::new(); + match &*arm.body { + syn::Expr::Block(b) => { + for stmt in &b.block.stmts { + self.stmt(stmt, &mut steps); + } + } + body => self.expr_stmt(body, &mut steps), + } + self.vars.truncate(depth); + *slot = Some(Arm { pat, steps }); + } + let (Some(ok), Some(err)) = (ok, err) else { + fail(m, "a match without both arms") + }; + Step::Match { value, ok, err } + } + + fn constant(&self, path: &syn::Path) -> Option { + let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); + (self.t.api.constants.iter()).position(|c| suffix(&c.path, &names) && c.path.last() == names.last()) + } + + /// An expression whose type follows from itself. + fn infer(&mut self, expr: &syn::Expr) -> Expr { + match expr { + syn::Expr::Paren(p) => self.infer(&p.expr), + syn::Expr::Reference(r) => self.infer(&r.expr), + syn::Expr::Group(g) => self.infer(&g.expr), + syn::Expr::Path(p) => { + if let Some(name) = p.path.get_ident().map(|i| i.to_string()) { + match self.lookup(&name) { + Some(Var::Typed(_, ty)) => return Expr::new(Kind::Var(name), ty.clone()), + Some(Var::Alias(_, expr)) => { + let expr = expr.clone(); + return self.infer(&expr); + } + None => {} + } + if self.units.contains(&name) { + fail(p, format!("{name}, a value of a local type, where nothing types it")); + } + } + if let Some(c) = self.constant(&p.path) { + let ty = match self.t.api.constants[c].value { + ir::Literal::Bool(_) => Type::Bool, + ir::Literal::Int(int, _) => Type::Int(int), + }; + return Expr::new(Kind::Const(c), ty); + } + // A constant the IR keeps as a function, such as `api::BOXED`. + if let Some(id) = self.function(&p.path, None, None) { + let f = self.t.function(id); + if f.access == Access::Const { + return Expr::new(Kind::Call(id, None, Vec::new()), f.ok.clone()); + } + } + // A plain enum's variant. + if let Some(e) = self.variant(&p.path, &[]) { + return e; + } + fail(p, "a path that names no local, constant, or variant") + } + syn::Expr::Lit(lit) => match &lit.lit { + syn::Lit::Str(s) => Expr::new(Kind::Str(s.value()), Type::Ref(Mutability::Not, Box::new(Type::Str))), + syn::Lit::Bool(b) => Expr::new(Kind::Bool(b.value), Type::Bool), + syn::Lit::ByteStr(b) => Expr::new(Kind::Bytes(b.value()), Type::Ref(Mutability::Not, Box::new(Type::Slice))), + syn::Lit::Int(i) if !i.suffix().is_empty() => { + let int = int_named(i.suffix()).unwrap_or_else(|| fail(i, "an integer suffix")); + self.check(expr, &Type::Int(int)) + } + lit => fail(lit, "a literal whose type nothing gives"), + }, + syn::Expr::Call(call) => self.call(call, None), + syn::Expr::MethodCall(m) => self.method(m, None), + syn::Expr::Field(f) => self.field(f), + syn::Expr::Struct(s) => self.structure(s, None), + syn::Expr::Binary(b) => self.binary(b), + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Deref(_)) => self.infer(&u.expr), + syn::Expr::Tuple(t) => { + let elements: Vec = t.elems.iter().map(|e| self.infer(e)).collect(); + let ty = Type::Tuple(elements.iter().map(|e| e.ty.clone()).collect()); + Expr::new(Kind::Tuple(elements), ty) + } + expr => fail(expr, "an expression outside the transcript's subset"), + } + } + + /// An expression that must be of type `ty`, such as an argument: literals take their + /// type from it, and Rust's own conversions between the forms of a value, such as + /// `.to_string()` or `&`, are the value itself. + fn check(&mut self, expr: &syn::Expr, ty: &Type) -> Expr { + let base = unref(ty); + match expr { + syn::Expr::Paren(p) => return self.check(&p.expr, ty), + syn::Expr::Group(g) => return self.check(&g.expr, ty), + syn::Expr::Reference(r) => return self.check(&r.expr, ty), + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Deref(_)) => return self.check(&u.expr, ty), + // `&b"lo"[..]`: the whole slice. + syn::Expr::Index(i) if matches!(&*i.index, syn::Expr::Range(r) if r.start.is_none() && r.end.is_none()) => { + return self.check(&i.expr, ty); + } + syn::Expr::Path(p) if p.path.get_ident().is_some() => { + let name = p.path.get_ident().unwrap().to_string(); + if let Some(Var::Alias(_, alias)) = self.lookup(&name) { + let alias = alias.clone(); + return self.check(&alias, ty); + } + if self.units.contains(&name) { + return Expr::new(Kind::Local(name, Vec::new()), ty.clone()); + } + if name == "None" { + return match base { + Type::Option(_) => Expr::new(Kind::None, ty.clone()), + _ => fail(expr, format!("None as {ty:?}")), + }; + } + } + syn::Expr::Path(p) if path_is(expr, "Vec::new") || path_is(expr, "String::new") || path_is(expr, "Bytes::new") => { + let _ = p; + return self.empty(expr, ty); + } + syn::Expr::MethodCall(m) if CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() => { + return self.check(&m.receiver, ty); + } + // `[..].into_iter().map(..).collect()`, as a map's or a set's items are built. + syn::Expr::MethodCall(m) if m.method == "collect" => return self.collected(m, ty), + syn::Expr::Call(call) => { + let func = &*call.func; + let one = call.args.len() == 1; + if one && ["String::from", "Bytes::from_static", "Box::new", "PathBuf::from", "Path::new", "Bytes::from"].iter().any(|p| path_is(func, p)) { + return self.check(&call.args[0], ty); + } + if one && path_is(func, "Some") { + let Type::Option(inner) = base else { + fail(expr, format!("Some as {ty:?}")) + }; + let inner = (**inner).clone(); + let value = self.check(&call.args[0], &inner); + return Expr::new(Kind::Some(Box::new(value)), ty.clone()); + } + if call.args.is_empty() && (path_is(func, "Default::default") || path_is(func, "Box::default")) { + return self.empty(expr, ty); + } + if let syn::Expr::Path(p) = func + && let Some(name) = p.path.get_ident() + && self.t.locals.contains_key(&name.to_string()) + { + let args = call.args.iter().map(|a| self.infer(a)).collect(); + return Expr::new(Kind::Local(name.to_string(), args), ty.clone()); + } + return self.call(call, Some(ty)); + } + syn::Expr::Macro(m) if m.mac.path.is_ident("vec") => { + let items = m + .mac + .parse_body_with(syn::punctuated::Punctuated::::parse_terminated) + .unwrap_or_else(|e| fail(m, e)); + let items: &[syn::Expr] = Box::leak(items.into_iter().collect::>().into_boxed_slice()); + return self.items(expr, items.iter(), ty); + } + syn::Expr::Array(a) => return self.items(expr, a.elems.iter(), ty), + syn::Expr::Lit(lit) => return self.literal(lit, ty), + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => { + if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. }) = &*u.expr { + let mut e = self.literal(&syn::ExprLit { attrs: Vec::new(), lit: syn::Lit::Int((*i).clone()) }, ty); + if let Kind::Int(n) = &mut e.kind { + n.negative = true; + } + if let Kind::Float(f) = &mut e.kind { + *f = -*f; + } + return e; + } + } + syn::Expr::Tuple(t) => { + let Type::Tuple(elements) = base else { + fail(expr, format!("a tuple as {ty:?}")) + }; + if elements.len() != t.elems.len() { + fail(expr, "a tuple of another length"); + } + let elements = elements.clone(); + let values = t.elems.iter().zip(&elements).map(|(e, ty)| self.check(e, ty)).collect(); + return Expr::new(Kind::Tuple(values), ty.clone()); + } + syn::Expr::Range(r) => return self.range(r, ty), + syn::Expr::Closure(c) => return self.closure(c, ty), + syn::Expr::Struct(s) => return self.structure(s, Some(ty)), + syn::Expr::MethodCall(m) => return self.method(m, Some(ty)), + _ => {} + } + let value = self.infer(expr); + if !fits(&value.ty, ty) { + fail(expr, format!("{:?} where {ty:?} is taken", value.ty)); + } + value + } + + /// An empty collection, string, or a type's default. + fn empty(&mut self, expr: &syn::Expr, ty: &Type) -> Expr { + match unref(ty) { + Type::String | Type::Str => Expr::new(Kind::Str(String::new()), ty.clone()), + Type::Bytes | Type::Vec | Type::Slice => Expr::new(Kind::Bytes(Vec::new()), ty.clone()), + Type::List(..) => Expr::new(Kind::List(Vec::new()), ty.clone()), + Type::Box(inner) if matches!(**inner, Type::List(..)) => Expr::new(Kind::List(Vec::new()), ty.clone()), + Type::Option(_) => Expr::new(Kind::None, ty.clone()), + Type::Record(_) | Type::Object(_) => Expr::new(Kind::Default, ty.clone()), + other => fail(expr, format!("an empty {other:?}")), + } + } + + /// The items of a list literal, as a list of `ty` or its bytes. + fn items<'e>(&mut self, expr: &syn::Expr, items: impl Iterator, ty: &Type) -> Expr { + match unref(ty) { + Type::List(_, item) => { + let item = (**item).clone(); + let items = items.map(|e| self.check(e, &item)).collect(); + Expr::new(Kind::List(items), ty.clone()) + } + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => { + let bytes = items + .map(|e| match self.check(e, &Type::Int(Int::U8)).kind { + Kind::Int(n) => n.magnitude as u8, + _ => fail(e, "a byte other than a literal"), + }) + .collect(); + Expr::new(Kind::Bytes(bytes), ty.clone()) + } + other => fail(expr, format!("a list as {other:?}")), + } + } + + /// `items.into_iter().map(..).collect()` as `ty`: the items, each mapped. + fn collected(&mut self, m: &syn::ExprMethodCall, ty: &Type) -> Expr { + let mut receiver = &*m.receiver; + let mut map = None; + loop { + match receiver { + syn::Expr::MethodCall(inner) if CONVERSIONS.contains(&inner.method.to_string().as_str()) || inner.method == "into_iter" => { + receiver = &inner.receiver; + } + syn::Expr::MethodCall(inner) if inner.method == "map" && map.is_none() => { + map = Some(&inner.args[0]); + receiver = &inner.receiver; + } + _ => break, + } + } + let syn::Expr::Array(array) = receiver else { + fail(m, "a collect of anything but an array literal") + }; + let Type::List(_, item) = unref(ty) else { + fail(m, format!("a collect as {ty:?}")) + }; + let item = (**item).clone(); + let Some(map) = map else { + return self.items(receiver, array.elems.iter(), ty); + }; + // The map is a closure of a tuple pattern: each item, bound by it, is its body. + let syn::Expr::Closure(closure) = map else { + fail(map, "a map of anything but a closure") + }; + let [syn::Pat::Tuple(pat)] = closure.inputs.iter().collect::>()[..] else { + fail(closure, "a map's closure of one tuple pattern") + }; + let items = array + .elems + .iter() + .map(|element| { + let syn::Expr::Tuple(values) = element else { + fail(element, "an item other than a tuple") + }; + let depth = self.vars.len(); + for (p, value) in pat.elems.iter().zip(&values.elems) { + let syn::Pat::Ident(name) = p else { fail(p, "a name") }; + self.vars.push(Var::Alias(name.ident.to_string(), value.clone())); + } + let value = self.check(&closure.body, &item); + self.vars.truncate(depth); + value + }) + .collect(); + Expr::new(Kind::List(items), ty.clone()) + } + + fn literal(&mut self, lit: &syn::ExprLit, ty: &Type) -> Expr { + let base = unref(ty); + match (&lit.lit, base) { + (syn::Lit::Str(s), Type::Str | Type::String | Type::Path | Type::PathBuf) => Expr::new(Kind::Str(s.value()), ty.clone()), + (syn::Lit::ByteStr(b), Type::Slice | Type::Vec | Type::Bytes | Type::Array(_)) => Expr::new(Kind::Bytes(b.value()), ty.clone()), + (syn::Lit::Byte(b), Type::Int(Int::U8)) => Expr::new(Kind::Int(Num { negative: false, magnitude: b.value().into() }), ty.clone()), + (syn::Lit::Bool(b), Type::Bool) => Expr::new(Kind::Bool(b.value), ty.clone()), + (syn::Lit::Char(c), Type::Char) => Expr::new(Kind::Char(c.value()), ty.clone()), + (syn::Lit::Int(i), Type::Int(_) | Type::U128 | Type::NonZero(_)) => { + let magnitude: u128 = i.base10_parse().unwrap_or_else(|e| fail(i, e)); + Expr::new(Kind::Int(Num { negative: false, magnitude }), ty.clone()) + } + (syn::Lit::Float(f), Type::F32 | Type::F64) => Expr::new(Kind::Float(f.base10_parse().unwrap_or_else(|e| fail(f, e))), ty.clone()), + (syn::Lit::Int(i), Type::F32 | Type::F64) => Expr::new(Kind::Float(i.base10_parse().unwrap_or_else(|e| fail(i, e))), ty.clone()), + (lit, _) => fail(lit, format!("this literal as {ty:?}")), + } + } + + fn range(&mut self, r: &syn::ExprRange, ty: &Type) -> Expr { + match unref(ty) { + Type::Range(int) => { + let int = Type::Int(*int); + let (Some(start), Some(end)) = (&r.start, &r.end) else { + fail(r, "a Range without both ends") + }; + if matches!(r.limits, syn::RangeLimits::Closed(_)) { + fail(r, "an inclusive range as a Range"); + } + let elements = vec![self.check(start, &int), self.check(end, &int)]; + Expr::new(Kind::Tuple(elements), ty.clone()) + } + Type::Bounds(int) => { + // The start and end bounds, each a `Bound`'s variant. + let int = *int; + let bound = |s: &mut Self, e: Option<&syn::Expr>, kind: &str| -> Expr { + let ty = Type::Bound(int); + match e { + None => Expr::new(Kind::Str("Unbounded".to_string()), ty), + Some(e) => { + let v = s.check(e, &Type::Int(int)); + Expr::new(Kind::Tuple(vec![Expr::new(Kind::Str(kind.to_string()), Type::Str), v]), ty) + } + } + }; + let end_kind = match r.limits { + syn::RangeLimits::HalfOpen(_) => "Excluded", + syn::RangeLimits::Closed(_) => "Included", + }; + let start = bound(self, r.start.as_deref(), "Included"); + let end = bound(self, r.end.as_deref(), end_kind); + Expr::new(Kind::Tuple(vec![start, end]), ty.clone()) + } + other => fail(r, format!("a range as {other:?}")), + } + } + + fn closure(&mut self, c: &syn::ExprClosure, ty: &Type) -> Expr { + let Type::Closure(closure) = unref(ty) else { + fail(c, format!("a closure as {ty:?}")) + }; + let closure = (**closure).clone(); + if closure.params.len() != c.inputs.len() { + fail(c, "a closure of another arity"); + } + let depth = self.vars.len(); + let params = c.inputs.iter().zip(&closure.params).map(|(p, ty)| self.bind(p, ty)).collect(); + let mut steps = Vec::new(); + let value = match &*c.body { + syn::Expr::Block(b) => { + let (last, init) = b.block.stmts.split_last().unwrap_or_else(|| fail(b, "an empty closure")); + for stmt in init { + self.stmt(stmt, &mut steps); + } + match last { + syn::Stmt::Expr(e, None) => self.check(e, &closure.ok), + stmt => { + self.stmt(stmt, &mut steps); + Expr::new(Kind::Unit, Type::Unit) + } + } + } + syn::Expr::Macro(m) => { + steps.push(self.mac(&m.mac)); + Expr::new(Kind::Unit, Type::Unit) + } + body => self.check(body, &closure.ok), + }; + self.vars.truncate(depth); + Expr::new(Kind::Closure(params, steps, Box::new(value)), ty.clone()) + } + + fn binary(&mut self, b: &syn::ExprBinary) -> Expr { + let op = match b.op { + syn::BinOp::Eq(_) => Op::Eq, + syn::BinOp::Ne(_) => Op::Ne, + syn::BinOp::Lt(_) => Op::Lt, + syn::BinOp::Gt(_) => Op::Gt, + syn::BinOp::Add(_) => Op::Add, + syn::BinOp::Sub(_) => Op::Sub, + syn::BinOp::Mul(_) => Op::Mul, + syn::BinOp::Rem(_) => Op::Rem, + syn::BinOp::And(_) => Op::And, + _ => fail(b, "this operator"), + }; + // The side whose type follows from itself types the other. + let (left, right) = match literalish(&b.left) { + false => { + let left = self.infer(&b.left); + let right = self.check(&b.right, &left.ty.clone()); + (left, right) + } + true => { + let right = self.infer(&b.right); + let left = self.check(&b.left, &right.ty.clone()); + (left, right) + } + }; + let ty = match op { + Op::Eq | Op::Ne | Op::Lt | Op::Gt | Op::And => Type::Bool, + _ => unref(&left.ty).clone(), + }; + Expr::new(Kind::Binary(op, Box::new(left), Box::new(right)), ty) + } + + fn field(&mut self, f: &syn::ExprField) -> Expr { + let base = self.infer(&f.base); + match &f.member { + syn::Member::Unnamed(i) => { + let Type::Tuple(elements) = unref(&base.ty) else { + fail(f, format!("an element of {:?}", base.ty)) + }; + let ty = elements.get(i.index as usize).unwrap_or_else(|| fail(f, "no such element")).clone(); + Expr::new(Kind::Element(Box::new(base), i.index as usize), ty) + } + syn::Member::Named(name) => { + let name = name.to_string(); + let owner = unref(&base.ty).clone(); + if let Type::Record(r) = owner + && let Some(i) = self.t.api.records[r].fields.iter().position(|f| f.name == name) + { + let ty = self.t.api.records[r].fields[i].ty.clone(); + return Expr::new(Kind::Field(Box::new(base), i), ty); + } + // A getter: an object's field, or an opaque value's. + let id = self.method_of(&owner, &name, |f| matches!(f.access, Access::Field { set: false, .. })); + let Some(id) = id else { + fail(f, format!("no field {name} on {owner:?}")) + }; + let ty = self.t.function(id).ok.clone(); + Expr::new(Kind::Call(id, Some(Box::new(base)), Vec::new()), ty) + } + } + } + + /// The method `name` of `owner`'s type for which `which` holds. + fn method_of(&self, owner: &Type, name: &str, which: impl Fn(&Function) -> bool) -> Option { + let (owner, methods) = match unref(owner) { + Type::Record(i) => (Owner::Record(*i), &self.t.api.records[*i].methods), + Type::Enum(i) => (Owner::Enum(*i), &self.t.api.enums[*i].methods), + Type::Object(i) => (Owner::Object(*i), &self.t.api.objects[*i].methods), + _ => return None, + }; + let index = methods.iter().position(|f| f.path.last().map(String::as_str) == Some(name) && which(f))?; + Some(FnId { owner, index }) + } + + /// A struct literal: a record's, or an enum's struct variant's. + fn structure(&mut self, s: &syn::ExprStruct, ty: Option<&Type>) -> Expr { + if let Some(e) = self.variant_struct(s) { + return e; + } + let named = self.type_of_path(&s.path); + // A generic record's instance: the one the expected type names, else the one whose + // fields the literal's types fit. + let candidates: Vec = match (ty.map(unref), &named) { + (Some(Type::Record(i)), _) => vec![*i], + (_, Some(Type::Record(i))) => { + let base = self.t.api.records[*i].path.clone(); + (0..self.t.api.records.len()).filter(|r| self.t.api.records[*r].path == base).collect() + } + _ => fail(s, "a struct literal of no record"), + }; + for (n, r) in candidates.iter().enumerate() { + let record = &self.t.api.records[*r]; + let fields: Vec<(String, Type)> = record.fields.iter().map(|f| (f.name.clone(), f.ty.clone())).collect(); + if fields.len() != s.fields.len() { + fail(s, "a record literal without each field"); + } + // Try each instance in turn, keeping the first whose fields all fit. + let last = n + 1 == candidates.len(); + let fits_all = last + || s.fields.iter().all(|fv| { + let syn::Member::Named(name) = &fv.member else { return false }; + let Some((_, ty)) = fields.iter().find(|(n, _)| name == n) else { return false }; + self.fits_expr(&fv.expr, ty) + }); + if !fits_all { + continue; + } + let mut values = Vec::new(); + for (name, ty) in &fields { + let fv = s + .fields + .iter() + .find(|fv| matches!(&fv.member, syn::Member::Named(n) if n == name)) + .unwrap_or_else(|| fail(s, format!("no field {name}"))); + values.push(self.check(&fv.expr, ty)); + } + return Expr::new(Kind::Record(*r, values), Type::Record(*r)); + } + fail(s, "a record literal fitting no instance") + } + + /// Whether `expr` may be of type `ty`, judged by what it plainly is without checking it: + /// a local's type, a struct literal's, or a suffixed literal's. What it cannot judge fits. + fn fits_expr(&self, expr: &syn::Expr, ty: &Type) -> bool { + let guess = match expr { + syn::Expr::Reference(r) => return self.fits_expr(&r.expr, ty), + syn::Expr::Paren(p) => return self.fits_expr(&p.expr, ty), + syn::Expr::Path(p) => match p.path.get_ident().and_then(|i| self.lookup(&i.to_string())) { + Some(Var::Typed(_, ty)) => Some(ty.clone()), + Some(Var::Alias(_, expr)) => return self.fits_expr(&expr.clone(), ty), + None => None, + }, + syn::Expr::Struct(s) => self.type_of_path(&s.path), + syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. }) if !i.suffix().is_empty() => int_named(i.suffix()).map(Type::Int), + _ => None, + }; + match (guess, unref(ty)) { + (None, _) => true, + // A generic record's literal names its type but not the instance. + (Some(Type::Record(a)), Type::Record(b)) => self.t.api.records[a].path == self.t.api.records[*b].path, + (Some(have), want) => fits(&have, want), + } + } + + fn variant_struct(&mut self, s: &syn::ExprStruct) -> Option { + let (e, v) = self.find_variant(&s.path)?; + let fields: Vec<(String, Type)> = + (self.t.api.enums[e].variants[v].fields.iter()).map(|f| (f.name.clone(), f.ty.clone())).collect(); + let values = fields + .iter() + .map(|(name, ty)| { + let fv = s + .fields + .iter() + .find(|fv| matches!(&fv.member, syn::Member::Named(n) if n == name)) + .unwrap_or_else(|| fail(s, format!("no field {name}"))); + self.check(&fv.expr, ty) + }) + .collect(); + Some(Expr::new(Kind::Variant(e, v, values), Type::Enum(e))) + } + + fn find_variant(&self, path: &syn::Path) -> Option<(usize, usize)> { + let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); + let (variant, enum_path) = names.split_last()?; + if enum_path.is_empty() { + return None; + } + let e = (self.t.api.enums.iter()).position(|e| e.path.last() == enum_path.last() && suffix(&e.path, enum_path))?; + let v = self.t.api.enums[e].variants.iter().position(|v| &v.name == variant)?; + Some((e, v)) + } + + /// A unit variant at `path`, or a tuple variant of `args`. + fn variant(&mut self, path: &syn::Path, args: &[syn::Expr]) -> Option { + let (e, v) = self.find_variant(path)?; + let fields: Vec = self.t.api.enums[e].variants[v].fields.iter().map(|f| f.ty.clone()).collect(); + if fields.len() != args.len() { + fail(path, "a variant of another arity"); + } + let values = args.iter().zip(&fields).map(|(a, ty)| self.check(a, ty)).collect(); + Some(Expr::new(Kind::Variant(e, v, values), Type::Enum(e))) + } + + /// A free function or associated function at `path`, whose instance, for a generic one, + /// is the one `turbofish` names or else the first whose parameters `args` fit. + fn function(&mut self, path: &syn::Path, args: Option<&[syn::Expr]>, expected: Option<&Type>) -> Option { + let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); + let (name, owner_path) = names.split_last()?; + let api = &self.t.api; + let mut candidates: Vec = Vec::new(); + for (i, f) in api.functions.iter().enumerate() { + if f.path.last() == Some(name) && suffix(&f.path, &names) { + candidates.push(FnId { owner: Owner::Free, index: i }); + } + } + if !owner_path.is_empty() { + let owned = |p: &[String]| p.last() == owner_path.last() && suffix(p, owner_path); + for (i, r) in api.records.iter().enumerate() { + if owned(&r.path) { + for (j, f) in r.methods.iter().enumerate() { + if f.path.last() == Some(name) && f.receiver.is_none() { + candidates.push(FnId { owner: Owner::Record(i), index: j }); + } + } + } + } + for (i, o) in api.objects.iter().enumerate() { + if owned(&o.path) { + for (j, f) in o.methods.iter().enumerate() { + if f.path.last() == Some(name) && f.receiver.is_none() { + candidates.push(FnId { owner: Owner::Object(i), index: j }); + } + } + } + } + for (i, e) in api.enums.iter().enumerate() { + if owned(&e.path) { + for (j, f) in e.methods.iter().enumerate() { + if f.path.last() == Some(name) && f.receiver.is_none() { + candidates.push(FnId { owner: Owner::Enum(i), index: j }); + } + } + } + } + } + // The turbofish's arguments narrow the instances. + let turbofish: Vec = path + .segments + .iter() + .filter_map(|s| match &s.arguments { + syn::PathArguments::AngleBracketed(a) => Some(a), + _ => None, + }) + .flat_map(|a| &a.args) + .filter_map(|a| match a { + syn::GenericArgument::Type(syn::Type::Path(p)) => self.type_of_path(&p.path).or_else(|| int_named(&p.path.get_ident()?.to_string()).map(Type::Int)), + _ => None, + }) + .collect(); + self.pick(path, candidates, args, expected, &turbofish) + } + + /// The candidate whose parameters `args` fit and whose return `expected` fits. + fn pick(&mut self, at: &dyn Spanned, candidates: Vec, args: Option<&[syn::Expr]>, expected: Option<&Type>, turbofish: &[Type]) -> Option { + let candidates: Vec = candidates + .into_iter() + .filter(|id| { + let f = self.t.function(*id); + let instance = f.instance.as_ref().map(|i| i.named.as_slice()).unwrap_or(&[]); + turbofish.iter().all(|t| instance.contains(t)) + && args.is_none_or(|a| a.len() == f.params.len()) + && expected.is_none_or(|e| fits(&f.ok, e) || f.err.is_some()) + }) + .collect(); + if candidates.len() <= 1 { + return candidates.first().copied(); + } + let Some(args) = args else { + fail(at, "an ambiguous function") + }; + let fitting: Vec = candidates + .iter() + .copied() + .filter(|id| { + let params: Vec = self.t.function(*id).params.iter().map(|p| p.ty.clone()).collect(); + args.iter().zip(¶ms).all(|(a, ty)| self.fits_expr(a, ty)) + }) + .collect(); + match fitting.as_slice() { + [one] => Some(*one), + [] => fail(at, "no instance fits these arguments"), + // Instances alike in every parameter: the first, as Rust's inference would pick + // no other for the same arguments. + [first, ..] => Some(*first), + } + } + + /// A call of a path: the API's function, a variant, `Some`, or a local function. + fn call(&mut self, call: &syn::ExprCall, expected: Option<&Type>) -> Expr { + let syn::Expr::Path(p) = &*call.func else { + fail(call, "a call of anything but a path") + }; + let args: Vec = call.args.iter().cloned().collect(); + let args: &[syn::Expr] = Box::leak(args.into_boxed_slice()); + if let Some(name) = p.path.get_ident().map(|i| i.to_string()) + && let Some(ty) = self.t.locals.get(&name) + { + let ty = ty.clone(); + let args = args.iter().map(|a| self.infer(a)).collect(); + return Expr::new(Kind::Local(name, args), ty); + } + if let Some(e) = self.variant(&p.path, args) { + return e; + } + let Some(id) = self.function(&p.path, Some(args), expected) else { + fail(call, "a call of no function the API exports") + }; + self.apply(call, id, None, args) + } + + /// The call of `id` on `receiver`, with `args` checked against its parameters. + fn apply(&mut self, at: &dyn Spanned, id: FnId, receiver: Option, args: &[syn::Expr]) -> Expr { + let params: Vec = self.t.function(id).params.iter().map(|p| p.ty.clone()).collect(); + if params.len() != args.len() { + fail(at, format!("{} takes {} arguments", self.t.key(id), params.len())); + } + let args = args.iter().zip(¶ms).map(|(a, ty)| self.check(a, ty)).collect(); + let f = self.t.function(id); + let ty = match &f.err { + Some(err) => Type::Result(Box::new(f.ok.clone()), Box::new(err.clone())), + None => f.ok.clone(), + }; + Expr::new(Kind::Call(id, receiver.map(Box::new), args), ty) + } + + fn method(&mut self, m: &syn::ExprMethodCall, expected: Option<&Type>) -> Expr { + let name = m.method.to_string(); + let args: Vec = m.args.iter().cloned().collect(); + let args: &[syn::Expr] = Box::leak(args.into_boxed_slice()); + let receiver = self.infer(&m.receiver); + let rty = unref(&receiver.ty).clone(); + let only = |s: &Self, kind: fn(Box) -> Kind, ty: Type| { + if !args.is_empty() { + fail(m, format!("{name} with arguments")); + } + let _ = s; + Expr::new(kind(Box::new(receiver.clone())), ty) + }; + match (name.as_str(), &rty) { + ("unwrap" | "expect", Type::Option(inner) | Type::Result(inner, _)) => { + let inner = (**inner).clone(); + return Expr::new(Kind::Unwrap(Box::new(receiver)), inner); + } + ("unwrap_err", Type::Result(_, err)) => { + let err = (**err).clone(); + return only(self, Kind::UnwrapErr, err); + } + ("is_some", Type::Option(_)) => return only(self, Kind::IsSome, Type::Bool), + ("is_none", Type::Option(_)) => return only(self, Kind::IsNone, Type::Bool), + ("is_err", Type::Result(..)) => return only(self, Kind::IsErr, Type::Bool), + ("err", Type::Result(_, err)) => { + // `.err().unwrap()`, the only use the subset has. + let err = (**err).clone(); + return Expr::new(Kind::UnwrapErr(Box::new(receiver)), Type::Option(Box::new(err))); + } + ("clone", _) if args.is_empty() => { + let ty = receiver.ty.clone(); + return Expr::new(Kind::Clone(Box::new(receiver)), ty); + } + (conversion, _) if CONVERSIONS.contains(&conversion) && args.is_empty() => { + // `.into()` of a value to the type the binding returns it as already. + let _ = expected; + return receiver; + } + _ => {} + } + let id = self.method_of(&rty, &name, |f| f.receiver.is_some() && f.access == Access::Call); + let id = match id { + Some(id) => id, + None => { + // A generic method's instances. + let candidates = self.methods_named(&rty, &name); + let turbofish: Vec = (m.turbofish.iter().flat_map(|t| &t.args)) + .filter_map(|a| match a { + syn::GenericArgument::Type(syn::Type::Path(p)) => self.type_of_path(&p.path), + _ => None, + }) + .collect(); + self.pick(m, candidates, Some(args), expected, &turbofish) + .unwrap_or_else(|| fail(m, format!("no method {name} on {}", self.describe(&rty)))) + } + }; + self.apply(m, id, Some(receiver), args) + } + + fn methods_named(&self, owner: &Type, name: &str) -> Vec { + let (owner, methods) = match unref(owner) { + Type::Record(i) => (Owner::Record(*i), &self.t.api.records[*i].methods), + Type::Enum(i) => (Owner::Enum(*i), &self.t.api.enums[*i].methods), + Type::Object(i) => (Owner::Object(*i), &self.t.api.objects[*i].methods), + _ => return Vec::new(), + }; + (methods.iter().enumerate()) + .filter(|(_, f)| f.path.last().map(String::as_str) == Some(name) && f.receiver.is_some() && f.access == Access::Call) + .map(|(index, _)| FnId { owner, index }) + .collect() + } + + fn describe(&self, ty: &Type) -> String { + match ty { + Type::Record(_) | Type::Enum(_) | Type::Object(_) => self.t.rust(ty), + ty => format!("{ty:?}"), + } + } +} + +/// Conversions that leave a value as the binding has it. +const CONVERSIONS: &[&str] = &["to_string", "to_vec", "to_owned", "into", "as_str", "as_ref", "as_slice", "as_deref"]; + +/// Whether `path`'s segments end with `names`' segments, ignoring the `api` crate's root. +fn suffix(path: &[String], names: &[String]) -> bool { + let names: Vec<&String> = names.iter().filter(|n| *n != "api").collect(); + names.len() <= path.len() && path[path.len() - names.len()..].iter().zip(&names).all(|(a, b)| a == *b) +} + +/// Whether `expr` is the path `path`, such as `String::from`. +fn path_is(expr: &syn::Expr, path: &str) -> bool { + let syn::Expr::Path(p) = expr else { return false }; + let names: Vec = p.path.segments.iter().map(|s| s.ident.to_string()).collect(); + let want: Vec<&str> = path.split("::").collect(); + names.len() >= want.len() && names[names.len() - want.len()..].iter().zip(&want).all(|(a, b)| a == b) +} + +/// Whether `expr` takes its type from the other side of an operator, as a literal does. +fn literalish(expr: &syn::Expr) -> bool { + match expr { + syn::Expr::Lit(_) => true, + syn::Expr::Unary(u) => literalish(&u.expr), + syn::Expr::Paren(p) => literalish(&p.expr), + _ => false, + } +} + +fn int_named(name: &str) -> Option { + Some(match name { + "u8" => Int::U8, + "u16" => Int::U16, + "u32" => Int::U32, + "u64" => Int::U64, + "usize" => Int::Usize, + "i8" => Int::I8, + "i16" => Int::I16, + "i32" => Int::I32, + "i64" => Int::I64, + "isize" => Int::Isize, + _ => return None, + }) +} + +/// `ty` behind any references. +pub(crate) fn unref(ty: &Type) -> &Type { + match ty { + Type::Ref(_, inner) => unref(inner), + ty => ty, + } +} + +/// Whether a value of `have` passes where `want` is taken: the same type, behind any +/// references or boxes, or a string or bytes in any of their forms. +fn fits(have: &Type, want: &Type) -> bool { + let (have, want) = (have.base(), want.base()); + let text = |t: &Type| matches!(t, Type::Str | Type::String); + let bytes = |t: &Type| matches!(t, Type::Slice | Type::Vec | Type::Bytes); + let path = |t: &Type| matches!(t, Type::Path | Type::PathBuf); + match (have, want) { + (Type::Option(a), Type::Option(b)) => fits(a, b), + (Type::List(_, a), Type::List(_, b)) => fits(a, b), + (Type::Tuple(a), Type::Tuple(b)) => a.len() == b.len() && a.iter().zip(b).all(|(a, b)| fits(a, b)), + (a, b) => a == b || (text(a) && text(b)) || (bytes(a) && bytes(b)) || (path(a) && path(b)), + } +} diff --git a/ffi/tests/fixtures/transcript/python.rs b/ffi/tests/fixtures/transcript/python.rs new file mode 100644 index 000000000..180e4b00d --- /dev/null +++ b/ffi/tests/fixtures/transcript/python.rs @@ -0,0 +1 @@ +//! The Python script. From de6da768a074df81b363db88d7e9c5781c250c92 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 03:19:58 -0800 Subject: [PATCH 03/28] wip: type the whole transcript --- ffi/fixtures/api/examples/transcript.rs | 9 +- ffi/tests/fixtures/transcript/mod.rs | 1290 ++---------------- ffi/tests/fixtures/transcript/parse.rs | 1649 +++++++++++++++++++++++ 3 files changed, 1738 insertions(+), 1210 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/parse.rs diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 77fae4fc6..0939016b7 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -438,10 +438,9 @@ fn main() { channel(); - let list = Node { - value: 1, - next: Some(Box::new(Node { value: 2, next: None })), - }; + // A recursive type is an object, made by its functions. + let mut list = Node::new(1, None); + list.push(2); println!("node {}", list.sum()); let tally = Tally::new(); @@ -541,7 +540,7 @@ fn main() { let five = Point { x: 5, y: 2 }; println!( "kept or {} {} keeper {}", - api::kept_or(five), + api::kept_or::(Some(five)), api::kept_or::(None), api::keeper(five) ); diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 1805d2666..76b496f43 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -1,31 +1,30 @@ //! The api fixture's transcript as data: `fixtures/api/examples/transcript.rs`'s `main`, -//! a typed subset of Rust, parsed and resolved against the export's `api.json`, then +//! a typed subset of Rust, read and resolved against the export's `api.json`, then //! written as each language's script, whose output must match the native one line for line. //! -//! The subset is what every binding can say alike: `let`, `println!`, calls of the API's -//! functions and methods, field reads and writes, `match` on a `Result` or an `Option`, -//! `for` over a literal array, which unrolls, closures, and literals of the API's types. -//! A call of a function `transcript.rs` defines itself is each language's own, hand-written -//! beside its script under the same name: what tests a language's idiom, such as its -//! futures, or prints a value no binding shapes alike, such as `hex`. Anything else is an -//! error naming its line. +//! The subset is what every binding can say alike: `let`, `println!` and `format!`, calls +//! of the API's functions and methods, field reads and writes, `match` on a `Result` or an +//! `Option`, `for` over an array literal, which unrolls, closures, `.map(..).collect()` +//! joined into a string, and literals of the API's types and of the standard library's it +//! maps. A call of a function `transcript.rs` defines itself is each language's own, +//! hand-written beside its script under the same name: what tests a language's idiom, such +//! as its futures, or prints a value no binding shapes alike, such as `hex`. Anything else +//! fails, naming its line. pub(crate) mod ir; +mod parse; pub(crate) mod python; use std::collections::BTreeMap; use std::path::Path; -use ir::{Access, Collection, Function, Int, Mutability, Type}; -use syn::spanned::Spanned; +use ir::{Access, Function, Type}; /// The transcript, resolved against an export. pub(crate) struct Transcript { pub(crate) api: ir::Api, names: BTreeMap>, pub(crate) steps: Vec, - /// The functions `transcript.rs` defines, each a language's own: what each returns. - pub(crate) locals: BTreeMap, } /// A statement of the script. @@ -33,18 +32,13 @@ pub(crate) struct Transcript { pub(crate) enum Step { Let(Pat, Expr), Print(Vec), - /// An expression whose value is dropped, such as a call made for its effect. + /// An expression whose value is dropped, such as a call made for its effect, a setter's + /// included. Do(Expr), - /// `drop(name)`: the local's value drops here, not at the end of the script. + /// `drop(name)`: the local's value drops here, not at the end of its scope. Drop(String), - /// `place.field = value`: a field's setter. - Set(Expr, Expr), /// A `match` on a `Result` or an `Option`, `ok` on `Ok` or `Some`. - Match { - value: Expr, - ok: Arm, - err: Arm, - }, + Match { value: Expr, ok: Arm, err: Arm }, } /// A `match` arm: the pattern binding the payload, if any, and the steps it runs. @@ -54,7 +48,8 @@ pub(crate) struct Arm { pub(crate) steps: Vec, } -/// What a `let`, an arm, or a closure's parameter binds. +/// What a `let`, an arm, or a closure's parameter binds. Each name is unique in the +/// script, so a language that cannot shadow need not rename. #[derive(Clone)] pub(crate) enum Pat { Name(String, Type), @@ -62,7 +57,7 @@ pub(crate) enum Pat { Ignore(Type), } -/// A piece of a `println!`. +/// A piece of a `println!` or a `format!`. #[derive(Clone)] pub(crate) enum Piece { Text(String), @@ -74,7 +69,7 @@ pub(crate) enum Piece { pub(crate) enum Spec { Display, Debug, - /// `{:0Nx}`: lowercase hex, zero-padded to `N` digits. + /// `{:x}`, or `{:0Nx}` zero-padded to `N` digits. Hex(usize), /// `{:0N}`: decimal, zero-padded to `N` digits. Padded(usize), @@ -95,6 +90,13 @@ pub(crate) struct Num { } impl Num { + pub(crate) fn new(v: i128) -> Num { + Num { + negative: v < 0, + magnitude: v.unsigned_abs(), + } + } + /// Its two's complement bits, truncated to 64. pub(crate) fn bits(self) -> u64 { let v = self.magnitude as u64; @@ -141,18 +143,32 @@ pub(crate) enum Op { And, } +/// A `std::ops::Bound`'s variant. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum BoundKind { + Included, + Excluded, + Unbounded, +} + #[derive(Clone)] pub(crate) enum Kind { Unit, Bool(bool), Int(Num), - /// A float's bits, an `f32`'s widened. + /// A float, an `f32`'s widened. Float(f64), Char(char), + /// A string, or a path spelled as one. Str(String), Bytes(Vec), + /// A `Duration`'s seconds and nanoseconds. + Duration(u64, u32), + Socket(std::net::SocketAddr), + Ip(std::net::IpAddr), None, Some(Box), + /// A tuple, or a `Range`'s start and end, or a `Bounds`'s two `Bound`s. Tuple(Vec), /// The items of a collection, a map's as tuples of a key and its value. List(Vec), @@ -160,7 +176,8 @@ pub(crate) enum Kind { Record(usize, Vec), /// An enum's variant, from its fields. Variant(usize, usize, Vec), - /// A record's `Default`, or an object's. + Bound(BoundKind, Option>), + /// A type's `Default`. Default, Var(String), /// A constant of the IR's `constants`. @@ -169,13 +186,13 @@ pub(crate) enum Kind { Call(FnId, Option>, Vec), /// A record's field, by index. Field(Box, usize), - /// A tuple's element. + /// A tuple's element, or a `Range`'s start (0) or end (1). Element(Box, usize), /// `Clone::clone`. Clone(Box), - /// `.unwrap()` of an `Option` or a `Result`, or `.expect(..)`. + /// `.unwrap()` or `.expect(..)` of an `Option` or a `Result`. Unwrap(Box), - /// `.unwrap_err()` or `.err().unwrap()` of a `Result`. + /// `.err().unwrap()` of a `Result`. UnwrapErr(Box), IsSome(Box), IsNone(Box), @@ -186,6 +203,26 @@ pub(crate) enum Kind { /// A call of a function `transcript.rs` defines, or a value of a unit struct it does, /// each a language's own. Local(String, Vec), + /// `format!` + Format(Vec), + /// `items.map(|pat| body).collect::>().join(sep)`, over a list or an iterator. + Join { + items: Box, + pat: Pat, + body: Box, + sep: String, + }, + /// `option.map_or(none, |pat| some)` + MapOr { + option: Box, + none: Box, + pat: Pat, + some: Box, + }, + /// Bytes as UTF-8 text: `String::from_utf8_lossy`, or `String::from_utf8(..).unwrap()`. + Utf8(Box), + /// `.len()` of bytes, a string, or a list. + Len(Box), } impl Expr { @@ -198,38 +235,12 @@ impl Transcript { /// The transcript of `source`, resolved against the export's `api.json`. pub(crate) fn load(lock: &Path, source: &Path) -> Transcript { let lock: ir::Lock = serde_json::from_str(&std::fs::read_to_string(lock).unwrap()).unwrap(); - let text = std::fs::read_to_string(source).unwrap(); - let file = syn::parse_file(&text).unwrap_or_else(|e| panic!("{}: {e}", at(e.span()))); let mut transcript = Transcript { api: lock.api, names: lock.names, steps: Vec::new(), - locals: BTreeMap::new(), }; - let mut main = None; - let mut units = Vec::new(); - for item in &file.items { - match item { - syn::Item::Fn(f) if f.sig.ident == "main" => main = Some(f), - syn::Item::Fn(f) => { - let ty = match &f.sig.output { - syn::ReturnType::Default => Type::Unit, - syn::ReturnType::Type(_, ty) => local_type(ty), - }; - transcript.locals.insert(f.sig.ident.to_string(), ty); - } - syn::Item::Struct(s) if matches!(s.fields, syn::Fields::Unit) => units.push(s.ident.to_string()), - _ => {} - } - } - let main = main.expect("transcript.rs has a main"); - let mut scope = Scope { - t: &transcript, - vars: Vec::new(), - units, - }; - let steps = scope.block(&main.block.stmts); - transcript.steps = steps; + transcript.steps = parse::main(&transcript, &std::fs::read_to_string(source).unwrap()); transcript } @@ -243,6 +254,16 @@ impl Transcript { } } + /// The type owning `id`, if any. + pub(crate) fn owner(&self, id: FnId) -> Option { + match id.owner { + Owner::Free => None, + Owner::Record(i) => Some(Type::Record(i)), + Owner::Enum(i) => Some(Type::Enum(i)), + Owner::Object(i) => Some(Type::Object(i)), + } + } + /// The Rust path of a type, with its arguments, as `api.json`'s names key it. pub(crate) fn rust(&self, ty: &Type) -> String { let named = |path: &[String], args: &[Type]| match args { @@ -275,15 +296,9 @@ impl Transcript { /// The key `api.json`'s names give `id`, such as `fn api::Counter::new`. pub(crate) fn key(&self, id: FnId) -> String { let f = self.function(id); - let owner = match id.owner { - Owner::Free => None, - Owner::Record(i) => Some(self.rust(&Type::Record(i))), - Owner::Enum(i) => Some(self.rust(&Type::Enum(i))), - Owner::Object(i) => Some(self.rust(&Type::Object(i))), - }; let name = f.path.last().unwrap(); - let mut path = match owner { - Some(owner) => format!("{owner}::{name}"), + let mut path = match self.owner(id) { + Some(owner) => format!("{}::{name}", self.rust(&owner)), None => f.path.join("::"), }; if let Some(instance) = &f.instance @@ -325,1135 +340,6 @@ impl Transcript { } } -/// `file:line:column` of a span in `transcript.rs`. -fn at(span: proc_macro2::Span) -> String { - let start = span.start(); - format!("transcript.rs:{}:{}", start.line, start.column + 1) -} - -/// Fail at `node`'s span: a construct the subset lacks, or one the API does not have. -fn fail(node: &dyn Spanned, message: impl std::fmt::Display) -> ! { - panic!("{}: {message}", at(node.span())) -} - -/// The type of a local function's return, which only names the standard library's. -fn local_type(ty: &syn::Type) -> Type { - let syn::Type::Path(path) = ty else { - fail(ty, "a local function returns a named type") - }; - let name = path.path.segments.last().unwrap().ident.to_string(); - match name.as_str() { - "String" => Type::String, - "bool" => Type::Bool, - "u8" => Type::Int(Int::U8), - "u32" => Type::Int(Int::U32), - "u64" => Type::Int(Int::U64), - "usize" => Type::Int(Int::Usize), - "i64" => Type::Int(Int::I64), - // What a hook makes is the API's, typed where it is used. - _ => fail(ty, format!("a local function returning {name}")), - } -} - -/// A local in scope: its type, or a loop's literal, typed at each use. -enum Var { - Typed(String, Type), - Alias(String, syn::Expr), -} - -struct Scope<'t> { - t: &'t Transcript, - vars: Vec, - /// The unit structs `transcript.rs` defines: each language's own implementation. - units: Vec, -} - -impl Scope<'_> { - fn block(&mut self, stmts: &[syn::Stmt]) -> Vec { - let depth = self.vars.len(); - let mut steps = Vec::new(); - for stmt in stmts { - self.stmt(stmt, &mut steps); - } - self.vars.truncate(depth); - steps - } - - fn lookup(&self, name: &str) -> Option<&Var> { - self.vars.iter().rev().find(|v| match v { - Var::Typed(n, _) | Var::Alias(n, _) => n == name, - }) - } - - fn stmt(&mut self, stmt: &syn::Stmt, steps: &mut Vec) { - match stmt { - syn::Stmt::Local(local) => { - let Some(init) = &local.init else { - fail(local, "a let without a value") - }; - if init.diverge.is_some() { - fail(local, "a let-else"); - } - let expected = match &local.pat { - syn::Pat::Type(typed) => Some(self.annotated(&typed.ty)), - _ => None, - }; - let value = match &expected { - Some(ty) => self.check(&init.expr, ty), - None => self.infer(&init.expr), - }; - let pat = self.bind(&local.pat, &value.ty); - steps.push(Step::Let(pat, value)); - } - syn::Stmt::Macro(m) => steps.push(self.mac(&m.mac)), - syn::Stmt::Expr(expr, _) => self.expr_stmt(expr, steps), - syn::Stmt::Item(item) => fail(item, "an item inside main"), - } - } - - fn expr_stmt(&mut self, expr: &syn::Expr, steps: &mut Vec) { - match expr { - syn::Expr::Macro(m) => steps.push(self.mac(&m.mac)), - syn::Expr::ForLoop(f) => { - let syn::Expr::Array(items) = &*f.expr else { - fail(&f.expr, "a for loop over anything but an array literal") - }; - let syn::Pat::Ident(name) = &*f.pat else { - fail(&f.pat, "a for loop binding anything but a name") - }; - for item in &items.elems { - self.vars.push(Var::Alias(name.ident.to_string(), item.clone())); - let body = self.block(&f.body.stmts); - self.vars.pop(); - steps.extend(body); - } - } - syn::Expr::Match(m) => steps.push(self.matched(m)), - syn::Expr::Assign(a) => { - let place = self.infer(&a.left); - let value = self.check(&a.right, &place.ty); - steps.push(Step::Set(place, value)); - } - syn::Expr::Call(call) if path_is(&call.func, "drop") => { - let [arg] = call.args.iter().collect::>()[..] else { - fail(call, "drop of one local") - }; - let syn::Expr::Path(p) = arg else { - fail(arg, "drop of anything but a local") - }; - let name = p.path.get_ident().unwrap().to_string(); - let Some(Var::Typed(..)) = self.lookup(&name) else { - fail(arg, format!("drop of {name}, which is no local")) - }; - steps.push(Step::Drop(name)); - } - expr => steps.push(Step::Do(self.infer(expr))), - } - } - - /// A `let`'s pattern, binding its names to the parts of `ty`. - fn bind(&mut self, pat: &syn::Pat, ty: &Type) -> Pat { - match pat { - syn::Pat::Type(typed) => self.bind(&typed.pat, ty), - syn::Pat::Ident(ident) => { - let name = ident.ident.to_string(); - self.vars.push(Var::Typed(name.clone(), ty.clone())); - Pat::Name(name, ty.clone()) - } - syn::Pat::Wild(_) => Pat::Ignore(ty.clone()), - syn::Pat::Tuple(tuple) => { - let Type::Tuple(elements) = unref(ty) else { - fail(pat, format!("a tuple pattern of {ty:?}")) - }; - if elements.len() != tuple.elems.len() { - fail(pat, "a tuple pattern of another length"); - } - let elements = elements.clone(); - Pat::Tuple(tuple.elems.iter().zip(&elements).map(|(p, ty)| self.bind(p, ty)).collect()) - } - pat => fail(pat, "a pattern other than a name, `_`, or a tuple"), - } - } - - /// The type an annotation on a `let` names. - fn annotated(&self, ty: &syn::Type) -> Type { - let syn::Type::Path(path) = ty else { - fail(ty, "an annotation other than a path") - }; - let last = path.path.segments.last().unwrap(); - match last.ident.to_string().as_str() { - "Vec" if matches!(&last.arguments, syn::PathArguments::AngleBracketed(args) if matches!(args.args.first(), Some(syn::GenericArgument::Type(syn::Type::Path(p))) if p.path.is_ident("String"))) => { - Type::List(Collection::Vec, Box::new(Type::String)) - } - _ => self.type_of_path(&path.path).unwrap_or_else(|| fail(ty, "an annotation of a type the API lacks")), - } - } - - /// The API's type a path names, such as `api::Batch` or `std::net::SocketAddr`. - fn type_of_path(&self, path: &syn::Path) -> Option { - let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); - let last = names.last()?.as_str(); - let api = &self.t.api; - let matches = |p: &[String]| p.last().map(String::as_str) == Some(last) && suffix(p, &names); - let found: Vec = (api.records.iter().enumerate()) - .filter(|(_, r)| matches(&r.path)) - .map(|(i, _)| Type::Record(i)) - .chain((api.enums.iter().enumerate()).filter(|(_, e)| matches(&e.path)).map(|(i, _)| Type::Enum(i))) - .chain((api.objects.iter().enumerate()).filter(|(_, o)| matches(&o.path)).map(|(i, _)| Type::Object(i))) - .collect(); - match (found.as_slice(), last) { - ([one], _) => Some(one.clone()), - // A generic type at its default, or its one instance. - ([first, ..], _) if found.iter().all(|t| self.t.rust(t).split('<').next() == self.t.rust(first).split('<').next()) => { - let plain = found.iter().find(|t| !self.t.rust(t).contains('<')); - Some(plain.unwrap_or(first).clone()) - } - (_, "SocketAddr") => Some(Type::SocketAddr(ir::Family::Any)), - (_, "Duration") => Some(Type::Duration), - (_, "Bytes") => Some(Type::Bytes), - _ => None, - } - } - - fn mac(&mut self, mac: &syn::Macro) -> Step { - if !mac.path.is_ident("println") { - fail(mac, "a macro other than println!"); - } - let args = mac - .parse_body_with(syn::punctuated::Punctuated::::parse_terminated) - .unwrap_or_else(|e| fail(mac, e)); - let mut args = args.into_iter(); - let Some(syn::Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(format), - .. - })) = args.next() - else { - fail(mac, "println! without a format string") - }; - let args: Vec = args.collect(); - // The arguments are parsed out of the macro's tokens, so they live as long as the - // transcript does by leaking: a test process parses one file once. - let args: &[syn::Expr] = Box::leak(args.into_boxed_slice()); - let pieces = self.format(&format, args); - Step::Print(pieces) - } - - /// The pieces of a format string and its arguments. - fn format(&mut self, lit: &syn::LitStr, args: &[syn::Expr]) -> Vec { - let text = lit.value(); - let mut pieces = Vec::new(); - let mut literal = String::new(); - let mut next = 0; - let mut chars = text.chars().peekable(); - while let Some(c) = chars.next() { - match c { - '{' if chars.peek() == Some(&'{') => { - chars.next(); - literal.push('{'); - } - '}' if chars.peek() == Some(&'}') => { - chars.next(); - literal.push('}'); - } - '{' => { - let mut inner = String::new(); - for c in chars.by_ref() { - if c == '}' { - break; - } - inner.push(c); - } - let (name, spec) = inner.split_once(':').unwrap_or((&inner, "")); - let spec = match spec { - "" => Spec::Display, - "?" => Spec::Debug, - s if s.starts_with('0') && s.ends_with('x') => Spec::Hex(s[1..s.len() - 1].parse().unwrap()), - s if s.starts_with('0') => Spec::Padded(s[1..].parse().unwrap()), - s => fail(lit, format!("the format {s}")), - }; - let value = if name.is_empty() { - let arg = args.get(next).unwrap_or_else(|| fail(lit, "too few arguments")); - next += 1; - self.infer(arg) - } else { - let expr: &syn::Expr = Box::leak(Box::new(syn::parse_str::(name).unwrap())); - self.infer_at(expr, lit) - }; - if !literal.is_empty() { - pieces.push(Piece::Text(std::mem::take(&mut literal))); - } - pieces.push(Piece::Value(value, spec)); - } - c => literal.push(c), - } - } - if next != args.len() { - fail(lit, "too many arguments"); - } - if !literal.is_empty() { - pieces.push(Piece::Text(literal)); - } - pieces - } - - /// `infer`, failing at `at`'s span, for an expression parsed from a format string. - fn infer_at(&mut self, expr: &syn::Expr, at: &dyn Spanned) -> Expr { - let syn::Expr::Path(p) = expr else { fail(at, "an inline format argument other than a name") }; - let name = p.path.segments.last().unwrap().ident.to_string(); - if self.lookup(&name).is_none() && self.constant(&p.path).is_none() { - fail(at, format!("{name} is no local or constant")); - } - self.infer(expr) - } - - fn matched(&mut self, m: &syn::ExprMatch) -> Step { - let value = self.infer(&m.expr); - let (ok_ty, err_ty, option) = match &value.ty { - Type::Result(ok, err) => ((**ok).clone(), Some((**err).clone()), false), - Type::Option(inner) => ((**inner).clone(), None, true), - ty => fail(&m.expr, format!("a match on {ty:?}")), - }; - let mut ok = None; - let mut err = None; - for arm in &m.arms { - let (variant, inner) = match &arm.pat { - syn::Pat::TupleStruct(ts) => { - let name = ts.path.segments.last().unwrap().ident.to_string(); - let [inner] = ts.elems.iter().collect::>()[..] else { - fail(ts, "a variant of one field") - }; - (name, Some(inner)) - } - syn::Pat::Ident(i) if i.ident == "None" => ("None".to_string(), None), - syn::Pat::Path(p) if p.path.is_ident("None") => ("None".to_string(), None), - pat => fail(pat, "an arm other than Ok, Err, Some, or None"), - }; - let depth = self.vars.len(); - let (slot, ty) = match (variant.as_str(), option) { - ("Ok", false) | ("Some", true) => (&mut ok, Some(&ok_ty)), - ("Err", false) => (&mut err, err_ty.as_ref()), - ("None", true) => (&mut err, None), - _ => fail(&arm.pat, format!("{variant} in a match on {:?}", value.ty)), - }; - let pat = inner.map(|p| self.bind(p, ty.unwrap())); - let mut steps = Vec::new(); - match &*arm.body { - syn::Expr::Block(b) => { - for stmt in &b.block.stmts { - self.stmt(stmt, &mut steps); - } - } - body => self.expr_stmt(body, &mut steps), - } - self.vars.truncate(depth); - *slot = Some(Arm { pat, steps }); - } - let (Some(ok), Some(err)) = (ok, err) else { - fail(m, "a match without both arms") - }; - Step::Match { value, ok, err } - } - - fn constant(&self, path: &syn::Path) -> Option { - let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); - (self.t.api.constants.iter()).position(|c| suffix(&c.path, &names) && c.path.last() == names.last()) - } - - /// An expression whose type follows from itself. - fn infer(&mut self, expr: &syn::Expr) -> Expr { - match expr { - syn::Expr::Paren(p) => self.infer(&p.expr), - syn::Expr::Reference(r) => self.infer(&r.expr), - syn::Expr::Group(g) => self.infer(&g.expr), - syn::Expr::Path(p) => { - if let Some(name) = p.path.get_ident().map(|i| i.to_string()) { - match self.lookup(&name) { - Some(Var::Typed(_, ty)) => return Expr::new(Kind::Var(name), ty.clone()), - Some(Var::Alias(_, expr)) => { - let expr = expr.clone(); - return self.infer(&expr); - } - None => {} - } - if self.units.contains(&name) { - fail(p, format!("{name}, a value of a local type, where nothing types it")); - } - } - if let Some(c) = self.constant(&p.path) { - let ty = match self.t.api.constants[c].value { - ir::Literal::Bool(_) => Type::Bool, - ir::Literal::Int(int, _) => Type::Int(int), - }; - return Expr::new(Kind::Const(c), ty); - } - // A constant the IR keeps as a function, such as `api::BOXED`. - if let Some(id) = self.function(&p.path, None, None) { - let f = self.t.function(id); - if f.access == Access::Const { - return Expr::new(Kind::Call(id, None, Vec::new()), f.ok.clone()); - } - } - // A plain enum's variant. - if let Some(e) = self.variant(&p.path, &[]) { - return e; - } - fail(p, "a path that names no local, constant, or variant") - } - syn::Expr::Lit(lit) => match &lit.lit { - syn::Lit::Str(s) => Expr::new(Kind::Str(s.value()), Type::Ref(Mutability::Not, Box::new(Type::Str))), - syn::Lit::Bool(b) => Expr::new(Kind::Bool(b.value), Type::Bool), - syn::Lit::ByteStr(b) => Expr::new(Kind::Bytes(b.value()), Type::Ref(Mutability::Not, Box::new(Type::Slice))), - syn::Lit::Int(i) if !i.suffix().is_empty() => { - let int = int_named(i.suffix()).unwrap_or_else(|| fail(i, "an integer suffix")); - self.check(expr, &Type::Int(int)) - } - lit => fail(lit, "a literal whose type nothing gives"), - }, - syn::Expr::Call(call) => self.call(call, None), - syn::Expr::MethodCall(m) => self.method(m, None), - syn::Expr::Field(f) => self.field(f), - syn::Expr::Struct(s) => self.structure(s, None), - syn::Expr::Binary(b) => self.binary(b), - syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Deref(_)) => self.infer(&u.expr), - syn::Expr::Tuple(t) => { - let elements: Vec = t.elems.iter().map(|e| self.infer(e)).collect(); - let ty = Type::Tuple(elements.iter().map(|e| e.ty.clone()).collect()); - Expr::new(Kind::Tuple(elements), ty) - } - expr => fail(expr, "an expression outside the transcript's subset"), - } - } - - /// An expression that must be of type `ty`, such as an argument: literals take their - /// type from it, and Rust's own conversions between the forms of a value, such as - /// `.to_string()` or `&`, are the value itself. - fn check(&mut self, expr: &syn::Expr, ty: &Type) -> Expr { - let base = unref(ty); - match expr { - syn::Expr::Paren(p) => return self.check(&p.expr, ty), - syn::Expr::Group(g) => return self.check(&g.expr, ty), - syn::Expr::Reference(r) => return self.check(&r.expr, ty), - syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Deref(_)) => return self.check(&u.expr, ty), - // `&b"lo"[..]`: the whole slice. - syn::Expr::Index(i) if matches!(&*i.index, syn::Expr::Range(r) if r.start.is_none() && r.end.is_none()) => { - return self.check(&i.expr, ty); - } - syn::Expr::Path(p) if p.path.get_ident().is_some() => { - let name = p.path.get_ident().unwrap().to_string(); - if let Some(Var::Alias(_, alias)) = self.lookup(&name) { - let alias = alias.clone(); - return self.check(&alias, ty); - } - if self.units.contains(&name) { - return Expr::new(Kind::Local(name, Vec::new()), ty.clone()); - } - if name == "None" { - return match base { - Type::Option(_) => Expr::new(Kind::None, ty.clone()), - _ => fail(expr, format!("None as {ty:?}")), - }; - } - } - syn::Expr::Path(p) if path_is(expr, "Vec::new") || path_is(expr, "String::new") || path_is(expr, "Bytes::new") => { - let _ = p; - return self.empty(expr, ty); - } - syn::Expr::MethodCall(m) if CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() => { - return self.check(&m.receiver, ty); - } - // `[..].into_iter().map(..).collect()`, as a map's or a set's items are built. - syn::Expr::MethodCall(m) if m.method == "collect" => return self.collected(m, ty), - syn::Expr::Call(call) => { - let func = &*call.func; - let one = call.args.len() == 1; - if one && ["String::from", "Bytes::from_static", "Box::new", "PathBuf::from", "Path::new", "Bytes::from"].iter().any(|p| path_is(func, p)) { - return self.check(&call.args[0], ty); - } - if one && path_is(func, "Some") { - let Type::Option(inner) = base else { - fail(expr, format!("Some as {ty:?}")) - }; - let inner = (**inner).clone(); - let value = self.check(&call.args[0], &inner); - return Expr::new(Kind::Some(Box::new(value)), ty.clone()); - } - if call.args.is_empty() && (path_is(func, "Default::default") || path_is(func, "Box::default")) { - return self.empty(expr, ty); - } - if let syn::Expr::Path(p) = func - && let Some(name) = p.path.get_ident() - && self.t.locals.contains_key(&name.to_string()) - { - let args = call.args.iter().map(|a| self.infer(a)).collect(); - return Expr::new(Kind::Local(name.to_string(), args), ty.clone()); - } - return self.call(call, Some(ty)); - } - syn::Expr::Macro(m) if m.mac.path.is_ident("vec") => { - let items = m - .mac - .parse_body_with(syn::punctuated::Punctuated::::parse_terminated) - .unwrap_or_else(|e| fail(m, e)); - let items: &[syn::Expr] = Box::leak(items.into_iter().collect::>().into_boxed_slice()); - return self.items(expr, items.iter(), ty); - } - syn::Expr::Array(a) => return self.items(expr, a.elems.iter(), ty), - syn::Expr::Lit(lit) => return self.literal(lit, ty), - syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => { - if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. }) = &*u.expr { - let mut e = self.literal(&syn::ExprLit { attrs: Vec::new(), lit: syn::Lit::Int((*i).clone()) }, ty); - if let Kind::Int(n) = &mut e.kind { - n.negative = true; - } - if let Kind::Float(f) = &mut e.kind { - *f = -*f; - } - return e; - } - } - syn::Expr::Tuple(t) => { - let Type::Tuple(elements) = base else { - fail(expr, format!("a tuple as {ty:?}")) - }; - if elements.len() != t.elems.len() { - fail(expr, "a tuple of another length"); - } - let elements = elements.clone(); - let values = t.elems.iter().zip(&elements).map(|(e, ty)| self.check(e, ty)).collect(); - return Expr::new(Kind::Tuple(values), ty.clone()); - } - syn::Expr::Range(r) => return self.range(r, ty), - syn::Expr::Closure(c) => return self.closure(c, ty), - syn::Expr::Struct(s) => return self.structure(s, Some(ty)), - syn::Expr::MethodCall(m) => return self.method(m, Some(ty)), - _ => {} - } - let value = self.infer(expr); - if !fits(&value.ty, ty) { - fail(expr, format!("{:?} where {ty:?} is taken", value.ty)); - } - value - } - - /// An empty collection, string, or a type's default. - fn empty(&mut self, expr: &syn::Expr, ty: &Type) -> Expr { - match unref(ty) { - Type::String | Type::Str => Expr::new(Kind::Str(String::new()), ty.clone()), - Type::Bytes | Type::Vec | Type::Slice => Expr::new(Kind::Bytes(Vec::new()), ty.clone()), - Type::List(..) => Expr::new(Kind::List(Vec::new()), ty.clone()), - Type::Box(inner) if matches!(**inner, Type::List(..)) => Expr::new(Kind::List(Vec::new()), ty.clone()), - Type::Option(_) => Expr::new(Kind::None, ty.clone()), - Type::Record(_) | Type::Object(_) => Expr::new(Kind::Default, ty.clone()), - other => fail(expr, format!("an empty {other:?}")), - } - } - - /// The items of a list literal, as a list of `ty` or its bytes. - fn items<'e>(&mut self, expr: &syn::Expr, items: impl Iterator, ty: &Type) -> Expr { - match unref(ty) { - Type::List(_, item) => { - let item = (**item).clone(); - let items = items.map(|e| self.check(e, &item)).collect(); - Expr::new(Kind::List(items), ty.clone()) - } - Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => { - let bytes = items - .map(|e| match self.check(e, &Type::Int(Int::U8)).kind { - Kind::Int(n) => n.magnitude as u8, - _ => fail(e, "a byte other than a literal"), - }) - .collect(); - Expr::new(Kind::Bytes(bytes), ty.clone()) - } - other => fail(expr, format!("a list as {other:?}")), - } - } - - /// `items.into_iter().map(..).collect()` as `ty`: the items, each mapped. - fn collected(&mut self, m: &syn::ExprMethodCall, ty: &Type) -> Expr { - let mut receiver = &*m.receiver; - let mut map = None; - loop { - match receiver { - syn::Expr::MethodCall(inner) if CONVERSIONS.contains(&inner.method.to_string().as_str()) || inner.method == "into_iter" => { - receiver = &inner.receiver; - } - syn::Expr::MethodCall(inner) if inner.method == "map" && map.is_none() => { - map = Some(&inner.args[0]); - receiver = &inner.receiver; - } - _ => break, - } - } - let syn::Expr::Array(array) = receiver else { - fail(m, "a collect of anything but an array literal") - }; - let Type::List(_, item) = unref(ty) else { - fail(m, format!("a collect as {ty:?}")) - }; - let item = (**item).clone(); - let Some(map) = map else { - return self.items(receiver, array.elems.iter(), ty); - }; - // The map is a closure of a tuple pattern: each item, bound by it, is its body. - let syn::Expr::Closure(closure) = map else { - fail(map, "a map of anything but a closure") - }; - let [syn::Pat::Tuple(pat)] = closure.inputs.iter().collect::>()[..] else { - fail(closure, "a map's closure of one tuple pattern") - }; - let items = array - .elems - .iter() - .map(|element| { - let syn::Expr::Tuple(values) = element else { - fail(element, "an item other than a tuple") - }; - let depth = self.vars.len(); - for (p, value) in pat.elems.iter().zip(&values.elems) { - let syn::Pat::Ident(name) = p else { fail(p, "a name") }; - self.vars.push(Var::Alias(name.ident.to_string(), value.clone())); - } - let value = self.check(&closure.body, &item); - self.vars.truncate(depth); - value - }) - .collect(); - Expr::new(Kind::List(items), ty.clone()) - } - - fn literal(&mut self, lit: &syn::ExprLit, ty: &Type) -> Expr { - let base = unref(ty); - match (&lit.lit, base) { - (syn::Lit::Str(s), Type::Str | Type::String | Type::Path | Type::PathBuf) => Expr::new(Kind::Str(s.value()), ty.clone()), - (syn::Lit::ByteStr(b), Type::Slice | Type::Vec | Type::Bytes | Type::Array(_)) => Expr::new(Kind::Bytes(b.value()), ty.clone()), - (syn::Lit::Byte(b), Type::Int(Int::U8)) => Expr::new(Kind::Int(Num { negative: false, magnitude: b.value().into() }), ty.clone()), - (syn::Lit::Bool(b), Type::Bool) => Expr::new(Kind::Bool(b.value), ty.clone()), - (syn::Lit::Char(c), Type::Char) => Expr::new(Kind::Char(c.value()), ty.clone()), - (syn::Lit::Int(i), Type::Int(_) | Type::U128 | Type::NonZero(_)) => { - let magnitude: u128 = i.base10_parse().unwrap_or_else(|e| fail(i, e)); - Expr::new(Kind::Int(Num { negative: false, magnitude }), ty.clone()) - } - (syn::Lit::Float(f), Type::F32 | Type::F64) => Expr::new(Kind::Float(f.base10_parse().unwrap_or_else(|e| fail(f, e))), ty.clone()), - (syn::Lit::Int(i), Type::F32 | Type::F64) => Expr::new(Kind::Float(i.base10_parse().unwrap_or_else(|e| fail(i, e))), ty.clone()), - (lit, _) => fail(lit, format!("this literal as {ty:?}")), - } - } - - fn range(&mut self, r: &syn::ExprRange, ty: &Type) -> Expr { - match unref(ty) { - Type::Range(int) => { - let int = Type::Int(*int); - let (Some(start), Some(end)) = (&r.start, &r.end) else { - fail(r, "a Range without both ends") - }; - if matches!(r.limits, syn::RangeLimits::Closed(_)) { - fail(r, "an inclusive range as a Range"); - } - let elements = vec![self.check(start, &int), self.check(end, &int)]; - Expr::new(Kind::Tuple(elements), ty.clone()) - } - Type::Bounds(int) => { - // The start and end bounds, each a `Bound`'s variant. - let int = *int; - let bound = |s: &mut Self, e: Option<&syn::Expr>, kind: &str| -> Expr { - let ty = Type::Bound(int); - match e { - None => Expr::new(Kind::Str("Unbounded".to_string()), ty), - Some(e) => { - let v = s.check(e, &Type::Int(int)); - Expr::new(Kind::Tuple(vec![Expr::new(Kind::Str(kind.to_string()), Type::Str), v]), ty) - } - } - }; - let end_kind = match r.limits { - syn::RangeLimits::HalfOpen(_) => "Excluded", - syn::RangeLimits::Closed(_) => "Included", - }; - let start = bound(self, r.start.as_deref(), "Included"); - let end = bound(self, r.end.as_deref(), end_kind); - Expr::new(Kind::Tuple(vec![start, end]), ty.clone()) - } - other => fail(r, format!("a range as {other:?}")), - } - } - - fn closure(&mut self, c: &syn::ExprClosure, ty: &Type) -> Expr { - let Type::Closure(closure) = unref(ty) else { - fail(c, format!("a closure as {ty:?}")) - }; - let closure = (**closure).clone(); - if closure.params.len() != c.inputs.len() { - fail(c, "a closure of another arity"); - } - let depth = self.vars.len(); - let params = c.inputs.iter().zip(&closure.params).map(|(p, ty)| self.bind(p, ty)).collect(); - let mut steps = Vec::new(); - let value = match &*c.body { - syn::Expr::Block(b) => { - let (last, init) = b.block.stmts.split_last().unwrap_or_else(|| fail(b, "an empty closure")); - for stmt in init { - self.stmt(stmt, &mut steps); - } - match last { - syn::Stmt::Expr(e, None) => self.check(e, &closure.ok), - stmt => { - self.stmt(stmt, &mut steps); - Expr::new(Kind::Unit, Type::Unit) - } - } - } - syn::Expr::Macro(m) => { - steps.push(self.mac(&m.mac)); - Expr::new(Kind::Unit, Type::Unit) - } - body => self.check(body, &closure.ok), - }; - self.vars.truncate(depth); - Expr::new(Kind::Closure(params, steps, Box::new(value)), ty.clone()) - } - - fn binary(&mut self, b: &syn::ExprBinary) -> Expr { - let op = match b.op { - syn::BinOp::Eq(_) => Op::Eq, - syn::BinOp::Ne(_) => Op::Ne, - syn::BinOp::Lt(_) => Op::Lt, - syn::BinOp::Gt(_) => Op::Gt, - syn::BinOp::Add(_) => Op::Add, - syn::BinOp::Sub(_) => Op::Sub, - syn::BinOp::Mul(_) => Op::Mul, - syn::BinOp::Rem(_) => Op::Rem, - syn::BinOp::And(_) => Op::And, - _ => fail(b, "this operator"), - }; - // The side whose type follows from itself types the other. - let (left, right) = match literalish(&b.left) { - false => { - let left = self.infer(&b.left); - let right = self.check(&b.right, &left.ty.clone()); - (left, right) - } - true => { - let right = self.infer(&b.right); - let left = self.check(&b.left, &right.ty.clone()); - (left, right) - } - }; - let ty = match op { - Op::Eq | Op::Ne | Op::Lt | Op::Gt | Op::And => Type::Bool, - _ => unref(&left.ty).clone(), - }; - Expr::new(Kind::Binary(op, Box::new(left), Box::new(right)), ty) - } - - fn field(&mut self, f: &syn::ExprField) -> Expr { - let base = self.infer(&f.base); - match &f.member { - syn::Member::Unnamed(i) => { - let Type::Tuple(elements) = unref(&base.ty) else { - fail(f, format!("an element of {:?}", base.ty)) - }; - let ty = elements.get(i.index as usize).unwrap_or_else(|| fail(f, "no such element")).clone(); - Expr::new(Kind::Element(Box::new(base), i.index as usize), ty) - } - syn::Member::Named(name) => { - let name = name.to_string(); - let owner = unref(&base.ty).clone(); - if let Type::Record(r) = owner - && let Some(i) = self.t.api.records[r].fields.iter().position(|f| f.name == name) - { - let ty = self.t.api.records[r].fields[i].ty.clone(); - return Expr::new(Kind::Field(Box::new(base), i), ty); - } - // A getter: an object's field, or an opaque value's. - let id = self.method_of(&owner, &name, |f| matches!(f.access, Access::Field { set: false, .. })); - let Some(id) = id else { - fail(f, format!("no field {name} on {owner:?}")) - }; - let ty = self.t.function(id).ok.clone(); - Expr::new(Kind::Call(id, Some(Box::new(base)), Vec::new()), ty) - } - } - } - - /// The method `name` of `owner`'s type for which `which` holds. - fn method_of(&self, owner: &Type, name: &str, which: impl Fn(&Function) -> bool) -> Option { - let (owner, methods) = match unref(owner) { - Type::Record(i) => (Owner::Record(*i), &self.t.api.records[*i].methods), - Type::Enum(i) => (Owner::Enum(*i), &self.t.api.enums[*i].methods), - Type::Object(i) => (Owner::Object(*i), &self.t.api.objects[*i].methods), - _ => return None, - }; - let index = methods.iter().position(|f| f.path.last().map(String::as_str) == Some(name) && which(f))?; - Some(FnId { owner, index }) - } - - /// A struct literal: a record's, or an enum's struct variant's. - fn structure(&mut self, s: &syn::ExprStruct, ty: Option<&Type>) -> Expr { - if let Some(e) = self.variant_struct(s) { - return e; - } - let named = self.type_of_path(&s.path); - // A generic record's instance: the one the expected type names, else the one whose - // fields the literal's types fit. - let candidates: Vec = match (ty.map(unref), &named) { - (Some(Type::Record(i)), _) => vec![*i], - (_, Some(Type::Record(i))) => { - let base = self.t.api.records[*i].path.clone(); - (0..self.t.api.records.len()).filter(|r| self.t.api.records[*r].path == base).collect() - } - _ => fail(s, "a struct literal of no record"), - }; - for (n, r) in candidates.iter().enumerate() { - let record = &self.t.api.records[*r]; - let fields: Vec<(String, Type)> = record.fields.iter().map(|f| (f.name.clone(), f.ty.clone())).collect(); - if fields.len() != s.fields.len() { - fail(s, "a record literal without each field"); - } - // Try each instance in turn, keeping the first whose fields all fit. - let last = n + 1 == candidates.len(); - let fits_all = last - || s.fields.iter().all(|fv| { - let syn::Member::Named(name) = &fv.member else { return false }; - let Some((_, ty)) = fields.iter().find(|(n, _)| name == n) else { return false }; - self.fits_expr(&fv.expr, ty) - }); - if !fits_all { - continue; - } - let mut values = Vec::new(); - for (name, ty) in &fields { - let fv = s - .fields - .iter() - .find(|fv| matches!(&fv.member, syn::Member::Named(n) if n == name)) - .unwrap_or_else(|| fail(s, format!("no field {name}"))); - values.push(self.check(&fv.expr, ty)); - } - return Expr::new(Kind::Record(*r, values), Type::Record(*r)); - } - fail(s, "a record literal fitting no instance") - } - - /// Whether `expr` may be of type `ty`, judged by what it plainly is without checking it: - /// a local's type, a struct literal's, or a suffixed literal's. What it cannot judge fits. - fn fits_expr(&self, expr: &syn::Expr, ty: &Type) -> bool { - let guess = match expr { - syn::Expr::Reference(r) => return self.fits_expr(&r.expr, ty), - syn::Expr::Paren(p) => return self.fits_expr(&p.expr, ty), - syn::Expr::Path(p) => match p.path.get_ident().and_then(|i| self.lookup(&i.to_string())) { - Some(Var::Typed(_, ty)) => Some(ty.clone()), - Some(Var::Alias(_, expr)) => return self.fits_expr(&expr.clone(), ty), - None => None, - }, - syn::Expr::Struct(s) => self.type_of_path(&s.path), - syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. }) if !i.suffix().is_empty() => int_named(i.suffix()).map(Type::Int), - _ => None, - }; - match (guess, unref(ty)) { - (None, _) => true, - // A generic record's literal names its type but not the instance. - (Some(Type::Record(a)), Type::Record(b)) => self.t.api.records[a].path == self.t.api.records[*b].path, - (Some(have), want) => fits(&have, want), - } - } - - fn variant_struct(&mut self, s: &syn::ExprStruct) -> Option { - let (e, v) = self.find_variant(&s.path)?; - let fields: Vec<(String, Type)> = - (self.t.api.enums[e].variants[v].fields.iter()).map(|f| (f.name.clone(), f.ty.clone())).collect(); - let values = fields - .iter() - .map(|(name, ty)| { - let fv = s - .fields - .iter() - .find(|fv| matches!(&fv.member, syn::Member::Named(n) if n == name)) - .unwrap_or_else(|| fail(s, format!("no field {name}"))); - self.check(&fv.expr, ty) - }) - .collect(); - Some(Expr::new(Kind::Variant(e, v, values), Type::Enum(e))) - } - - fn find_variant(&self, path: &syn::Path) -> Option<(usize, usize)> { - let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); - let (variant, enum_path) = names.split_last()?; - if enum_path.is_empty() { - return None; - } - let e = (self.t.api.enums.iter()).position(|e| e.path.last() == enum_path.last() && suffix(&e.path, enum_path))?; - let v = self.t.api.enums[e].variants.iter().position(|v| &v.name == variant)?; - Some((e, v)) - } - - /// A unit variant at `path`, or a tuple variant of `args`. - fn variant(&mut self, path: &syn::Path, args: &[syn::Expr]) -> Option { - let (e, v) = self.find_variant(path)?; - let fields: Vec = self.t.api.enums[e].variants[v].fields.iter().map(|f| f.ty.clone()).collect(); - if fields.len() != args.len() { - fail(path, "a variant of another arity"); - } - let values = args.iter().zip(&fields).map(|(a, ty)| self.check(a, ty)).collect(); - Some(Expr::new(Kind::Variant(e, v, values), Type::Enum(e))) - } - - /// A free function or associated function at `path`, whose instance, for a generic one, - /// is the one `turbofish` names or else the first whose parameters `args` fit. - fn function(&mut self, path: &syn::Path, args: Option<&[syn::Expr]>, expected: Option<&Type>) -> Option { - let names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); - let (name, owner_path) = names.split_last()?; - let api = &self.t.api; - let mut candidates: Vec = Vec::new(); - for (i, f) in api.functions.iter().enumerate() { - if f.path.last() == Some(name) && suffix(&f.path, &names) { - candidates.push(FnId { owner: Owner::Free, index: i }); - } - } - if !owner_path.is_empty() { - let owned = |p: &[String]| p.last() == owner_path.last() && suffix(p, owner_path); - for (i, r) in api.records.iter().enumerate() { - if owned(&r.path) { - for (j, f) in r.methods.iter().enumerate() { - if f.path.last() == Some(name) && f.receiver.is_none() { - candidates.push(FnId { owner: Owner::Record(i), index: j }); - } - } - } - } - for (i, o) in api.objects.iter().enumerate() { - if owned(&o.path) { - for (j, f) in o.methods.iter().enumerate() { - if f.path.last() == Some(name) && f.receiver.is_none() { - candidates.push(FnId { owner: Owner::Object(i), index: j }); - } - } - } - } - for (i, e) in api.enums.iter().enumerate() { - if owned(&e.path) { - for (j, f) in e.methods.iter().enumerate() { - if f.path.last() == Some(name) && f.receiver.is_none() { - candidates.push(FnId { owner: Owner::Enum(i), index: j }); - } - } - } - } - } - // The turbofish's arguments narrow the instances. - let turbofish: Vec = path - .segments - .iter() - .filter_map(|s| match &s.arguments { - syn::PathArguments::AngleBracketed(a) => Some(a), - _ => None, - }) - .flat_map(|a| &a.args) - .filter_map(|a| match a { - syn::GenericArgument::Type(syn::Type::Path(p)) => self.type_of_path(&p.path).or_else(|| int_named(&p.path.get_ident()?.to_string()).map(Type::Int)), - _ => None, - }) - .collect(); - self.pick(path, candidates, args, expected, &turbofish) - } - - /// The candidate whose parameters `args` fit and whose return `expected` fits. - fn pick(&mut self, at: &dyn Spanned, candidates: Vec, args: Option<&[syn::Expr]>, expected: Option<&Type>, turbofish: &[Type]) -> Option { - let candidates: Vec = candidates - .into_iter() - .filter(|id| { - let f = self.t.function(*id); - let instance = f.instance.as_ref().map(|i| i.named.as_slice()).unwrap_or(&[]); - turbofish.iter().all(|t| instance.contains(t)) - && args.is_none_or(|a| a.len() == f.params.len()) - && expected.is_none_or(|e| fits(&f.ok, e) || f.err.is_some()) - }) - .collect(); - if candidates.len() <= 1 { - return candidates.first().copied(); - } - let Some(args) = args else { - fail(at, "an ambiguous function") - }; - let fitting: Vec = candidates - .iter() - .copied() - .filter(|id| { - let params: Vec = self.t.function(*id).params.iter().map(|p| p.ty.clone()).collect(); - args.iter().zip(¶ms).all(|(a, ty)| self.fits_expr(a, ty)) - }) - .collect(); - match fitting.as_slice() { - [one] => Some(*one), - [] => fail(at, "no instance fits these arguments"), - // Instances alike in every parameter: the first, as Rust's inference would pick - // no other for the same arguments. - [first, ..] => Some(*first), - } - } - - /// A call of a path: the API's function, a variant, `Some`, or a local function. - fn call(&mut self, call: &syn::ExprCall, expected: Option<&Type>) -> Expr { - let syn::Expr::Path(p) = &*call.func else { - fail(call, "a call of anything but a path") - }; - let args: Vec = call.args.iter().cloned().collect(); - let args: &[syn::Expr] = Box::leak(args.into_boxed_slice()); - if let Some(name) = p.path.get_ident().map(|i| i.to_string()) - && let Some(ty) = self.t.locals.get(&name) - { - let ty = ty.clone(); - let args = args.iter().map(|a| self.infer(a)).collect(); - return Expr::new(Kind::Local(name, args), ty); - } - if let Some(e) = self.variant(&p.path, args) { - return e; - } - let Some(id) = self.function(&p.path, Some(args), expected) else { - fail(call, "a call of no function the API exports") - }; - self.apply(call, id, None, args) - } - - /// The call of `id` on `receiver`, with `args` checked against its parameters. - fn apply(&mut self, at: &dyn Spanned, id: FnId, receiver: Option, args: &[syn::Expr]) -> Expr { - let params: Vec = self.t.function(id).params.iter().map(|p| p.ty.clone()).collect(); - if params.len() != args.len() { - fail(at, format!("{} takes {} arguments", self.t.key(id), params.len())); - } - let args = args.iter().zip(¶ms).map(|(a, ty)| self.check(a, ty)).collect(); - let f = self.t.function(id); - let ty = match &f.err { - Some(err) => Type::Result(Box::new(f.ok.clone()), Box::new(err.clone())), - None => f.ok.clone(), - }; - Expr::new(Kind::Call(id, receiver.map(Box::new), args), ty) - } - - fn method(&mut self, m: &syn::ExprMethodCall, expected: Option<&Type>) -> Expr { - let name = m.method.to_string(); - let args: Vec = m.args.iter().cloned().collect(); - let args: &[syn::Expr] = Box::leak(args.into_boxed_slice()); - let receiver = self.infer(&m.receiver); - let rty = unref(&receiver.ty).clone(); - let only = |s: &Self, kind: fn(Box) -> Kind, ty: Type| { - if !args.is_empty() { - fail(m, format!("{name} with arguments")); - } - let _ = s; - Expr::new(kind(Box::new(receiver.clone())), ty) - }; - match (name.as_str(), &rty) { - ("unwrap" | "expect", Type::Option(inner) | Type::Result(inner, _)) => { - let inner = (**inner).clone(); - return Expr::new(Kind::Unwrap(Box::new(receiver)), inner); - } - ("unwrap_err", Type::Result(_, err)) => { - let err = (**err).clone(); - return only(self, Kind::UnwrapErr, err); - } - ("is_some", Type::Option(_)) => return only(self, Kind::IsSome, Type::Bool), - ("is_none", Type::Option(_)) => return only(self, Kind::IsNone, Type::Bool), - ("is_err", Type::Result(..)) => return only(self, Kind::IsErr, Type::Bool), - ("err", Type::Result(_, err)) => { - // `.err().unwrap()`, the only use the subset has. - let err = (**err).clone(); - return Expr::new(Kind::UnwrapErr(Box::new(receiver)), Type::Option(Box::new(err))); - } - ("clone", _) if args.is_empty() => { - let ty = receiver.ty.clone(); - return Expr::new(Kind::Clone(Box::new(receiver)), ty); - } - (conversion, _) if CONVERSIONS.contains(&conversion) && args.is_empty() => { - // `.into()` of a value to the type the binding returns it as already. - let _ = expected; - return receiver; - } - _ => {} - } - let id = self.method_of(&rty, &name, |f| f.receiver.is_some() && f.access == Access::Call); - let id = match id { - Some(id) => id, - None => { - // A generic method's instances. - let candidates = self.methods_named(&rty, &name); - let turbofish: Vec = (m.turbofish.iter().flat_map(|t| &t.args)) - .filter_map(|a| match a { - syn::GenericArgument::Type(syn::Type::Path(p)) => self.type_of_path(&p.path), - _ => None, - }) - .collect(); - self.pick(m, candidates, Some(args), expected, &turbofish) - .unwrap_or_else(|| fail(m, format!("no method {name} on {}", self.describe(&rty)))) - } - }; - self.apply(m, id, Some(receiver), args) - } - - fn methods_named(&self, owner: &Type, name: &str) -> Vec { - let (owner, methods) = match unref(owner) { - Type::Record(i) => (Owner::Record(*i), &self.t.api.records[*i].methods), - Type::Enum(i) => (Owner::Enum(*i), &self.t.api.enums[*i].methods), - Type::Object(i) => (Owner::Object(*i), &self.t.api.objects[*i].methods), - _ => return Vec::new(), - }; - (methods.iter().enumerate()) - .filter(|(_, f)| f.path.last().map(String::as_str) == Some(name) && f.receiver.is_some() && f.access == Access::Call) - .map(|(index, _)| FnId { owner, index }) - .collect() - } - - fn describe(&self, ty: &Type) -> String { - match ty { - Type::Record(_) | Type::Enum(_) | Type::Object(_) => self.t.rust(ty), - ty => format!("{ty:?}"), - } - } -} - -/// Conversions that leave a value as the binding has it. -const CONVERSIONS: &[&str] = &["to_string", "to_vec", "to_owned", "into", "as_str", "as_ref", "as_slice", "as_deref"]; - -/// Whether `path`'s segments end with `names`' segments, ignoring the `api` crate's root. -fn suffix(path: &[String], names: &[String]) -> bool { - let names: Vec<&String> = names.iter().filter(|n| *n != "api").collect(); - names.len() <= path.len() && path[path.len() - names.len()..].iter().zip(&names).all(|(a, b)| a == *b) -} - -/// Whether `expr` is the path `path`, such as `String::from`. -fn path_is(expr: &syn::Expr, path: &str) -> bool { - let syn::Expr::Path(p) = expr else { return false }; - let names: Vec = p.path.segments.iter().map(|s| s.ident.to_string()).collect(); - let want: Vec<&str> = path.split("::").collect(); - names.len() >= want.len() && names[names.len() - want.len()..].iter().zip(&want).all(|(a, b)| a == b) -} - -/// Whether `expr` takes its type from the other side of an operator, as a literal does. -fn literalish(expr: &syn::Expr) -> bool { - match expr { - syn::Expr::Lit(_) => true, - syn::Expr::Unary(u) => literalish(&u.expr), - syn::Expr::Paren(p) => literalish(&p.expr), - _ => false, - } -} - -fn int_named(name: &str) -> Option { - Some(match name { - "u8" => Int::U8, - "u16" => Int::U16, - "u32" => Int::U32, - "u64" => Int::U64, - "usize" => Int::Usize, - "i8" => Int::I8, - "i16" => Int::I16, - "i32" => Int::I32, - "i64" => Int::I64, - "isize" => Int::Isize, - _ => return None, - }) -} - /// `ty` behind any references. pub(crate) fn unref(ty: &Type) -> &Type { match ty { @@ -1462,17 +348,11 @@ pub(crate) fn unref(ty: &Type) -> &Type { } } -/// Whether a value of `have` passes where `want` is taken: the same type, behind any -/// references or boxes, or a string or bytes in any of their forms. -fn fits(have: &Type, want: &Type) -> bool { - let (have, want) = (have.base(), want.base()); - let text = |t: &Type| matches!(t, Type::Str | Type::String); - let bytes = |t: &Type| matches!(t, Type::Slice | Type::Vec | Type::Bytes); - let path = |t: &Type| matches!(t, Type::Path | Type::PathBuf); - match (have, want) { - (Type::Option(a), Type::Option(b)) => fits(a, b), - (Type::List(_, a), Type::List(_, b)) => fits(a, b), - (Type::Tuple(a), Type::Tuple(b)) => a.len() == b.len() && a.iter().zip(b).all(|(a, b)| fits(a, b)), - (a, b) => a == b || (text(a) && text(b)) || (bytes(a) && bytes(b)) || (path(a) && path(b)), +/// Each name a step binds, in order, a closure's and an arm's included. +pub(crate) fn bound(pat: &Pat, out: &mut Vec<(String, Type)>) { + match pat { + Pat::Name(name, ty) => out.push((name.clone(), ty.clone())), + Pat::Tuple(pats) => pats.iter().for_each(|p| bound(p, out)), + Pat::Ignore(_) => {} } } diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs new file mode 100644 index 000000000..3b34f067d --- /dev/null +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -0,0 +1,1649 @@ +//! `transcript.rs` read into steps: each expression typed against the API, bidirectionally, +//! so a literal takes the type of the parameter it is passed to. + +use std::collections::BTreeMap; + +use syn::spanned::Spanned; + +use super::ir::{Access, Collection, Family, Function, Int, Literal, Mutability, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; + +/// The steps of `source`'s `main`. +pub(super) fn main(t: &Transcript, source: &str) -> Vec { + let file = syn::parse_file(source).unwrap_or_else(|e| panic!("{}: {e}", at(e.span()))); + let mut scope = Scope { + t, + vars: Vec::new(), + units: Vec::new(), + locals: BTreeMap::new(), + uses: BTreeMap::new(), + taken: BTreeMap::new(), + }; + let mut main = None; + for item in &file.items { + match item { + syn::Item::Use(u) => scope.import(&u.tree, &mut Vec::new()), + syn::Item::Struct(s) if matches!(s.fields, syn::Fields::Unit) => scope.units.push(s.ident.to_string()), + syn::Item::Static(s) => scope.vars.push(Var::Alias(s.ident.to_string(), (*s.expr).clone())), + syn::Item::Const(c) => scope.vars.push(Var::Alias(c.ident.to_string(), (*c.expr).clone())), + _ => {} + } + } + for item in &file.items { + if let syn::Item::Fn(f) = item { + if f.sig.ident == "main" { + main = Some(f); + continue; + } + scope.locals.insert(f.sig.ident.to_string(), f.sig.output.clone()); + } + } + let main = main.expect("transcript.rs has a main"); + scope.block(&main.block.stmts) +} + +/// `transcript.rs:line:column` of a span. +fn at(span: proc_macro2::Span) -> String { + let start = span.start(); + format!("transcript.rs:{}:{}", start.line, start.column + 1) +} + +/// Fail at `node`'s span: a construct the subset lacks, or one the API does not have. +fn fail(node: &dyn Spanned, message: impl std::fmt::Display) -> ! { + panic!("{}: {message}", at(node.span())) +} + +/// A local in scope: its unique name and type, or a loop's literal, typed at each use. +enum Var { + Typed(String, String, Type), + Alias(String, syn::Expr), +} + +struct Scope<'t> { + t: &'t Transcript, + vars: Vec, + /// The unit structs `transcript.rs` defines: each language's own implementation. + units: Vec, + /// The functions `transcript.rs` defines, each a language's own: what each returns, + /// typed where it is called. + locals: BTreeMap, + /// What each name a `use` brings in stands for. + uses: BTreeMap>, + /// How many locals took each name, so each binding gets its own. + taken: BTreeMap, +} + +/// Conversions that leave a value as the binding has it. +const CONVERSIONS: &[&str] = &["to_string", "to_vec", "to_owned", "into", "as_ref", "into_iter", "iter", "as_deref"]; + +impl Scope<'_> { + fn import(&mut self, tree: &syn::UseTree, prefix: &mut Vec) { + match tree { + syn::UseTree::Path(p) => { + prefix.push(p.ident.to_string()); + self.import(&p.tree, prefix); + prefix.pop(); + } + syn::UseTree::Name(n) => { + let mut path = prefix.clone(); + path.push(n.ident.to_string()); + self.uses.insert(n.ident.to_string(), path); + } + syn::UseTree::Group(g) => g.items.iter().for_each(|t| self.import(t, prefix)), + tree => fail(tree, "a use other than of names"), + } + } + + /// A path's segments, its first expanded through the `use`s. + fn segments(&self, path: &syn::Path) -> Vec { + let mut names: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); + if let Some(full) = self.uses.get(&names[0]) { + names.splice(0..1, full.iter().cloned()); + } + names + } + + fn block(&mut self, stmts: &[syn::Stmt]) -> Vec { + let depth = self.vars.len(); + let mut steps = Vec::new(); + for stmt in stmts { + self.stmt(stmt, &mut steps); + } + self.vars.truncate(depth); + steps + } + + fn lookup(&self, name: &str) -> Option<&Var> { + self.vars.iter().rev().find(|v| match v { + Var::Typed(n, ..) | Var::Alias(n, _) => n == name, + }) + } + + fn stmt(&mut self, stmt: &syn::Stmt, steps: &mut Vec) { + match stmt { + syn::Stmt::Local(local) => { + let Some(init) = &local.init else { + fail(local, "a let without a value") + }; + if init.diverge.is_some() { + fail(local, "a let-else"); + } + let value = match &local.pat { + syn::Pat::Type(typed) => { + let ty = self.ty(&typed.ty); + self.check(&init.expr, &ty) + } + _ => self.infer(&init.expr), + }; + let pat = self.bind(&local.pat, &value.ty); + steps.push(Step::Let(pat, value)); + } + syn::Stmt::Macro(m) => steps.push(Step::Print(self.print(&m.mac))), + syn::Stmt::Expr(expr, _) => self.expr_stmt(expr, steps), + syn::Stmt::Item(item) => fail(item, "an item inside main"), + } + } + + fn expr_stmt(&mut self, expr: &syn::Expr, steps: &mut Vec) { + match expr { + syn::Expr::Macro(m) => steps.push(Step::Print(self.print(&m.mac))), + syn::Expr::Block(b) => steps.extend(self.block(&b.block.stmts)), + syn::Expr::ForLoop(f) => { + let syn::Expr::Array(items) = &*f.expr else { + fail(&f.expr, "a for loop over anything but an array literal") + }; + let syn::Pat::Ident(name) = &*f.pat else { + fail(&f.pat, "a for loop binding anything but a name") + }; + for item in &items.elems { + self.vars.push(Var::Alias(name.ident.to_string(), item.clone())); + let body = self.block(&f.body.stmts); + self.vars.pop(); + steps.extend(body); + } + } + syn::Expr::Match(m) => steps.push(self.matched(m)), + syn::Expr::Assign(a) => steps.push(Step::Do(self.assign(a))), + syn::Expr::Call(call) if path_is(&call.func, "drop") => { + let [syn::Expr::Path(p)] = call.args.iter().collect::>()[..] else { + fail(call, "drop of anything but a local") + }; + let name = p.path.get_ident().unwrap().to_string(); + let Some(Var::Typed(_, unique, _)) = self.lookup(&name) else { + fail(p, format!("drop of {name}, which is no local")) + }; + steps.push(Step::Drop(unique.clone())); + } + expr => steps.push(Step::Do(self.infer(expr))), + } + } + + /// `place.field = value`: the field's setter, called on the place's receiver. + fn assign(&mut self, a: &syn::ExprAssign) -> Expr { + let syn::Expr::Field(field) = &*a.left else { + fail(&a.left, "an assignment to anything but a field") + }; + let syn::Member::Named(name) = &field.member else { + fail(field, "an assignment to an element") + }; + let receiver = self.infer(&field.base); + let Some(id) = self.method_of(&receiver.ty, &name.to_string(), |f| matches!(f.access, Access::Field { set: true, .. })) else { + fail(field, format!("no setter of {name} on {}", self.describe(&receiver.ty))) + }; + let ty = self.t.function(id).params[0].ty.clone(); + let value = self.check(&a.right, &ty); + Expr::new(Kind::Call(id, Some(Box::new(receiver)), vec![value]), Type::Unit) + } + + /// A unique name for a local named `name`. + fn unique(&mut self, name: &str) -> String { + let n = self.taken.entry(name.to_string()).or_insert(0); + *n += 1; + match *n { + 1 => name.to_string(), + n => format!("{name}_{n}"), + } + } + + /// A pattern, binding its names to the parts of `ty`. + fn bind(&mut self, pat: &syn::Pat, ty: &Type) -> Pat { + match pat { + syn::Pat::Type(typed) => self.bind(&typed.pat, ty), + syn::Pat::Ident(ident) => { + let name = ident.ident.to_string(); + let unique = self.unique(&name); + self.vars.push(Var::Typed(name, unique.clone(), ty.clone())); + Pat::Name(unique, ty.clone()) + } + syn::Pat::Wild(_) => Pat::Ignore(ty.clone()), + syn::Pat::Reference(r) => self.bind(&r.pat, ty), + syn::Pat::Tuple(tuple) => { + // A `Bounds` is its start and end `Bound`. + let bounds = match unref(ty).base() { + Type::Bounds(int) => Some(Type::Tuple(vec![Type::Bound(*int), Type::Bound(*int)])), + _ => None, + }; + let Type::Tuple(elements) = bounds.as_ref().unwrap_or(unref(ty).base()) else { + fail(pat, format!("a tuple pattern of {}", self.describe(ty))) + }; + if elements.len() != tuple.elems.len() { + fail(pat, "a tuple pattern of another length"); + } + let elements = elements.clone(); + Pat::Tuple(tuple.elems.iter().zip(&elements).map(|(p, ty)| self.bind(p, ty)).collect()) + } + pat => fail(pat, "a pattern other than a name, `_`, or a tuple"), + } + } + + /// The type a Rust type names: the API's, or the standard library's it maps. + fn ty(&self, ty: &syn::Type) -> Type { + match ty { + syn::Type::Reference(r) => { + let mutability = if r.mutability.is_some() { Mutability::Mut } else { Mutability::Not }; + Type::Ref(mutability, Box::new(self.ty(&r.elem))) + } + syn::Type::Paren(p) => self.ty(&p.elem), + syn::Type::TraitObject(t) => { + let Some(syn::TypeParamBound::Trait(bound)) = t.bounds.first() else { + fail(t, "a trait object of no trait") + }; + self.type_of_path(&bound.path).unwrap_or_else(|| fail(t, "a trait object the API lacks")) + } + syn::Type::Tuple(t) if t.elems.is_empty() => Type::Unit, + syn::Type::Tuple(t) => Type::Tuple(t.elems.iter().map(|e| self.ty(e)).collect()), + syn::Type::Array(a) => { + let len = match &a.len { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), .. + }) => i.base10_parse().unwrap(), + len => fail(len, "an array length other than a literal"), + }; + match self.ty(&a.elem) { + Type::Int(Int::U8) => Type::Array(len), + item => Type::List(Collection::Array(len), Box::new(item)), + } + } + syn::Type::Slice(s) => match self.ty(&s.elem) { + Type::Int(Int::U8) => Type::Slice, + item => Type::List(Collection::Slice, Box::new(item)), + }, + syn::Type::Path(p) => { + let last = p.path.segments.last().unwrap(); + let arg = || match &last.arguments { + syn::PathArguments::AngleBracketed(a) => match a.args.first() { + Some(syn::GenericArgument::Type(t)) => self.ty(t), + _ => fail(a, "a type argument"), + }, + _ => fail(last, "a type without its argument"), + }; + let name = last.ident.to_string(); + if let Some(int) = int_named(&name) { + return Type::Int(int); + } + match name.as_str() { + "bool" => Type::Bool, + "char" => Type::Char, + "f32" => Type::F32, + "f64" => Type::F64, + "u128" => Type::U128, + "str" => Type::Str, + "String" => Type::String, + "Bytes" => Type::Bytes, + "Duration" => Type::Duration, + "Path" => Type::Path, + "PathBuf" => Type::PathBuf, + "SocketAddr" => Type::SocketAddr(Family::Any), + "SocketAddrV4" => Type::SocketAddr(Family::V4), + "SocketAddrV6" => Type::SocketAddr(Family::V6), + "IpAddr" => Type::IpAddr(Family::Any), + "Ipv4Addr" => Type::IpAddr(Family::V4), + "Ipv6Addr" => Type::IpAddr(Family::V6), + "Option" => Type::Option(Box::new(arg())), + "Box" => Type::Box(Box::new(arg())), + "Vec" => match arg() { + Type::Int(Int::U8) => Type::Vec, + item => Type::List(Collection::Vec, Box::new(item)), + }, + _ => self.type_of_path(&p.path).unwrap_or_else(|| fail(ty, "a type the API lacks")), + } + } + ty => fail(ty, "this type"), + } + } + + /// The API's record, enum, or object a path names: the one whose path or shown path it + /// is, else the only one of its last segment, a generic one at its default. + fn type_of_path(&self, path: &syn::Path) -> Option { + let names = self.segments(path); + let api = &self.t.api; + let types: Vec<(Type, &Vec, bool)> = (api.records.iter().enumerate()) + .map(|(i, r)| (Type::Record(i), &r.path, r.args.is_empty())) + .chain(api.enums.iter().enumerate().map(|(i, e)| (Type::Enum(i), &e.path, e.args.is_empty()))) + .chain(api.objects.iter().enumerate().map(|(i, o)| (Type::Object(i), &o.path, o.args.is_empty()))) + .collect(); + let pick = |found: Vec<&(Type, &Vec, bool)>| -> Option { + match found.as_slice() { + [] => None, + [one] => Some(one.0.clone()), + // A generic type: the instance at its defaults, which takes no arguments, else its + // first, which a literal's fields narrow. + many => Some(many.iter().find(|t| t.2).unwrap_or(&many[0]).0.clone()), + } + }; + let exact: Vec<_> = types.iter().filter(|t| *t.1 == names).collect(); + if !exact.is_empty() { + return pick(exact); + } + pick(types.iter().filter(|t| t.1.last() == names.last()).collect()) + } + + fn print(&mut self, mac: &syn::Macro) -> Vec { + if !mac.path.is_ident("println") { + fail(mac, "a macro other than println!"); + } + self.format(mac) + } + + /// The pieces of a `println!` or `format!`'s format string and its arguments. + fn format(&mut self, mac: &syn::Macro) -> Vec { + let args = mac + .parse_body_with(syn::punctuated::Punctuated::::parse_terminated) + .unwrap_or_else(|e| fail(mac, e)); + let mut args = args.into_iter(); + let Some(syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(lit), .. + })) = args.next() + else { + fail(mac, "a format without its string") + }; + let args: Vec = args.collect(); + let text = lit.value(); + let mut pieces = Vec::new(); + let mut literal = String::new(); + let mut next = 0; + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '{' if chars.peek() == Some(&'{') => { + chars.next(); + literal.push('{'); + } + '}' if chars.peek() == Some(&'}') => { + chars.next(); + literal.push('}'); + } + '{' => { + let inner: String = chars.by_ref().take_while(|c| *c != '}').collect(); + let (name, spec) = inner.split_once(':').unwrap_or((&inner, "")); + let spec = match spec { + "" => Spec::Display, + "?" => Spec::Debug, + "x" => Spec::Hex(0), + s if s.starts_with('0') && s.ends_with('x') => Spec::Hex(s[1..s.len() - 1].parse().unwrap()), + s if s.starts_with('0') => Spec::Padded(s[1..].parse().unwrap()), + s => fail(&lit, format!("the format {s}")), + }; + let value = if name.is_empty() { + let arg = args.get(next).unwrap_or_else(|| fail(&lit, "too few arguments")); + next += 1; + self.infer(arg) + } else { + let ident = syn::Ident::new(name, lit.span()); + let path = syn::Expr::Path(syn::ExprPath { + attrs: Vec::new(), + qself: None, + path: ident.into(), + }); + self.infer(&path) + }; + if !literal.is_empty() { + pieces.push(Piece::Text(std::mem::take(&mut literal))); + } + pieces.push(Piece::Value(value, spec)); + } + c => literal.push(c), + } + } + if next != args.len() { + fail(&lit, "too many arguments"); + } + if !literal.is_empty() { + pieces.push(Piece::Text(literal)); + } + pieces + } + + fn matched(&mut self, m: &syn::ExprMatch) -> Step { + let value = self.infer(&m.expr); + let (ok_ty, err_ty) = match &value.ty { + Type::Result(ok, err) => ((**ok).clone(), Some((**err).clone())), + Type::Option(inner) => ((**inner).clone(), None), + ty => fail(&m.expr, format!("a match on {}", self.describe(ty))), + }; + let option = err_ty.is_none(); + let mut ok = None; + let mut err = None; + for arm in &m.arms { + let (variant, inner) = match &arm.pat { + syn::Pat::TupleStruct(ts) => { + let name = ts.path.segments.last().unwrap().ident.to_string(); + let [inner] = ts.elems.iter().collect::>()[..] else { + fail(ts, "a variant of one field") + }; + (name, Some(inner)) + } + syn::Pat::Ident(i) if i.ident == "None" => ("None".to_string(), None), + syn::Pat::Path(p) if p.path.is_ident("None") => ("None".to_string(), None), + pat => fail(pat, "an arm other than Ok, Err, Some, or None"), + }; + let depth = self.vars.len(); + let (slot, ty) = match (variant.as_str(), option) { + ("Ok", false) | ("Some", true) => (&mut ok, Some(ok_ty.clone())), + ("Err", false) => (&mut err, err_ty.clone()), + ("None", true) => (&mut err, None), + _ => fail(&arm.pat, format!("{variant} in this match")), + }; + let pat = inner.map(|p| self.bind(p, ty.as_ref().unwrap())); + let mut steps = Vec::new(); + match &*arm.body { + syn::Expr::Block(b) => b.block.stmts.iter().for_each(|s| self.stmt(s, &mut steps)), + body => self.expr_stmt(body, &mut steps), + } + self.vars.truncate(depth); + *slot = Some(Arm { pat, steps }); + } + let (Some(ok), Some(err)) = (ok, err) else { + fail(m, "a match without both arms") + }; + Step::Match { value, ok, err } + } + + /// The constant at `path`, if the API has one. + fn constant(&self, path: &syn::Path) -> Option { + let names = self.segments(path); + (self.t.api.constants.iter()).position(|c| c.path == names) + } + + /// An expression whose type follows from itself. + fn infer(&mut self, expr: &syn::Expr) -> Expr { + match expr { + syn::Expr::Paren(p) => self.infer(&p.expr), + syn::Expr::Reference(r) => self.infer(&r.expr), + syn::Expr::Group(g) => self.infer(&g.expr), + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Deref(_)) => self.infer(&u.expr), + syn::Expr::Path(p) => { + if let Some(name) = p.path.get_ident().map(|i| i.to_string()) { + match self.lookup(&name) { + Some(Var::Typed(_, unique, ty)) => return Expr::new(Kind::Var(unique.clone()), ty.clone()), + Some(Var::Alias(_, expr)) => { + let expr = expr.clone(); + return self.infer(&expr); + } + None => {} + } + } + if let Some(c) = self.constant(&p.path) { + let ty = match self.t.api.constants[c].value { + Literal::Bool(_) => Type::Bool, + Literal::Int(int, _) => Type::Int(int), + }; + return Expr::new(Kind::Const(c), ty); + } + // A constant the IR keeps as a function, such as `api::BOXED`. + if let Some(id) = self.function(&p.path, &[], None) + && self.t.function(id).access == Access::Const + { + return Expr::new(Kind::Call(id, None, Vec::new()), self.t.function(id).ok.clone()); + } + if let Some(e) = self.variant(&p.path, &[], None) { + return e; + } + fail(p, "a path that names no local, constant, or variant") + } + syn::Expr::Lit(lit) => match &lit.lit { + syn::Lit::Str(s) => Expr::new(Kind::Str(s.value()), Type::Ref(Mutability::Not, Box::new(Type::Str))), + syn::Lit::Bool(b) => Expr::new(Kind::Bool(b.value), Type::Bool), + syn::Lit::ByteStr(b) => Expr::new(Kind::Bytes(b.value()), Type::Ref(Mutability::Not, Box::new(Type::Slice))), + syn::Lit::Int(i) if !i.suffix().is_empty() => { + let int = int_named(i.suffix()).unwrap_or_else(|| fail(i, "this integer suffix")); + self.check(expr, &Type::Int(int)) + } + lit => fail(lit, "a literal whose type nothing gives"), + }, + syn::Expr::Call(call) => self.call(call, None), + syn::Expr::MethodCall(m) => self.method(m, None), + syn::Expr::Field(f) => self.field(f), + syn::Expr::Struct(s) => self.structure(s, None), + syn::Expr::Binary(b) => self.binary(b), + syn::Expr::Macro(m) if m.mac.path.is_ident("format") => { + Expr::new(Kind::Format(self.format(&m.mac)), Type::String) + } + syn::Expr::Tuple(t) => { + let elements: Vec = t.elems.iter().map(|e| self.infer(e)).collect(); + let ty = Type::Tuple(elements.iter().map(|e| e.ty.clone()).collect()); + Expr::new(Kind::Tuple(elements), ty) + } + expr => fail(expr, "an expression outside the transcript's subset"), + } + } + + /// An expression that must be of type `ty`, such as an argument: literals take their + /// type from it, and Rust's own conversions between the forms of a value, such as + /// `.to_string()` or `&`, are the value itself. + fn check(&mut self, expr: &syn::Expr, ty: &Type) -> Expr { + let base = unref(ty).base().clone(); + if let Some(value) = self.constant_of(expr, &base) { + return Expr::new(value, ty.clone()); + } + match expr { + syn::Expr::Paren(p) => return self.check(&p.expr, ty), + syn::Expr::Group(g) => return self.check(&g.expr, ty), + syn::Expr::Reference(r) => return self.check(&r.expr, ty), + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Deref(_)) => return self.check(&u.expr, ty), + // `&b"lo"[..]`: the whole slice. + syn::Expr::Index(i) if matches!(&*i.index, syn::Expr::Range(r) if r.start.is_none() && r.end.is_none()) => { + return self.check(&i.expr, ty); + } + syn::Expr::Path(p) if p.path.get_ident().is_some() => { + let name = p.path.get_ident().unwrap().to_string(); + if let Some(Var::Alias(_, alias)) = self.lookup(&name) { + let alias = alias.clone(); + return self.check(&alias, ty); + } + if self.lookup(&name).is_none() && self.units.contains(&name) { + return Expr::new(Kind::Local(name, Vec::new()), ty.clone()); + } + if name == "None" { + let Type::Option(_) = base else { + fail(expr, format!("None as {}", self.describe(ty))) + }; + return Expr::new(Kind::None, ty.clone()); + } + } + // A foreign enum's constant, which the IR keeps as a variant: tracing's `Level`, + // and `LevelFilter`, an optional level whose `OFF` is none. + syn::Expr::Path(p) if matches!(base, Type::Enum(_) | Type::Option(_)) => { + if let Some(e) = self.variant(&p.path, &[], Some(&base)) { + return Expr::new(e.kind, ty.clone()); + } + } + syn::Expr::MethodCall(m) if m.method == "parse" || (m.method == "unwrap" && matches!(&*m.receiver, syn::Expr::MethodCall(r) if r.method == "parse")) => { + return self.parsed(m, ty); + } + syn::Expr::MethodCall(m) if CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() && !self.api_method(m) => { + return self.check(&m.receiver, ty); + } + // `[..].into_iter().map(..).collect()`, as a map's or a set's items are built. + syn::Expr::MethodCall(m) if m.method == "collect" => return self.collected(m, ty), + syn::Expr::Call(call) => { + let func = &*call.func; + let one = call.args.len() == 1; + let passed = ["String::from", "Bytes::from_static", "Box::new", "PathBuf::from", "Path::new", "Bytes::from"]; + if one && passed.iter().any(|p| path_is(func, p)) { + return self.check(&call.args[0], ty); + } + if one && path_is(func, "Some") { + let Type::Option(inner) = &base else { + fail(expr, format!("Some as {}", self.describe(ty))) + }; + let value = self.check(&call.args[0], inner); + return Expr::new(Kind::Some(Box::new(value)), ty.clone()); + } + let empties = ["Default::default", "Box::default", "Vec::new", "String::new", "Bytes::new"]; + if call.args.is_empty() && empties.iter().any(|p| path_is(func, p)) { + return self.empty(expr, ty); + } + if let syn::Expr::Path(p) = func + && let Some(name) = p.path.get_ident() + && self.locals.contains_key(&name.to_string()) + { + let args = call.args.iter().map(|a| self.infer(a)).collect(); + return Expr::new(Kind::Local(name.to_string(), args), ty.clone()); + } + if let Some(bound) = self.bound(call, &base) { + return bound; + } + return self.call(call, Some(ty)); + } + syn::Expr::Macro(m) if m.mac.path.is_ident("vec") => { + let items = m + .mac + .parse_body_with(syn::punctuated::Punctuated::::parse_terminated) + .unwrap_or_else(|e| fail(m, e)); + let items: Vec = items.into_iter().collect(); + return self.items(expr, &items, ty); + } + syn::Expr::Array(a) => { + let items: Vec = a.elems.iter().cloned().collect(); + return self.items(expr, &items, ty); + } + syn::Expr::Lit(lit) => return self.literal(lit, ty), + syn::Expr::Tuple(t) => { + if let Type::Bounds(int) = base { + let elements = t.elems.iter().map(|e| self.check(e, &Type::Bound(int))).collect(); + return Expr::new(Kind::Tuple(elements), ty.clone()); + } + let Type::Tuple(elements) = &base else { + fail(expr, format!("a tuple as {}", self.describe(ty))) + }; + if elements.len() != t.elems.len() { + fail(expr, "a tuple of another length"); + } + let values = t.elems.iter().zip(elements).map(|(e, ty)| self.check(e, ty)).collect(); + return Expr::new(Kind::Tuple(values), ty.clone()); + } + syn::Expr::Range(r) => return self.range(r, ty), + syn::Expr::Closure(c) => return self.closure(c, ty), + syn::Expr::Struct(s) => return self.structure(s, Some(ty)), + syn::Expr::MethodCall(m) => return self.method(m, Some(ty)), + _ => {} + } + let value = self.infer(expr); + if !fits(&value.ty, ty) { + fail(expr, format!("{} where {} is taken", self.describe(&value.ty), self.describe(ty))); + } + value + } + + /// Whether `m` calls a method of the API's, not a conversion of the same name. + fn api_method(&self, m: &syn::ExprMethodCall) -> bool { + let Some(ty) = self.peek(&m.receiver) else { return false }; + !self.methods_named(&ty, &m.method.to_string()).is_empty() + } + + /// The type of `expr` where it plainly has one, without typing it: a local's. + fn peek(&self, expr: &syn::Expr) -> Option { + match expr { + syn::Expr::Reference(r) => self.peek(&r.expr), + syn::Expr::Paren(p) => self.peek(&p.expr), + syn::Expr::Path(p) => match self.lookup(&p.path.get_ident()?.to_string())? { + Var::Typed(_, _, ty) => Some(ty.clone()), + Var::Alias(..) => None, + }, + _ => None, + } + } + + /// A value of a standard type spelled by its constructors or constants, which only + /// literals feed: an integer past a literal's reach, a float, a duration, an address. + fn constant_of(&self, expr: &syn::Expr, ty: &Type) -> Option { + match ty { + Type::Int(_) | Type::U128 | Type::NonZero(_) => match expr { + syn::Expr::Lit(_) => None, + expr => const_int(expr).map(Kind::Int), + }, + Type::F32 | Type::F64 => const_float(expr).map(Kind::Float), + Type::Char if path_is(expr, "char::MAX") => Some(Kind::Char(char::MAX)), + Type::Duration => const_duration(expr).map(|(s, n)| Kind::Duration(s, n)), + Type::SocketAddr(_) => match const_net(expr)? { + Net::Socket(addr) => Some(Kind::Socket(addr)), + Net::Text(text) => Some(Kind::Socket(text.parse().unwrap_or_else(|e| fail(expr, e)))), + Net::Ip(_) => fail(expr, "an IP address as a socket address"), + }, + Type::IpAddr(_) => match const_net(expr)? { + Net::Ip(ip) => Some(Kind::Ip(ip)), + Net::Text(text) => Some(Kind::Ip(text.parse().unwrap_or_else(|e| fail(expr, e)))), + Net::Socket(_) => fail(expr, "a socket address as an IP address"), + }, + _ => None, + } + } + + /// `Bound::Included(v)`, `Bound::Excluded(v)`, as a `Bound`. + fn bound(&mut self, call: &syn::ExprCall, ty: &Type) -> Option { + let Type::Bound(int) = ty else { return None }; + let kind = if path_is(&call.func, "Bound::Included") { + BoundKind::Included + } else if path_is(&call.func, "Bound::Excluded") { + BoundKind::Excluded + } else { + return None; + }; + let value = self.check(&call.args[0], &Type::Int(*int)); + Some(Expr::new(Kind::Bound(kind, Some(Box::new(value))), ty.clone())) + } + + /// `"text".parse()` as `ty`: an address the generator parses, or the API's parse. + fn parsed(&mut self, m: &syn::ExprMethodCall, ty: &Type) -> Expr { + let (parse, unwrapped) = match &*m.receiver { + syn::Expr::MethodCall(r) if m.method == "unwrap" => (r, true), + _ => (m, false), + }; + let target = match unwrapped { + true => ty.clone(), + false => match unref(ty) { + Type::Result(ok, _) => (**ok).clone(), + _ => fail(m, "a parse not unwrapped"), + }, + }; + let id = self + .method_of(&target, "parse", |f| f.access == Access::Parse) + .unwrap_or_else(|| fail(m, format!("no parse of {}", self.describe(&target)))); + let text = self.check(&parse.receiver, &Type::Ref(Mutability::Not, Box::new(Type::Str))); + let call = self.apply_checked(id, None, vec![text]); + match unwrapped { + true => Expr::new(Kind::Unwrap(Box::new(call)), target), + false => call, + } + } + + /// An empty collection, string, or a type's default. + fn empty(&mut self, expr: &syn::Expr, ty: &Type) -> Expr { + match unref(ty).base() { + Type::String | Type::Str => Expr::new(Kind::Str(String::new()), ty.clone()), + Type::Bytes | Type::Vec | Type::Slice => Expr::new(Kind::Bytes(Vec::new()), ty.clone()), + Type::List(..) => Expr::new(Kind::List(Vec::new()), ty.clone()), + Type::Option(_) => Expr::new(Kind::None, ty.clone()), + Type::Record(_) | Type::Object(_) => Expr::new(Kind::Default, ty.clone()), + other => fail(expr, format!("an empty {}", self.describe(other))), + } + } + + /// The items of a list literal, as a list of `ty` or its bytes. + fn items(&mut self, expr: &syn::Expr, items: &[syn::Expr], ty: &Type) -> Expr { + match unref(ty).base() { + Type::List(_, item) => { + let item = (**item).clone(); + let items = items.iter().map(|e| self.check(e, &item)).collect(); + Expr::new(Kind::List(items), ty.clone()) + } + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => { + let bytes = items + .iter() + .map(|e| match self.check(e, &Type::Int(Int::U8)).kind { + Kind::Int(n) => n.magnitude as u8, + _ => fail(e, "a byte other than a literal"), + }) + .collect(); + Expr::new(Kind::Bytes(bytes), ty.clone()) + } + other => fail(expr, format!("a list as {}", self.describe(other))), + } + } + + /// `items.into_iter().map(..).collect()` as `ty`: the items, each mapped, of an array + /// literal, which a map's closure of a tuple pattern binds by name. + fn collected(&mut self, m: &syn::ExprMethodCall, ty: &Type) -> Expr { + let mut receiver = &*m.receiver; + let mut map = None; + loop { + match receiver { + syn::Expr::MethodCall(inner) if CONVERSIONS.contains(&inner.method.to_string().as_str()) => { + receiver = &inner.receiver; + } + syn::Expr::MethodCall(inner) if inner.method == "map" && map.is_none() => { + map = Some(&inner.args[0]); + receiver = &inner.receiver; + } + _ => break, + } + } + let syn::Expr::Array(array) = receiver else { + fail(m, "a collect of anything but an array literal") + }; + let items: Vec = array.elems.iter().cloned().collect(); + let Some(map) = map else { + return self.items(receiver, &items, ty); + }; + let Type::List(_, item) = unref(ty) else { + fail(m, format!("a collect as {}", self.describe(ty))) + }; + let syn::Expr::Closure(closure) = map else { + fail(map, "a map of anything but a closure") + }; + let [syn::Pat::Tuple(pat)] = closure.inputs.iter().collect::>()[..] else { + fail(closure, "a map's closure of one tuple pattern") + }; + let values = items + .iter() + .map(|element| { + let syn::Expr::Tuple(values) = element else { + fail(element, "an item other than a tuple") + }; + let depth = self.vars.len(); + for (p, value) in pat.elems.iter().zip(&values.elems) { + let syn::Pat::Ident(name) = p else { fail(p, "a name") }; + self.vars.push(Var::Alias(name.ident.to_string(), value.clone())); + } + let value = self.check(&closure.body, item); + self.vars.truncate(depth); + value + }) + .collect(); + Expr::new(Kind::List(values), ty.clone()) + } + + fn literal(&mut self, lit: &syn::ExprLit, ty: &Type) -> Expr { + let kind = match (&lit.lit, unref(ty).base()) { + (syn::Lit::Str(s), Type::Str | Type::String | Type::Path | Type::PathBuf) => Kind::Str(s.value()), + (syn::Lit::ByteStr(b), Type::Slice | Type::Vec | Type::Bytes | Type::Array(_)) => Kind::Bytes(b.value()), + (syn::Lit::Byte(b), Type::Int(Int::U8)) => Kind::Int(Num::new(b.value().into())), + (syn::Lit::Bool(b), Type::Bool) => Kind::Bool(b.value), + (syn::Lit::Char(c), Type::Char) => Kind::Char(c.value()), + (syn::Lit::Int(i), Type::Int(_) | Type::U128 | Type::NonZero(_)) => Kind::Int(Num { + negative: false, + magnitude: i.base10_parse().unwrap_or_else(|e| fail(i, e)), + }), + (syn::Lit::Float(f), Type::F32 | Type::F64) => Kind::Float(f.base10_parse().unwrap_or_else(|e| fail(f, e))), + (syn::Lit::Int(i), Type::F32 | Type::F64) => Kind::Float(i.base10_parse().unwrap_or_else(|e| fail(i, e))), + (lit, _) => fail(lit, format!("this literal as {}", self.describe(ty))), + }; + Expr::new(kind, ty.clone()) + } + + fn range(&mut self, r: &syn::ExprRange, ty: &Type) -> Expr { + let closed = matches!(r.limits, syn::RangeLimits::Closed(_)); + match unref(ty) { + Type::Range(int) => { + let int = Type::Int(*int); + let (Some(start), Some(end), false) = (&r.start, &r.end, closed) else { + fail(r, "a Range other than start..end") + }; + let elements = vec![self.check(start, &int), self.check(end, &int)]; + Expr::new(Kind::Tuple(elements), ty.clone()) + } + Type::Bounds(int) => { + let bound = Type::Bound(*int); + let mut end = |s: &mut Self, e: Option<&syn::Expr>, kind: BoundKind| match e { + None => Expr::new(Kind::Bound(BoundKind::Unbounded, None), bound.clone()), + Some(e) => { + let v = s.check(e, &Type::Int(*int)); + Expr::new(Kind::Bound(kind, Some(Box::new(v))), bound.clone()) + } + }; + let start = end(self, r.start.as_deref(), BoundKind::Included); + let last = end(self, r.end.as_deref(), if closed { BoundKind::Included } else { BoundKind::Excluded }); + Expr::new(Kind::Tuple(vec![start, last]), ty.clone()) + } + other => fail(r, format!("a range as {}", self.describe(other))), + } + } + + fn closure(&mut self, c: &syn::ExprClosure, ty: &Type) -> Expr { + let Type::Closure(closure) = unref(ty).base() else { + fail(c, format!("a closure as {}", self.describe(ty))) + }; + let closure = (**closure).clone(); + if closure.params.len() != c.inputs.len() { + fail(c, "a closure of another arity"); + } + let depth = self.vars.len(); + let params = c.inputs.iter().zip(&closure.params).map(|(p, ty)| self.bind(p, ty)).collect(); + let (steps, value) = self.body(&c.body, &closure.ok); + self.vars.truncate(depth); + Expr::new(Kind::Closure(params, steps, Box::new(value)), ty.clone()) + } + + /// A closure's body: the steps it runs, and its value, of type `ok`. + fn body(&mut self, body: &syn::Expr, ok: &Type) -> (Vec, Expr) { + let mut steps = Vec::new(); + let value = match body { + syn::Expr::Block(b) => { + let (last, init) = b.block.stmts.split_last().unwrap_or_else(|| fail(b, "an empty closure")); + init.iter().for_each(|s| self.stmt(s, &mut steps)); + match last { + syn::Stmt::Expr(e, None) => self.check(e, ok), + stmt => { + self.stmt(stmt, &mut steps); + Expr::new(Kind::Unit, Type::Unit) + } + } + } + syn::Expr::Macro(m) if m.mac.path.is_ident("println") => { + steps.push(Step::Print(self.print(&m.mac))); + Expr::new(Kind::Unit, Type::Unit) + } + body => self.check(body, ok), + }; + (steps, value) + } + + fn binary(&mut self, b: &syn::ExprBinary) -> Expr { + let op = match b.op { + syn::BinOp::Eq(_) => Op::Eq, + syn::BinOp::Ne(_) => Op::Ne, + syn::BinOp::Lt(_) => Op::Lt, + syn::BinOp::Gt(_) => Op::Gt, + syn::BinOp::Add(_) => Op::Add, + syn::BinOp::Sub(_) => Op::Sub, + syn::BinOp::Mul(_) => Op::Mul, + syn::BinOp::Rem(_) => Op::Rem, + syn::BinOp::And(_) => Op::And, + _ => fail(b, "this operator"), + }; + // The side whose type follows from itself types the other. + let (left, right) = match literalish(&b.left) { + false => { + let left = self.infer(&b.left); + let want = unref(&left.ty).clone(); + (left, self.check(&b.right, &want)) + } + true => { + let right = self.infer(&b.right); + let want = unref(&right.ty).clone(); + (self.check(&b.left, &want), right) + } + }; + let ty = match op { + Op::Eq | Op::Ne | Op::Lt | Op::Gt | Op::And => Type::Bool, + _ => unref(&left.ty).clone(), + }; + Expr::new(Kind::Binary(op, Box::new(left), Box::new(right)), ty) + } + + fn field(&mut self, f: &syn::ExprField) -> Expr { + let base = self.infer(&f.base); + let owner = unref(&base.ty).base().clone(); + match (&f.member, &owner) { + (syn::Member::Unnamed(i), Type::Tuple(elements)) => { + let ty = elements.get(i.index as usize).unwrap_or_else(|| fail(f, "no such element")).clone(); + Expr::new(Kind::Element(Box::new(base), i.index as usize), ty) + } + (syn::Member::Named(name), Type::Range(int)) if name == "start" || name == "end" => { + let at = usize::from(name == "end"); + Expr::new(Kind::Element(Box::new(base), at), Type::Int(*int)) + } + (syn::Member::Named(name), _) => { + let name = name.to_string(); + if let Type::Record(r) = owner + && let Some(i) = self.t.api.records[r].fields.iter().position(|f| f.name == name) + { + let ty = self.t.api.records[r].fields[i].ty.clone(); + return Expr::new(Kind::Field(Box::new(base), i), ty); + } + // A getter: an object's field, or an opaque value's. + let Some(id) = self.method_of(&owner, &name, |f| matches!(f.access, Access::Field { set: false, .. })) else { + fail(f, format!("no field {name} on {}", self.describe(&owner))) + }; + let ty = self.t.function(id).ok.clone(); + Expr::new(Kind::Call(id, Some(Box::new(base)), Vec::new()), ty) + } + _ => fail(f, format!("an element of {}", self.describe(&owner))), + } + } + + /// The method `name` of `owner`'s type for which `which` holds. + fn method_of(&self, owner: &Type, name: &str, which: impl Fn(&Function) -> bool) -> Option { + let (owner, methods) = self.methods(owner)?; + let index = methods.iter().position(|f| f.path.last().map(String::as_str) == Some(name) && which(f))?; + Some(FnId { owner, index }) + } + + fn methods(&self, ty: &Type) -> Option<(Owner, &Vec)> { + Some(match unref(ty).base() { + Type::Record(i) => (Owner::Record(*i), &self.t.api.records[*i].methods), + Type::Enum(i) => (Owner::Enum(*i), &self.t.api.enums[*i].methods), + Type::Object(i) => (Owner::Object(*i), &self.t.api.objects[*i].methods), + _ => return None, + }) + } + + /// A struct literal: a record's, or an enum's struct variant's. + fn structure(&mut self, s: &syn::ExprStruct, ty: Option<&Type>) -> Expr { + if let Some((e, v)) = self.find_variant(&s.path, None) { + let fields: Vec<(String, Type)> = + (self.t.api.enums[e].variants[v].fields.iter()).map(|f| (f.name.clone(), f.ty.clone())).collect(); + let values = self.fields(s, &fields); + return Expr::new(Kind::Variant(e, v, values), Type::Enum(e)); + } + let named = self.type_of_path(&s.path); + // A generic record's instance: the one the expected type names, else the first whose + // fields the literal's plainly fit. + let candidates: Vec = match (ty.map(|t| unref(t).base()), &named) { + (Some(Type::Record(i)), _) => vec![*i], + (_, Some(Type::Record(i))) => { + let path = &self.t.api.records[*i].path; + (0..self.t.api.records.len()).filter(|r| self.t.api.records[*r].path == *path).collect() + } + _ => fail(s, "a struct literal of no record"), + }; + let r = candidates + .iter() + .copied() + .find(|r| { + (self.t.api.records[*r].fields.iter()).all(|f| { + (s.fields.iter()) + .find(|fv| matches!(&fv.member, syn::Member::Named(n) if *n == f.name)) + .is_some_and(|fv| self.fits_expr(&fv.expr, &f.ty)) + }) + }) + .unwrap_or_else(|| fail(s, "a record literal fitting no instance")); + let fields: Vec<(String, Type)> = (self.t.api.records[r].fields.iter()).map(|f| (f.name.clone(), f.ty.clone())).collect(); + if fields.len() != s.fields.len() { + fail(s, "a record literal without each field"); + } + let values = self.fields(s, &fields); + Expr::new(Kind::Record(r, values), Type::Record(r)) + } + + fn fields(&mut self, s: &syn::ExprStruct, fields: &[(String, Type)]) -> Vec { + fields + .iter() + .map(|(name, ty)| { + let fv = (s.fields.iter()) + .find(|fv| matches!(&fv.member, syn::Member::Named(n) if n == name)) + .unwrap_or_else(|| fail(s, format!("no field {name}"))); + self.check(&fv.expr, ty) + }) + .collect() + } + + /// Whether `expr` may be of type `ty`, judged by what it plainly is without checking it: + /// a local's type, a struct literal's, or a suffixed literal's. What it cannot judge fits. + fn fits_expr(&self, expr: &syn::Expr, ty: &Type) -> bool { + let guess = match expr { + syn::Expr::Reference(r) => return self.fits_expr(&r.expr, ty), + syn::Expr::Paren(p) => return self.fits_expr(&p.expr, ty), + syn::Expr::Path(p) => match p.path.get_ident().and_then(|i| self.lookup(&i.to_string())) { + Some(Var::Typed(_, _, have)) => return fits(have, ty), + Some(Var::Alias(_, expr)) => return self.fits_expr(&expr.clone(), ty), + None => None, + }, + syn::Expr::Struct(s) => self.type_of_path(&s.path), + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), .. + }) if !i.suffix().is_empty() => int_named(i.suffix()).map(Type::Int), + syn::Expr::Call(c) if path_is(&c.func, "NonZero::new") => return matches!(unref(ty), Type::NonZero(_)), + syn::Expr::Call(c) if path_is(&c.func, "Bytes::from_static") => Some(Type::Bytes), + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(_), .. + }) => Some(Type::Str), + expr if const_duration(expr).is_some() => Some(Type::Duration), + syn::Expr::MethodCall(m) if m.method == "unwrap" => return self.fits_expr(&m.receiver, ty), + _ => None, + }; + match (guess, unref(ty).base()) { + (None, _) => true, + // A generic record's literal names its type but not the instance. + (Some(Type::Record(a)), Type::Record(b)) => self.t.api.records[a].path == self.t.api.records[*b].path, + (Some(have), want) => fits(&have, want), + } + } + + /// The enum and variant `path` names: by name, or for a foreign enum, as the constant + /// of the same name in capitals, such as tracing's `Level::WARN`. + fn find_variant(&self, path: &syn::Path, ty: Option<&Type>) -> Option<(usize, usize)> { + let names = self.segments(path); + let (variant, enum_path) = names.split_last()?; + let enum_path = enum_path.to_vec(); + let found = |e: &super::ir::Enum| { + e.path == enum_path || (e.path.last() == enum_path.last() && !enum_path.is_empty()) || e.foreign && ty.is_some() + }; + let (e, en) = (self.t.api.enums.iter().enumerate()).find(|(i, e)| { + found(e) && ty.is_none_or(|t| matches!(unref(t), Type::Enum(j) if j == i) || matches!(unref(t), Type::Option(inner) if **inner == Type::Enum(*i))) + })?; + let v = (en.variants.iter()).position(|v| &v.name == variant || (en.foreign && v.name.to_uppercase() == *variant))?; + Some((e, v)) + } + + /// A unit variant at `path`, or a tuple variant of `args`, as `ty` if given. + fn variant(&mut self, path: &syn::Path, args: &[syn::Expr], ty: Option<&Type>) -> Option { + // `LevelFilter::OFF`, the level filter that is none. + if let Some(Type::Option(_)) = ty + && path.segments.last().is_some_and(|s| s.ident == "OFF") + { + return Some(Expr::new(Kind::None, ty.unwrap().clone())); + } + let (e, v) = self.find_variant(path, ty)?; + let fields: Vec = self.t.api.enums[e].variants[v].fields.iter().map(|f| f.ty.clone()).collect(); + if fields.len() != args.len() { + fail(path, "a variant of another arity"); + } + let values = args.iter().zip(&fields).map(|(a, ty)| self.check(a, ty)).collect(); + let value = Expr::new(Kind::Variant(e, v, values), Type::Enum(e)); + Some(match ty { + Some(Type::Option(_)) => Expr::new(Kind::Some(Box::new(value)), ty.unwrap().clone()), + _ => value, + }) + } + + /// The functions `path` names: free functions, or associated functions of a type, + /// including methods called by their path with the receiver first. + fn functions(&self, path: &syn::Path) -> Vec { + let names = self.segments(path); + let Some((name, owner_path)) = names.split_last() else { return Vec::new() }; + let api = &self.t.api; + let mut exact = Vec::new(); + let mut loose = Vec::new(); + for (i, f) in api.functions.iter().enumerate() { + if f.path == names { + exact.push(FnId { owner: Owner::Free, index: i }); + } else if f.path.last() == Some(name) && names.len() == 1 { + loose.push(FnId { owner: Owner::Free, index: i }); + } + } + if !owner_path.is_empty() { + let owners = (api.records.iter().enumerate()) + .map(|(i, r)| (Owner::Record(i), &r.path, &r.methods)) + .chain(api.enums.iter().enumerate().map(|(i, e)| (Owner::Enum(i), &e.path, &e.methods))) + .chain(api.objects.iter().enumerate().map(|(i, o)| (Owner::Object(i), &o.path, &o.methods))); + for (owner, path, methods) in owners { + let list = match () { + _ if *path == owner_path => &mut exact, + _ if path.last() == owner_path.last() => &mut loose, + _ => continue, + }; + for (index, f) in methods.iter().enumerate() { + if f.path.last() == Some(name) && matches!(f.access, Access::Call | Access::Const | Access::Parse) { + list.push(FnId { owner, index }); + } + } + } + } + if exact.is_empty() { loose } else { exact } + } + + /// The function at `path` taking `args`, whose instance, for a generic one, is the one + /// the path's type arguments name, else the first whose parameters `args` plainly fit. + fn function(&self, path: &syn::Path, args: &[syn::Expr], expected: Option<&Type>) -> Option { + let turbofish: Vec = (path.segments.iter()) + .filter_map(|s| match &s.arguments { + syn::PathArguments::AngleBracketed(a) => Some(a), + _ => None, + }) + .flat_map(|a| &a.args) + .filter_map(|a| match a { + syn::GenericArgument::Type(t) => Some(self.ty(t)), + _ => None, + }) + .collect(); + self.pick(self.functions(path), args, expected, &turbofish) + } + + /// The candidate whose parameters `args` fit and whose return `expected` fits. + fn pick(&self, candidates: Vec, args: &[syn::Expr], expected: Option<&Type>, turbofish: &[Type]) -> Option { + let fitting: Vec = candidates + .into_iter() + .filter(|id| { + let f = self.t.function(*id); + let named: Vec = match &f.instance { + Some(i) if !i.named.is_empty() => i.named.clone(), + _ => match self.t.owner(*id).map(|o| unref(&o).clone()) { + Some(Type::Record(r)) => self.t.api.records[r].args.clone(), + Some(Type::Object(o)) => self.t.api.objects[o].args.clone(), + _ => Vec::new(), + }, + }; + let receiver = usize::from(f.receiver.is_some()); + let params: Vec<&Type> = f.params.iter().map(|p| &p.ty).collect(); + let args: Vec<&syn::Expr> = args.iter().filter(|a| !is_unit(a)).collect(); + turbofish.iter().zip(&named).all(|(t, n)| t == n) + && args.len() == params.len() + receiver + && args[receiver..].iter().zip(¶ms).all(|(a, ty)| self.fits_expr(a, ty)) + && expected.is_none_or(|e| f.err.is_some() || fits(&f.ok, e) || matches!(unref(e), Type::Result(..))) + }) + .collect(); + fitting.first().copied() + } + + /// A call of a path: the API's function, a variant, or a local function. + fn call(&mut self, call: &syn::ExprCall, expected: Option<&Type>) -> Expr { + let syn::Expr::Path(p) = &*call.func else { + fail(call, "a call of anything but a path") + }; + let args: Vec = call.args.iter().cloned().collect(); + if let Some(name) = p.path.get_ident().map(|i| i.to_string()) + && let Some(output) = self.locals.get(&name) + { + let ty = match output.clone() { + syn::ReturnType::Default => Type::Unit, + syn::ReturnType::Type(_, ty) => self.ty(&ty), + }; + let args = args.iter().map(|a| self.infer(a)).collect(); + return Expr::new(Kind::Local(name, args), ty); + } + if path_is(&call.func, "String::from_utf8_lossy") { + let value = self.infer(&args[0]); + return Expr::new(Kind::Utf8(Box::new(value)), Type::String); + } + if let Some(e) = self.variant(&p.path, &args, None) { + return e; + } + // A type's `Default`, which the IR keeps among its traits. + if p.path.segments.last().is_some_and(|s| s.ident == "default") && args.is_empty() { + let mut owner = p.path.clone(); + owner.segments.pop(); + owner.segments.pop_punct(); + if let Some(ty) = self.type_of_path(&owner) { + return Expr::new(Kind::Default, ty); + } + } + let Some(id) = self.function(&p.path, &args, expected) else { + fail(call, format!("a call of {}, which the API does not export", self.segments(&p.path).join("::"))) + }; + let args: Vec = args.into_iter().filter(|a| !is_unit(a)).collect(); + match self.t.function(id).receiver { + // A method called by its path, its receiver first. + Some(_) => { + let receiver = self.infer(&args[0]); + self.apply(call, id, Some(receiver), &args[1..]) + } + None => self.apply(call, id, None, &args), + } + } + + /// The call of `id` on `receiver`, with `args` checked against its parameters. + fn apply(&mut self, at: &dyn Spanned, id: FnId, receiver: Option, args: &[syn::Expr]) -> Expr { + let params: Vec = self.t.function(id).params.iter().map(|p| p.ty.clone()).collect(); + let args: Vec<&syn::Expr> = args.iter().filter(|a| !is_unit(a)).collect(); + if params.len() != args.len() { + fail(at, format!("{} takes {} arguments", self.t.key(id), params.len())); + } + let args = args.iter().zip(¶ms).map(|(a, ty)| self.check(a, ty)).collect(); + self.apply_checked(id, receiver, args) + } + + fn apply_checked(&self, id: FnId, receiver: Option, args: Vec) -> Expr { + let f = self.t.function(id); + let ty = match &f.err { + Some(err) => Type::Result(Box::new(f.ok.clone()), Box::new(err.clone())), + None => f.ok.clone(), + }; + Expr::new(Kind::Call(id, receiver.map(Box::new), args), ty) + } + + fn method(&mut self, m: &syn::ExprMethodCall, expected: Option<&Type>) -> Expr { + let name = m.method.to_string(); + let args: Vec = m.args.iter().cloned().collect(); + match name.as_str() { + "join" if matches!(m.args.first(), Some(syn::Expr::Lit(_))) => return self.join(m), + "parse" => { + let Some(ty) = (m.turbofish.iter().flat_map(|t| &t.args)).find_map(|a| match a { + syn::GenericArgument::Type(t) => Some(self.ty(t)), + _ => None, + }) else { + fail(m, "a parse without the type it makes") + }; + let f = self.method_of(&ty, "parse", |f| f.access == Access::Parse); + let err = f.and_then(|id| self.t.function(id).err.clone()).unwrap_or(Type::String); + return self.parsed(m, &Type::Result(Box::new(ty), Box::new(err))); + } + // `String::from_utf8(..).unwrap()`, of bytes the transcript knows are text. + "unwrap" if matches!(&*m.receiver, syn::Expr::Call(c) if path_is(&c.func, "String::from_utf8")) => { + let syn::Expr::Call(c) = &*m.receiver else { unreachable!() }; + let value = self.infer(&c.args[0]); + return Expr::new(Kind::Utf8(Box::new(value)), Type::String); + } + // `.err().unwrap()`, the error of a call that must fail. + "unwrap" if matches!(&*m.receiver, syn::Expr::MethodCall(e) if e.method == "err" && e.args.is_empty()) => { + let syn::Expr::MethodCall(e) = &*m.receiver else { unreachable!() }; + let value = self.infer(&e.receiver); + let Type::Result(_, err) = &value.ty else { + fail(e, "err() of no Result") + }; + let err = (**err).clone(); + return Expr::new(Kind::UnwrapErr(Box::new(value)), err); + } + _ => {} + } + let receiver = self.infer(&m.receiver); + let rty = unref(&receiver.ty).clone(); + let only = |kind: fn(Box) -> Kind, ty: Type, receiver: Expr| { + if !args.is_empty() { + fail(m, format!("{name} with arguments")); + } + Expr::new(kind(Box::new(receiver)), ty) + }; + // The API's own method of the name first, then the standard library's. + let api = self.methods_named(&rty, &name); + if api.is_empty() { + match (name.as_str(), rty.base()) { + ("unwrap" | "expect", Type::Option(inner) | Type::Result(inner, _)) => { + let inner = (**inner).clone(); + return Expr::new(Kind::Unwrap(Box::new(receiver)), inner); + } + ("unwrap_err", Type::Result(_, err)) => { + let err = (**err).clone(); + return only(Kind::UnwrapErr, err, receiver); + } + ("is_some", Type::Option(_)) => return only(Kind::IsSome, Type::Bool, receiver), + ("is_none", Type::Option(_)) => return only(Kind::IsNone, Type::Bool, receiver), + ("is_err", Type::Result(..)) => return only(Kind::IsErr, Type::Bool, receiver), + ("len", Type::List(..) | Type::Vec | Type::Slice | Type::Bytes | Type::String | Type::Str) => { + return only(Kind::Len, Type::Int(Int::Usize), receiver); + } + ("clone", _) => { + let ty = receiver.ty.clone(); + return only(Kind::Clone, ty, receiver); + } + // A `NonZero`'s value, which crosses as its integer. + ("get", Type::NonZero(_)) => return receiver, + ("collect", Type::Vec | Type::Slice | Type::Bytes) => return Expr::new(receiver.kind, Type::Vec), + // A list collected again: the items, now a `Vec` of them. + ("collect", Type::List(_, item)) => { + let item = item.clone(); + return Expr::new(receiver.kind, Type::List(Collection::Vec, item)); + } + ("map_or", Type::Option(inner)) => { + let inner = (**inner).clone(); + return self.map_or(m, receiver, &inner); + } + (conversion, _) if CONVERSIONS.contains(&conversion) && args.is_empty() => { + let _ = expected; + return receiver; + } + _ => fail(m, format!("no method {name} on {}", self.describe(&rty))), + } + } + let turbofish: Vec = (m.turbofish.iter().flat_map(|t| &t.args)) + .filter_map(|a| match a { + syn::GenericArgument::Type(t) => Some(self.ty(t)), + _ => None, + }) + .collect(); + let mut with_receiver = vec![(*m.receiver).clone()]; + with_receiver.extend(args.iter().cloned()); + let id = self + .pick(api, &with_receiver, expected, &turbofish) + .unwrap_or_else(|| fail(m, format!("no instance of {name} on {} fits", self.describe(&rty)))); + self.apply(m, id, Some(receiver), &args) + } + + /// `option.map_or(none, |v| some)`. + fn map_or(&mut self, m: &syn::ExprMethodCall, option: Expr, inner: &Type) -> Expr { + let [none, syn::Expr::Closure(c)] = m.args.iter().collect::>()[..] else { + fail(m, "a map_or other than of a default and a closure") + }; + let none = self.infer(none); + let [p] = c.inputs.iter().collect::>()[..] else { + fail(c, "a map_or closure of one parameter") + }; + let depth = self.vars.len(); + let pat = self.bind(p, inner); + let ty = none.ty.clone(); + let some = self.check(&c.body, &ty); + self.vars.truncate(depth); + Expr::new( + Kind::MapOr { + option: Box::new(option), + none: Box::new(none), + pat, + some: Box::new(some), + }, + ty, + ) + } + + /// `items.map(|pat| body).collect::>().join(sep)`. + fn join(&mut self, m: &syn::ExprMethodCall) -> Expr { + let [syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(sep), .. + })] = m.args.iter().collect::>()[..] + else { + fail(m, "a join other than on a string literal") + }; + let syn::Expr::MethodCall(collect) = &*m.receiver else { + fail(m, "a join of anything but a collect") + }; + let syn::Expr::MethodCall(map) = &*collect.receiver else { + fail(collect, "a collect of anything but a map") + }; + if collect.method != "collect" || map.method != "map" { + fail(m, "a join of anything but .map(..).collect()"); + } + let [syn::Expr::Closure(c)] = map.args.iter().collect::>()[..] else { + fail(map, "a map of anything but a closure") + }; + let items = self.infer(&map.receiver); + let Type::List(_, item) = unref(&items.ty).base() else { + fail(map, format!("a map over {}", self.describe(&items.ty))) + }; + let item = (**item).clone(); + let [p] = c.inputs.iter().collect::>()[..] else { + fail(c, "a map's closure of one parameter") + }; + let depth = self.vars.len(); + let pat = self.bind(p, &item); + let body = self.check(&c.body, &Type::String); + self.vars.truncate(depth); + Expr::new( + Kind::Join { + items: Box::new(items), + pat, + body: Box::new(body), + sep: sep.value(), + }, + Type::String, + ) + } + + fn methods_named(&self, owner: &Type, name: &str) -> Vec { + let Some((owner, methods)) = self.methods(owner) else { return Vec::new() }; + (methods.iter().enumerate()) + .filter(|(_, f)| f.path.last().map(String::as_str) == Some(name) && f.receiver.is_some() && f.access == Access::Call) + .map(|(index, _)| FnId { owner, index }) + .collect() + } + + fn describe(&self, ty: &Type) -> String { + match ty { + Type::Record(_) | Type::Enum(_) | Type::Object(_) => self.t.rust(ty), + ty => format!("{ty:?}"), + } + } +} + +/// Whether `expr` is `()`, an argument the IR drops. +fn is_unit(expr: &syn::Expr) -> bool { + matches!(expr, syn::Expr::Tuple(t) if t.elems.is_empty()) +} + +/// Whether `expr` is the path ending in `path`, such as `String::from`. +fn path_is(expr: &syn::Expr, path: &str) -> bool { + let syn::Expr::Path(p) = expr else { return false }; + let names: Vec = p.path.segments.iter().map(|s| s.ident.to_string()).collect(); + let want: Vec<&str> = path.split("::").collect(); + names.len() >= want.len() && names[names.len() - want.len()..].iter().zip(&want).all(|(a, b)| a == b) +} + +/// Whether `expr` takes its type from the other side of an operator, as a literal does. +fn literalish(expr: &syn::Expr) -> bool { + match expr { + syn::Expr::Lit(_) => true, + syn::Expr::Unary(u) => literalish(&u.expr), + syn::Expr::Paren(p) => literalish(&p.expr), + _ => false, + } +} + +fn int_named(name: &str) -> Option { + Some(match name { + "u8" => Int::U8, + "u16" => Int::U16, + "u32" => Int::U32, + "u64" => Int::U64, + "usize" => Int::Usize, + "i8" => Int::I8, + "i16" => Int::I16, + "i32" => Int::I32, + "i64" => Int::I64, + "isize" => Int::Isize, + _ => return None, + }) +} + +/// An integer spelled by literals, constants such as `u64::MAX`, shifts, sums, and casts, +/// or `NonZero::new(..).unwrap()` of one. +fn const_int(expr: &syn::Expr) -> Option { + let num = |v: i128| Some(Num::new(v)); + match expr { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), .. + }) => Some(Num { + negative: false, + magnitude: i.base10_parse().ok()?, + }), + syn::Expr::Paren(p) => const_int(&p.expr), + syn::Expr::Cast(c) => const_int(&c.expr), + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => { + let n = const_int(&u.expr)?; + Some(Num { + negative: !n.negative, + ..n + }) + } + syn::Expr::Binary(b) => { + let (l, r) = (const_int(&b.left)?, const_int(&b.right)?); + let (l, r) = (l.magnitude, r.magnitude); + match b.op { + syn::BinOp::Shl(_) => Some(Num { + negative: false, + magnitude: l << r, + }), + syn::BinOp::Add(_) => Some(Num { + negative: false, + magnitude: l + r, + }), + _ => None, + } + } + syn::Expr::MethodCall(m) if m.method == "unwrap" => match &*m.receiver { + syn::Expr::Call(c) if path_is(&c.func, "NonZero::new") => const_int(&c.args[0]), + _ => None, + }, + syn::Expr::Path(p) => { + let names: Vec = p.path.segments.iter().map(|s| s.ident.to_string()).collect(); + let [ty, name] = &names[..] else { return None }; + let bits = |signed: bool, bits: u32| match (name.as_str(), signed) { + ("MAX", false) => Some(Num { + negative: false, + magnitude: if bits == 128 { u128::MAX } else { (1u128 << bits) - 1 }, + }), + ("MAX", true) => num((1i128 << (bits - 1)) - 1), + ("MIN", false) => num(0), + ("MIN", true) => Some(Num { + negative: true, + magnitude: 1u128 << (bits - 1), + }), + _ => None, + }; + match ty.as_str() { + "u128" => bits(false, 128), + "char" if name == "MAX" => num(char::MAX as i128), + ty => { + let int = int_named(ty)?; + bits(int.signed(), int.bits()) + } + } + } + _ => None, + } +} + +/// A float spelled by a literal, `f64::NAN`, `f64::from_bits(..)`, or a negation of one. +fn const_float(expr: &syn::Expr) -> Option { + match expr { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Float(f), .. + }) => f.base10_parse().ok(), + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), .. + }) => i.base10_parse().ok(), + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => const_float(&u.expr).map(|f| -f), + syn::Expr::Path(p) if p.path.segments.last()?.ident == "NAN" => Some(f64::NAN), + syn::Expr::Call(c) if path_is(&c.func, "f64::from_bits") => Some(f64::from_bits(const_int(&c.args[0])?.bits())), + _ => None, + } +} + +/// A `Duration` spelled by its constructors or constants: its seconds and nanoseconds. +fn const_duration(expr: &syn::Expr) -> Option<(u64, u32)> { + match expr { + syn::Expr::Path(p) => match p.path.segments.last()?.ident.to_string().as_str() { + "ZERO" => Some((0, 0)), + "MAX" => Some((u64::MAX, 999_999_999)), + _ => None, + }, + syn::Expr::Call(c) => { + let v = const_int(c.args.first()?)?.magnitude as u64; + let syn::Expr::Path(p) = &*c.func else { return None }; + match p.path.segments.last()?.ident.to_string().as_str() { + "from_secs" => Some((v, 0)), + "from_millis" => Some((v / 1000, (v % 1000) as u32 * 1_000_000)), + "from_nanos" => Some((v / 1_000_000_000, (v % 1_000_000_000) as u32)), + _ => None, + } + } + _ => None, + } +} + +/// An address spelled by literals: parsed from text, or built by `std::net`'s +/// constructors and constants. +enum Net { + Text(String), + Socket(std::net::SocketAddr), + Ip(std::net::IpAddr), +} + +fn const_net(expr: &syn::Expr) -> Option { + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6}; + let int = |e: &syn::Expr| const_int(e).map(|n| n.magnitude); + match expr { + syn::Expr::Paren(p) => const_net(&p.expr), + syn::Expr::MethodCall(m) if m.method == "into" => const_net(&m.receiver), + syn::Expr::MethodCall(m) if m.method == "unwrap" => match &*m.receiver { + syn::Expr::MethodCall(p) if p.method == "parse" => match &*p.receiver { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(s), .. + }) => Some(Net::Text(s.value())), + _ => None, + }, + _ => None, + }, + syn::Expr::Path(p) => { + let names: Vec = p.path.segments.iter().map(|s| s.ident.to_string()).collect(); + let [.., ty, name] = &names[..] else { return None }; + Some(Net::Ip(match (ty.as_str(), name.as_str()) { + ("Ipv4Addr", "BROADCAST") => IpAddr::V4(Ipv4Addr::BROADCAST), + ("Ipv4Addr", "LOCALHOST") => IpAddr::V4(Ipv4Addr::LOCALHOST), + ("Ipv6Addr", "LOCALHOST") => IpAddr::V6(Ipv6Addr::LOCALHOST), + _ => return None, + })) + } + syn::Expr::Call(c) => { + let args: Vec<&syn::Expr> = c.args.iter().collect(); + if path_is(&c.func, "Ipv4Addr::new") { + let o: Vec = args.iter().map(|a| int(a).map(|v| v as u8)).collect::>()?; + return Some(Net::Ip(IpAddr::V4(Ipv4Addr::new(o[0], o[1], o[2], o[3])))); + } + if path_is(&c.func, "Ipv6Addr::new") { + let s: Vec = args.iter().map(|a| int(a).map(|v| v as u16)).collect::>()?; + return Some(Net::Ip(IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7])))); + } + let ip = |e: &syn::Expr| match const_net(e)? { + Net::Ip(ip) => Some(ip), + _ => None, + }; + if path_is(&c.func, "SocketAddrV4::new") { + let IpAddr::V4(v4) = ip(args[0])? else { return None }; + return Some(Net::Socket(SocketAddrV4::new(v4, int(args[1])? as u16).into())); + } + if path_is(&c.func, "SocketAddrV6::new") { + let IpAddr::V6(v6) = ip(args[0])? else { return None }; + let addr = SocketAddrV6::new(v6, int(args[1])? as u16, int(args[2])? as u32, int(args[3])? as u32); + return Some(Net::Socket(addr.into())); + } + None + } + _ => None, + } +} + +/// Whether a value of `have` passes where `want` is taken: the same type, behind any +/// references or boxes, a string or bytes in any of their forms, or an address of one +/// family where any is. +pub(super) fn fits(have: &Type, want: &Type) -> bool { + let (have, want) = (unref(have).base(), unref(want).base()); + let text = |t: &Type| matches!(t, Type::Str | Type::String); + let bytes = |t: &Type| matches!(t, Type::Slice | Type::Vec | Type::Bytes | Type::Array(_)); + let path = |t: &Type| matches!(t, Type::Path | Type::PathBuf); + match (have, want) { + (Type::Option(a), Type::Option(b)) => fits(a, b), + (Type::List(_, a), Type::List(_, b)) => fits(a, b), + (Type::Tuple(a), Type::Tuple(b)) => a.len() == b.len() && a.iter().zip(b).all(|(a, b)| fits(a, b)), + (Type::SocketAddr(_), Type::SocketAddr(Family::Any)) | (Type::IpAddr(_), Type::IpAddr(Family::Any)) => true, + (a, b) => a == b || (text(a) && text(b)) || (bytes(a) && bytes(b)) || (path(a) && path(b)), + } +} From 2a13cc51179fb6381eecaf7379633e1e84cc53f4 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 04:00:31 -0800 Subject: [PATCH 04/28] wip: generate the Python transcript Co-Authored-By: Claude Opus 5.5 --- ffi/src/python.rs | 3 +- ffi/tests/api.py | 730 +++------------------- ffi/tests/fixtures.rs | 35 +- ffi/tests/fixtures/transcript/ir.rs | 9 + ffi/tests/fixtures/transcript/mod.rs | 24 +- ffi/tests/fixtures/transcript/python.rs | 795 +++++++++++++++++++++++- 6 files changed, 944 insertions(+), 652 deletions(-) diff --git a/ffi/src/python.rs b/ffi/src/python.rs index 66d2a8a9d..c0f36b231 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -1661,6 +1661,7 @@ impl<'a> Gen<'a> { let member = match (place, constant) { (Place::Top, true) => self.claim(&member.to_uppercase(), format!("const `{}`", function.path.join("::"))), (Place::Top, false) => self.claim(&member, format!("fn `{}`", function.path.join("::"))), + (Place::Static, true) => member.to_uppercase(), _ => member, }; @@ -1916,7 +1917,7 @@ impl<'a> Gen<'a> { return None; } (Access::Const, Place::Static) if constant => { - let name = member.to_uppercase(); + let name = member.clone(); self.natives .push(format!("@_staticmethod\ndef {bare}() -> {ret}: ...\n")); // An `Enum` makes a member of any other value, to a type checker as at run time. diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 43cebc3f9..1b5fc7d35 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -1,5 +1,6 @@ # The api fixture's Python test: the script fixtures/api/examples/transcript.rs runs -# natively, through the generated Python. tests/fixtures.rs compares the transcripts. +# natively, through the Python tests/fixtures/transcript writes from it, which calls the +# functions here that transcript.rs defines. tests/fixtures.rs compares the transcripts. # # With an argument, it instead checks the futures' semantics, what frees what nobody # closed, the values only Python's types bound, or how Python calls into the extension, @@ -25,7 +26,7 @@ sys.stdout.reconfigure(encoding="utf-8", newline="\n") -class PrintLog(api.Log): +class Print(api.Log): """The Log callback: keeps even levels.""" def log(self, level, line): @@ -123,6 +124,42 @@ def socket_hex(addr): return ":".join([ip] + [str(part) for part in addr[1:]]) +def hex(data): + return bytes(data).hex() + + +def path_hex(path): + return os.fsencode(path).hex() + + +def seconds(duration): + return f"{duration.secs}.{duration.nanos:09}" + + +def code(c): + return ord(c) + + +def reversed(items): + return items[::-1] + + +def f64_bits(floats): + return bits(floats, "Q") + + +def ip_hex(ip): + return ip.packed.hex() + + +def unspelled(): + """A path no Rust string spells: on Unix, bytes that are not UTF-8; on Windows, a + lone surrogate.""" + if os.name == "nt": + return "\ud800" + return api.stray() + + def check(ok, what): if not ok: print(f"failed: {what}", file=sys.stderr) @@ -144,280 +181,15 @@ async def wait(): loop.run_until_complete(asyncio.wait_for(wait(), 5)) + def script(): - print(f"limit {api.LIMIT}") - - p = api.Point(1, 2).offset(2, 3) - print(f"offset {p.x} {p.y}") - print(f"debug {p!r}") - print(f"eq {flag(p == api.Point(3, 5))}") - d = api.Point.default() - print(f"default {d.x} {d.y}") - - c = api.Counter.new("c", 5) - print(f"get {c.get()}") - print(f"name {c.name()}") - print(f"add ok {c.add(10)}") - try: - c.add(2000) - except api.ErrorException as e: - print(f"add err {e} {e.error!r}") - try: - c.sub(20) - except api.ErrorException as e: - print(f"sub err {e} {e.error!r}") - c.rename("d") - print(f"name {c.name()}") - print(f"is d {flag(c.is_('d'))}") - copy = c.clone() - copy.add(1) - print(f"clone {copy.get()} original {c.get()}") - print(f"debug {c!r}") - label = c.into_label(p) - print(f"label {label!r}") - print(f"note {flag(api.has_text(api.Note('')))} {flag(api.has_text(api.Note(None)))}") - - below, above = api.Counter.new("s", 7).split(5) - print(f"split {below.name()} {below.get()} {above.name()} {above.get()}") - (only,) = api.only(api.Counter.new("o", 3)) - print(f"only {only.name()} {only.get()}") - w8, w16, w32, w64 = api.widths(98305) - print(f"widths {w8} {w16} {w32} {w64}") - for b in [2, 0]: - try: - q, r = api.divide(7, b) - print(f"divide {q} {r}") - except api.ErrorException as e: - print(f"divide err {e}") - for n in [98305, 0]: - spread = api.spread(n) - print("spread none" if spread is None else f"spread {spread[0]} {spread[1]} {spread[2]} {spread[3]}") - for needle in [b"lo", b"x"]: - found = api.find(b"hello", needle) - print("find none" if found is None else f"find {found[0]} {found[1]}") - stat_rows = api.rows([api.Point(1, 2), api.Point(3, 3)]) - print("rows " + ", ".join(f"{name} {shape!r} {p.x} {p.y}" for name, shape, p in stat_rows)) - # Each handle in a tuple moves in, as one taken by value does. - board = api.Board.new([("low", api.Counter.new("l", 1)), ("high", api.Counter.new("h", 9))]) - ranked = board.ranked() - print("ranked " + ", ".join(f"{name} {counter.name()} {counter.get()}" for name, counter in ranked)) - best = board.best() - print(f"best {best.name()} {best.get()}") - # A map crosses as its pairs and a set as its items, which Rust collects in order, each - # key once, the last kept. - atlas = api.Atlas([("b", api.Point(1, 1)), ("ab", api.Point(2, 3)), ("b", api.Point(4, 4))], [3, 1, 3]) - atlas = atlas.with_("c", api.Point(5, 6)) - atlas_points = ", ".join(f"{name} {p.x} {p.y}" for name, p in atlas.points) - print(f"atlas {atlas_points}; ids {' '.join(str(i) for i in atlas.ids)}") - # Another crate's error crosses as its message. - for port_text in ["80", "x"]: - try: - print(f"port {api.port(port_text)}") - except api.StringException as e: - print(f"port err {e.error}") - span = api.Span((2, 10), ("s", api.Shape.SQUARE)) - lower_half, upper_half = api.halves(span) - print(f"halves {lower_half[0]} {lower_half[1]} {upper_half[0]} {upper_half[1]} {span!r}") - swapped_n, swapped_text = api.swapped(("t", 4)) - print(f"swapped {swapped_n} {swapped_text}") - for value in [None, (None,), (3,)]: - doubled = api.doubled(value) - if doubled is None: - print("doubled None") - else: - print(f"doubled Some(({'None' if doubled[0] is None else f'Some({doubled[0]})'},))") - # A borrowed or boxed tuple of one is a tuple, not its element. - lent_one = list(data(api.lent_back((bytes([1, 2]),))[0])) - boxed_one = list(data(api.boxed_tuple(bytes([3]))[0])) - print(f"lent back {lent_one} boxed {boxed_one}") - # A borrowed string and an owned one share a tuple struct. - print( - f'title Some(("{api.title(True)[0]}",)) {"None" if api.title(False) is None else "Some"} ' - f'named Some(("{api.named("x")[0]}",))' - ) - - # Each lent counter is a new handle to a clone. - registry = api.Registry.new(api.Counter.new("first", 1)) - print(f"last {flag(registry.last() is not None)}") - registry.push(api.Counter.new("last", 2)) - first = registry.first_get - first.add(10) - print(f"first {registry.first_get.get()} lent {first.get()}") - last = registry.last() - last.add(10) - print(f"last {registry.last().get()} lent {last.get()}") - # A closure lent for the call edits the first counter through a handle. - by = 5 - - def edit(counter): - counter.add(by) - return counter.edited() and counter.get() == 6 - - print(f"edit {flag(registry.edit(edit))} {registry.first_get.get()}") - # A setter moves an object in, as assignment does, closing it. - registry.first_set(api.Counter.new("second", 3)) - print(f"set first {registry.first_get.get()} {registry.first_get.name()}") - print(f"walk {api.walk(3, lambda cursor: cursor.at() * 2)}") - print(f"each {api.each(2, lambda at: print(f'visit {at}'))}") - print(f"offset {api.offset(lambda: 7, 3)}") - print(f"shift {api.shift(lambda: 7, 4)}") - - name = api.Name.owned("a") - joined = name.join(api.Name.owned("b")) - print(f"joined {joined.as_str()} {joined!r} {flag(joined == name)}") - joined.rename("c") - print(f"renamed {joined.as_str()}") - long = api.longer(joined, api.Name.owned("dd")) - print(f"longer {long.as_str()}") - print(f"unnamed [{api.unnamed().as_str()}]") - lit = api.Name.borrowed("lit") - shares = [str(lit.shares(api.Name.borrowed(text))).lower() for text in ("lit", "other")] - print(f"borrowed {lit.as_str()} {' '.join(shares)}") - - print(f"total {api.total(range(2, 5))}") - print(f"reach {api.reach(2, 5)}") - scaled = [api.scaled(2**128 - 1, 1), api.scaled(2**64 + 1, 2**63), api.scaled(2**127, 2)] - print("scaled " + " ".join("none" if v is None else f"{v:032x}" for v in scaled)) - digest = api.Digest.new() - digest.sum_set(api.fingerprint("deadbeef")) - try: - api.fingerprint("zz") - unparsed = "" - except api.StringException as e: - unparsed = e.error - flipped = digest.flipped(api.ArrayU8x4(bytes([0xFF, 0, 0xFF, 0]))) - print(f"digest {digest.sum_get.hex()} {flipped.hex()} {unparsed}") - batch, batch2 = api.Batch.new(), api.pair() - accepted = sum(batch.push(v) for v in range(1, 6)) - paired = sum(batch2.push(v) for v in range(1, 4)) - emptied = api.drain_4(batch) - print(f"batch {batch.capacity()} {accepted} {emptied} {api.drain_4(batch)} {batch2.capacity()} {paired} {api.drain_2(batch2)}") - print(f"capacities {api.capacities_4_2(batch, batch2)} {api.capacities_2_2(batch2, batch2)}") - wide = api.widen(range(2, 5), 1) - print(f"widen {wide.start} {wide.stop}") - inc, exc, unb = api.Bound.INCLUDED, api.Bound.EXCLUDED, api.Bound.UNBOUNDED - counts = [ - api.count(api.BoundsU64(api.BoundU64(start, s), api.BoundU64(end, e))) - for (start, s), (end, e) in [ - ((inc, 2), (exc, 5)), - ((inc, 2), (inc, 5)), - ((inc, 3), (unb, 0)), - ((unb, 0), (unb, 0)), - ((exc, 2), (inc, 4)), - ] - ] - print("count " + " ".join(str(n) for n in counts)) - print(f"end {bound(api.end(3))} {bound(api.end(0))}") - ends_start, ends_end = api.ends(3) - print(f"ends {bound(ends_start)} {bound(ends_end)}") - for n in [2, 5]: - try: - print(f"below {api.below(n, 3)}") - except api.BoundsU64Exception as e: - print(f"below err {bound(e.error.start)} {bound(e.error.end)}") - window = api.Window(range(2, 8), api.end(5)) - print(f"window {flag(window.contains(4))} {flag(window.contains(6))} {window!r}") - - print(api.greet("x", api.Shape.SQUARE)) - print(f"len {api.len(b'abc')}") - binary = bytes([0xFF, 0, ord("a")]) - print(f"hex {api.hex(binary)}") - print(f"timed hex {api.timed_hex(binary)}") - print(f"sample hex {api.sample_hex(binary)}") - print(f"queued hex {api.queued_hex(binary)}") - print(f"tick {api.tick_name(api.Label('tick', None, None))}") - print(f"rooted {api.rooted_name(api.Label('rooted', None, None))}") - print(f"stored {api.stored_text('stored')}") - print(f"layer {api.layer_name(api.Label('layer', None, None))}") - for event in [api.Event.Moved(p), api.Event.Named("n"), api.Event.Done()]: - print(api.describe(event)) - - # A `Copy` handle passed by value is copied, so it stays usable. - stamp = api.Stamp.from_millis(2500) - print(f"secs {stamp.secs()}") - print(f"later {flag(api.Stamp.from_millis(3000).later(stamp))}") - print(f"secs {stamp.secs()}") - print(f"whole {stamp.whole()!r}") - message = api.Message.new(stamp, b"body") - print(f"payload {text(message.payload_get)}") - print(f"stamp {message.stamp_get!r}") - print(f"sent {flag(message.sent())}") - # Setters assign in place: the bytes are copied in, and a `Copy` handle copied. - reset = api.Stamp.from_millis(4000) - message.stamp_set(reset) - message.payload_set(b"edited") - print(f"payload {text(message.payload_get)}") - print(f"stamp {message.stamp_get!r}") - print(f"secs {reset.secs()}") - message.stamp_set(None) - print(f"stamp {flag(message.stamp_get is not None)}") - - # A value past a word, copied across: a closure takes and returns one by value. - moment = api.Moment.new(1500, 1000) - print(f"moment {moment.millis()} {flag(api.Moment.new(1, 0) is None)}") - shifted = api.shifted(moment, lambda m: m.after(500)) - print(f"shifted {shifted.millis()} {flag(shifted == moment.after(500))}") - print(f"wrapped {moment.after(2**64 - 1).millis()} {flag(moment == shifted)}") - try: - api.Moment() - check(False, "Python makes no opaque value") - except TypeError: - pass + import transcript - # A value with padding, or bytes that vary, is a handle, as no table says where padding is. - gap = api.Gap.new(7, 3) - print(f"gap {gap.sum()} {flag(gap == api.Gap.new(7, 3))}") - berth = api.Berth.new(4) - print(f"berth Some({berth.at()}) {'None' if api.Berth.new(None).at() is None else 'Some'}") - - # A `Copy` type changed in place is a value, which a `&mut self` method returns as the - # call left it, Rust's own return beside it: a change reaches only the copy it replaces. - score = api.Score.of(2) - increment = api.Score.of(3) - score = score.add(increment) - score = score.add(increment) - print(f"score {score.count()} {increment.doubled().count()} {increment.count()}") - score_copy, taken = score.take() - print(f"taken {taken} {score_copy.count()} {score.count()}") - other_score = api.Mut(increment) - score_copy, before0, before1 = score_copy.absorb(other_score) - print(f"absorbed {before0} {before1} {score_copy.count()} {other_score.value.count()} {increment.count()}") - hits = api.Hits.of(1, 2) - kept_hits = hits - hits = hits.add(api.Hits.of(10, 20)) - hits = hits.hits_set(7) - print(f"hits {hits.hits_get} {hits.misses_get} {kept_hits.hits_get} {kept_hits.misses_get} {flag(hits == kept_hits)}") - counted, same = kept_hits.eq(kept_hits) - print(f"counted {flag(same)} {counted.hits_get}") - extent = api.Extent.new(5, 3) - extent_start = extent - extent, old = extent.slide(10) - extent = extent.start_set(extent.start_get + 1) - print(f"extent {old} {extent.start_get} {extent.end()} {extent_start.start_get} {extent_start.end()}") - weighted = api.Weighted(increment, 4) - print(f"weighted {weighted.total()} {weighted.score.count() + increment.count()}") - # A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. - mark = api.Mark.of(1) - mark.add(2) - print(f"heft {api.heft((mark, b'ab'), api.Parcel(mark, b'abc'), (api.Counter.new('w', 1), b'abcd'))}") - # A value's `&mut self` beside a checked handle. - noted, noted_before = api.Score.of(2).note(api.Mark.of(5)) - print(f"noted {noted_before} {noted.count()}") - - print(f"kept {api.emit(PrintLog(), bytes([1, 2, 3, 4]))}") - logger = api.Logger.new(PrintLog()) - print(f"write {flag(logger.write('hi'))}") - del logger - print("dropped") - # Rust calls it on another thread, before the call returns. - threshold = 2 - - def keep(level, line): - print(f"filter {level} {line}") - return level > threshold - - print(f"filtered {api.filter(bytes([1, 2, 3, 4]), keep)}") + transcript.script() + +def channel(): + """A channel's futures, on a loop the script steps.""" loop = asyncio.new_event_loop() channel = api.Channel.new() wakes = 0 @@ -500,358 +272,13 @@ async def polls(): channel.clear() loop.close() - nodes = api.Node.new(1, None) - nodes.push(2) - print(f"node {nodes.sum()}") - - tally = api.Tally.new() - tally.bump() - print(f"tally {tally.bump()} {flag(tally == tally)}") - print(f"both {api.bump_both(tally, tally)}") - print(f"peek {api.peek(tally, lambda lent: lent.bump())}") - - area = api.grow(api.Area.new(api.Size(2, 3)), 1) - size = area.size() - print(f"area {size.width} {size.height} {area.pixels()}") - - # Generic types, each at the instances it infers, named by their arguments. - pair = api.PairU32(2, 5) - swapped = pair.swap() - print(f"pair {swapped.left} {swapped.right} sum {pair.sum()} {pair!r} {flag(pair == swapped)}") - print(f"even {flag(pair.even())} {flag(api.PairU32(7, 7).even())}") - # An instance renamed alone, beside another of `Pair` that keeps its name. - sized = api.tag(api.Size(1, 2), 3) - flipped = sized.swap() - print(f"sized {flipped.left} {flipped.right.width} {flipped!r}") - beside = api.PairU32(258, 9).beside_size(sized.left) - print(f"beside {beside.left} {beside!r}") - # At its default, named as the type itself. - stack = api.Stack.new() - for i, n in enumerate(["a", "b"]): - stack.push(api.Counter.new(n, i + 1)) - top = stack.pop().get() - print(f"stack {stack.depth()} Some({top}) {flag(stack.pop() is not None)} {flag(stack.pop() is None)}") - # Generic functions and methods, at each implementation of the trait bounding them, by - # reference, which leaves Python its object. - from_point = api.Counter.seeded_point("p", api.Point(-3, 4)) - from_size = api.Counter.seeded_size("s", api.Size(5, 6)) - from_counter = api.Counter.seeded_counter("c", from_point) - from_polar = api.Counter.seeded_polar_point("q", api.PolarPoint(1, 2)) - print( - f"seeded {from_point.get()} {from_size.get()} {from_counter.get()} {from_polar.get()} " - f"past {stack.depth_past_point(api.Point(1, 2))} seeds {api.seeds_point_size(api.Size(2, 3))}" - ) - - # A trait implemented for `Point` and `&Point` apart: one instance. - print(f"weigh {api.weigh_point(api.Point(-1, 2))}") - # A function named as the type it returns, and one named as a type it does not. - polar = api.polar_point(2) - check(polar is not None, "a point off the origin") - print(f"polar {polar.distance} {flag(api.polar_point(0) is None)} area {api.area(api.Size(2, 3))}") - # Two types whose paths join alike, the second kept apart where its path splits. - print(f"wind {api.wind(api.PolarTurn(2), api.Polar_Turn(3))}") - # Names that clash in some language, each kept apart there. - clash_span = api.ClashSpan(4) - clash_store = api.ClashStore.new(7) - print( - f"clash {api.ClashTone(440)!r} {api.ClashTone_(3)!r} {api.Cancelled(2)!r} " - f"span {clash_span.width_()} {clash_span.to_string()} {clash_span} " - f"store {clash_store.free()} {clash_store.close()} " - f"audio {api.clash_audio_encoder_finish()} {api.clash_audio_encoder_finish_()} " - f"nested {api.clash_nested(((1, 2), 3), ((1, 2, 3),))}" - ) - # Instances that name each other, and one made only by an impl of it. - cross = api.cross(api.LeftRightU8(api.RightU8(1)), api.RightLeftU8(api.LeftU8(2))) - print(f"cross {cross} outer {api.OuterInnerU8.new(4).get()}") - # A bound that outlives the call takes a value, and an instance only a constant names. - print(f"kept {api.kept_point(api.Point(1, -2))} boxed {api.BOXED.value}") - print(f"keep {api.keep_point(api.Point(1, -2))}") - five = api.Point(5, 2) - print(f"kept or {api.kept_or_point(five)} {api.kept_or_point(None)} keeper {api.keeper_point(five)}") - # Inferred instances taking a lent closure and a foreign implementation, and one only - # its impl of a trait names. - sides = api.PairU32(2, 5) - print(f"apply {api.apply_u32(sides, lambda side: side * 3)}") - print(f"report {api.report_u32(sides, PrintLog())}") - print(f"wrapped {api.kept_wrap_u32(api.WrapU32(4))}") - print(f"keeps {api.keeps(PrintLog()).value}") - - # Its Drop runs when its last reference goes, not before. - token = api.Token.new(7) - print(f"token {token.id_get} dropped {api.dropped()}") - del token - print(f"dropped {api.dropped()}") - - # A field and the method of its name, each its own member. - retry = api.Retry.new(5) - limit = retry.limit_get - print(f"retry {0 if limit is None else 1} {limit or 0} {retry.limit()} {retry.delay()}") - # The renamed field's setter, named as its getter. - retry.limit_set(None) - print(f"retry {retry.limit()}") - print(f"slot {api.SlotU8.new(200).value()}") - - # Foreign types: a URL parsed from text, socket addresses, OS paths, and `Vec`s. - base = api.Url.parse("https://example.com/a/b") - host = api.host(base) - host = "None" if host is None else f'Some("{host}")' - print(f"url {base} host {host}") - url = api.resolve(base.clone(), "c?d") - print(f"resolve {url} {flag(url == base)}") - try: - api.Url.parse("no scheme") - except api.StringException as e: - print(f"parse err {e.error}") - v4 = ("127.0.0.1", 8080) - v6 = ("::1", 443, 0, 3) - print(f"ports {api.ports([v4, v6]).tolist()}") - peer = api.Peer(v6, ["a", "b"]).next("c") - print(f"peer {peer!r} {quoted(peer.aliases())}") - file = api.file("dir", "f\\'\"\t") - print(f"file {escaped(file)}") - print("parents " + " ".join("none" if p is None else escaped(p) for p in api.parents([file, "/"]))) - words = api.words(" one two three ") - print(f"words {len(words)} {quoted(words)}") - print(f"sentence {api.sentence(words)} {api.sentence(None)}") - print(f"sentence {api.sentence([])}|") - print(f"either {api.either('abc')} {api.either(None)}") - print(f"prefixed {bytes(api.prefixed(b'cd', b'ab')).decode()} {bytes(api.prefixed(b'cd', None)).decode()}") - print(f"coordinates {api.coordinates(api.Point(2, 3))} {api.coordinates(None)}") - two, three = api.Counter.new("two", 2), api.Counter.new("three", 3) - print(f"plus {two.plus(three)} {two.plus(None)}") - print(f"add_to {str(two.add_to(three)).lower()} {str(two.add_to(None)).lower()} {three.get()}") - encoded = api.Mut(memoryview(b"0,")) - api.put_number(1, encoded) - api.put_number(23, encoded) - print(f"put_number {bytes(encoded.value).decode()}") - entry = api.Mut((memoryview(b"ab"), 1)) - stamps = api.push_counted(entry, ord("c")) - print(f"push_counted {stamps} {bytes(entry.value[0]).decode()} {entry.value[1]}") - digits = api.Mut(memoryview(b"7x9")) - first_digit = api.digit(digits) - try: - api.digit(digits) - skipped = False - except api.ErrorException: - skipped = True - print(f"digit {first_digit} {str(skipped).lower()} {api.digit(digits)} {len(digits.value)}") - nudged = api.Mut(api.Point(1, 2)) - api.nudge(nudged, 3) - print(f"nudge {nudged.value.x} {nudged.value.y}") - config = api.secure("h3") - print(f"secure {api.alpn_lent(config)} {api.alpn(config.clone())}") - cert = api.certify(b"der") - print(f"cert {api.cert_len(cert)} {text(api.cert_der(cert))} {api.chain_len([api.certify(b'a'), api.certify(b'bc')])}") - # Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. - print(f"resolver {api.resolved(api.resolver('r1'))}") - codecs = api.Codecs.new() - print(f"codecs {codecs.ids()}") - codecs.list_set(list(reversed(codecs.list_get))) - print(f"codecs reversed {codecs.ids()}") - # A standard library value no type maps, in a handle. - failure = api.failure("boom") - print(f"failure {api.failure_message(failure)} {api.failure_kind(failure)}") - # Iterators, passed as the arrays of their items. - print(f"sum_all {api.sum_all(iter([1, 2, 3]))}") - print(f"weigh_all {api.weigh_all_counter([api.Counter.new('w', 3)])}") - print(f"offered_len {api.offered_len([b'h3', b'moq-00'])}") - print(f"join_words {api.join_words(['a', 'b', 'c'])}") - # Bytes that must be `'static`, interned. - print(f"der {text(api.Der.from_slice(b'der').bytes())}") - print(f"der again {text(api.Der.from_slice(b'der').bytes())}") - session = api.resume("h3", 60) - print(f"resume {session.alpn()} {session.lifetime().seconds}") - try: - api.resume("", 60) - except api.StringException as e: - print(f"resume err {e.error}") - meters = api.Meters.new() - first = meters.first() - first.add(2) - print(f"lent {first.add(3)} {meters.first().count()}") - meters.clear() - print(f"cleared {meters.first().count()}") - lent_last = meters.last_get - lent_last.add(4) - print(f"field lent {lent_last.add(1)}") - # An optional field that is not Clone, lent as `Some` of a handle. - print(f"spare {str(meters.spare_get is not None).lower()}") - meters.spare_set(api.Meter.default()) - spare = meters.spare_get - assert spare is not None - spare.add(5) - print(f"spare lent {spare.add(1)}") - tallies = api.Tallies.new() - tallies.first().bump() - print(f"tallied {tallies.first().bump()}") - # A draft borrowing its ledger exclusively until its last reference goes, through which - # its sheet's members are reached by Deref and DerefMut: the ledger refuses any other use - # meanwhile. - ledger = api.Ledger.new() - draft = ledger.edit() - draft.title_set("minutes") - draft.write("first") - print(f"draft {draft.title_get} {draft.lines()} {draft.describe()} {flag(draft.edited())}") - try: - ledger.published() - check(False, "a lent ledger refuses a read") - except RuntimeError as e: - check(str(e) == "api_Ledger_published: a handle is borrowed exclusively", repr(e)) - print(f"committed {draft.commit()}") - del draft - print(f"ledger {ledger.title()} {ledger.published()}") - draft = ledger.edit() - print(f"read {draft.lines()} {flag(draft.edited())}") - del draft - draft = ledger.edit() - draft.write("second") - del draft - print(f"dropped {ledger.published()}") - print(f"receipt {ledger.receipt().count()}") - marker = api.Marker.new("m", 3, 5) - marker.y_set(7) - print( - f"forwarded {api.PadU16.wide().title()} {api.Layered.new().lines()} {marker.x_get} {marker.y_get}" - f" [{api.PadU8.small().describe()}] [{api.PadU16.wide().describe()}]" - ) - ledger.seal() - try: - ledger.edit() - except api.ErrorException as e: - print(f"sealed {e}") - print(f"chunks {[list(data(chunk)) for chunk in api.chunks(b'abcde', 2)]}") - counters = api.counters(["x", "y"]) - print("counters " + ", ".join(f"{c.name()} {c.get()}" for c in counters)) - # Each counter moves in, so a later call raises. - print(f"worth {api.worth([counters[0]], [counters[1]])} {api.worth(None, [])}") - for counter in counters: - try: - counter.get() - check(False, "a counter moved in is closed") - except ValueError: - pass - held = [api.held_count((api.Counter.new("h", 4),)), api.held_count(None)] - print("held " + " ".join("None" if n is None else f"Some({n})" for n in held)) - print(f'boxed Some("{api.boxed_name(api.boxed_counter("b"))}") {api.boxed_name(None)} {str(api.boxed_counter(None) is None).lower()}') - print(f"less {api.less(5, 2)}") - rows = [array.array("I", [1, 2]), array.array("I"), memoryview(struct.pack("=I", 3)).cast("I")] - print(f"sums {api.sums(rows).tolist()}") - print("least " + " ".join(str(s) for s in api.least([{3, 1}, set(), [2]]))) - numbers("edges", api.Numbers.edges()) - numbers("reversed", api.Numbers.edges().reversed()) - edges = api.Numbers.edges() - nan = api.Measure.new(math.nan, False) - equal = [edges == edges, edges == api.Numbers.edges(), api.Numbers.zero(True) == api.Numbers.zero(False), nan == nan, api.Measure.new(-0.0, True) == api.Measure.new(0.0, False)] - print("float equal " + " ".join(str(e).lower() for e in equal)) - # A record compares a buffer passed in by its numbers, as Rust does, not by its own `==`. - held = [api.Shadowed(Elementwise("i", items), 1, 2) for items in [[1, 2], [1, 2], [1, 3]]] - check(held[0] == held[1] and not held[0] == held[2], "a record compares a buffer by its numbers") - print(f"sum u32 {api.sum_u32(array.array('I'))} {api.sum_u32(array.array('I', [2**32 - 1, 2**32 - 1, 2]))}") - print(f"doubled i64 {api.doubled_i64(array.array('q', [-(2**63), -1, 0, 2**63 - 1])).tolist()}") - floats = api.boxed_floats(array.array("d", struct.pack("=dQ", -0.0, 0x7FF8000000000001))) - print(f"boxed floats {bits(floats, 'Q')}") - summed = api.summed([api.Point(1, 2), api.Point(-4, 6)]) - none_summed = api.summed([]) - print(f"summed {summed.x} {summed.y} {none_summed.x} {none_summed.y}") - print(f"longest {api.longest(['a', 'abc'])} {api.longest([])}") - print(f'first of Some("{api.first_of(["a", "b"])}") {api.first_of([]) or "None"}') - limits = api.byte_limits(b'a', b'bc') - waits = api.LimitsDuration(api.Duration(0, 5_000_000), api.Duration(2)) - breadth = millis(api.breadth(waits)) - print(f"limits {bytes(limits.low).decode()} {bytes(limits.high).decode()} breadth {breadth}") - joined = bytes(api.joined([b'ab', b'', b'c'])).decode() - print(f"joined {joined} {len(api.joined([]))} read {api.read_len(b'hello')}") - doc = api.Json.parse('{"b": [1, 2.5, null], "a": "é"}') - print(f"json {api.encode(doc)}") - print(f"timed text {api.timed_text(doc)}") - tagged = api.tagged(doc, "t") - print(f"tagged {tagged.to_text()}") - # A JSON object's entries cross as pairs of a key and its document, each moved in. - entries = api.entries([("b", api.Json.parse("[1]")), ("a", api.Json.parse("2"))], "t") - print("entries " + ", ".join(f"{key} {value.to_text()}" for key, value in entries)) - try: - api.Json.parse('{"a":') - except api.StringException as e: - print(f"json parse err {e.error}") - site = api.Site.new(base) - print(f"site {site.home_get} {site.home_get}") - - # Slices, passed in and returned as clones, and the socket address of each family. - print(f"shapes {debugs(api.Shape.ALL)} greetings {quoted(api.GREETINGS)}") - print(f"both {debugs(api.Shape.BOTH)} primes {list(api.PRIMES)}") - trail = api.Trail.new([api.Point(1, 2), api.Point(3, 4)], ["a", "b"]) - print(f"trail {debugs(trail.points())} {debugs(trail.labels())}") - # Returned iterators, each collected at the call: drained labels are gone after. - print(f"iterated {debugs(trail.iter())} {quoted(trail.names())} {list(data(trail.bytes()))}") - print(f"drained {debugs(trail.drain())} then {debugs(trail.labels())}") - # A filter, collected at the call. - print("beyond " + ", ".join(f"{p.x} {p.y}" for p in trail.beyond(1))) - numbered = api.numbered(["p", "q"]) - print("numbered " + ", ".join(f"{c.name()} {c.get()}" for c in numbered)) - next4, next6 = api.nexts(v4, v6) - print(f"nexts {next4[0]} {next4[1]} {next6[1]} {next6[3]}") - nextip4, nextip6 = api.next_ips(ipaddress.IPv4Address("10.0.0.255"), ipaddress.IPv6Address("::ffff")) - mapped = api.flip(ipaddress.IPv4Address("127.0.0.1")) - ips = [nextip4, nextip6, mapped, api.flip(mapped), api.flip(ipaddress.IPv6Address("::1"))] - print("ips " + " ".join(ip.packed.hex() for ip in ips)) - - # Lossless round trips: each type's edge values, passed through Rust and back. - durations = [api.Duration(0), api.Duration(0, 1), api.Duration(9223372036, 854775808), api.Duration(2**64 - 1, 999_999_999)] - print("lossless duration " + " ".join(f"{d.secs}.{d.nanos:09}" for d in map(api.same_duration, durations))) - print(f"lossless u64 {api.same_u64(0)} {api.same_u64(2**63)} {api.same_u64(2**64 - 1)}") - usize = 2 ** (struct.calcsize("P") * 8) - print(f"lossless usize {api.same_usize(0)} {api.same_usize(usize - 1)}") - print(f"lossless isize {api.same_isize(-usize // 2)} {api.same_isize(usize // 2 - 1)}") - print("lossless u128 " + " ".join(f"{api.same_u128(v):032x}" for v in [0, 2**64, 2**128 - 1])) - print("lossless char " + " ".join(f"{ord(api.same_char(c)):x}" for c in ["\0", "\ud7ff", "\ue000", "\U0010ffff"])) - # A path no Rust string spells: bytes that are not UTF-8, or on Windows, WTF-8's lone - # surrogate, which its filesystem encoding passes through. - paths = ["a/é", os.fsdecode(b"\xff" if os.name == "posix" else b"\xed\xa0\x80")] - print("lossless path " + " ".join(os.fsencode(api.same_path(p)).hex() for p in paths)) - sv4 = api.same_socket_addr_v4(("255.255.255.255", 65535)) - sv6 = api.same_socket_addr_v6(("1::2", 3, 2**32 - 1, 2**32 - 1)) - sockets = [sv4, sv6] + [api.same_socket_addr(a) for a in [sv4, sv6]] - print("lossless socket " + " ".join(socket_hex(a) for a in sockets)) - key = api.Key.new("a") - print(f"key {flag(hash(key) == hash(api.Key.new('a')))} {flag(hash(key) == hash(api.Key.new('b')))}") - ips = [api.same_ip_addr(ipaddress.IPv4Address("255.255.255.255")), api.same_ip_addr(ipaddress.IPv6Address("ffff::1"))] - print("lossless ip " + " ".join(ip.packed.hex() for ip in ips)) - - # serde_json's map iterator, collected as pairs of a key and its document. - sections = api.sections([("b", api.Json.parse("[1]")), ("a", api.Json.parse("2"))]) - print("sections " + ", ".join(f"{key} {value.to_text()}" for key, value in sections)) - # An instant only Rust makes, which each call copies out of its handle, and compares. - began = api.now() - ended = api.later(began, api.Duration.from_timedelta(datetime.timedelta(milliseconds=1500))) - same = api.later(began, api.Duration(0)) - print(f"instants {millis(api.since(ended, began))} {millis(api.since(began, ended))} {flag(began == same)} {flag(began == ended)}") - print(f"has_instant {flag(api.has_instant(began))} {flag(api.has_instant(None))}") - # tracing's level, and its filter as an optional level whose None is `OFF`. - verbosity = api.Verbosity.new(api.Level.WARN) - print(f"verbosity {api.spell(verbosity.filter())} {api.spell(api.louder(verbosity.filter()))}") - verbosity.level_set(api.Level.TRACE) - louder = api.spell(api.louder(verbosity.filter())) - print( - f"verbosity {flag(verbosity.level_get == api.Level.TRACE)} {api.spell(verbosity.filter())} {louder} {api.spell(api.louder(None))}" - ) - - print(f"made {api.made(3, lambda n: f'{n} times')}") - # A closure taking and returning `Copy` objects copies them, never running their `Clone`. - kept = api.Ticket.new(9) - given = api.reissue(api.Ticket.new(7), lambda t: api.Ticket.new(t.number() + 1)).number() - held = api.reissue(api.Ticket.new(7), lambda _: kept).number() - print(f"reissued {given} {held}, cloned {api.Ticket.clones()}") - # A record's traits borrow the checked handle it holds. - nines = api.Mark.of(9) - front, back = api.seat(nines, 1), api.seat(nines, 2) - print(f"seat {front!r} {str(front == api.seat(nines, 1)).lower()} {str(front == back).lower()}") - # A kept closure, called on another thread after the call that took it returned. - check(api.Spawned.new(lambda: 7).join() == 7, "a kept closure runs on another thread") - # A kept closure: called again at the instant it asks for, then once its waiter wakes. + +def drive(): + """A kept closure: called again at the instant it asks for, then once its waiter wakes.""" start = api.Moment.new(0, 1000) calls = 0 - def drive(now, waiter): + def kept(now, waiter): nonlocal calls calls += 1 match calls: @@ -864,7 +291,11 @@ def drive(now, waiter): case _: raise api.StringException(f"stopped after {calls}") - print(f"drive {asyncio.run(api.drive(start, drive))}") + print(f"drive {asyncio.run(api.drive(start, kept))}") + + +def readers(): + """Readers over bytes, whose reads fail, and that seek past `i64::MAX`.""" for file in (io.BytesIO(b"hello world"), Broken()): try: tail, at = api.tail(file, 5) @@ -876,23 +307,48 @@ def drive(now, waiter): print(f"sought {api.seek_to(Far(), 2**64 - 1)}") except api.StringException as e: print(f"sought error {e}") - print(f"non zeros {api.describe_non_zeros(api.non_zeros())}") - for hop in [None, 1, 2**64 - 1]: - next = api.next_hop(hop) - print("hop None" if next is None else f"hop Some({next})") - print(f"farther hop {api.farther_hop(api.PairNonZeroU16(3, 0xFFFF))}") - local = api.Local.new() - shared = api.local_or_new(local) - bumped = local.bump() - print(f"local {bumped} {shared.bump()}") - print(f"local fresh {api.local_or_new(None).bump()}") - print(f"local either {api.bump_either(None, shared)}") + + +def local_later(local): + """Futures of a value that is not `Send`, run on this thread.""" loop = asyncio.new_event_loop() print(f"local later {loop.run_until_complete(api.local_or_new_later(local)).bump()}") print(f"local later fresh {loop.run_until_complete(api.local_or_new_later(None)).bump()}") loop.close() +def checks(): + """What the transcript's script says only in Rust: Python's own errors and equality.""" + try: + api.Moment() + check(False, "Python makes no opaque value") + except TypeError: + pass + # A draft borrows its ledger exclusively: the ledger refuses any other use meanwhile. + ledger = api.Ledger.new() + draft = ledger.edit() + try: + ledger.published() + check(False, "a lent ledger refuses a read") + except RuntimeError as e: + check(str(e) == "api_Ledger_published: a handle is borrowed exclusively", repr(e)) + del draft + # Each counter moves in, so a later call raises. + counters = api.counters(["x", "y"]) + api.worth([counters[0]], [counters[1]]) + for counter in counters: + try: + counter.get() + check(False, "a counter moved in is closed") + except ValueError: + pass + # A record compares a buffer passed in by its numbers, as Rust does, not by its own `==`. + held = [api.Shadowed(Elementwise("i", items), 1, 2) for items in [[1, 2], [1, 2], [1, 3]]] + check(held[0] == held[1] and not held[0] == held[2], "a record compares a buffer by its numbers") + # A kept closure, called on another thread after the call that took it returned. + check(api.Spawned.new(lambda: 7).join() == 7, "a kept closure runs on another thread") + + class Elementwise(array.array): """A buffer whose `==` compares item by item into an object of no truth, as numpy's does. A native buffer, since CPython before 3.12 takes no `__buffer__` written in Python.""" @@ -1103,7 +559,7 @@ def close(self): loop.run_until_complete(asyncio.wait_for(polled(), 5)) loop.run_until_complete(asyncio.wait_for(kept(), 5)) loop.close() - readers() + reading() print("futures ok") @@ -1221,7 +677,7 @@ def ask(now, waiter): check(later.millis() == 7, "a returned moment stays the caller's") -def readers(): +def reading(): """Readers Rust reads and seeks during the call.""" data = bytes(range(256)) * 64 file = io.BytesIO(data) @@ -1781,5 +1237,7 @@ def readinto(self, buffer, /): values() case ["calls"]: calls() + case ["checks"]: + checks() case [which]: broken(which) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 893445b53..9b5eadc00 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -149,6 +149,27 @@ impl Api { } } +/// The fixture's script as data, typed against the export's API, which each language's +/// test generates its own differential script from. +fn transcript() -> &'static transcript::Transcript { + static TRANSCRIPT: OnceLock = OnceLock::new(); + TRANSCRIPT.get_or_init(|| { + transcript::Transcript::load( + &api().out.join("api.json"), + &manifest_dir().join("fixtures/api/examples/transcript.rs"), + ) + }) +} + +/// `contents` written as `file` in a scratch directory of `language`'s, which the +/// language's test puts on its path. +fn generated(language: &str, file: &str, contents: &str) -> PathBuf { + let dir = scratch().join("api").join(format!("{language}-transcript")); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(file), contents).unwrap(); + dir +} + fn api() -> &'static Api { static API: OnceLock = OnceLock::new(); API.get_or_init(|| { @@ -996,6 +1017,7 @@ const PYTHON_LIB: &str = match (cfg!(windows), cfg!(target_os = "macos")) { #[test] fn api_python() { let api = api(); + let scripts = generated("python", "transcript.py", &transcript::python::emit(transcript())); let python = |dir: &Path, args: &[&str]| { let mut cmd = Command::new(std::env::var_os("PYTHON").unwrap_or_else(|| "python3".into())); // `-P` keeps `tests/` off the path, where `api.py` is this script; dev mode and @@ -1003,7 +1025,7 @@ fn api_python() { cmd.args(["-P", "-X", "dev", "-W", "error"]) .arg(manifest_dir().join("tests").join("api.py")) .args(args) - .env("PYTHONPATH", dir); + .env("PYTHONPATH", std::env::join_paths([dir, &scripts]).unwrap()); cmd }; let dir = api.out.join("python"); @@ -1013,7 +1035,7 @@ fn api_python() { api.transcript, "the Python transcript differs from the native one" ); - for case in ["futures", "owned", "values", "calls"] { + for case in ["futures", "owned", "values", "calls", "checks"] { run(&mut python(&dir, &[case])); } for (case, message) in [ @@ -3852,12 +3874,3 @@ fn profiled() { ); } -#[test] -fn transcript_parses() { - let api = api(); - let t = transcript::Transcript::load( - &api.out.join("api.json"), - &manifest_dir().join("fixtures/api/examples/transcript.rs"), - ); - assert!(!t.steps.is_empty()); -} diff --git a/ffi/tests/fixtures/transcript/ir.rs b/ffi/tests/fixtures/transcript/ir.rs index 88406d380..58a95d4a0 100644 --- a/ffi/tests/fixtures/transcript/ir.rs +++ b/ffi/tests/fixtures/transcript/ir.rs @@ -25,6 +25,9 @@ pub(crate) struct Api { #[derive(serde::Deserialize)] pub(crate) struct Record { pub(crate) path: Vec, + /// The path, with any arguments, the API shows the type at, which its keys name it by. + #[serde(default)] + pub(crate) shown: Option>, pub(crate) args: Vec, pub(crate) fields: Vec, pub(crate) tuple: bool, @@ -42,6 +45,9 @@ pub(crate) struct Field { #[derive(serde::Deserialize)] pub(crate) struct Enum { pub(crate) path: Vec, + /// The path, with any arguments, the API shows the type at, which its keys name it by. + #[serde(default)] + pub(crate) shown: Option>, pub(crate) args: Vec, pub(crate) variants: Vec, pub(crate) methods: Vec, @@ -59,6 +65,9 @@ pub(crate) struct Variant { #[derive(serde::Deserialize)] pub(crate) struct Object { pub(crate) path: Vec, + /// The path, with any arguments, the API shows the type at, which its keys name it by. + #[serde(default)] + pub(crate) shown: Option>, pub(crate) args: Vec, #[serde(default = "yes")] pub(crate) send: bool, diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 76b496f43..79879ef50 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -284,9 +284,27 @@ impl Transcript { Type::String => "String".to_string(), Type::Bytes => "bytes::Bytes".to_string(), Type::Duration => "std::time::Duration".to_string(), - Type::Record(i) => named(&self.api.records[*i].path, &self.api.records[*i].args), - Type::Enum(i) => named(&self.api.enums[*i].path, &self.api.enums[*i].args), - Type::Object(i) => named(&self.api.objects[*i].path, &self.api.objects[*i].args), + Type::Record(i) => { + let r = &self.api.records[*i]; + match &r.shown { + Some(shown) => shown.join("::"), + None => named(&r.path, &r.args), + } + } + Type::Enum(i) => { + let e = &self.api.enums[*i]; + match &e.shown { + Some(shown) => shown.join("::"), + None => named(&e.path, &e.args), + } + } + Type::Object(i) => { + let o = &self.api.objects[*i]; + match &o.shown { + Some(shown) => shown.join("::"), + None => named(&o.path, &o.args), + } + } Type::Const(ir::Literal::Int(_, v)) => v.to_string(), Type::Const(ir::Literal::Bool(v)) => v.to_string(), other => panic!("no type argument is {other:?}"), diff --git a/ffi/tests/fixtures/transcript/python.rs b/ffi/tests/fixtures/transcript/python.rs index 180e4b00d..7451cf90d 100644 --- a/ffi/tests/fixtures/transcript/python.rs +++ b/ffi/tests/fixtures/transcript/python.rs @@ -1 +1,794 @@ -//! The Python script. +//! The transcript as Python: a module whose `script()` runs it through the generated +//! Python, calling `tests/api.py`'s own functions, which it imports as `__main__`. + +use std::fmt::Write; + +use super::ir::{Access, Collection, Int, Mutability, Receiver, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; + +const LANGUAGE: &str = "Python"; + +/// Helpers the script calls, each for a value Python shapes apart from Rust. +const PRELUDE: &str = r#"# Generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript. + +import array +import copy +import ipaddress +import struct + +import __main__ as local +import api + + +def _flag(value): + return "true" if value else "false" + + +def _text(view): + """Bytes as text, releasing a view Rust lent.""" + if isinstance(view, memoryview): + with view: + return bytes(view).decode() + return bytes(view).decode() + + +def _bytes(view): + if isinstance(view, memoryview): + with view: + return bytes(view) + return bytes(view) + + +def _quoted(s): + """A string as Rust's `Debug` prints it.""" + out = '"' + for c in s: + match c: + case '"' | "\\": + out += "\\" + c + case "\n": + out += "\\n" + case "\t": + out += "\\t" + case "\r": + out += "\\r" + case c: + out += c + return out + '"' + + +def _bound(b): + match b.kind: + case api.Bound.INCLUDED: + return f"Included({b.value})" + case api.Bound.EXCLUDED: + return f"Excluded({b.value})" + case api.Bound.UNBOUNDED: + return "Unbounded" + + +def _list(items, show): + return "[" + ", ".join(show(item) for item in items) + "]" + + +def _option(value, show): + return "None" if value is None else f"Some({show(value)})" + + +def _err(call, exception): + """The error of a call that must fail.""" + try: + call() + except exception as e: + return e.error + raise AssertionError("the call did not fail") + + +def _fails(call, exception): + try: + call() + except exception: + return True + return False + + +def _f64(bits): + return struct.unpack(" String { + let mut e = Emitter { + t, + out: String::new(), + depth: 1, + mutated: Vec::new(), + fresh: 0, + }; + mutated(&t.steps, t, &mut e.mutated); + e.out.push_str(PRELUDE); + e.out.push_str("\n\ndef script():\n"); + let body = e.steps(&t.steps); + e.out.push_str(&body); + e.out +} + +/// The locals a call takes `&mut` that are values, not objects: each is an `api.Mut`, +/// whose `value` the script reads. +fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec) { + let mut visit = |expr: &Expr| walk(expr, &mut |e| { + if let Kind::Call(id, _, args) = &e.kind { + for (arg, param) in args.iter().zip(&t.function(*id).params) { + if let (Kind::Var(name), Type::Ref(Mutability::Mut, inner)) = (&arg.kind, ¶m.ty) + && !matches!(**inner, Type::Object(_) | Type::Reader) + && !out.contains(name) + { + out.push(name.clone()); + } + } + } + }); + for step in steps { + each_expr(step, &mut visit); + } +} + +/// Each expression a step holds, its arms' and closures' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) | Kind::Field(e, _) | Kind::Element(e, _) | Kind::Clone(e) | Kind::Unwrap(e) | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => es.iter().for_each(inner), + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +struct Emitter<'t> { + t: &'t Transcript, + out: String, + depth: usize, + /// The locals each an `api.Mut`. + mutated: Vec, + fresh: usize, +} + +/// Python's keywords, which no name may be. +const KEYWORDS: &[&str] = &["from", "in", "is", "not", "and", "or", "None", "True", "False", "lambda", "def", "del", "pass", "with", "yield", "async", "await", "class", "global", "import", "return", "try", "except", "raise", "while", "for", "if", "else", "elif", "break", "continue", "as", "assert", "finally", "nonlocal", "match", "case", "type"]; + +/// What the script itself calls, which no local of its may shadow. +const BUILTINS: &[&str] = &["list", "bytes", "str", "len", "range", "iter", "format", "print", "repr", "copy", "array", "struct", "ipaddress", "api", "local", "id", "hex", "min", "max", "sum", "next", "map", "filter", "bool", "int", "float", "tuple", "set", "dict", "object", "input", "open", "round", "all", "any", "zip", "slice", "vars", "bin", "oct", "ord", "chr", "abs", "hash", "callable"]; + +/// A local's name in Python. +fn ident(name: &str) -> String { + match KEYWORDS.contains(&name) || BUILTINS.contains(&name) { + true => format!("{name}_"), + false => name.to_string(), + } +} + +impl Emitter<'_> { + fn indent(&self) -> String { + "\t".repeat(self.depth) + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("_{what}{}", self.fresh) + } + + fn steps(&mut self, steps: &[Step]) -> String { + let mut out = String::new(); + for step in steps { + self.step(step, &mut out); + } + if out.is_empty() { + let _ = writeln!(out, "{}pass", self.indent()); + } + out + } + + fn line(&self, out: &mut String, line: &str) { + let _ = writeln!(out, "{}{line}", self.indent()); + } + + fn step(&mut self, step: &Step, out: &mut String) { + match step { + Step::Let(pat, value) => { + // A value's `&mut self` returns it as the call left it, before what Rust returns. + if let Some((name, call)) = self.mut_receiver(value) { + let target = match pat { + Pat::Ignore(_) => "_".to_string(), + pat => self.pat(pat), + }; + let line = match unref(&value.ty) { + Type::Unit => format!("{name} = {call}"), + Type::Tuple(elements) if elements.len() > 1 => format!("{name}, *{target} = {call}"), + _ => format!("{name}, {target} = {call}"), + }; + let line = match pat { + Pat::Tuple(_) => { + let tmp = self.fresh("t"); + self.line(out, &format!("{name}, {tmp} = {call}")); + format!("{target} = {tmp}") + } + _ => line, + }; + return self.line(out, &line); + } + let v = self.expr(value, out); + match pat { + Pat::Name(name, _) if self.mutated.contains(name) => self.line(out, &format!("{} = api.Mut({v})", ident(name))), + pat => self.bind(pat, &v, &value.ty, out), + } + } + Step::Print(pieces) => { + let v = self.pieces(pieces, out); + self.line(out, &format!("print({v})")); + } + Step::Do(value) => { + if let Some((name, call)) = self.mut_receiver(value) { + return match unref(&value.ty) { + Type::Unit => self.line(out, &format!("{name} = {call}")), + _ => self.line(out, &format!("{name}, _ = {call}")), + }; + } + let v = self.expr(value, out); + self.line(out, &v); + } + Step::Drop(name) => self.line(out, &format!("del {}", ident(name))), + Step::Match { value, ok, err } => self.matched(value, ok, err, out), + } + } + + /// A call of a method taking a value's `&mut self` on a local: the local's name, and + /// the call, which Python returns the value from as the call left it. + fn mut_receiver(&mut self, value: &Expr) -> Option<(String, String)> { + let Kind::Call(id, Some(receiver), args) = &value.kind else { return None }; + let f = self.t.function(*id); + if f.receiver != Some(Receiver::Mut) || !matches!(id.owner, Owner::Record(_)) { + return None; + } + let Kind::Var(name) = &receiver.kind else { + panic!("a value's &mut self method on anything but a local") + }; + let mut scratch = String::new(); + let call = self.call(*id, Some(receiver), args, &mut scratch); + assert!(scratch.is_empty(), "a value's &mut self method taking a closure of steps"); + Some((ident(name), call)) + } + + /// `pat` bound to `v`, a value of `ty`: bounds, which Python keeps as a record, by its + /// fields. + fn bind(&mut self, pat: &Pat, v: &str, ty: &Type, out: &mut String) { + match pat { + Pat::Tuple(pats) if matches!(unref(ty).base(), Type::Bounds(_)) => { + let (a, b) = (self.pat(&pats[0]), self.pat(&pats[1])); + self.line(out, &format!("{a}, {b} = {v}.start, {v}.end")); + } + pat => { + let target = self.pat(pat); + self.line(out, &format!("{target} = {v}")); + } + } + } + + fn pat(&self, pat: &Pat) -> String { + match pat { + Pat::Name(name, _) => ident(name), + Pat::Ignore(_) => "_".to_string(), + Pat::Tuple(pats) => { + let parts: Vec = pats.iter().map(|p| self.pat(p)).collect(); + match parts.len() { + 1 => format!("({},)", parts[0]), + _ => format!("({})", parts.join(", ")), + } + } + } + } + + fn matched(&mut self, value: &Expr, ok: &Arm, err: &Arm, out: &mut String) { + match &value.ty { + Type::Option(inner) => { + let v = self.expr(value, out); + let tmp = self.fresh("o"); + self.line(out, &format!("{tmp} = {v}")); + self.line(out, &format!("if {tmp} is not None:")); + self.depth += 1; + if let Some(pat) = &ok.pat { + self.bind(pat, &tmp, inner, out); + } + let body = self.steps(&ok.steps); + out.push_str(&body); + self.depth -= 1; + self.line(out, "else:"); + self.depth += 1; + let body = self.steps(&err.steps); + out.push_str(&body); + self.depth -= 1; + } + Type::Result(ok_ty, err_ty) => { + let exception = self.exception(err_ty); + self.line(out, "try:"); + self.depth += 1; + let mut pre = String::new(); + let v = self.expr(value, &mut pre); + out.push_str(&pre); + let ok_value = self.fresh("v"); + self.line(out, &format!("{ok_value} = {v}")); + self.depth -= 1; + let e = self.fresh("e"); + self.line(out, &format!("except api.{exception} as {e}:")); + self.depth += 1; + if let Some(pat) = &err.pat { + self.bind(pat, &format!("{e}.error"), err_ty, out); + } + let body = self.steps(&err.steps); + out.push_str(&body); + self.depth -= 1; + self.line(out, "else:"); + self.depth += 1; + if let Some(pat) = &ok.pat { + self.bind(pat, &ok_value, ok_ty, out); + } + let body = self.steps(&ok.steps); + out.push_str(&body); + self.depth -= 1; + } + ty => panic!("a match on {ty:?}"), + } + } + + /// The exception a call failing with `err` raises. + fn exception(&self, err: &Type) -> String { + format!("{}Exception", self.error_name(err)) + } + + fn error_name(&self, ty: &Type) -> String { + match unref(ty).base() { + Type::String | Type::Str => "String".to_string(), + Type::Bounds(int) => format!("Bounds{}", int_name(*int)), + Type::List(_, item) => format!("List{}", self.error_name(item)), + ty @ (Type::Record(_) | Type::Enum(_) | Type::Object(_)) => self.t.type_name(LANGUAGE, ty).to_string(), + ty => panic!("an error of {ty:?}"), + } + } + + /// The Python of a format's pieces: a string expression. + fn pieces(&mut self, pieces: &[Piece], out: &mut String) -> String { + let mut parts = Vec::new(); + for piece in pieces { + match piece { + Piece::Text(text) => parts.push(string(text)), + Piece::Value(e, spec) => { + let v = self.expr(e, out); + parts.push(self.show(&v, &e.ty, *spec)); + } + } + } + match parts.len() { + 0 => "\"\"".to_string(), + _ => parts.join(" + "), + } + } + + /// `v`, a value of `ty`, as a `str` the way Rust formats it with `spec`. + fn show(&mut self, v: &str, ty: &Type, spec: Spec) -> String { + let ty = unref(ty).base(); + match spec { + Spec::Hex(0) => return format!("format({v}, \"x\")"), + Spec::Hex(width) => return format!("format({v}, \"0{width}x\")"), + Spec::Padded(width) => return format!("format({v}, \"0{width}\")"), + Spec::Debug => return self.debug(v, ty), + Spec::Display => {} + } + match ty { + Type::Bool => format!("_flag({v})"), + Type::String | Type::Str | Type::Char => v.to_string(), + Type::Int(_) | Type::U128 | Type::NonZero(_) => format!("str({v})"), + Type::Object(_) | Type::Record(_) | Type::Enum(_) => match self.text_of(ty) { + Some(text) => format!("{v}.{text}()"), + None => format!("str({v})"), + }, + ty => panic!("Display of {ty:?}"), + } + } + + /// The name of a type's `Access::Text` method, which Python names its `Display`. + fn text_of(&self, ty: &Type) -> Option<&str> { + let Type::Object(i) = ty else { return None }; + let o = &self.t.api.objects[*i]; + let index = o.methods.iter().position(|m| m.access == Access::Text)?; + Some(self.t.name(LANGUAGE, FnId { owner: Owner::Object(*i), index })) + } + + /// `v` as Rust's `Debug` prints a value of `ty`. + fn debug(&mut self, v: &str, ty: &Type) -> String { + match unref(ty).base() { + Type::Bool => format!("_flag({v})"), + Type::Int(_) | Type::U128 | Type::NonZero(_) => format!("str({v})"), + Type::String | Type::Str => format!("_quoted({v})"), + Type::Option(inner) => { + let x = self.fresh("x"); + let show = self.debug(&x, inner); + format!("_option({v}, lambda {x}: {show})") + } + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => format!("str(list(_bytes({v})))"), + Type::List(_, item) => { + let x = self.fresh("x"); + let show = self.debug(&x, item); + format!("_list({v}, lambda {x}: {show})") + } + Type::Tuple(elements) => { + let parts: Vec = (0..elements.len()).map(|i| self.debug(&format!("{v}[{i}]"), &elements[i])).collect(); + let tail = if parts.len() == 1 { ",)" } else { ")" }; + format!("\"(\" + {} + \"{tail}\"", parts.join(" + \", \" + ")) + } + Type::Bound(_) => format!("_bound({v})"), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => format!("repr({v})"), + ty => panic!("Debug of {ty:?}"), + } + } + + fn expr(&mut self, e: &Expr, out: &mut String) -> String { + self.value(e, &e.ty, out) + } + + /// The Python of `e`, passed where `want` is taken. + fn value(&mut self, e: &Expr, want: &Type, out: &mut String) -> String { + match &e.kind { + Kind::Unit => "None".to_string(), + Kind::Bool(b) => if *b { "True" } else { "False" }.to_string(), + Kind::Int(n) => n.to_string(), + Kind::Float(f) if !f.is_finite() || (*f == 0.0 && f.is_sign_negative()) => format!("_f64({:#x})", f.to_bits()), + Kind::Float(f) => format!("{f:?}"), + Kind::Char(c) => string(&c.to_string()), + Kind::Str(s) => string(s), + Kind::Bytes(b) => match unref(want).base() { + Type::Array(n) => format!("api.ArrayU8x{n}({})", bytes(b)), + _ => bytes(b), + }, + Kind::Duration(secs, nanos) => format!("api.Duration({secs}, {nanos})"), + Kind::Socket(std::net::SocketAddr::V4(a)) => format!("(\"{}\", {})", a.ip(), a.port()), + Kind::Socket(std::net::SocketAddr::V6(a)) => { + format!("(\"{}\", {}, {}, {})", a.ip(), a.port(), a.flowinfo(), a.scope_id()) + } + Kind::Ip(std::net::IpAddr::V4(ip)) => format!("ipaddress.IPv4Address(\"{ip}\")"), + Kind::Ip(std::net::IpAddr::V6(ip)) => format!("ipaddress.IPv6Address(\"{ip}\")"), + Kind::None => "None".to_string(), + Kind::Some(inner) => { + let want = match unref(want).base() { + Type::Option(inner) => (**inner).clone(), + _ => inner.ty.clone(), + }; + self.value(inner, &want, out) + } + Kind::Tuple(elements) => self.tuple(e, elements, want, out), + Kind::List(items) => self.list(items, want, out), + Kind::Record(r, fields) => { + let name = self.t.type_name(LANGUAGE, &Type::Record(*r)).to_string(); + let field_types: Vec = self.t.api.records[*r].fields.iter().map(|f| f.ty.clone()).collect(); + let args: Vec = fields.iter().zip(&field_types).map(|(f, ty)| self.value(f, ty, out)).collect(); + format!("api.{name}({})", args.join(", ")) + } + Kind::Variant(en, v, fields) => { + let name = self.t.type_name(LANGUAGE, &Type::Enum(*en)).to_string(); + let enumeration = &self.t.api.enums[*en]; + let variant = &enumeration.variants[*v]; + if enumeration.variants.iter().all(|v| v.fields.is_empty()) { + return format!("api.{name}.{}", upper(&variant.name)); + } + let field_types: Vec = variant.fields.iter().map(|f| f.ty.clone()).collect(); + let variant_name = variant.name.clone(); + let args: Vec = fields.iter().zip(&field_types).map(|(f, ty)| self.value(f, ty, out)).collect(); + format!("api.{name}.{variant_name}({})", args.join(", ")) + } + Kind::Bound(kind, value) => { + let Type::Bound(int) = unref(&e.ty) else { panic!("a bound of {:?}", e.ty) }; + let (kind, v) = match (kind, value) { + (BoundKind::Unbounded, _) => ("UNBOUNDED", "0".to_string()), + (BoundKind::Included, Some(v)) => ("INCLUDED", self.expr(v, out)), + (BoundKind::Excluded, Some(v)) => ("EXCLUDED", self.expr(v, out)), + _ => unreachable!(), + }; + format!("api.Bound{}(api.Bound.{kind}, {v})", int_name(*int)) + } + Kind::Default => { + let name = self.t.type_name(LANGUAGE, unref(&e.ty).base()).to_string(); + format!("api.{name}.default()") + } + Kind::Var(name) => match self.mutated.contains(name) { + // Passed `&mut`, the wrapper itself; read, its value. + true if matches!(want, Type::Ref(Mutability::Mut, _)) => ident(name), + true => format!("{}.value", ident(name)), + false => ident(name), + }, + Kind::Const(c) => format!("api.{}", self.t.named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::")))), + Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args, out), + Kind::Field(base, i) => { + let b = self.expr(base, out); + let Type::Record(r) = unref(&base.ty).base() else { panic!("a field of {:?}", base.ty) }; + format!("{b}.{}", self.t.api.records[*r].fields[*i].name) + } + Kind::Element(base, i) => { + let b = self.expr(base, out); + match unref(&base.ty).base() { + Type::Range(_) => format!("{b}.{}", if *i == 0 { "start" } else { "stop" }), + _ => format!("{b}[{i}]"), + } + } + Kind::Clone(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + Type::Object(_) => format!("{v}.clone()"), + Type::List(..) => format!("list({v})"), + _ => format!("copy.copy({v})"), + } + } + Kind::Unwrap(inner) => { + let v = self.expr(inner, out); + match &inner.ty { + Type::Result(..) => v, + _ => format!("_some({v})"), + } + } + Kind::UnwrapErr(inner) => { + let Type::Result(_, err) = &inner.ty else { panic!("unwrap_err of {:?}", inner.ty) }; + let exception = self.exception(err); + let v = self.expr(inner, out); + format!("_err(lambda: {v}, api.{exception})") + } + Kind::IsErr(inner) => { + let Type::Result(_, err) = &inner.ty else { panic!("is_err of {:?}", inner.ty) }; + let exception = self.exception(err); + let v = self.expr(inner, out); + format!("_fails(lambda: {v}, api.{exception})") + } + Kind::IsSome(inner) => format!("({} is not None)", self.expr(inner, out)), + Kind::IsNone(inner) => format!("({} is None)", self.expr(inner, out)), + Kind::Binary(op, a, b) => { + let (a, b) = (self.expr(a, out), self.expr(b, out)); + let op = match op { + Op::Eq => "==", + Op::Ne => "!=", + Op::Lt => "<", + Op::Gt => ">", + Op::Add => "+", + Op::Sub => "-", + Op::Mul => "*", + Op::Rem => "%", + Op::And => "and", + }; + format!("({a} {op} {b})") + } + Kind::Closure(params, steps, value) => self.closure(params, steps, value, out), + Kind::Local(name, args) => { + let args: Vec = args.iter().map(|a| self.expr(a, out)).collect(); + format!("local.{name}({})", args.join(", ")) + } + Kind::Format(pieces) => self.pieces(pieces, out), + Kind::Join { items, pat, body, sep } => { + let items = self.expr(items, out); + let target = self.pat(pat); + let body = self.expr(body, out); + format!("{}.join({body} for {target} in {items})", string(sep)) + } + Kind::MapOr { option, none, pat, some } => { + let option = self.expr(option, out); + let none = self.expr(none, out); + let target = self.pat(pat); + let some = self.expr(some, out); + format!("(lambda {target}: {none} if {target} is None else {some})({option})") + } + Kind::Utf8(inner) => format!("_text({})", self.expr(inner, out)), + Kind::Len(inner) => format!("len({})", self.expr(inner, out)), + } + } + + fn tuple(&mut self, e: &Expr, elements: &[Expr], want: &Type, out: &mut String) -> String { + match unref(&e.ty).base() { + Type::Range(_) => { + let (a, b) = (self.expr(&elements[0], out), self.expr(&elements[1], out)); + format!("range({a}, {b})") + } + Type::Bounds(int) => { + let (a, b) = (self.expr(&elements[0], out), self.expr(&elements[1], out)); + format!("api.Bounds{}({a}, {b})", int_name(*int)) + } + _ => { + let wants: Vec = match unref(want).base() { + Type::Tuple(ts) => ts.clone(), + _ => elements.iter().map(|e| e.ty.clone()).collect(), + }; + let parts: Vec = elements.iter().zip(&wants).map(|(e, t)| self.value(e, t, out)).collect(); + match parts.len() { + 1 => format!("({},)", parts[0]), + _ => format!("({})", parts.join(", ")), + } + } + } + } + + fn list(&mut self, items: &[Expr], want: &Type, out: &mut String) -> String { + let (collection, item) = match unref(want).base() { + Type::List(c, item) => (*c, (**item).clone()), + ty => panic!("a list as {ty:?}"), + }; + let parts: Vec = items.iter().map(|e| self.value(e, &item, out)).collect(); + let code = match &item { + Type::Int(int) => Some(array_code(*int)), + Type::F64 => Some("d"), + Type::F32 => Some("f"), + _ => None, + }; + match (code, collection) { + (Some(code), _) => format!("array.array(\"{code}\", [{}])", parts.join(", ")), + (None, Collection::Iter) => format!("iter([{}])", parts.join(", ")), + _ => format!("[{}]", parts.join(", ")), + } + } + + fn closure(&mut self, params: &[Pat], steps: &[Step], value: &Expr, out: &mut String) -> String { + let params: Vec = params.iter().map(|p| self.pat(p)).collect(); + if steps.is_empty() { + let mut pre = String::new(); + let v = self.expr(value, &mut pre); + if pre.is_empty() { + return format!("(lambda {}: {v})", params.join(", ")); + } + } + // A closure of steps: a function defined before the statement that passes it. + let name = self.fresh("f"); + self.line(out, &format!("def {name}({}):", params.join(", "))); + self.depth += 1; + let mut body = self.steps(steps); + if !matches!(value.kind, Kind::Unit) { + let v = self.expr(value, &mut body); + let _ = writeln!(body, "{}return {v}", self.indent()); + } + out.push_str(&body); + self.depth -= 1; + name + } + + /// A call of `id`: a function of the module, an associated function of a type, a + /// method, or a field's getter or setter. + fn call(&mut self, id: FnId, receiver: Option<&Expr>, args: &[Expr], out: &mut String) -> String { + let f = self.t.function(id); + let name = self.t.name(LANGUAGE, id).to_string(); + let params: Vec = f.params.iter().map(|p| p.ty.clone()).collect(); + let access = f.access; + let args: Vec = args.iter().zip(¶ms).map(|(a, ty)| self.value(a, ty, out)).collect(); + let owner = match self.t.owner(id) { + Some(ty) => format!("api.{}", self.t.type_name(LANGUAGE, &ty)), + None => "api".to_string(), + }; + let target = match receiver { + Some(r) => self.expr(r, out), + None => owner, + }; + match access { + Access::Field { set: false, .. } | Access::Const => format!("{target}.{name}"), + _ => format!("{target}.{name}({})", args.join(", ")), + } + } +} + +fn upper(name: &str) -> String { + let mut out = String::new(); + for (i, c) in name.chars().enumerate() { + if c.is_uppercase() && i > 0 { + out.push('_'); + } + out.push(c.to_ascii_uppercase()); + } + out +} + +fn int_name(int: Int) -> String { + let rust = int.rust(); + let mut chars = rust.chars(); + let first = chars.next().unwrap().to_ascii_uppercase(); + format!("{first}{}", chars.as_str()) +} + +fn array_code(int: Int) -> &'static str { + match int { + Int::U8 => "B", + Int::U16 => "H", + Int::U32 => "I", + Int::U64 | Int::Usize => "Q", + Int::I8 => "b", + Int::I16 => "h", + Int::I32 => "i", + Int::I64 | Int::Isize => "q", + } +} + +/// A Python string literal. +fn string(s: &str) -> String { + let mut out = String::from("\""); + for c in s.chars() { + match c { + '"' | '\\' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 || (0xd800..0xe000).contains(&(c as u32)) => { + let _ = write!(out, "\\U{:08x}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); + out +} + +/// A Python bytes literal. +fn bytes(b: &[u8]) -> String { + let mut out = String::from("b\""); + for &byte in b { + match byte { + b'"' | b'\\' => { + out.push('\\'); + out.push(byte as char); + } + 0x20..0x7f => out.push(byte as char), + _ => { + let _ = write!(out, "\\x{byte:02x}"); + } + } + } + out.push('"'); + out +} From 7c8c4c57efee0ef1cf0b2217cf33ea5722e901dd Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 04:03:32 -0800 Subject: [PATCH 05/28] docs(ffi): the api scripts are written from the transcript Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ffi/README.md b/ffi/README.md index fa002c4d9..0e42a6c48 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -1435,9 +1435,15 @@ nix develop .#sanitize --command just ffi sanitize # api's C and C++ scripts un The `api` fixture covers each rule once, and re-exports the `dep` fixture's types, which export into the same library. The fixture's binding serves the host and wasm32, whose items the host's library lacks, and each language's test checks that the host's items work -and that wasm32's fail. `tests/api.c` runs the same script as the -fixture's `examples/transcript.rs`, and the two transcripts must match line for line; -then it breaks each runtime check, which must abort with its message. `tests/api.cpp` +and that wasm32's fail. Each language's script is written at test time by +`tests/fixtures/transcript` from the fixture's `examples/transcript.rs`, whose `main` is a +typed subset of Rust checked against the export's `api.json`: an item it cannot resolve, or +a construct a language's writer cannot spell, fails the test naming it. Each function the +example defines is a hook each language's test writes by hand under the same name, for what +tests its idiom, such as futures and readers, or prints a value no two bindings shape alike. +A new rule's case is a few lines of `main`, which every language then runs. +`tests/api.c` runs the script through the C, and its transcript must match the native one +line for line; then it breaks each runtime check, which must abort with its message. `tests/api.cpp` runs the script through the C++ header at C++17, 20, and 23, with exceptions and RTTI off at 17 and 23, builds it under Clang's `-Wconsumed -Wdangling -Werror`, each case of `tests/api_strict.cpp` failing there, then checks its futures: a wake that lands during a poll, a cancel between a From f6653608f07adfce02dbd4b2c57d9dd70fc2ee3e Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 04:26:42 -0800 Subject: [PATCH 06/28] wip: generate the Dart transcript Co-Authored-By: Claude Opus 5.5 --- ffi/tests/api.dart | 934 +++--------------- ffi/tests/fixtures.rs | 36 +- ffi/tests/fixtures/shapes.rs | 2 +- ffi/tests/fixtures/transcript/dart.rs | 1286 +++++++++++++++++++++++++ ffi/tests/fixtures/transcript/mod.rs | 1 + 5 files changed, 1447 insertions(+), 812 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/dart.rs diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 801c6f4a3..be361a912 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -1,9 +1,10 @@ // The api fixture's Dart test: the script fixtures/api/examples/transcript.rs runs -// natively, through the generated Dart. tests/fixtures.rs compares the transcripts. +// natively, through the Dart tests/fixtures/transcript writes from it, which calls the +// functions here that transcript.rs defines. tests/fixtures.rs compares the transcripts. // -// With an argument, it instead checks the futures' semantics, what closing and the garbage -// collector free, what a closed object refuses, how returned bytes cross, or breaks a -// contract, which must fail. +// With an argument, it instead checks what the script says only in Rust, the futures' +// semantics, what closing and the garbage collector free, what a closed object refuses, +// how returned bytes cross, or breaks a contract, which must fail. import 'dart:async'; import 'dart:collection'; @@ -14,91 +15,12 @@ import 'dart:isolate'; import 'dart:typed_data'; import 'package:api/api.dart' as api; - -/// The unsigned value of a `u64`'s bits, which Dart's `int` reads as signed. -String u64(int v) => BigInt.from(v).toUnsigned(64).toString(); - -/// The `f64` of `bits`. -double f64(int bits) => (Uint64List(1)..[0] = bits).buffer.asFloat64List()[0]; - -/// Each float's bits, as transcript.rs prints them. -String bits32(Float32List v) => Uint32List.fromList(v.buffer.asUint32List(v.offsetInBytes, v.length)).toString(); - -String bits64(Float64List v) => '[${v.buffer.asUint64List(v.offsetInBytes, v.length).map(u64).join(', ')}]'; - -/// Print each of `n`'s lists, its floats as their bits, as transcript.rs does. -void numbers(String what, api.Numbers n) { - print('$what u16 ${n.u16s}'); - print('$what u32 ${n.u32s}'); - print('$what u64 [${n.u64s.map((v) => v.toRadixString(10)).join(', ')}]'); - print('$what i8 ${n.i8s}'); - print('$what i16 ${n.i16s}'); - print('$what i32 ${n.i32s}'); - print('$what i64 ${n.i64s}'); - print('$what f32 ${bits32(n.f32s)}'); - print('$what f64 ${bits64(n.f64s)}'); - final some = n.some; - print('$what some ${some == null ? 'None' : 'Some($some)'}'); -} - -/// The Log callback: keeps even levels. -final class PrintLog extends api.Log { - @override - bool log(int level, String line) { - print('log $level $line'); - return level % 2 == 0; - } - - // Rust closes it once it drops the implementation. - @override - void close() => print('freed'); -} - -String bound(api.BoundU64 b) => switch (b) { - api.BoundU64Included(:final value) => 'Included($value)', - api.BoundU64Excluded(:final value) => 'Excluded($value)', - api.BoundU64Unbounded() => 'Unbounded', -}; +import 'package:transcript/transcript.dart' as transcript; Uint8List bytes(List values) => Uint8List.fromList(values); -/// Bytes in hex, as transcript.rs prints them. -String hex(List bytes) => bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); - -/// A socket address as its IP's bytes in hex, its port, flow label, and scope, each -/// IPv6's alone, apart by colons, as transcript.rs prints it. -String socketHex(api.SocketAddr addr) => switch (addr) { - api.SocketAddrV4(:final ip, :final port) => '${hex(ip.octets)}:$port', - api.SocketAddrV6(:final ip, :final port, :final flowinfo, :final scopeId) => - '${hex(ip.octets)}:$port:$flowinfo:$scopeId', -}; - String text(Uint8List data) => utf8.decode(data); -String quoted(List values) => '[${values.map((v) => '"$v"').join(', ')}]'; - -/// A path's bytes as Rust's `escape_ascii` prints them. -String escaped(api.PathBuf path) { - final out = StringBuffer(); - for (final b in path.bytes) { - switch (b) { - case 0x09: - out.write(r'\t'); - case 0x0d: - out.write(r'\r'); - case 0x0a: - out.write(r'\n'); - case 0x5c || 0x27 || 0x22: - out.write('\\${String.fromCharCode(b)}'); - case >= 0x20 && < 0x7f: - out.write(String.fromCharCode(b)); - default: - out.write('\\x${b.toRadixString(16).padLeft(2, '0')}'); - } - } - return out.toString(); -} - void check(bool ok, String what) { if (!ok) { stderr.writeln('failed: $what'); @@ -152,296 +74,98 @@ Future until(bool Function() done, String what) async { } } -Future script() async { - print('limit ${api.LIMIT}'); +/// The Log callback: keeps even levels. +final class Print extends api.Log { + @override + bool log(int level, String line) { + print('log $level $line'); + return level % 2 == 0; + } - final p = const api.Point(x: 1, y: 2).offset(2, 3); - print('offset ${p.x} ${p.y}'); - print('debug ${p.debug()}'); - print('eq ${p == const api.Point(x: 3, y: 5)}'); - final d = api.Point.default_(); - print('default ${d.x} ${d.y}'); + // Rust closes it once it drops the implementation. + @override + void close() => print('freed'); +} - final c = api.Counter('c', api.U64(5)); - print('get ${c.get()}'); - print('name ${c.name()}'); - print('add ok ${c.add(api.U64(10))}'); - try { - c.add(api.U64(2000)); - } on api.Error catch (e) { - print('add err $e ${e.debug()}'); - } - try { - c.sub(api.U64(20)); - } on api.Error catch (e) { - print('sub err $e ${e.debug()}'); - } - c.rename('d'); - print('name ${c.name()}'); - print('is d ${c.is_('d')}'); - final copy = c.clone(); - copy.add(api.U64(1)); - print('clone ${copy.get()} original ${c.get()}'); - copy.close(); - print('debug ${c.debug()}'); - final label = c.intoLabel(p); - print('label ${label.debug()}'); - print('note ${api.hasText(const api.Note(text: ''))} ${api.hasText(const api.Note(text: null))}'); - - final (below, above) = api.Counter('s', api.U64(7)).split(api.U64(5)); - print('split ${below.name()} ${below.get()} ${above.name()} ${above.get()}'); - final (only,) = api.only(api.Counter('o', api.U64(3))); - print('only ${only.name()} ${only.get()}'); - final (w8, w16, w32, w64) = api.widths(api.U64(98305)); - print('widths $w8 $w16 $w32 $w64'); - for (final b in [2, 0]) { - try { - final (q, r) = api.divide(api.U64(7), api.U64(b)); - print('divide $q $r'); - } on api.Error catch (e) { - print('divide err $e'); - } - } - for (final n in [98305, 0]) { - final spread = api.spread(api.U64(n)); - print(spread == null ? 'spread none' : 'spread ${spread.$1} ${spread.$2} ${spread.$3} ${spread.$4}'); - } - for (final needle in ['lo', 'x']) { - final found = api.find(utf8.encode('hello'), utf8.encode(needle)); - print(found == null ? 'find none' : 'find ${found.$1} ${found.$2}'); - } - final statRows = api.rows([const api.Point(x: 1, y: 2), const api.Point(x: 3, y: 3)]); - print('rows ${statRows.map((r) => '${r.$1} ${r.$2.debug()} ${r.$3.x} ${r.$3.y}').join(', ')}'); - // Each handle in a tuple moves in, as one taken by value does. - final board = api.Board([('low', api.Counter('l', api.U64(1))), ('high', api.Counter('h', api.U64(9)))]); - final ranked = board.ranked(); - print('ranked ${ranked.map((r) => '${r.$1} ${r.$2.name()} ${r.$2.get()}').join(', ')}'); - final best = board.best(); - print('best ${best.name()} ${best.get()}'); - best.close(); - board.close(); - // A map crosses as its pairs and a set as its items, which Rust collects in order, each - // key once, the last kept. - final atlas = const api.Atlas( - points: [('b', api.Point(x: 1, y: 1)), ('ab', api.Point(x: 2, y: 3)), ('b', api.Point(x: 4, y: 4))], - ids: [3, 1, 3], - ).with_('c', const api.Point(x: 5, y: 6)); - final atlasPoints = atlas.points.map((p) => '${p.$1} ${p.$2.x} ${p.$2.y}').join(', '); - print('atlas $atlasPoints; ids ${atlas.ids.join(' ')}'); - // Another crate's error crosses as its message. - for (final text in ['80', 'x']) { - try { - print('port ${api.port(text)}'); - } on api.StringException catch (e) { - print('port err ${e.error}'); - } - } - const span = api.Span(bounds: (2, 10), named: ('s', api.Shape.square)); - final (lowerHalf, upperHalf) = api.halves(span); - print('halves ${lowerHalf.$1} ${lowerHalf.$2} ${upperHalf.$1} ${upperHalf.$2} ${span.debug()}'); - final (swappedN, swappedText) = api.swapped(('t', 4)); - print('swapped $swappedN $swappedText'); - for (final value in <(int?,)?>[null, (null,), (3,)]) { - final doubled = api.doubled(value); - if (doubled == null) { - print('doubled None'); - } else { - print('doubled Some((${doubled.$1 == null ? 'None' : 'Some(${doubled.$1})'},))'); - } - } - // A borrowed or boxed tuple of one is a tuple, not its element. - final (lentOne,) = api.lentBack((bytes([1, 2]),)); - final (boxedOne,) = api.boxedTuple(bytes([3])); - print('lent back $lentOne boxed $boxedOne'); - // A borrowed string and an owned one share a tuple struct. - print( - 'title Some(("${api.title(true)!.$1}",)) ${api.title(false) == null ? 'None' : 'Some'} ' - 'named Some(("${api.named('x')!.$1}",))', - ); +/// Bytes in hex, two digits each. +String _hex(List bytes) => bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); - // Each lent counter is a new handle to a clone. - final registry = api.Registry(api.Counter('first', api.U64(1))); - print('last ${registry.last() != null}'); - registry.push(api.Counter('last', api.U64(2))); - final first = registry.firstGet; - first.add(api.U64(10)); - print('first ${registry.firstGet.get()} lent ${first.get()}'); - final last = registry.last()!; - last.add(api.U64(10)); - print('last ${registry.last()!.get()} lent ${last.get()}'); - // A closure lent for the call edits the first counter through a handle. - const by = 5; - final edited = registry.edit((counter) { - counter.add(api.U64(by)); - return counter.edited() && counter.get() == 6; - }); - print('edit $edited ${registry.firstGet.get()}'); - // A setter moves an object in, as assignment does, closing it. - registry.firstSet(api.Counter('second', api.U64(3))); - print('set first ${registry.firstGet.get()} ${registry.firstGet.name()}'); - print('walk ${api.walk(api.U64(3), (cursor) => api.U64(cursor.at().toInt() * 2))}'); - print('each ${api.each(2, (at) => print('visit $at'))}'); - print('offset ${api.offset(() => 7, 3)}'); - print('shift ${api.shift(() => 7, 4)}'); - - final name = api.Name.owned('a'); - final joined = name.join(api.Name.owned('b')); - print('joined ${joined.asStr()} ${joined.debug()} ${joined == name}'); - joined.rename('c'); - print('renamed ${joined.asStr()}'); - final long = api.longer(joined, api.Name.owned('dd')); - print('longer ${long.asStr()}'); - print('unnamed [${api.unnamed().asStr()}]'); - final lit = api.Name.borrowed('lit'); - print('borrowed ${lit.asStr()} ${lit.shares(api.Name.borrowed('lit'))} ${lit.shares(api.Name.borrowed('other'))}'); - - print('total ${api.total(api.RangeU64(api.U64(2), api.U64(5)))}'); - print('reach ${api.reach(2, 5)}'); - final scaled = [ - api.scaled((BigInt.one << 128) - BigInt.one, api.U64(1)), - api.scaled((BigInt.one << 64) + BigInt.one, api.U64.fromBits(1 << 63)), - api.scaled(BigInt.one << 127, api.U64(2)), - ]; - print('scaled ${scaled.map((v) => v?.toRadixString(16).padLeft(32, '0') ?? 'none').join(' ')}'); - final digest = api.Digest(); - digest.sumSet(api.fingerprint('deadbeef')); - var unparsed = ''; - try { - api.fingerprint('zz'); - } on api.StringException catch (e) { - unparsed = e.error; - } - print('digest ${digest.sumGet} ${digest.flipped(api.ArrayU8x4([0xff, 0, 0xff, 0]))} $unparsed'); - digest.close(); - final batch = api.Batch(), batch2 = api.pair(); - final accepted = [for (var v = 1; v <= 5; v++) batch.push(v)].where((p) => p).length; - final paired = [for (var v = 1; v <= 3; v++) batch2.push(v)].where((p) => p).length; - final emptied = api.drain4(batch); - print('batch ${batch.capacity()} $accepted $emptied ${api.drain4(batch)} ${batch2.capacity()} $paired ${api.drain2(batch2)}'); - print('capacities ${api.capacities42(batch, batch2)} ${api.capacities22(batch2, batch2)}'); - batch.close(); - batch2.close(); - final wide = api.widen(api.RangeU64(api.U64(2), api.U64(5)), api.U64(1)); - print('widen ${wide.start} ${wide.end}'); - final counts = [ - api.BoundsU64(api.BoundU64Included(api.U64(2)), api.BoundU64Excluded(api.U64(5))), - api.BoundsU64(api.BoundU64Included(api.U64(2)), api.BoundU64Included(api.U64(5))), - api.BoundsU64(api.BoundU64Included(api.U64(3)), api.BoundU64Unbounded()), - api.BoundsU64(api.BoundU64Unbounded(), api.BoundU64Unbounded()), - api.BoundsU64(api.BoundU64Excluded(api.U64(2)), api.BoundU64Included(api.U64(4))), - ].map(api.count); - print('count ${counts.join(' ')}'); - print('end ${bound(api.end(api.U64(3)))} ${bound(api.end(api.U64(0)))}'); - final (endsStart, endsEnd) = api.ends(api.U64(3)); - print('ends ${bound(endsStart)} ${bound(endsEnd)}'); - for (final n in [2, 5]) { - try { - print('below ${api.below(api.U64(n), api.U64(3))}'); - } on api.BoundsU64Exception catch (e) { - print('below err ${bound(e.error.start)} ${bound(e.error.end)}'); +String hex(api.ArrayU8x4 bytes) => _hex(bytes.toBytes()); + +/// A path's bytes as Rust's `escape_ascii` prints them. +String escaped(api.PathBuf path) { + final out = StringBuffer(); + for (final b in path.bytes) { + switch (b) { + case 0x09: + out.write(r'\t'); + case 0x0d: + out.write(r'\r'); + case 0x0a: + out.write(r'\n'); + case 0x5c || 0x27 || 0x22: + out.write('\\${String.fromCharCode(b)}'); + case >= 0x20 && < 0x7f: + out.write(String.fromCharCode(b)); + default: + out.write('\\x${b.toRadixString(16).padLeft(2, '0')}'); } } - final window = api.Window(range: api.RangeU64(api.U64(2), api.U64(8)), end: api.end(api.U64(5))); - print('window ${window.contains(api.U64(4))} ${window.contains(api.U64(6))} ${window.debug()}'); - - print(api.greet('x', api.Shape.square)); - print('len ${api.len(utf8.encode('abc'))}'); - final binary = bytes([0xff, 0, 0x61]); - print('hex ${api.hex(binary)}'); - print('timed hex ${api.timedHex(binary)}'); - print('sample hex ${api.sampleHex(binary)}'); - print('queued hex ${api.queuedHex(binary)}'); - print('tick ${api.tickName(const api.Label(name: 'tick', at: null, ttl: null))}'); - print('rooted ${api.rootedName(const api.Label(name: 'rooted', at: null, ttl: null))}'); - print('stored ${api.storedText('stored')}'); - print('layer ${api.layerName(const api.Label(name: 'layer', at: null, ttl: null))}'); - for (final event in [api.EventMoved(p), const api.EventNamed(name: 'n'), const api.EventDone()]) { - print(api.describe(event)); - } + return out.toString(); +} - // A `Copy` handle passed by value is copied, so it stays usable. - final stamp = api.Stamp.fromMillis(api.U64(2500)); - print('secs ${stamp.secs()}'); - print('later ${api.Stamp.fromMillis(api.U64(3000)).later(stamp)}'); - print('secs ${stamp.secs()}'); - print('whole ${stamp.whole().debug()}'); - final message = api.Message(stamp, utf8.encode('body')); - print('payload ${text(message.payloadGet)}'); - print('stamp ${message.stampGet!.debug()}'); - print('sent ${message.sent()}'); - // Setters assign in place: the bytes are copied in, and a `Copy` handle copied. - final reset = api.Stamp.fromMillis(api.U64(4000)); - message.stampSet(reset); - message.payloadSet(utf8.encode('edited')); - print('payload ${text(message.payloadGet)}'); - print('stamp ${message.stampGet!.debug()}'); - print('secs ${reset.secs()}'); - message.stampSet(null); - print('stamp ${message.stampGet != null}'); - - // A value past a word, copied across: a closure takes and returns one by value. - final moment = api.Moment.new_(api.U64(1500), api.U64(1000))!; - print('moment ${moment.millis()} ${api.Moment.new_(api.U64(1), api.U64(0)) == null}'); - final shifted = api.shifted(moment, (m) => m.after(api.U64(500))); - print('shifted ${shifted.millis()} ${shifted == moment.after(api.U64(500))}'); - print('wrapped ${moment.after(api.U64.max).millis()} ${moment == shifted}'); - - // A value with padding, or bytes that vary, is a handle, as no table says where padding is. - final gap = api.Gap(api.U64(7), 3); - print('gap ${gap.sum()} ${gap == api.Gap(api.U64(7), 3)}'); - final berth = api.Berth(4); - print('berth Some(${berth.at()}) ${api.Berth(null).at() == null ? 'None' : 'Some'}'); - - // A `Copy` type changed in place is a value, which a `&mut self` method returns as the - // call left it, Rust's own return beside it: a change reaches only the copy it replaces. - var score = api.Score.of(api.U64(2)); - final increment = api.Score.of(api.U64(3)); - score = score.add(increment); - score = score.add(increment); - print('score ${score.count()} ${increment.doubled().count()} ${increment.count()}'); - var (scoreCopy, taken) = score.take(); - print('taken $taken ${scoreCopy.count()} ${score.count()}'); - final otherScore = api.Mut(increment); - final (absorbed, before0, before1) = scoreCopy.absorb(otherScore); - scoreCopy = absorbed; - print('absorbed $before0 $before1 ${scoreCopy.count()} ${otherScore.value.count()} ${increment.count()}'); - var hits = api.Hits.of(api.U64(1), api.U64(2)); - final keptHits = hits; - hits = hits.add(api.Hits.of(api.U64(10), api.U64(20))); - hits = hits.hitsSet(api.U64(7)); - print('hits ${hits.hitsGet} ${hits.missesGet} ${keptHits.hitsGet} ${keptHits.missesGet} ${hits == keptHits}'); - final (counted, countedSame) = keptHits.eq(keptHits); - print('counted $countedSame ${counted.hitsGet}'); - var extent = api.Extent(api.U64(5), api.U64(3)); - final extentStart = extent; - final (slid, old) = extent.slide(api.U64(10)); - extent = slid; - extent = extent.startSet(api.U64(extent.startGet.toInt() + 1)); - print('extent $old ${extent.startGet} ${extent.end()} ${extentStart.startGet} ${extentStart.end()}'); - final weighted = api.Weighted(score: increment, weight: 4); - print('weighted ${weighted.total()} ${weighted.score.count().toInt() + increment.count().toInt()}'); - // A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. - final mark = api.Mark.of(api.U64(1)); - mark.add(api.U64(2)); - final parcel = api.Parcel(mark: mark, payload: bytes([97, 98, 99])); - print('heft ${api.heft((mark, bytes([97, 98])), parcel, (api.Counter('w', api.U64(1)), bytes([97, 98, 99, 100])))}'); - // A value's `&mut self` beside a checked handle. - final (noted, notedBefore) = api.Score.of(api.U64(2)).note(api.Mark.of(api.U64(5))); - print('noted $notedBefore ${noted.count()}'); - - print('kept ${api.emit(PrintLog(), bytes([1, 2, 3, 4]))}'); - final logger = api.Logger(PrintLog()); - print('write ${logger.write('hi')}'); - logger.close(); - print('dropped'); - // Rust calls it on another thread, before the call returns. - const threshold = 2; - final filtered = api.filter(bytes([1, 2, 3, 4]), (level, line) { - print('filter $level $line'); - return level > threshold; - }); - print('filtered $filtered'); +String pathHex(api.PathBuf path) => _hex(path.bytes); + +/// A duration as its seconds and nine digits of nanoseconds. +String seconds(api.RustDuration d) => '${d.secs.toRadixString(10)}.${d.nanos.toString().padLeft(9, '0')}'; + +/// A duration in whole milliseconds, cut to a `u64` as Rust's `as` does. +api.U64 millis(api.RustDuration d) => + api.U64.fromBigInt((d.secs.toBigInt() * BigInt.from(1000) + BigInt.from(d.nanos ~/ 1000000)).toUnsigned(64)); + +/// A char's code point. +int code(String c) => c.runes.single; + +List reversed(List list) => list.reversed.toList(); +/// Each float's bits. +List f64Bits(Float64List floats) => + floats.buffer.asUint64List(floats.offsetInBytes, floats.length).map(api.U64.fromBits).toList(); + +/// A socket address as its IP's bytes in hex, its port, flow label, and scope, each +/// IPv6's alone, apart by colons. +String socketHex(api.SocketAddr addr) => switch (addr) { + api.SocketAddrV4(:final ip, :final port) => '${_hex(ip.octets)}:$port', + api.SocketAddrV6(:final ip, :final port, :final flowinfo, :final scopeId) => + '${_hex(ip.octets)}:$port:$flowinfo:$scopeId', +}; + +/// An address's bytes in hex, so the length shows its family. +String ipHex(api.IpAddr ip) => _hex(ip.octets); + +/// A path no Rust string spells: bytes that are not UTF-8, or on Windows, WTF-8's lone +/// surrogate. +api.PathBuf unspelled() => Platform.isWindows ? api.PathBuf.fromBytes([0xed, 0xa0, 0x80]) : api.stray(); + +/// Print each of `n`'s lists, its floats as their bits. +Future numbers(String what, api.Numbers n) async { + String bits32(Float32List v) => Uint32List.fromList(v.buffer.asUint32List(v.offsetInBytes, v.length)).toString(); + String digits(Iterable v) => '[${v.map((v) => v.toRadixString(10)).join(', ')}]'; + print('$what u16 ${n.u16s}'); + print('$what u32 ${n.u32s}'); + print('$what u64 ${digits(n.u64s)}'); + print('$what i8 ${n.i8s}'); + print('$what i16 ${n.i16s}'); + print('$what i32 ${n.i32s}'); + print('$what i64 ${n.i64s}'); + print('$what f32 ${bits32(n.f32s)}'); + print('$what f64 ${digits(f64Bits(n.f64s))}'); + final some = n.some; + print('$what some ${some == null ? 'None' : 'Some($some)'}'); +} + +/// A channel's futures, on the isolate's event loop. +Future channel() async { final channel = api.Channel(); var wakes = 0; // Polled at the call, it pends, and the wake the send posts resumes it from the event loop. @@ -502,427 +226,11 @@ Future script() async { throws(waker.call, 'a closed waker throws'); await until(() => wakes == 5, 'a returned waker wakes the waiter'); print('woken $wakes'); +} - final nodes = api.Node(api.U64(1), null); - nodes.push(api.U64(2)); - print('node ${nodes.sum()}'); - - final tally = api.Tally(); - tally.bump(); - print('tally ${tally.bump()} ${tally == tally}'); - print('both ${api.bumpBoth(tally, tally)}'); - print('peek ${api.peek(tally, (lent) => lent.bump())}'); - - final area = api.grow(api.Area(const api.Size(width: 2, height: 3)), 1); - final areaSize = area.size(); - print('area ${areaSize.width} ${areaSize.height} ${area.pixels()}'); - - // Generic types, each at the instances it infers, named by their arguments. - const pair = api.PairU32(left: 2, right: 5); - final swapped = pair.swap(); - print('pair ${swapped.left} ${swapped.right} sum ${pair.sum()} ${pair.debug()} ${pair == swapped}'); - print('even ${pair.even()} ${const api.PairU32(left: 7, right: 7).even()}'); - // An instance renamed alone, beside another of `Pair` that keeps its name. - final sized = api.tag(const api.Size(width: 1, height: 2), 3); - final flipped = sized.swap(); - print('sized ${flipped.left} ${flipped.right.width} ${flipped.debug()}'); - final beside = const api.PairU32(left: 258, right: 9).besideSize(sized.left); - print('beside ${beside.left} ${beside.debug()}'); - // At its default, named as the type itself. - final stack = api.Stack(); - for (final (i, n) in ['a', 'b'].indexed) { - stack.push(api.Counter(n, api.U64(i + 1))); - } - final top = stack.pop()!.get(); - print('stack ${stack.depth()} Some($top) ${stack.pop() != null} ${stack.pop() == null}'); - // Generic functions and methods, at each implementation of the trait bounding them, by - // reference, which leaves Dart its object. - final fromPoint = api.Counter.seededPoint('p', const api.Point(x: -3, y: 4)); - final fromSize = api.Counter.seededSize('s', const api.Size(width: 5, height: 6)); - final fromCounter = api.Counter.seededCounter('c', fromPoint); - final fromPolar = api.Counter.seededPolarPoint('q', const api.PolarPoint(turns: 1, distance: 2)); - print( - 'seeded ${fromPoint.get()} ${fromSize.get()} ${fromCounter.get()} ${fromPolar.get()} ' - 'past ${stack.depthPastPoint(const api.Point(x: 1, y: 2))} ' - 'seeds ${api.seedsPointSize(const api.Size(width: 2, height: 3))}', - ); - - // A trait implemented for `Point` and `&Point` apart: one instance. - print('weigh ${api.weighPoint(const api.Point(x: -1, y: 2))}'); - // A function named as the type it returns, and one named as a type it does not. - print('polar ${api.polarPoint(2)!.distance} ${api.polarPoint(0) == null} ' - 'area ${api.area(const api.Size(width: 2, height: 3))}'); - // Two types whose paths join alike, the second kept apart where its path splits. - print('wind ${api.wind(const api.PolarTurn(whole: 2), const api.Polar_Turn(part: 3))}'); - // Names that clash in some language, each kept apart there. - const clashSpan = api.ClashSpan(width: 4); - final clashStore = api.ClashStore(7); - print('clash ${const api.ClashTone(hz: 440).debug()} ${const api.ClashTone_(db: 3).debug()} ' - '${const api.Cancelled_(step: 2).debug()} span ${clashSpan.width_()} ${clashSpan.toString_()} $clashSpan ' - 'store ${clashStore.free()} ${clashStore.close_()} ' - 'audio ${api.clashAudioEncoderFinish()} ${api.clashAudioEncoderFinish_()} ' - 'nested ${api.clashNested(((1, 2), 3), ((1, 2, 3),))}'); - clashStore.close(); - // Instances that name each other, and one made only by an impl of it. - final cross = api.cross( - const api.LeftRightU8(value: api.RightU8(value: 1)), - const api.RightLeftU8(value: api.LeftU8(value: 2)), - ); - print('cross $cross outer ${api.OuterInnerU8(4).get()}'); - // A bound that outlives the call takes a value, and an instance only a constant names. - print('kept ${api.keptPoint(const api.Point(x: 1, y: -2))} boxed ${api.BOXED.value}'); - print('keep ${api.keepPoint(const api.Point(x: 1, y: -2))}'); - const five = api.Point(x: 5, y: 2); - print('kept or ${api.keptOrPoint(five)} ${api.keptOrPoint(null)} keeper ${api.keeperPoint(five)}'); - // Inferred instances taking a lent closure and a foreign implementation, and one only - // its impl of a trait names. - const sides = api.PairU32(left: 2, right: 5); - print('apply ${api.applyU32(sides, (side) => side * 3)}'); - print('report ${api.reportU32(sides, PrintLog())}'); - print('wrapped ${api.keptWrapU32(const api.WrapU32(value: 4))}'); - print('keeps ${api.keeps(PrintLog()).value}'); - - // Its Drop runs when Dart closes it, not before. - final token = api.Token(7); - print('token ${token.idGet} dropped ${api.dropped()}'); - token.close(); - print('dropped ${api.dropped()}'); - - // A field and the method of its name, each its own member. - final retry = api.Retry(5); - final limit = retry.limitGet; - print('retry ${limit == null ? 0 : 1} ${limit ?? 0} ${retry.limit()} ${retry.delay()}'); - // The renamed field's setter, named as its getter. - retry.limitSet(null); - print('retry ${retry.limit()}'); - print('slot ${api.SlotU8(200).value()}'); - - // Foreign types: a URL parsed from text, socket addresses, OS paths, and lists. - final base = api.Url.parse('https://example.com/a/b'); - final host = api.host(base); - print('url $base host ${host == null ? 'None' : 'Some("$host")'}'); - final url = api.resolve(base.clone(), 'c?d'); - print('resolve $url ${url == base}'); - url.close(); - try { - api.Url.parse('no scheme').close(); - } on api.StringException catch (e) { - print('parse err ${e.error}'); - } - final v4 = api.SocketAddrV4(api.Ipv4Addr.from(InternetAddress('127.0.0.1')), 8080); - final v6 = api.SocketAddrV6(api.Ipv6Addr.from(InternetAddress('::1')), 443, scopeId: 3); - print('ports ${api.ports([v4, v6])}'); - final peer = api.Peer(addr: v6, names: ['a', 'b']).next('c'); - print('peer ${peer.debug()} ${quoted(peer.aliases())}'); - final file = api.file(api.PathBuf('dir'), 'f\\\'"\t'); - print('file ${escaped(file)}'); - print('parents ${api.parents([file, api.PathBuf('/')]).map((p) => p == null ? 'none' : escaped(p)).join(' ')}'); - final words = api.words(' one two three '); - print('words ${words.length} ${quoted(words)}'); - print('sentence ${api.sentence(words)} ${api.sentence(null)}'); - print('sentence ${api.sentence([])}|'); - print('either ${api.either('abc')} ${api.either(null)}'); - print('prefixed ${utf8.decode(api.prefixed(utf8.encode('cd'), utf8.encode('ab')))} ' - '${utf8.decode(api.prefixed(utf8.encode('cd'), null))}'); - print('coordinates ${api.coordinates(const api.Point(x: 2, y: 3))} ${api.coordinates(null)}'); - final two = api.Counter('two', api.U64(2)); - final three = api.Counter('three', api.U64(3)); - print('plus ${two.plus(three)} ${two.plus(null)}'); - print('add_to ${two.addTo(three)} ${two.addTo(null)} ${three.get()}'); - two.close(); - three.close(); - final encoded = api.Mut(utf8.encode('0,')); - api.putNumber(1, encoded); - api.putNumber(23, encoded); - print('put_number ${utf8.decode(encoded.value)}'); - final entry = api.Mut((utf8.encode('ab'), 1)); - final stamps = api.pushCounted(entry, 0x63); - print('push_counted $stamps ${utf8.decode(entry.value.$1)} ${entry.value.$2}'); - final digits = api.Mut(utf8.encode('7x9')); - final firstDigit = api.digit(digits); - var skipped = false; - try { - api.digit(digits); - } on api.Error { - skipped = true; - } - print('digit $firstDigit $skipped ${api.digit(digits)} ${digits.value.length}'); - final nudged = api.Mut(const api.Point(x: 1, y: 2)); - api.nudge(nudged, 3); - print('nudge ${nudged.value.x} ${nudged.value.y}'); - final config = api.secure('h3'); - print('secure ${api.alpnLent(config)} ${api.alpn(config.clone())}'); - final cert = api.certify(utf8.encode('der')); - final certLen = api.certLen(cert); - print('cert $certLen ${text(api.certDer(cert))} ${api.chainLen([api.certify(utf8.encode('a')), api.certify(utf8.encode('bc'))])}'); - config.close(); - // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. - print('resolver ${api.resolved(api.resolver('r1'))}'); - final codecs = api.Codecs(); - print('codecs ${codecs.ids()}'); - codecs.listSet(codecs.listGet.reversed.toList()); - print('codecs reversed ${codecs.ids()}'); - codecs.close(); - // A standard library value no type maps, in a handle. - final failure = api.failure('boom'); - print('failure ${api.failureMessage(failure)} ${api.failureKind(failure)}'); - // Iterators, passed as the arrays of their items. - print('sum_all ${api.sumAll([1, 2, 3])}'); - print('weigh_all ${api.weighAllCounter([api.Counter('w', api.U64(3))])}'); - print('offered_len ${api.offeredLen([utf8.encode('h3'), utf8.encode('moq-00')])}'); - print('join_words ${api.joinWords(['a', 'b', 'c'])}'); - // Bytes that must be `'static`, interned. - for (final label in ['der', 'der again']) { - final der = api.Der.fromSlice(utf8.encode('der')); - print('$label ${text(der.bytes())}'); - der.close(); - } - final session = api.resume('h3', 60); - print('resume ${session.alpn()} ${session.lifetime().seconds}'); - session.close(); - try { - api.resume('', 60); - } on api.StringException catch (e) { - print('resume err ${e.error}'); - } - final meters = api.Meters(); - final lentMeter = meters.first(); - lentMeter.add(api.U64(2)); - print('lent ${lentMeter.add(api.U64(3))} ${meters.first().count()}'); - lentMeter.close(); - meters.clear(); - print('cleared ${meters.first().count()}'); - final lastMeter = meters.lastGet; - lastMeter.add(api.U64(4)); - print('field lent ${lastMeter.add(api.U64(1))}'); - lastMeter.close(); - // An optional field that is not Clone, lent as `Some` of a handle. - print('spare ${meters.spareGet != null}'); - meters.spareSet(api.Meter.default_()); - final spare = meters.spareGet!; - spare.add(api.U64(5)); - print('spare lent ${spare.add(api.U64(1))}'); - spare.close(); - meters.close(); - final tallies = api.Tallies(); - tallies.first().bump(); - print('tallied ${tallies.first().bump()}'); - // A draft borrowing its ledger exclusively until it closes, through which its sheet's - // members are reached by Deref and DerefMut: the ledger refuses any other use meanwhile. - final ledger = api.Ledger(); - var draft = ledger.edit(); - draft.titleSet('minutes'); - draft.write('first'); - print('draft ${draft.titleGet} ${draft.lines()} ${draft.describe()} ${draft.edited()}'); - try { - ledger.published(); - check(false, 'a lent ledger refuses a read'); - } on StateError catch (e) { - check(e.message == 'api_Ledger_published: a handle is borrowed exclusively', 'a lent ledger: $e'); - } - print('committed ${draft.commit()}'); - print('ledger ${ledger.title()} ${ledger.published()}'); - draft = ledger.edit(); - print('read ${draft.lines()} ${draft.edited()}'); - draft.close(); - draft = ledger.edit(); - draft.write('second'); - draft.close(); - print('dropped ${ledger.published()}'); - final receipt = ledger.receipt(); - print('receipt ${receipt.count()}'); - receipt.close(); - final padSmall = api.PadU8.small(), padWide = api.PadU16.wide(), layered = api.Layered(); - final marker = api.Marker('m', 3, 5); - marker.ySet(7); - print('forwarded ${padWide.title()} ${layered.lines()} ${marker.xGet} ${marker.yGet} ' - '[${padSmall.describe()}] [${padWide.describe()}]'); - for (final handle in [padSmall, padWide, layered, marker]) { - handle.close(); - } - ledger.seal(); - try { - ledger.edit().close(); - } on api.Error catch (e) { - print('sealed $e'); - } - ledger.close(); - tallies.close(); - print('chunks ${api.chunks(utf8.encode('abcde'), api.U64(2))}'); - final counters = api.counters(['x', 'y']); - print('counters ${counters.map((c) => '${c.name()} ${c.get()}').join(', ')}'); - // Each counter moves in, so a later call throws. - print('worth ${api.worth([counters[0]], [counters[1]])} ${api.worth(null, [])}'); - for (final counter in counters) { - closed(counter.get, 'Counter', 'a counter moved in is closed'); - } - final held = [api.heldCount((api.Counter('h', api.U64(4)),)), api.heldCount(null)]; - print('held ${held.map((n) => n == null ? 'None' : 'Some($n)').join(' ')}'); - print( - 'boxed Some("${api.boxedName(api.boxedCounter('b'))}") ' - '${api.boxedName(null) == null ? 'None' : 'Some'} ${api.boxedCounter(null) == null}', - ); - print('less ${api.less(5, 2)}'); - print( - 'sums ${api.sums([ - Uint32List.fromList([1, 2]), - Uint32List(0), - Uint32List.fromList([3]), - ])}', - ); - print('least ${api.least([[3, 1], [], [2]]).join(' ')}'); - numbers('edges', api.Numbers.edges()); - numbers('reversed', api.Numbers.edges().reversed()); - final edges = api.Numbers.edges(); - final nan = api.Measure.new_(double.nan, false); - print('float equal ${edges == edges} ${edges == api.Numbers.edges()} ${api.Numbers.zero(true) == api.Numbers.zero(false)} ${nan == nan} ${api.Measure.new_(-0.0, true) == api.Measure.new_(0.0, false)}'); - print('sum u32 ${api.sumU32(Uint32List(0))} ${api.sumU32(Uint32List.fromList([0xffffffff, 0xffffffff, 2]))}'); - print('doubled i64 ${api.doubledI64(Int64List.fromList([-0x8000000000000000, -1, 0, 0x7fffffffffffffff]))}'); - final floats = api.boxedFloats(Float64List.fromList([-0.0, f64(0x7ff8000000000001)])); - print('boxed floats ${bits64(floats)}'); - final summed = api.summed([const api.Point(x: 1, y: 2), const api.Point(x: -4, y: 6)]); - final noneSummed = api.summed([]); - print('summed ${summed.x} ${summed.y} ${noneSummed.x} ${noneSummed.y}'); - print('longest ${api.longest(['a', 'abc'])} ${api.longest([])}'); - print('first of Some("${api.firstOf(['a', 'b'])}") ${api.firstOf([]) ?? 'None'}'); - final limits = api.byteLimits(utf8.encode('a'), utf8.encode('bc')); - final waits = api.breadth( - api.LimitsDuration( - low: api.RustDuration.from(const Duration(milliseconds: 5)), - high: api.RustDuration.from(const Duration(seconds: 2)), - ), - ); - print('limits ${utf8.decode(limits.low)} ${utf8.decode(limits.high)} breadth ${waits.toDuration().inMilliseconds}'); - final parts = utf8.decode(api.joined([utf8.encode('ab'), Uint8List(0), utf8.encode('c')])); - print('joined $parts ${api.joined([]).length} read ${api.readLen(utf8.encode('hello'))}'); - final doc = api.Json.parse('{"b": [1, 2.5, null], "a": "é"}'); - print('json ${api.encode(doc)}'); - print('timed text ${api.timedText(doc)}'); - final tagged = api.tagged(doc, 't'); - print('tagged ${tagged.toText()}'); - tagged.close(); - // A JSON object's entries cross as pairs of a key and its document, each moved in. - final entries = api.entries([('b', api.Json.parse('[1]')), ('a', api.Json.parse('2'))], 't'); - print('entries ${entries.map((e) => '${e.$1} ${e.$2.toText()}').join(', ')}'); - for (final entry in entries) { - entry.$2.close(); - } - try { - api.Json.parse('{"a":').close(); - } on api.StringException catch (e) { - print('json parse err ${e.error}'); - } - final site = api.Site(base); - print('site ${site.homeGet} ${site.homeGet}'); - - // Slices, passed in and returned as clones, and the socket address of each family. - String debugs(List values) => - '[${values.map((v) => switch (v) { - api.Shape s => s.debug(), - api.Point p => p.debug(), - api.Label l => l.debug(), - _ => throw ArgumentError(v), - }).join(', ')}]'; - print('shapes ${debugs(api.Shape.ALL)} greetings ${quoted(api.GREETINGS)}'); - print('both ${debugs(api.Shape.BOTH)} primes ${api.PRIMES}'); - final trail = api.Trail([const api.Point(x: 1, y: 2), const api.Point(x: 3, y: 4)], ['a', 'b']); - print('trail ${debugs(trail.points())} ${debugs(trail.labels())}'); - // Returned iterators, each collected at the call: drained labels are gone after. - print('iterated ${debugs(trail.iter())} ${quoted(trail.names())} ${trail.bytes()}'); - print('drained ${debugs(trail.drain())} then ${debugs(trail.labels())}'); - // A filter, collected at the call. - print('beyond ${trail.beyond(1).map((p) => '${p.x} ${p.y}').join(', ')}'); - trail.close(); - final numbered = api.numbered(['p', 'q']); - print('numbered ${numbered.map((c) => '${c.name()} ${c.get()}').join(', ')}'); - final (next4, next6) = api.nexts(v4, v6); - print('nexts ${next4.ip} ${next4.port} ${next6.port} ${next6.scopeId}'); - final (nextIp4, nextIp6) = api.nextIps( - api.Ipv4Addr.from(InternetAddress('10.0.0.255')), - api.Ipv6Addr.from(InternetAddress('::ffff')), - ); - final mapped = api.flip(api.IpAddr.from(InternetAddress('127.0.0.1'))); - final ips = [nextIp4, nextIp6, mapped, api.flip(mapped), api.flip(api.IpAddr.from(InternetAddress('::1')))]; - print('ips ${ips.map((ip) => hex(ip.octets)).join(' ')}'); - - // Lossless round trips: each type's edge values, passed through Rust and back. - final durations = [ - api.RustDuration.zero, - api.RustDuration(api.U64(0), 1), - api.RustDuration(api.U64(9223372036), 854775808), - api.RustDuration(api.U64.max, 999999999), - ].map(api.sameDuration); - print('lossless duration ${durations.map((d) => '${d.secs.toRadixString(10)}.${d.nanos.toString().padLeft(9, '0')}').join(' ')}'); - final u64s = [api.U64(0), api.U64.fromBigInt(BigInt.one << 63), api.U64.max]; - print('lossless u64 ${u64s.map((v) => api.sameU64(v).toRadixString(10)).join(' ')}'); - print('lossless usize ${[api.U64(0), api.U64.max].map((v) => api.sameUsize(v).toRadixString(10)).join(' ')}'); - print('lossless isize ${api.sameIsize(-0x8000000000000000)} ${api.sameIsize(0x7fffffffffffffff)}'); - final u128s = [BigInt.zero, BigInt.one << 64, (BigInt.one << 128) - BigInt.one]; - print('lossless u128 ${u128s.map((v) => api.sameU128(v).toRadixString(16).padLeft(32, '0')).join(' ')}'); - final chars = ['\u{0}', '\u{d7ff}', '\u{e000}', '\u{10ffff}']; - print('lossless char ${chars.map((c) => api.sameChar(c).runes.single.toRadixString(16)).join(' ')}'); - // A path no Rust string spells: bytes that are not UTF-8, or on Windows, WTF-8's lone surrogate. - final unspelled = api.PathBuf.fromBytes(Platform.isWindows ? [0xed, 0xa0, 0x80] : [0xff]); - print('lossless path ${[api.PathBuf('a/é'), unspelled].map((p) => hex(api.samePath(p).bytes)).join(' ')}'); - final sockV4 = api.sameSocketAddrV4(api.SocketAddrV4(api.Ipv4Addr.fromOctets([255, 255, 255, 255]), 65535)); - final sockV6 = api.sameSocketAddrV6( - api.SocketAddrV6( - api.Ipv6Addr.fromOctets([0, 1, for (var i = 0; i < 13; i++) 0, 2]), - 3, - flowinfo: 0xffffffff, - scopeId: 0xffffffff, - ), - ); - final socks = [sockV4, sockV6].map(api.sameSocketAddr); - print('lossless socket ${socketHex(sockV4)} ${socketHex(sockV6)} ${socks.map(socketHex).join(' ')}'); - // A key hashes by Rust's `Hash`: equal keys alike, and these two apart. - final key = api.Key('a'); - print('key ${key.hashCode == api.Key('a').hashCode} ${key.hashCode == api.Key('b').hashCode}'); - final sameIps = [ - api.sameIpAddr(api.Ipv4Addr.fromOctets([255, 255, 255, 255])), - api.sameIpAddr(api.Ipv6Addr.fromOctets([0xff, 0xff, for (var i = 0; i < 13; i++) 0, 1])), - ]; - print('lossless ip ${sameIps.map((ip) => hex(ip.octets)).join(' ')}'); - - // serde_json's map iterator, collected as pairs of a key and its document. - final sections = api.sections([('b', api.Json.parse('[1]')), ('a', api.Json.parse('2'))]); - print('sections ${sections.map((e) => '${e.$1} ${e.$2.toText()}').join(', ')}'); - for (final section in sections) { - section.$2.close(); - } - // An instant only Rust makes, which each call copies out of its handle, and compares. - final began = api.now(); - final ended = api.later(began, api.RustDuration.from(const Duration(milliseconds: 1500))); - final same = api.later(began, api.RustDuration.zero); - print( - 'instants ${api.since(ended, began).toDuration().inMilliseconds} ' - '${api.since(began, ended).toDuration().inMilliseconds} ${began == same} ${began == ended}', - ); - print('has_instant ${api.hasInstant(began)} ${api.hasInstant(null)}'); - // tracing's level, and its filter as an optional level whose null is `OFF`. - final verbosity = api.Verbosity(api.Level.warn); - print('verbosity ${api.spell(verbosity.filter())} ${api.spell(api.louder(verbosity.filter()))}'); - verbosity.levelSet(api.Level.trace); - print('verbosity ${verbosity.levelGet == api.Level.trace} ${api.spell(verbosity.filter())} ${api.spell(api.louder(verbosity.filter()))} ${api.spell(api.louder(null))}'); - verbosity.close(); - - // A closure's string, which Rust takes. - print('made ${api.made(3, (n) => '$n times')}'); - // A closure taking and returning `Copy` values copies them, never running their `Clone`. - final nine = api.Ticket(9); - final renewed = api.reissue(api.Ticket(7), (t) => api.Ticket(t.number() + 1)).number(); - final copied = api.reissue(api.Ticket(7), (_) => nine).number(); - print('reissued $renewed $copied, cloned ${api.Ticket.clones()}'); - // A record's traits borrow the checked handle it holds. - final nines = api.Mark.of(api.U64(9)); - final front = api.seat(nines, 1); - final back = api.seat(nines, 2); - print('seat ${front.debug()} ${front == api.seat(nines, 1)} ${front == back}'); - // A kept closure, called on another thread after the call that took it returned. - final spawned = api.Spawned(() => 7); - check(spawned.join() == 7, 'a kept closure runs on another thread'); - // A kept closure: called again at the instant it asks for, then once its waiter wakes, - // failing with the exception the binding throws for Rust's error. +/// A kept closure: called again at the instant it asks for, then once its waiter wakes, +/// failing with the exception the binding throws for Rust's error. +Future drive() async { final start = api.Moment.new_(api.U64(0), api.U64(1000))!; var calls = 0; final stopped = await within( @@ -944,7 +252,11 @@ Future script() async { 'a kept closure wakes its future', ); print('drive $stopped'); - // A reader the caller implements: dart:io's file, then one whose reads fail. +} + +/// Readers the caller implements: dart:io's file, one whose reads fail, and one that seeks +/// past `i64::MAX`. +Future readers() async { final dir = Directory.systemTemp.createTempSync('api'); final opened = (File('${dir.path}/tail')..writeAsStringSync('hello world')).openSync(); for (final reader in [api.SeekableReader.file(opened), Broken()]) { @@ -963,23 +275,38 @@ Future script() async { } on api.StringException catch (e) { print('sought error $e'); } - print('non zeros ${api.describeNonZeros(api.nonZeros())}'); - for (final hop in [null, api.U64(1), api.U64.max]) { - final next = api.nextHop(hop); - print(next == null ? 'hop None' : 'hop Some(${next.toRadixString(10)})'); - } - print('farther hop ${api.fartherHop(const api.PairNonZeroU16(left: 3, right: 0xFFFF))}'); - final local = api.Local(); - final shared = api.localOrNew(local); - final bumped = local.bump(); - print('local $bumped ${shared.bump()}'); - print('local fresh ${api.localOrNew(null).bump()}'); - print('local either ${api.bumpEither(null, shared)}'); +} + +/// Futures of a value that is not `Send`, awaited on the isolate's thread. +Future localLater(api.Local local) async { print('local later ${(await api.localOrNewLater(local)).bump()}'); print('local later fresh ${(await api.localOrNewLater(null)).bump()}'); } -/// A reader whose reads fail, as the transcript's: each seek lands at 0. +/// What the transcript's script says only in Rust: Dart's own errors. +void checks() { + // A draft borrows its ledger exclusively until it closes: the ledger refuses any other + // use meanwhile. + final ledger = api.Ledger(); + final draft = ledger.edit(); + try { + ledger.published(); + check(false, 'a lent ledger refuses a read'); + } on StateError catch (e) { + check(e.message == 'api_Ledger_published: a handle is borrowed exclusively', 'a lent ledger: $e'); + } + draft.close(); + // Each counter moves in, so a later call throws. + final counters = api.counters(['x', 'y']); + api.worth([counters[0]], [counters[1]]); + for (final counter in counters) { + closed(counter.get, 'Counter', 'a counter moved in is closed'); + } + // A kept closure, called on another thread after the call that took it returned. + check(api.Spawned(() => 7).join() == 7, 'a kept closure runs on another thread'); + print('checks ok'); +} + /// A reader of nothing, which seeks anywhere from its start, as Rust's `Cursor` does: a /// `u64` offset is its bits, so -1 is `u64::MAX`. final class Far implements api.SeekableReader { @@ -990,6 +317,7 @@ final class Far implements api.SeekableReader { int seek(int offset, api.SeekFrom from) => offset; } +/// A reader whose reads fail, as the transcript's: each seek lands at 0. final class Broken implements api.SeekableReader { @override int readInto(Uint8List buffer) => throw const Failure('broken'); @@ -1793,7 +1121,9 @@ void broken(String which) { Future main(List args) async { switch (args) { case []: - await script(); + await transcript.script(); + case ['checks']: + checks(); case ['futures']: await futures(); case ['owned']: diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 9b5eadc00..55de98017 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1593,6 +1593,7 @@ const TSCONFIG: &str = r#"{ #[test] fn api_dart() { let api = api(); + let scripts = generated("dart", "transcript.dart", &transcript::dart::emit(transcript())); let dir = scratch().join("api").join("dart"); let generated = api.out.join("dart"); let step = Step { @@ -1602,12 +1603,21 @@ fn api_dart() { }; step.run(Command::new("dart").args(["analyze", "--fatal-infos"]).arg(&generated)); let lib = api.lib.join(PYTHON_LIB); + // The entry beside the script imports the test as a package, as the script does, so + // both name the one library. + let main = scripts.join("main.dart"); + step::write( + &main, + "import 'package:api_test/api.dart' as test;\n\nFuture main(List args) => test.main(args);\n", + ); + let tests = manifest_dir().join("tests"); let exe = dart_compile( "api", &dir, &generated, &lib, - &manifest_dir().join("tests").join("api.dart"), + &main, + &[("api_test", &tests), ("transcript", &scripts)], ); let dart = run(&mut dart_run(&exe, &[])); assert_eq!( @@ -1615,7 +1625,7 @@ fn api_dart() { api.transcript, "the Dart transcript differs from the native one" ); - for case in ["futures", "owned", "closed", "bytes", "bounds"] { + for case in ["checks", "futures", "owned", "closed", "bytes", "bounds"] { run(&mut dart_run(&exe, &[case])); } for (case, message) in [ @@ -1662,7 +1672,7 @@ fn api_dart() { &main, "import 'package:api/api.dart' as api;\n\nvoid main() => api.dropped();\n", ); - let exe = dart_compile("api", &contract, &package, &lib, &main); + let exe = dart_compile("api", &contract, &package, &lib, &main, &[]); let output = dart_run(&exe, &[]).output().unwrap(); failed(&output, "a mismatched contract"); let stderr = String::from_utf8_lossy(&output.stderr); @@ -1675,7 +1685,8 @@ fn api_dart() { /// `main` compiled into a kernel snapshot in `dir`, importing the generated Dart in /// `package` as `package:/.dart`, whose native asset is the shared library /// `lib`: as a package's build hook would bundle it, which `dart compile` has no flag for. -fn dart_compile(name: &str, dir: &Path, package: &Path, lib: &Path, main: &Path) -> PathBuf { +/// Each of `others` is a package of its own, by its name and its directory. +fn dart_compile(name: &str, dir: &Path, package: &Path, lib: &Path, main: &Path, others: &[(&str, &Path)]) -> PathBuf { let sdk = std::fs::canonicalize(which("dart")) .unwrap() .parent() @@ -1683,12 +1694,16 @@ fn dart_compile(name: &str, dir: &Path, package: &Path, lib: &Path, main: &Path) .expect("dart is in the SDK's bin") .to_path_buf(); let config = dir.join("package_config.json"); - let root = url(package); + let packages: Vec = std::iter::once((name, package)) + .chain(others.iter().copied()) + .map(|(name, root)| { + let root = url(root); + format!("{{\"name\": \"{name}\", \"rootUri\": \"{root}/\", \"packageUri\": \"./\"}}") + }) + .collect(); step::write( &config, - format!( - "{{\"configVersion\": 2, \"packages\": [{{\"name\": \"{name}\", \"rootUri\": \"{root}/\", \"packageUri\": \"./\"}}]}}\n" - ), + format!("{{\"configVersion\": 2, \"packages\": [{}]}}\n", packages.join(", ")), ); let os = match std::env::consts::OS { "macos" => "macos", @@ -1709,9 +1724,12 @@ fn dart_compile(name: &str, dir: &Path, package: &Path, lib: &Path, main: &Path) ); let dill = dir.join(format!("{}.dill", main.file_stem().unwrap().to_string_lossy())); // The snapshot names the library by path, so a change to it rebuilds nothing. + let version = sdk.join("version"); + let mut reads: Vec<&Path> = vec![main, package, &config, &assets, &version]; + reads.extend(others.iter().map(|(_, root)| *root)); let step = Step { stamp: &step::stamp(&dill), - reads: &[main, package, &config, &assets, &sdk.join("version")], + reads: &reads, writes: &[&dill], }; step.run( diff --git a/ffi/tests/fixtures/shapes.rs b/ffi/tests/fixtures/shapes.rs index 20be278ef..eb19814ba 100644 --- a/ffi/tests/fixtures/shapes.rs +++ b/ffi/tests/fixtures/shapes.rs @@ -1574,7 +1574,7 @@ fn round_trip(built: &Built, language: &str) { let main = dir.join("main.dart"); step::write(&main, dart(built, calls)); let lib = built.lib.join(shared(&name)); - let dill = super::dart_compile(&name, &dir, &built.out.join("dart"), &lib, &main); + let dill = super::dart_compile(&name, &dir, &built.out.join("dart"), &lib, &main, &[]); run(&mut super::dart_run(&dill, &[])) } _ => unreachable!("no driver for {language}"), diff --git a/ffi/tests/fixtures/transcript/dart.rs b/ffi/tests/fixtures/transcript/dart.rs new file mode 100644 index 000000000..7ad7d3e9f --- /dev/null +++ b/ffi/tests/fixtures/transcript/dart.rs @@ -0,0 +1,1286 @@ +//! The transcript as Dart: a library whose `script()` runs it through the generated Dart, +//! calling `tests/api.dart`'s own functions, which it imports as `package:api_test/api.dart`. + +use std::fmt::Write; + +use super::ir::{Access, Collection, Int, Mutability, Receiver, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; + +const LANGUAGE: &str = "Dart"; + +/// Helpers the script calls, each for a value Dart shapes apart from Rust. +const PRELUDE: &str = r#"// Generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:api/api.dart' as api; +import 'package:api_test/api.dart' as local; + +/// A string as Rust's `Debug` prints it. +String _quoted(String s) { + final out = StringBuffer('"'); + for (final c in s.runes) { + switch (c) { + case 0x22: + out.write(r'\"'); + case 0x5c: + out.write(r'\\'); + case 0x0a: + out.write(r'\n'); + case 0x09: + out.write(r'\t'); + case 0x0d: + out.write(r'\r'); + case 0x00: + out.write(r'\0'); + case < 0x20 || 0x7f: + out.write('\\u{${c.toRadixString(16)}}'); + default: + out.writeCharCode(c); + } + } + out.write('"'); + return out.toString(); +} + +String _list(Iterable items, String Function(T) show) => '[${items.map(show).join(', ')}]'; + +/// An `Option` as Rust's `Debug` prints it. Unbounded, so it takes a `U64`, which is no +/// `Object`. +String _option(T? value, String Function(T) show) => value == null ? 'None' : 'Some(${show(value as T)})'; + +Uint8List _bytes(List bytes) => Uint8List.fromList(bytes); + +/// The `f64` of `bits`. +double _f64(int bits) => (Uint64List(1)..[0] = bits).buffer.asFloat64List()[0]; + +/// Bytes as text, what is not UTF-8 replaced. +String _text(List bytes) => utf8.decode(bytes, allowMalformed: true); + +/// `value`, an object a statement made and only borrows, which Rust drops as the statement +/// ends: `_close` closes it then. +T _tmp(List temps, T value) { + temps.add(value); + return value; +} + +/// Close each of a statement's temporaries, the last made first, as Rust drops them. +void _close(List temps) { + for (final value in temps.reversed) { + (value as dynamic)?.close(); + } +} + +T _some(T? value) => value == null ? throw StateError('unwrap of None') : value as T; + +/// A call's value, or what it threw that `caught` takes as its error. +sealed class _Result {} + +final class _Ok extends _Result { + final T value; + + _Ok(this.value); +} + +final class _Err extends _Result { + final Object error; + + _Err(this.error); +} + +_Result _try(T Function() call, bool Function(Object) caught) { + try { + return _Ok(call()); + } catch (e) { + if (caught(e)) return _Err(e); + rethrow; + } +} + +/// The error of a call that must fail. +E _err(void Function() call) { + try { + call(); + } on E catch (e) { + return e; + } + throw StateError('the call did not fail'); +} + +bool _fails(void Function() call) { + try { + call(); + } on E { + return true; + } + return false; +} + +/// `value`, which Rust's arithmetic left in `lo` through `hi`, or else its overflow panic. +int _int(int value, int lo, int hi) => + value < lo || value > hi ? throw StateError('attempt to overflow') : value; + +/// `value` as an `i64`, or else its overflow panic. +int _i64(BigInt value) => value.isValidInt ? value.toInt() : throw StateError('attempt to overflow'); + +/// `value` as a `u64`, or else its overflow panic. +api.U64 _u64(BigInt value) => + value.isNegative || value.bitLength > 64 ? throw StateError('attempt to overflow') : api.U64.fromBigInt(value); +"#; + +/// The Dart library of `t`'s script. +pub(crate) fn emit(t: &Transcript) -> String { + let mut e = Emitter { + t, + depth: 1, + mutated: Vec::new(), + locals: Vec::new(), + closures: 0, + fresh: 0, + temps: Vec::new(), + }; + mutated(&t.steps, t, &mut e.mutated); + let body = e.steps(&t.steps); + format!("{PRELUDE}\nFuture script() async {{\n{body}}}\n") +} + +/// The locals a call takes `&mut` that are values, not objects: each is an `api.Mut`, +/// whose `value` the script reads. +fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec) { + let mut visit = |expr: &Expr| { + walk(expr, &mut |e| { + if let Kind::Call(id, _, args) = &e.kind { + for (arg, param) in args.iter().zip(&t.function(*id).params) { + if let (Kind::Var(name), Type::Ref(Mutability::Mut, inner)) = (&arg.kind, ¶m.ty) + && !matches!(**inner, Type::Object(_) | Type::Reader) + && !out.contains(name) + { + out.push(name.clone()); + } + } + } + }) + }; + for step in steps { + each_expr(step, &mut visit); + } +} + +/// Each expression a step holds, its arms' and closures' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +struct Emitter<'t> { + t: &'t Transcript, + depth: usize, + /// The locals each an `api.Mut`. + mutated: Vec, + /// Each local bound so far, with its type. + locals: Vec<(String, Type)>, + /// How many closures deep the script is, where it awaits nothing. + closures: usize, + fresh: usize, + /// Each statement's list of its temporaries, innermost last, and whether it holds any. + temps: Vec<(String, bool)>, +} + +/// Dart's reserved words, which no name may be. +const RESERVED: &[&str] = &[ + "assert", "await", "break", "case", "catch", "class", "const", "continue", "default", "do", "else", "enum", + "extends", "false", "final", "finally", "for", "if", "in", "is", "new", "null", "rethrow", "return", "super", + "switch", "this", "throw", "true", "try", "var", "void", "while", "with", "yield", +]; + +/// Dart's built-in and contextual words, which no local may be. +const BUILT_IN: &[&str] = &[ + "abstract", + "as", + "covariant", + "deferred", + "dynamic", + "export", + "extension", + "external", + "factory", + "Function", + "get", + "implements", + "import", + "interface", + "late", + "library", + "mixin", + "operator", + "part", + "required", + "set", + "static", + "typedef", + "base", + "sealed", + "when", + "on", + "show", + "hide", + "async", + "sync", + "of", +]; + +/// What the script itself names, which no local of its may shadow. +const BUILTINS: &[&str] = &[ + "api", + "local", + "print", + "utf8", + "script", + "identical", + "int", + "double", + "bool", + "num", + "List", + "String", + "Object", +]; + +/// A local's name in Dart. +fn ident(name: &str) -> String { + match RESERVED.contains(&name) || BUILT_IN.contains(&name) || BUILTINS.contains(&name) { + true => format!("{name}_"), + false => name.to_string(), + } +} + +/// A Rust identifier in snake case, as the exporter splits it: `TrackProducer` is +/// `track_producer`, and `WARN` is `warn`. +fn snake(name: &str) -> String { + let chars: Vec = name.chars().collect(); + let mut out = String::new(); + for (i, &c) in chars.iter().enumerate() { + if c.is_uppercase() { + let prev = i.checked_sub(1).map(|j| chars[j]); + let next = chars.get(i + 1); + let boundary = match prev { + Some(p) if p.is_lowercase() || p.is_ascii_digit() => true, + Some(p) if p.is_uppercase() => next.is_some_and(|n| n.is_lowercase()), + _ => false, + }; + if boundary && !out.ends_with('_') { + out.push('_'); + } + out.extend(c.to_lowercase()); + } else { + out.push(c); + } + } + out +} + +/// A name in camel case, as Dart names members: `into_label` is `intoLabel`. +fn camel(name: &str) -> String { + if name.starts_with(|c: char| c.is_ascii_digit()) { + return format!("${name}"); + } + let mut out = String::new(); + for (i, word) in snake(name).split('_').filter(|w| !w.is_empty()).enumerate() { + let mut chars = word.chars(); + match (i, chars.next()) { + (0, Some(first)) => out.extend(first.to_lowercase().chain(chars)), + (_, Some(first)) => out.extend(first.to_uppercase().chain(chars)), + _ => {} + } + } + out +} + +/// A member's name: camel case, with `_` past a reserved word or one of `taken`. +fn member(name: &str, taken: &[&str]) -> String { + let name = camel(name); + match RESERVED.contains(&name.as_str()) || taken.contains(&name.as_str()) { + true => format!("{name}_"), + false => name, + } +} + +/// A record's field, as the exporter names it. +fn field(name: &str) -> String { + member(name, &["hashCode", "noSuchMethod", "runtimeType", "toString"]) +} + +/// The Dart of an integer's name, as the runtime's classes end in it: `u64` is `U64`. +fn int_name(int: Int) -> String { + let rust = int.rust(); + let mut chars = rust.chars(); + let first = chars.next().unwrap().to_ascii_uppercase(); + format!("{first}{}", chars.as_str()) +} + +/// Whether an integer crosses as `api.U64`. +fn wide(int: Int) -> bool { + matches!(int, Int::U64 | Int::Usize) +} + +/// The `dart:typed_data` list of a block's element, as the exporter picks one, or `None` +/// for a list of no block. +fn block(ty: &Type) -> Option<&'static str> { + let Type::List(Collection::Vec | Collection::Slice | Collection::Box | Collection::Array(_), inner) = ty else { + return None; + }; + Some(match &**inner { + Type::Int(Int::U8) => "Uint8List", + Type::Int(Int::U16) => "Uint16List", + Type::Int(Int::U32) => "Uint32List", + // A `Uint64List` read as `U64`, which the binding passes as a `List`. + Type::Int(Int::U64) => "", + Type::Int(Int::I8) => "Int8List", + Type::Int(Int::I16) => "Int16List", + Type::Int(Int::I32) => "Int32List", + Type::Int(Int::I64) => "Int64List", + Type::F32 => "Float32List", + Type::F64 => "Float64List", + _ => return None, + }) +} + +/// `ty` past references, boxes, and an `Option`. +fn plain(ty: &Type) -> &Type { + match unref(ty).base() { + Type::Option(inner) => plain(inner), + ty => ty, + } +} + +impl Emitter<'_> { + fn indent(&self) -> String { + " ".repeat(self.depth) + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("_{what}{}", self.fresh) + } + + fn steps(&mut self, steps: &[Step]) -> String { + let mut out = String::new(); + for step in steps { + let (temps, body) = self.scoped(|e| { + let mut out = String::new(); + e.step(step, &mut out); + out + }); + match temps { + Some(temps) => { + self.line(&mut out, &format!("final {temps} = [];")); + out.push_str(&body); + self.line(&mut out, &format!("_close({temps});")); + } + None => out.push_str(&body), + } + } + out + } + + /// What `f` emits in a scope of its own temporaries, and the list holding them, if any. + fn scoped(&mut self, f: impl FnOnce(&mut Self) -> T) -> (Option, T) { + let name = self.fresh("d"); + self.temps.push((name, false)); + let v = f(self); + let (name, used) = self.temps.pop().unwrap(); + (used.then_some(name), v) + } + + /// `v`, the Dart of `e`, kept to close as its statement ends if it is an object only + /// borrowed there that the statement made. + fn temp(&mut self, v: String, e: &Expr) -> String { + fn made(e: &Expr) -> bool { + match &e.kind { + Kind::Call(..) | Kind::Clone(_) | Kind::Default => true, + Kind::Unwrap(inner) => made(inner), + _ => false, + } + } + if !made(e) || !matches!(plain(&e.ty), Type::Object(_)) { + return v; + } + let (temps, used) = self.temps.last_mut().expect("a statement's temporaries"); + *used = true; + format!("_tmp({temps}, {v})") + } + + /// The Dart of `e`, an operand only borrowed. + fn lent(&mut self, e: &Expr) -> String { + let v = self.expr(e); + self.temp(v, e) + } + + fn line(&self, out: &mut String, line: &str) { + let _ = writeln!(out, "{}{line}", self.indent()); + } + + /// A local's place: its `api.Mut`'s value, if it is one. + fn place(&self, name: &str) -> String { + match self.mutated.iter().any(|m| m == name) { + true => format!("{}.value", ident(name)), + false => ident(name), + } + } + + fn step(&mut self, step: &Step, out: &mut String) { + match step { + Step::Let(pat, value) => { + // A value's `&mut self` returns it as the call left it, before what Rust returns. + if let Some((name, call)) = self.mut_receiver(value) { + match unref(&value.ty) { + Type::Unit => { + self.line(out, &format!("{name} = {call};")); + return self.bind(pat, "null", &value.ty, out); + } + ty => { + let tmp = self.fresh("t"); + self.line(out, &format!("final {tmp} = {call};")); + self.line(out, &format!("{name} = {tmp}.$1;")); + let rest = match ty { + Type::Tuple(elements) if elements.len() > 1 => { + let parts: Vec = + (0..elements.len()).map(|i| format!("{tmp}.${}", i + 2)).collect(); + format!("({})", parts.join(", ")) + } + _ => format!("{tmp}.$2"), + }; + return self.bind(pat, &rest, &value.ty, out); + } + } + } + let v = self.expr(value); + match pat { + Pat::Name(name, ty) if self.mutated.contains(name) => { + self.locals.push((name.clone(), ty.clone())); + self.line(out, &format!("final {} = api.Mut({v});", ident(name))); + } + pat => self.bind(pat, &v, &value.ty, out), + } + } + Step::Print(pieces) => { + let v = self.pieces(pieces); + self.line(out, &format!("print({v});")); + } + Step::Do(value) => { + if let Some((name, call)) = self.mut_receiver(value) { + return match unref(&value.ty) { + Type::Unit => self.line(out, &format!("{name} = {call};")), + _ => self.line(out, &format!("{name} = ({call}).$1;")), + }; + } + let v = self.lent(value); + self.line(out, &format!("{v};")); + } + Step::Drop(name) => { + let ty = self.local(name).clone(); + match unref(&ty).base() { + Type::Object(_) => self.line(out, &format!("{}.close();", self.place(name))), + ty => panic!("Dart drops no {ty:?} but by the garbage collector"), + } + } + Step::Match { value, ok, err } => self.matched(value, ok, err, out), + } + } + + fn local(&self, name: &str) -> &Type { + match self.locals.iter().rev().find(|(n, _)| n == name) { + Some((_, ty)) => ty, + None => panic!("no local {name}"), + } + } + + /// A call of a method taking a value's `&mut self` on a local: the local's place, and + /// the call, which Dart returns the value from as the call left it. + fn mut_receiver(&mut self, value: &Expr) -> Option<(String, String)> { + let Kind::Call(id, Some(receiver), args) = &value.kind else { + return None; + }; + let f = self.t.function(*id); + if f.receiver != Some(Receiver::Mut) || !matches!(id.owner, Owner::Record(_)) { + return None; + } + let Kind::Var(name) = &receiver.kind else { + panic!("a value's &mut self method on anything but a local") + }; + let call = self.call(*id, Some(receiver), args); + Some((self.place(name), call)) + } + + /// `pat` bound to `v`, a value of `ty`: a `Bounds`, a class, by its fields. + fn bind(&mut self, pat: &Pat, v: &str, ty: &Type, out: &mut String) { + let mut names = Vec::new(); + super::bound(pat, &mut names); + self.locals.extend(names); + match pat { + Pat::Ignore(_) if v == "null" => {} + Pat::Ignore(_) => self.line(out, &format!("{v};")), + Pat::Tuple(pats) if matches!(unref(ty).base(), Type::Bounds(_)) => { + let tmp = self.fresh("b"); + self.line(out, &format!("final {tmp} = {v};")); + for (pat, end) in pats.iter().zip(["start", "end"]) { + let target = self.pat(pat); + self.line(out, &format!("var {target} = {tmp}.{end};")); + } + } + pat => { + let target = self.pat(pat); + self.line(out, &format!("var {target} = {v};")); + } + } + } + + fn pat(&self, pat: &Pat) -> String { + match pat { + Pat::Name(name, _) => ident(name), + Pat::Ignore(_) => "_".to_string(), + Pat::Tuple(pats) => { + let parts: Vec = pats.iter().map(|p| self.pat(p)).collect(); + match parts.len() { + 1 => format!("({},)", parts[0]), + _ => format!("({})", parts.join(", ")), + } + } + } + } + + /// An arm's steps, in a block of their own. + fn arm(&mut self, arm: &Arm, payload: Option<(&str, &Type)>, out: &mut String) { + self.depth += 1; + if let (Some(pat), Some((v, ty))) = (&arm.pat, payload) { + self.bind(pat, v, ty, out); + } + let body = self.steps(&arm.steps); + out.push_str(&body); + self.depth -= 1; + } + + fn matched(&mut self, value: &Expr, ok: &Arm, err: &Arm, out: &mut String) { + match &value.ty { + Type::Option(inner) => { + let v = self.expr(value); + let tmp = self.fresh("o"); + self.line(out, &format!("final {tmp} = {v};")); + self.line(out, &format!("if ({tmp} != null) {{")); + self.arm(ok, Some((&tmp, inner)), out); + self.line(out, "} else {"); + self.arm(err, None, out); + self.line(out, "}"); + } + Type::Result(ok_ty, err_ty) => { + let caught = self.caught(err_ty); + // Called in a closure, where the script awaits nothing. + self.closures += 1; + let v = self.expr(value); + self.closures -= 1; + let result = self.fresh("r"); + self.line(out, &format!("final {result} = _try(() => {v}, (e) => e is {caught});")); + self.line(out, &format!("switch ({result}) {{")); + let ok_value = self.fresh("v"); + self.line(out, &format!(" case _Ok(value: final {ok_value}):")); + self.depth += 1; + self.arm(ok, Some((&ok_value, ok_ty)), out); + self.depth -= 1; + let e = self.fresh("e"); + self.line(out, &format!(" case _Err(error: final {e}):")); + self.depth += 1; + let error = self.error_of(&format!("({e} as {caught})"), err_ty); + self.arm(err, Some((&error, err_ty)), out); + self.depth -= 1; + self.line(out, "}"); + } + ty => panic!("a match on {ty:?}"), + } + } + + /// The class a call failing with `err` throws: the error itself, if an exported type, + /// or else the exception the binding names for it. + fn caught(&self, err: &Type) -> String { + match unref(err).base() { + ty @ (Type::Record(_) | Type::Enum(_) | Type::Object(_)) => { + format!("api.{}", self.t.type_name(LANGUAGE, ty)) + } + ty => format!( + "api.{}", + self.t.named(LANGUAGE, &format!("error {}", self.error_key(ty))) + ), + } + } + + /// The error Rust returned, of the thrown `v`. + fn error_of(&self, v: &str, err: &Type) -> String { + match unref(err).base() { + Type::Record(_) | Type::Enum(_) | Type::Object(_) => v.to_string(), + _ => format!("{v}.error"), + } + } + + /// The key `api.json` names an error type's exception by. + fn error_key(&self, ty: &Type) -> String { + match unref(ty).base() { + Type::String | Type::Str => "string".to_string(), + Type::Bool => "bool".to_string(), + Type::Int(int) => int.rust().to_string(), + Type::Bounds(int) => format!("bounds_{}", int.rust()), + Type::Range(int) => format!("range_{}", int.rust()), + Type::List(_, item) => format!("vec_{}", self.error_key(item)), + Type::Option(inner) => format!("option_{}", self.error_key(inner)), + ty => panic!("Dart's exception of an error of {ty:?}"), + } + } + + /// The Dart of a format's pieces: a string literal, interpolating each value. + fn pieces(&mut self, pieces: &[Piece]) -> String { + let mut out = String::from("'"); + for piece in pieces { + match piece { + Piece::Text(text) => out.push_str(&escape(text)), + Piece::Value(e, spec) => { + let v = self.lent(e); + let shown = self.show(&v, &e.ty, *spec); + let _ = write!(out, "${{{shown}}}"); + } + } + } + out.push('\''); + out + } + + /// `v`, a value of `ty`, as a `String` the way Rust formats it with `spec`. + fn show(&mut self, v: &str, ty: &Type, spec: Spec) -> String { + let ty = unref(ty).base(); + match spec { + Spec::Hex(0) => return format!("{v}.toRadixString(16)"), + Spec::Hex(width) => return format!("{v}.toRadixString(16).padLeft({width}, '0')"), + Spec::Padded(width) => return format!("{}.padLeft({width}, '0')", self.decimal(v, ty)), + Spec::Debug => return self.debug(v, ty), + Spec::Display => {} + } + match ty { + Type::Bool | Type::String | Type::Str | Type::Char => v.to_string(), + Type::Int(_) | Type::U128 | Type::NonZero(_) => self.decimal(v, ty), + Type::Object(_) | Type::Record(_) | Type::Enum(_) => match self.text_of(ty) { + Some(text) => format!("{v}.{text}()"), + None => format!("{v}.toString()"), + }, + ty => panic!("Display of {ty:?}"), + } + } + + /// An integer's decimal digits: an `api.U64`'s unsigned. + fn decimal(&self, v: &str, ty: &Type) -> String { + match ty { + Type::Int(int) | Type::NonZero(int) if wide(*int) => format!("{v}.toRadixString(10)"), + Type::Int(_) | Type::NonZero(_) | Type::U128 => format!("{v}.toString()"), + ty => panic!("the digits of {ty:?}"), + } + } + + /// The name of a type's `Access::Text` method, which Dart names apart from `toString`. + fn text_of(&self, ty: &Type) -> Option<&str> { + let Type::Object(i) = ty else { return None }; + let o = &self.t.api.objects[*i]; + let index = o.methods.iter().position(|m| m.access == Access::Text)?; + Some(self.t.name( + LANGUAGE, + FnId { + owner: Owner::Object(*i), + index, + }, + )) + } + + /// `v` as Rust's `Debug` prints a value of `ty`. + fn debug(&mut self, v: &str, ty: &Type) -> String { + match unref(ty).base() { + Type::Bool => format!("{v}.toString()"), + ty @ (Type::Int(_) | Type::U128 | Type::NonZero(_)) => self.decimal(v, ty), + Type::String | Type::Str => format!("_quoted({v})"), + Type::Option(inner) => { + let x = self.fresh("x"); + let show = self.debug(&x, inner); + format!("_option({v}, ({x}) => {show})") + } + Type::Vec | Type::Slice | Type::Bytes => format!("_list({v}, (x) => x.toString())"), + Type::Array(_) => format!("_list({v}.toBytes(), (x) => x.toString())"), + Type::List(_, item) => { + let x = self.fresh("x"); + let show = self.debug(&x, item); + format!("_list({v}, ({x}) => {show})") + } + Type::Tuple(elements) => { + let parts: Vec = (0..elements.len()) + .map(|i| format!("${{{}}}", self.debug(&format!("{v}.${}", i + 1), &elements[i]))) + .collect(); + let tail = if parts.len() == 1 { ",)" } else { ")" }; + format!("'({}{tail}'", parts.join(", ")) + } + Type::Bound(int) => { + let class = format!("api.Bound{}", int_name(*int)); + let value = self.decimal("value", &Type::Int(*int)); + format!( + "switch ({v}) {{ {class}Included(:final value) => 'Included(${{{value}}})', {class}Excluded(:final value) => 'Excluded(${{{value}}})', {class}Unbounded() => 'Unbounded' }}" + ) + } + Type::Range(_) => format!("{v}.toString()"), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => format!("{v}.debug()"), + ty => panic!("Debug of {ty:?}"), + } + } + + fn expr(&mut self, e: &Expr) -> String { + self.value(e, &e.ty) + } + + /// The Dart of `e`, passed where `want` is taken. + fn value(&mut self, e: &Expr, want: &Type) -> String { + match &e.kind { + Kind::Unit => "null".to_string(), + Kind::Bool(b) => b.to_string(), + Kind::Int(n) => { + let ty = match plain(&e.ty) { + ty @ (Type::Int(_) | Type::NonZero(_) | Type::U128 | Type::F32 | Type::F64) => ty, + _ => plain(want), + }; + int(*n, ty) + } + Kind::Float(f) if !f.is_finite() || (*f == 0.0 && f.is_sign_negative()) => { + format!("_f64(0x{:x})", f.to_bits()) + } + Kind::Float(f) => format!("{f:?}"), + Kind::Char(c) => string(&c.to_string()), + Kind::Str(s) => match plain(want) { + Type::Path | Type::PathBuf => format!("api.PathBuf({})", string(s)), + _ => string(s), + }, + Kind::Bytes(b) => { + let bytes: Vec = b.iter().map(|b| b.to_string()).collect(); + match plain(want) { + Type::Array(n) => format!("api.ArrayU8x{n}([{}])", bytes.join(", ")), + _ => format!("_bytes([{}])", bytes.join(", ")), + } + } + Kind::Duration(secs, nanos) => { + format!( + "api.RustDuration({}, {nanos})", + int(Num::new((*secs).into()), &Type::Int(Int::U64)) + ) + } + Kind::Socket(std::net::SocketAddr::V4(a)) => { + format!("api.SocketAddrV4({}, {})", ip(&std::net::IpAddr::V4(*a.ip())), a.port()) + } + Kind::Socket(std::net::SocketAddr::V6(a)) => format!( + "api.SocketAddrV6({}, {}, flowinfo: {}, scopeId: {})", + ip(&std::net::IpAddr::V6(*a.ip())), + a.port(), + a.flowinfo(), + a.scope_id() + ), + Kind::Ip(addr) => ip(addr), + Kind::None => "null".to_string(), + Kind::Some(inner) => { + let want = match unref(want).base() { + Type::Option(inner) => (**inner).clone(), + _ => inner.ty.clone(), + }; + self.value(inner, &want) + } + Kind::Tuple(elements) => self.tuple(e, elements, want), + Kind::List(items) => self.list(items, want), + Kind::Record(r, fields) => { + let record = &self.t.api.records[*r]; + assert!( + record.opaque.is_none(), + "Dart makes no opaque record but by its functions" + ); + let name = self.t.type_name(LANGUAGE, &Type::Record(*r)).to_string(); + let tuple = record.tuple; + let fields_of: Vec<(String, Type)> = + record.fields.iter().map(|f| (field(&f.name), f.ty.clone())).collect(); + let args = self.fields(fields, &fields_of, tuple); + format!("api.{name}({args})") + } + Kind::Variant(en, v, fields) => { + let enumeration = &self.t.api.enums[*en]; + let variant = &enumeration.variants[*v]; + let name = self.t.type_name(LANGUAGE, &Type::Enum(*en)).to_string(); + if enumeration.variants.iter().all(|v| v.fields.is_empty()) { + return format!( + "api.{name}.{}", + member(&snake(&variant.name), &["values", "index", "name"]) + ); + } + let key = format!("type {} / variant {}", self.t.rust(&Type::Enum(*en)), variant.name); + let class = self.t.named(LANGUAGE, &key).to_string(); + let tuple = variant.tuple; + let fields_of: Vec<(String, Type)> = + variant.fields.iter().map(|f| (field(&f.name), f.ty.clone())).collect(); + let args = self.fields(fields, &fields_of, tuple); + format!("api.{class}({args})") + } + Kind::Bound(kind, value) => { + let Type::Bound(int) = unref(&e.ty) else { + panic!("a bound of {:?}", e.ty) + }; + let class = format!("api.Bound{}", int_name(*int)); + match (kind, value) { + (BoundKind::Unbounded, _) => format!("{class}Unbounded()"), + (BoundKind::Included, Some(v)) => format!("{class}Included({})", self.value(v, &Type::Int(*int))), + (BoundKind::Excluded, Some(v)) => format!("{class}Excluded({})", self.value(v, &Type::Int(*int))), + _ => unreachable!(), + } + } + Kind::Default => { + let name = self.t.type_name(LANGUAGE, unref(&e.ty).base()).to_string(); + format!("api.{name}.default_()") + } + Kind::Var(name) => match self.mutated.contains(name) { + // Passed `&mut`, the wrapper itself; read, its value. + true if matches!(want, Type::Ref(Mutability::Mut, _)) => ident(name), + _ => self.place(name), + }, + Kind::Const(c) => format!( + "api.{}", + self.t + .named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::"))) + ), + Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args), + Kind::Field(base, i) => { + let b = self.expr(base); + let Type::Record(r) = unref(&base.ty).base() else { + panic!("a field of {:?}", base.ty) + }; + format!("{b}.{}", field(&self.t.api.records[*r].fields[*i].name)) + } + Kind::Element(base, i) => { + let b = self.expr(base); + match unref(&base.ty).base() { + Type::Range(_) => format!("{b}.{}", if *i == 0 { "start" } else { "end" }), + _ => format!("{b}.${}", i + 1), + } + } + Kind::Clone(inner) => { + let v = self.lent(inner); + match unref(&inner.ty).base() { + Type::Object(_) => format!("{v}.clone()"), + ty @ Type::List(..) => match block(ty) { + Some("") | None => format!("List.of({v})"), + Some(list) => format!("{list}.fromList({v})"), + }, + Type::Vec | Type::Slice | Type::Bytes => format!("Uint8List.fromList({v})"), + // Every other value is immutable in Dart, so the value is its clone. + _ => v, + } + } + Kind::Unwrap(inner) => { + let v = self.expr(inner); + match &inner.ty { + Type::Result(..) => v, + _ => format!("_some({v})"), + } + } + Kind::UnwrapErr(inner) => { + let Type::Result(_, err) = &inner.ty else { + panic!("unwrap_err of {:?}", inner.ty) + }; + let caught = self.caught(err); + self.closures += 1; + let v = self.expr(inner); + self.closures -= 1; + self.error_of(&format!("_err<{caught}>(() => {v})"), err) + } + Kind::IsErr(inner) => { + let Type::Result(_, err) = &inner.ty else { + panic!("is_err of {:?}", inner.ty) + }; + let caught = self.caught(err); + self.closures += 1; + let v = self.expr(inner); + self.closures -= 1; + format!("_fails<{caught}>(() => {v})") + } + Kind::IsSome(inner) => format!("({} != null)", self.lent(inner)), + Kind::IsNone(inner) => format!("({} == null)", self.lent(inner)), + Kind::Binary(op, a, b) => self.binary(*op, a, b, &e.ty), + Kind::Closure(params, steps, value) => self.closure(params, steps, value), + Kind::Local(name, args) => { + let args: Vec = args.iter().map(|a| self.expr(a)).collect(); + let name = match name.starts_with(char::is_uppercase) { + true => name.clone(), + false => camel(name), + }; + let call = format!("local.{name}({})", args.join(", ")); + // A hook run as a step may be async: the script awaits it. + match (unref(&e.ty), self.closures) { + (Type::Unit, 0) => format!("await {call}"), + (Type::Unit, _) => panic!("a hook {name} in a closure, which Dart cannot await"), + _ => call, + } + } + Kind::Format(pieces) => self.pieces(pieces), + Kind::Join { items, pat, body, sep } => { + let items = self.expr(items); + let x = self.fresh("x"); + let target = self.pat(pat); + self.closures += 1; + let mut block = String::new(); + let body = self.returned(body, &mut block); + self.closures -= 1; + let block = block.lines().map(str::trim).collect::>().join(" "); + format!( + "{items}.map(({x}) {{ var {target} = {x}; {block} return {body}; }}).join({})", + string(sep) + ) + } + Kind::MapOr { + option, + none, + pat, + some, + } => { + let option = self.expr(option); + let none = self.expr(none); + let x = self.fresh("x"); + let target = self.pat(pat); + self.closures += 1; + let mut block = String::new(); + let some = self.returned(some, &mut block); + self.closures -= 1; + let block = block.lines().map(str::trim).collect::>().join(" "); + format!( + "(switch ({option}) {{ final {x}? => (() {{ var {target} = {x}; {block} return {some}; }})(), null => {none} }})" + ) + } + Kind::Utf8(inner) => format!("_text({})", self.expr(inner)), + Kind::Len(inner) => { + let v = self.expr(inner); + match unref(&inner.ty).base() { + Type::String | Type::Str => format!("api.U64(utf8.encode({v}).length)"), + _ => format!("api.U64({v}.length)"), + } + } + } + } + + /// A record's or a variant's fields as the arguments of its constructor: positional + /// for a tuple's, or else named. + fn fields(&mut self, values: &[Expr], fields: &[(String, Type)], tuple: bool) -> String { + let args: Vec = values + .iter() + .zip(fields) + .map(|(v, (name, ty))| { + let v = self.value(v, ty); + match tuple { + true => v, + false => format!("{name}: {v}"), + } + }) + .collect(); + args.join(", ") + } + + /// `a op b`, with Rust's overflow panic, of `ty`. + fn binary(&mut self, op: Op, a: &Expr, b: &Expr, ty: &Type) -> String { + let operand = unref(&a.ty).base().clone(); + let (a, b) = { + let (va, vb) = (self.value(a, &operand), self.value(b, &operand)); + (self.temp(va, a), self.temp(vb, b)) + }; + let compare = |op: &str| format!("({a} {op} {b})"); + match op { + Op::Eq => compare("=="), + Op::Ne => compare("!="), + Op::Lt => compare("<"), + Op::Gt => compare(">"), + Op::And => compare("&&"), + Op::Add | Op::Sub | Op::Mul | Op::Rem => { + let Type::Int(int) = unref(ty).base() else { + panic!("arithmetic of {ty:?}") + }; + let sym = match op { + Op::Add => "+", + Op::Sub => "-", + Op::Mul => "*", + _ => "%", + }; + match (int, op) { + (int, _) if wide(*int) => { + let big = match op { + Op::Rem => format!("{a}.toBigInt().remainder({b}.toBigInt())"), + _ => format!("{a}.toBigInt() {sym} {b}.toBigInt()"), + }; + format!("_u64({big})") + } + // Rust's `%` truncates, as Dart's `remainder` does, never past either operand. + (_, Op::Rem) => format!("{a}.remainder({b})"), + (Int::I64 | Int::Isize, _) => format!("_i64(BigInt.from({a}) {sym} BigInt.from({b}))"), + (int, _) => { + let (lo, hi) = match int.signed() { + true => (-(1i64 << (int.bits() - 1)), (1i64 << (int.bits() - 1)) - 1), + false => (0, (1i64 << int.bits()) - 1), + }; + format!("_int({a} {sym} {b}, {lo}, {hi})") + } + } + } + } + } + + fn tuple(&mut self, e: &Expr, elements: &[Expr], want: &Type) -> String { + match unref(&e.ty).base() { + Type::Range(int) => { + let item = Type::Int(*int); + let (a, b) = (self.value(&elements[0], &item), self.value(&elements[1], &item)); + format!("api.Range{}({a}, {b})", int_name(*int)) + } + Type::Bounds(int) => { + let bound = Type::Bound(*int); + let (a, b) = (self.value(&elements[0], &bound), self.value(&elements[1], &bound)); + format!("api.Bounds{}({a}, {b})", int_name(*int)) + } + _ => { + let wants: Vec = match unref(want).base() { + Type::Tuple(ts) => ts.clone(), + _ => elements.iter().map(|e| e.ty.clone()).collect(), + }; + let parts: Vec = elements.iter().zip(&wants).map(|(e, t)| self.value(e, t)).collect(); + match parts.len() { + 1 => format!("({},)", parts[0]), + _ => format!("({})", parts.join(", ")), + } + } + } + } + + fn list(&mut self, items: &[Expr], want: &Type) -> String { + let want = unref(want).base(); + let item = match want { + Type::List(_, item) => (**item).clone(), + ty => panic!("a list as {ty:?}"), + }; + let parts: Vec = items.iter().map(|e| self.value(e, &item)).collect(); + match block(want) { + Some(typed @ "") => format!("{typed}[{}]", parts.join(", ")), + Some(typed) => format!("{typed}.fromList([{}])", parts.join(", ")), + None => format!("[{}]", parts.join(", ")), + } + } + + fn closure(&mut self, params: &[Pat], steps: &[Step], value: &Expr) -> String { + let mut names = Vec::new(); + params.iter().for_each(|p| super::bound(p, &mut names)); + self.locals.extend(names); + // Dart's parameters bind no tuples: each binds a fresh name, which the body takes apart. + let mut binds = Vec::new(); + let params: Vec = params + .iter() + .map(|p| match p { + Pat::Tuple(_) => { + let x = self.fresh("p"); + binds.push(format!("var {} = {x};", self.pat(p))); + x + } + p => self.pat(p), + }) + .collect(); + self.closures += 1; + self.depth += 1; + let mut body = String::new(); + for bind in &binds { + self.line(&mut body, bind); + } + body.push_str(&self.steps(steps)); + let returned = match value.kind { + Kind::Unit => None, + _ => Some(self.returned(value, &mut body)), + }; + self.depth -= 1; + self.closures -= 1; + match returned { + Some(v) if body.is_empty() => format!("({}) => {v}", params.join(", ")), + Some(v) => { + self.depth += 1; + self.line(&mut body, &format!("return {v};")); + self.depth -= 1; + format!("({}) {{\n{body}{}}}", params.join(", "), self.indent()) + } + None => format!("({}) {{\n{body}{}}}", params.join(", "), self.indent()), + } + } + + /// The value a closure's body returns, in a scope of its own temporaries, which close + /// before it returns. + fn returned(&mut self, value: &Expr, body: &mut String) -> String { + let (temps, v) = self.scoped(|e| e.expr(value)); + let Some(temps) = temps else { return v }; + let result = self.fresh("v"); + self.line(body, &format!("final {temps} = [];")); + self.line(body, &format!("final {result} = {v};")); + self.line(body, &format!("_close({temps});")); + result + } + + /// A call of `id`: a function of the library, a constructor or a static member of a + /// type, a method, or a field's getter or setter. + fn call(&mut self, id: FnId, receiver: Option<&Expr>, args: &[Expr]) -> String { + let f = self.t.function(id); + assert!(!f.future, "a future of {}, which only a hook awaits", f.path.join("::")); + let name = self.t.name(LANGUAGE, id).to_string(); + let params: Vec = f.params.iter().map(|p| p.ty.clone()).collect(); + let access = f.access; + // A unit crosses as nothing, so Dart takes no parameter of it. + let receives = f.receiver; + let args: Vec = (args.iter().zip(¶ms)) + .filter(|(_, ty)| !matches!(unref(ty), Type::Unit)) + .map(|(a, ty)| { + let v = self.value(a, ty); + match borrows(ty) { + true => self.temp(v, a), + false => v, + } + }) + .collect(); + let args = args.join(", "); + let owner = self + .t + .owner(id) + .map(|ty| format!("api.{}", self.t.type_name(LANGUAGE, &ty))); + let (target, member) = match (receiver, name.split_once(' ')) { + (Some(r), _) => { + let v = self.expr(r); + let v = match receives { + Some(Receiver::Owned) => v, + _ => self.temp(v, r), + }; + (v, name.rsplit(' ').next().unwrap().to_string()) + } + (None, Some(("new", ""))) => return format!("{}({args})", owner.expect("a constructor of a type")), + (None, Some(("new" | "static", member))) => (owner.expect("a static member of a type"), member.to_string()), + (None, None) => (owner.unwrap_or_else(|| "api".to_string()), name.clone()), + (None, Some(_)) => panic!("a Dart name {name}"), + }; + match access { + Access::Field { set: false, .. } | Access::Const => format!("{target}.{member}"), + _ => format!("{target}.{member}({args})"), + } + } +} + +/// Whether a parameter of `ty` only borrows the object passed. +fn borrows(ty: &Type) -> bool { + match ty { + Type::Ref(_, inner) => matches!(plain(inner), Type::Object(_)), + Type::Option(inner) => borrows(inner), + _ => false, + } +} + +/// A Dart integer literal of `n`, a value of `ty`. +fn int(n: Num, ty: &Type) -> String { + match ty { + Type::Int(int) | Type::NonZero(int) if wide(*int) => match n.magnitude <= i64::MAX as u128 && !n.negative { + true => format!("api.U64({})", n.magnitude), + false => format!("api.U64.fromBits(0x{:x})", n.bits()), + }, + Type::U128 => format!("BigInt.parse('{n}')"), + Type::F32 | Type::F64 => format!("{n}.0"), + _ if n.negative && n.magnitude == 1 << 63 => "-0x8000000000000000".to_string(), + _ => n.to_string(), + } +} + +/// An IP address of its octets. +fn ip(addr: &std::net::IpAddr) -> String { + let (class, octets) = match addr { + std::net::IpAddr::V4(v4) => ("Ipv4Addr", v4.octets().to_vec()), + std::net::IpAddr::V6(v6) => ("Ipv6Addr", v6.octets().to_vec()), + }; + let octets: Vec = octets.iter().map(|o| o.to_string()).collect(); + format!("api.{class}.fromOctets([{}])", octets.join(", ")) +} + +/// Text escaped for a single-quoted Dart string. +fn escape(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + match c { + '\'' | '\\' | '$' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + let _ = write!(out, "\\u{{{:x}}}", c as u32); + } + c => out.push(c), + } + } + out +} + +/// A Dart string literal. +fn string(s: &str) -> String { + format!("'{}'", escape(s)) +} diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 79879ef50..804edc176 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -11,6 +11,7 @@ //! as its futures, or prints a value no binding shapes alike, such as `hex`. Anything else //! fails, naming its line. +pub(crate) mod dart; pub(crate) mod ir; mod parse; pub(crate) mod python; From d51bd30092511ff4602163d3d08dad60afd4c820 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 04:46:21 -0800 Subject: [PATCH 07/28] wip: generate the Go transcript Co-Authored-By: Claude Opus 5.5 --- ffi/tests/api.go | 1086 ++++------------- ffi/tests/fixtures.rs | 7 +- ffi/tests/fixtures/transcript/go.rs | 1695 ++++++++++++++++++++++++++ ffi/tests/fixtures/transcript/ir.rs | 24 + ffi/tests/fixtures/transcript/mod.rs | 6 + 5 files changed, 1943 insertions(+), 875 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/go.rs diff --git a/ffi/tests/api.go b/ffi/tests/api.go index d944aa4b6..976081c6e 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -1,9 +1,12 @@ -// The api fixture's Go test: the script fixtures/api/examples/transcript.rs runs natively, -// through the generated Go. tests/fixtures.rs compares the transcripts. +// The api fixture's Go test: tests/fixtures/transcript generates the script +// fixtures/api/examples/transcript.rs runs natively as transcript.go, beside this file, which +// calls the functions here that the transcript names. tests/fixtures.rs compares the +// transcripts. // // With an argument, it instead checks the futures' semantics, what Rust keeps of closures // and reads of readers, what closing and the GC free, what a closed object returns, how -// long returned bytes live, or breaks a contract, which must fail. +// long returned bytes live, what the transcript does not print, or breaks a contract, +// which must fail. package main import ( @@ -26,25 +29,22 @@ import ( "unsafe" "api/api" - "api/dep" "api/rt" "api/serdejson" - "api/std" "api/tls" - "api/tracingcore" "api/url" ) -// printLog keeps even levels. -type printLog struct{} +// Print is the transcript's: it keeps even levels. +type Print struct{} // Close runs once Rust drops the implementation. -func (printLog) Close() error { +func (Print) Close() error { fmt.Println("freed") return nil } -func (printLog) Log(level uint8, line string) bool { +func (Print) Log(level uint8, line string) bool { fmt.Printf("log %d %s\n", level, line) return level%2 == 0 } @@ -58,8 +58,8 @@ func list[T any](items []T, show func(T) string) string { return "[" + strings.Join(shown, ", ") + "]" } -func f64Bits(f float64) string { - return number(math.Float64bits(f)) +func number[T any](n T) string { + return fmt.Sprint(n) } // numbers prints each of n's lists, its floats as their bits, as transcript.rs does. @@ -72,7 +72,7 @@ func numbers(what string, n api.Numbers) { fmt.Printf("%s i32 %s\n", what, list(n.I32s, number)) fmt.Printf("%s i64 %s\n", what, list(n.I64s, number)) fmt.Printf("%s f32 %s\n", what, list(n.F32s, func(f float32) string { return number(math.Float32bits(f)) })) - fmt.Printf("%s f64 %s\n", what, list(n.F64s, f64Bits)) + fmt.Printf("%s f64 %s\n", what, list(f64Bits(n.F64s), number)) if n.Some == nil { fmt.Printf("%s some None\n", what) } else { @@ -80,41 +80,88 @@ func numbers(what string, n api.Numbers) { } } -// socketHex is a socket address as its IP's octets in hex, its port, and, IPv6's alone, its -// flow label and scope, apart by colons. -func socketHex(a rt.SocketAddr) string { - if v4, ok := a.V4(); ok { - return fmt.Sprintf("%x:%d", v4.IP, v4.Port) +// f64Bits is each float's bits. +func f64Bits(floats []float64) []uint64 { + bits := make([]uint64, len(floats)) + for i, f := range floats { + bits[i] = math.Float64bits(f) } - v6, _ := a.V6() - return fmt.Sprintf("%x:%d:%d:%d", v6.IP, v6.Port, v6.FlowInfo, v6.ScopeID) + return bits } -// ipHex is an IP address's octets in hex, so the length shows its family. -func ipHex(ip rt.IpAddr) string { - if v4, ok := ip.V4(); ok { - return fmt.Sprintf("%x", v4) +// hex is bytes, a slice or an array of them, in lowercase hex, two digits each. +func hex(bytes any) string { + if b, ok := bytes.(rt.Bytes); ok { + bytes = b.Copy() } - v6, _ := ip.V6() - return fmt.Sprintf("%x", v6) + return fmt.Sprintf("%x", bytes) } -func quoted(s string) string { - return fmt.Sprintf("%q", s) +// pathHex is a path's bytes in hex. +func pathHex(path string) string { + return fmt.Sprintf("%x", path) } -func number[T any](n T) string { - return fmt.Sprint(n) +// seconds is a duration as its seconds and nine digits of nanoseconds. +func seconds(d rt.Duration) string { + return fmt.Sprintf("%d.%09d", d.Secs(), d.Nanos()) +} + +// millis is a duration in whole milliseconds, as Rust's `as u64` truncates them. +func millis(d rt.Duration) uint64 { + return d.Secs()*1000 + uint64(d.Nanos())/1_000_000 +} + +// code is a char's code point. +func code(c rune) uint32 { + return uint32(c) +} + +// reversed is the list reversed. +func reversed(list []*tls.Codec) []*tls.Codec { + list = slices.Clone(list) + slices.Reverse(list) + return list +} + +// unspelled is a path no Rust string spells: on Unix, bytes that are not UTF-8. +func unspelled() string { + return api.Stray() +} + +// socketHex is a socket address of any family as its IP's octets in hex, its port, and, +// IPv6's alone, its flow label and scope, apart by colons. +func socketHex(addr any) string { + switch a := addr.(type) { + case rt.SocketAddrV4: + return fmt.Sprintf("%x:%d", a.IP, a.Port) + case rt.SocketAddrV6: + return fmt.Sprintf("%x:%d:%d:%d", a.IP, a.Port, a.FlowInfo, a.ScopeID) + case rt.SocketAddr: + if v4, ok := a.V4(); ok { + return socketHex(v4) + } + v6, _ := a.V6() + return socketHex(v6) + } + panic(fmt.Sprintf("no socket address is a %T", addr)) } -func bound(b rt.BoundU64) string { - switch b.Kind { - case rt.BoundIncluded: - return fmt.Sprintf("Included(%d)", b.Value) - case rt.BoundExcluded: - return fmt.Sprintf("Excluded(%d)", b.Value) +// ipHex is an IP address of any family's octets in hex, so the length shows its family. +func ipHex(ip any) string { + switch a := ip.(type) { + case rt.Ipv4Addr: + return fmt.Sprintf("%x", a) + case rt.Ipv6Addr: + return fmt.Sprintf("%x", a) + case rt.IpAddr: + if v4, ok := a.V4(); ok { + return ipHex(v4) + } + v6, _ := a.V6() + return ipHex(v6) } - return "Unbounded" + panic(fmt.Sprintf("no IP address is a %T", ip)) } // escaped is a path's bytes as Rust's escape_ascii prints them. @@ -191,374 +238,27 @@ func (w *watched) Err() error { return w.Context.Err() } -func script() { +// channel is the transcript's: a channel's futures, each a call blocking until Rust's +// future is ready, its pending seen as the call waits on its context. +func channel() { ctx := context.Background() - fmt.Printf("limit %d\n", api.LIMIT) - - p := api.Point{X: 1, Y: 2}.Offset(2, 3) - fmt.Printf("offset %d %d\n", p.X, p.Y) - fmt.Printf("debug %s\n", p.GoString()) - fmt.Printf("eq %t\n", p.Equal(api.Point{X: 3, Y: 5})) - d := api.PointDefault() - fmt.Printf("default %d %d\n", d.X, d.Y) - - c := must(api.NewCounter("c", 5)) - fmt.Printf("get %d\n", must(c.Get())) - fmt.Printf("name %s\n", must(c.Name())) - fmt.Printf("add ok %d\n", must(c.Add(10))) - // An exported error type is returned as itself. - var e api.Error - _, err := c.Add(2000) - check(errors.As(err, &e), "add returns an api.Error") - fmt.Printf("add err %s %s\n", e.Error(), e.GoString()) - _, err = c.Sub(20) - check(errors.As(err, &e), "sub returns an api.Error") - fmt.Printf("sub err %s %s\n", err, e.GoString()) - ok(c.Rename("d")) - fmt.Printf("name %s\n", must(c.Name())) - fmt.Printf("is d %t\n", must(c.Is("d"))) - cp := must(c.Clone()) - must(cp.Add(1)) - fmt.Printf("clone %d original %d\n", must(cp.Get()), must(c.Get())) - cp.Close() - fmt.Printf("debug %s\n", c.GoString()) - label := must(c.IntoLabel(&p)) - fmt.Printf("label %s\n", label.GoString()) - fmt.Printf("note %t %t\n", must(api.HasText(api.Note{Text: ptr("")})), must(api.HasText(api.NoteDefault()))) - - below, above, err := must(api.NewCounter("s", 7)).Split(5) - ok(err) - fmt.Printf("split %s %d %s %d\n", must(below.Name()), must(below.Get()), must(above.Name()), must(above.Get())) - one := must(api.Only(must(api.NewCounter("o", 3)))) - fmt.Printf("only %s %d\n", must(one.Name()), must(one.Get())) - w8, w16, w32, w64 := api.Widths(98305) - fmt.Printf("widths %d %d %d %d\n", w8, w16, w32, w64) - for _, b := range []uint64{2, 0} { - if q, r, err := api.Divide(7, b); err != nil { - fmt.Printf("divide err %s\n", err) - } else { - fmt.Printf("divide %d %d\n", q, r) - } - } - for _, n := range []uint64{98305, 0} { - if s := api.Spread(n); s != nil { - fmt.Printf("spread %d %d %d %d\n", s.V0, s.V1, s.V2, s.V3) - } else { - fmt.Println("spread none") - } - } - for _, needle := range []string{"lo", "x"} { - if found := api.Find(rt.NewBytes([]byte("hello")), rt.NewBytes([]byte(needle))); found != nil { - fmt.Printf("find %d %d\n", found.V0, found.V1) - } else { - fmt.Println("find none") - } - } - rows := api.Rows([]api.Point{{X: 1, Y: 2}, {X: 3, Y: 3}}) - shapes := map[api.Shape]string{api.ShapeCircle: "Circle", api.ShapeSquare: "Square"} - fmt.Printf("rows %s\n", strings.Trim(list(rows, func(r rt.Tuple3[string, api.Shape, api.Point]) string { - return fmt.Sprintf("%s %s %d %d", r.V0, shapes[r.V1], r.V2.X, r.V2.Y) - }), "[]")) - // Each handle in a tuple moves in, as one taken by value does. - board := must(api.NewBoard([]rt.Tuple2[string, *api.Counter]{ - {V0: "low", V1: must(api.NewCounter("l", 1))}, - {V0: "high", V1: must(api.NewCounter("h", 9))}, - })) - fmt.Printf("ranked %s\n", strings.Trim(list(must(board.Ranked()), func(r rt.Tuple2[string, *api.Counter]) string { - return fmt.Sprintf("%s %s %d", r.V0, must(r.V1.Name()), must(r.V1.Get())) - }), "[]")) - best := must(board.Best()) - fmt.Printf("best %s %d\n", must(best.Name()), must(best.Get())) - best.Close() - board.Close() - // A map crosses as its pairs and a set as its items, which Rust collects in order, each - // key once, the last kept. - atlas := must(api.Atlas{ - Points: []rt.Tuple2[string, api.Point]{ - {V0: "b", V1: api.Point{X: 1, Y: 1}}, - {V0: "ab", V1: api.Point{X: 2, Y: 3}}, - {V0: "b", V1: api.Point{X: 4, Y: 4}}, - }, - Ids: []uint32{3, 1, 3}, - }.With("c", api.Point{X: 5, Y: 6})) - atlasPoints := strings.Trim(list(atlas.Points, func(r rt.Tuple2[string, api.Point]) string { - return fmt.Sprintf("%s %d %d", r.V0, r.V1.X, r.V1.Y) - }), "[]") - atlasIds := strings.Trim(fmt.Sprint(atlas.Ids), "[]") - fmt.Printf("atlas %s; ids %s\n", atlasPoints, atlasIds) - // Another crate's error crosses as its message. - for _, text := range []string{"80", "x"} { - if port, err := api.Port(text); err == nil { - fmt.Printf("port %d\n", port) - } else { - fmt.Printf("port err %s\n", err) - } - } - square := api.ShapeSquare - span := api.Span{Bounds: rt.Tuple2[uint32, uint32]{V0: 2, V1: 10}, Named: &rt.Tuple2[string, api.Shape]{V0: "s", V1: square}} - lower, upper, err := api.Halves(span) - ok(err) - fmt.Printf("halves %d %d %d %d %s\n", lower.V0, lower.V1, upper.V0, upper.V1, span.GoString()) - n, text, err := api.Swapped(rt.Tuple2[string, uint32]{V0: "t", V1: 4}) - ok(err) - fmt.Printf("swapped %d %s\n", n, text) - // A tuple of one is its element, so `Option<(Option,)>` nests two pointers. - for _, value := range []**uint32{nil, ptr[*uint32](nil), ptr(ptr[uint32](3))} { - switch doubled := api.Doubled(value); { - case doubled == nil: - fmt.Println("doubled None") - case *doubled == nil: - fmt.Println("doubled Some((None,))") - default: - fmt.Printf("doubled Some((Some(%d),))\n", **doubled) - } - } - fmt.Printf("lent back %s boxed %s\n", list(api.LentBack(rt.NewBytes([]byte{1, 2})).Copy(), number), list(api.BoxedTuple(rt.NewBytes([]byte{3})).Copy(), number)) - // A borrowed string and an owned one share a tuple struct. - check(api.Title(false) == nil, "an informal title is none") - fmt.Printf("title Some((%s,)) None named Some((%s,))\n", quoted(*api.Title(true)), quoted(*must(api.Named("x")))) - - // Each lent counter is a new handle to a clone. - registry := must(api.NewRegistry(must(api.NewCounter("first", 1)))) - fmt.Printf("last %t\n", must(registry.Last()) != nil) - ok(registry.Push(must(api.NewCounter("last", 2)))) - first := must(registry.FirstGet()) - must(first.Add(10)) - fmt.Printf("first %d lent %d\n", must(must(registry.FirstGet()).Get()), must(first.Get())) - last := must(registry.Last()) - must(last.Add(10)) - fmt.Printf("last %d lent %d\n", must(must(registry.Last()).Get()), must(last.Get())) - // A closure lent for the call edits the first counter through a handle. - by := uint64(5) - edited := must(registry.Edit(func(counter *api.Counter) bool { - must(counter.Add(by)) - return must(counter.Edited()) && must(counter.Get()) == 6 - })) - fmt.Printf("edit %t %d\n", edited, must(must(registry.FirstGet()).Get())) - // A setter moves an object in, as assignment does, closing its handle. - ok(registry.FirstSet(must(api.NewCounter("second", 3)))) - fmt.Printf("set first %d %s\n", must(must(registry.FirstGet()).Get()), must(must(registry.FirstGet()).Name())) - fmt.Printf("walk %d\n", api.Walk(3, func(cursor *api.Cursor) uint64 { return must(cursor.At()) * 2 })) - fmt.Printf("each %d\n", api.Each(2, func(at uint32) { fmt.Printf("visit %d\n", at) })) - fmt.Printf("offset %d\n", api.Offset(func() uint32 { return 7 }, 3)) - fmt.Printf("shift %d\n", api.Shift(func() uint32 { return 7 }, 4)) - - name := must(api.NameOwned("a")) - joined := must(name.Join(must(api.NameOwned("b")))) - fmt.Printf("joined %s %s %t\n", must(joined.AsStr()), joined.GoString(), must(joined.Equal(name))) - ok(joined.Rename("c")) - fmt.Printf("renamed %s\n", must(joined.AsStr())) - long := must(api.Longer(joined, must(api.NameOwned("dd")))) - fmt.Printf("longer %s\n", must(long.AsStr())) - fmt.Printf("unnamed [%s]\n", must(api.Unnamed().AsStr())) - lit := must(api.NameBorrowed("lit")) - fmt.Printf("borrowed %s %t %t\n", must(lit.AsStr()), must(lit.Shares(must(api.NameBorrowed("lit")))), must(lit.Shares(must(api.NameBorrowed("other"))))) - - fmt.Printf("total %d\n", api.Total(rt.RangeU64{Start: 2, End: 5})) - fmt.Printf("reach %d\n", api.Reach(2, 5)) - fmt.Print("scaled") - for _, v := range []*rt.U128{ - api.Scaled(rt.U128{Hi: math.MaxUint64, Lo: math.MaxUint64}, 1), - api.Scaled(rt.U128{Hi: 1, Lo: 1}, 1<<63), - api.Scaled(rt.U128{Hi: 1 << 63}, 2), - } { - if v == nil { - fmt.Print(" none") - } else { - fmt.Printf(" %016x%016x", v.Hi, v.Lo) - } - } - fmt.Println() - { - digest := api.NewDigest() - if err := digest.SumSet(must(api.Fingerprint("deadbeef"))); err != nil { - panic(err) - } - _, unparsed := api.Fingerprint("zz") - fmt.Printf("digest %x %x %s\n", must(digest.SumGet()), must(digest.Flipped([4]byte{0xff, 0, 0xff, 0})), unparsed) - digest.Close() - } - batch, batch2 := api.NewBatch(), api.Pair() - accepted, paired := 0, 0 - for v := uint32(1); v <= 5; v++ { - if must(batch.Push(v)) { - accepted++ - } - } - for v := uint32(1); v <= 3; v++ { - if must(batch2.Push(v)) { - paired++ - } - } - emptied := must(api.Drain4(batch)) - fmt.Printf("batch %d %d %d %d %d %d %d\n", must(batch.Capacity()), accepted, emptied, must(api.Drain4(batch)), - must(batch2.Capacity()), paired, must(api.Drain2(batch2))) - fmt.Printf("capacities %d %d\n", must(api.Capacities42(batch, batch2)), must(api.Capacities22(batch2, batch2))) - wide := api.Widen(rt.RangeU64{Start: 2, End: 5}, 1) - fmt.Printf("widen %d %d\n", wide.Start, wide.End) - included := func(n uint64) rt.BoundU64 { return rt.BoundU64{Kind: rt.BoundIncluded, Value: n} } - excluded := func(n uint64) rt.BoundU64 { return rt.BoundU64{Kind: rt.BoundExcluded, Value: n} } - unbounded := rt.BoundU64{Kind: rt.BoundUnbounded} - counts := list([]rt.BoundsU64{ - {Start: included(2), End: excluded(5)}, - {Start: included(2), End: included(5)}, - {Start: included(3), End: unbounded}, - {Start: unbounded, End: unbounded}, - {Start: excluded(2), End: included(4)}, - }, func(b rt.BoundsU64) string { return fmt.Sprint(api.Count(b)) }) - fmt.Printf("count %s\n", strings.ReplaceAll(strings.Trim(counts, "[]"), ",", "")) - fmt.Printf("end %s %s\n", bound(api.End(3)), bound(api.End(0))) - start, end := api.Ends(3) - fmt.Printf("ends %s %s\n", bound(start), bound(end)) - for _, n := range []uint64{2, 5} { - got, err := api.Below(n, 3) - var bounds rt.BoundsU64Error - switch { - case err == nil: - fmt.Printf("below %d\n", got) - case errors.As(err, &bounds): - fmt.Printf("below err %s %s\n", bound(bounds.Value.Start), bound(bounds.Value.End)) - default: - check(false, "below returns its bounds") - } - } - window := api.Window{Range: rt.RangeU64{Start: 2, End: 8}, End: api.End(5)} - fmt.Printf("window %t %t %s\n", window.Contains(4), window.Contains(6), window.GoString()) - - fmt.Println(must(api.Greet("x", api.ShapeSquare))) - fmt.Printf("len %d\n", api.Len(rt.NewBytes([]byte("abc")))) - binary := []byte{0xff, 0, 0x61} - fmt.Printf("hex %s\n", api.Hex(rt.NewBytes(binary))) - fmt.Printf("timed hex %s\n", api.TimedHex(rt.NewBytes(binary))) - fmt.Printf("sample hex %s\n", api.SampleHex(rt.NewBytes(binary))) - fmt.Printf("queued hex %s\n", api.QueuedHex(rt.NewBytes(binary))) - fmt.Printf("tick %s\n", must(api.TickName(api.Label{Name: "tick"}))) - fmt.Printf("rooted %s\n", must(api.RootedName(api.Label{Name: "rooted"}))) - fmt.Printf("stored %s\n", must(api.StoredText("stored"))) - fmt.Printf("layer %s\n", must(api.LayerName(api.Label{Name: "layer"}))) - for _, event := range []api.Event{api.EventMoved{V0: p}, api.EventNamed{Name: "n"}, api.EventDone{}} { - fmt.Println(must(api.Describe(event))) - } - - // A `Copy` value passed by value is copied, so it stays usable. - stamp := api.StampFromMillis(2500) - fmt.Printf("secs %d\n", stamp.Secs()) - fmt.Printf("later %t\n", api.StampFromMillis(3000).Later(stamp)) - fmt.Printf("secs %d\n", stamp.Secs()) - fmt.Printf("whole %s\n", stamp.Whole().GoString()) - message := api.NewMessage(&stamp, rt.NewBytes([]byte("body"))) - fmt.Printf("payload %s\n", must(message.PayloadGet()).Copy()) - fmt.Printf("stamp %s\n", must(message.StampGet()).GoString()) - fmt.Printf("sent %t\n", must(message.Sent())) - // Setters assign in place: the bytes are copied in, and a `Copy` value copied. - reset := api.StampFromMillis(4000) - ok(message.StampSet(&reset)) - ok(message.PayloadSet(rt.NewBytes([]byte("edited")))) - fmt.Printf("payload %s\n", must(message.PayloadGet()).Copy()) - fmt.Printf("stamp %s\n", must(message.StampGet()).GoString()) - fmt.Printf("secs %d\n", reset.Secs()) - ok(message.StampSet(nil)) - fmt.Printf("stamp %t\n", must(message.StampGet()) != nil) - - // A value past a word, copied across: a closure takes and returns one by value. - moment := *api.NewMoment(1500, 1000) - fmt.Printf("moment %d %t\n", moment.Millis(), api.NewMoment(1, 0) == nil) - shifted := api.Shifted(moment, func(m api.Moment) api.Moment { return m.After(500) }) - fmt.Printf("shifted %d %t\n", shifted.Millis(), shifted.Equal(moment.After(500))) - fmt.Printf("wrapped %d %t\n", moment.After(math.MaxUint64).Millis(), moment.Equal(shifted)) - - // A value with padding, or bytes that vary, is a handle, as no table says where padding is. - gap := api.NewGap(7, 3) - sameGap := api.NewGap(7, 3) - fmt.Printf("gap %d %t\n", must(gap.Sum()), must(gap.Equal(sameGap))) - gap.Close() - sameGap.Close() - four := uint32(4) - berth := api.NewBerth(&four) - empty := api.NewBerth(nil) - berthAt := *must(berth.At()) - emptyAt := "Some" - if must(empty.At()) == nil { - emptyAt = "None" - } - fmt.Printf("berth Some(%d) %s\n", berthAt, emptyAt) - berth.Close() - empty.Close() - - // A `Copy` type changed in place is a value, whose change reaches only the copy changed. - score := api.ScoreOf(2) - step := api.ScoreOf(3) - score.Add(step) - score.Add(step) - fmt.Printf("score %d %d %d\n", score.Count(), step.Doubled().Count(), step.Count()) - scoreCopy := score - taken := scoreCopy.Take() - fmt.Printf("taken %d %d %d\n", taken, scoreCopy.Count(), score.Count()) - otherScore := step - before0, before1 := scoreCopy.Absorb(&otherScore) - fmt.Printf("absorbed %d %d %d %d %d\n", before0, before1, scoreCopy.Count(), otherScore.Count(), step.Count()) - hits := api.HitsOf(1, 2) - keptHits := hits - hits.Add(api.HitsOf(10, 20)) - hits.HitsSet(7) - fmt.Printf("hits %d %d %d %d %t\n", hits.HitsGet(), hits.MissesGet(), keptHits.HitsGet(), keptHits.MissesGet(), hits.Equal(keptHits)) - counted := keptHits - countedSame := counted.Eq(keptHits) - fmt.Printf("counted %t %d\n", countedSame, counted.HitsGet()) - extent := api.NewExtent(5, 3) - extentStart := extent - old := extent.Slide(10) - extent.StartSet(extent.StartGet() + 1) - fmt.Printf("extent %d %d %d %d %d\n", old, extent.StartGet(), extent.End(), extentStart.StartGet(), extentStart.End()) - weighted := api.Weighted{Score: step, Weight: 4} - fmt.Printf("weighted %d %d\n", weighted.Total(), weighted.Score.Count()+step.Count()) - // A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. - mark := api.MarkOf(1) - ok(mark.Add(2)) - parcel := api.Parcel{Mark: mark, Payload: rt.NewBytes([]byte("abc"))} - hefted := must(api.NewCounter("w", 1)) - fmt.Printf("heft %d\n", must(api.Heft(rt.Tuple2[*api.Mark, rt.Bytes]{V0: mark, V1: rt.NewBytes([]byte("ab"))}, parcel, rt.Tuple2[*api.Counter, rt.Bytes]{V0: hefted, V1: rt.NewBytes([]byte("abcd"))}))) - hefted.Close() - // A value's `&mut self` beside a checked handle. - noted := api.ScoreOf(2) - notedBy := api.MarkOf(5) - notedBefore := must(noted.Note(notedBy)) - fmt.Printf("noted %d %d\n", notedBefore, noted.Count()) - notedBy.Close() - // Refused over a closed mark, the call writes nothing back. - _, refused := noted.Note(notedBy) - check(refused != nil && noted.Count() == 7, "a refused note leaves the score as it was") - mark.Close() - - // Rust frees the implementation once it drops it, releasing Go's. - fmt.Printf("kept %d\n", api.Emit(printLog{}, rt.NewBytes([]byte{1, 2, 3, 4}))) - logger := api.NewLogger(printLog{}) - fmt.Printf("write %t\n", must(logger.Write("hi"))) - logger.Close() - fmt.Println("dropped") - // Rust calls it on another thread, before the call returns. - threshold := uint8(2) - filtered := api.Filter(rt.NewBytes([]byte{1, 2, 3, 4}), func(level uint8, line string) bool { - fmt.Printf("filter %d %s\n", level, line) - return level > threshold - }) - fmt.Printf("filtered %d\n", filtered) - - channel := api.NewChannel() + c := api.NewChannel() // The receive waits once its future pends, until the send wakes it. watching := watch(ctx) got := make(chan []byte) - go func() { got <- must(channel.Recv(watching)).Copy() }() + go func() { got <- must(c.Recv(watching)).Copy() }() <-watching.waiting fmt.Println("recv pending true") - channel.Send(rt.NewBytes([]byte("hi"))) + c.Send(rt.NewBytes([]byte("hi"))) payload := <-got wakes := 1 fmt.Printf("woken %d\n", wakes) fmt.Printf("recv %s\n", payload) - channel.Send(rt.Bytes{}) - if _, err := channel.RecvNonempty(ctx); err != nil { + c.Send(rt.Bytes{}) + if nonempty, err := c.RecvNonempty(ctx); err != nil { fmt.Printf("nonempty err %s\n", err) + } else { + fmt.Printf("nonempty %d\n", nonempty.Len()) } fmt.Print("fill") for _, v := range append(must(api.Fill4(ctx, api.NewBatch(), 9)), must(api.Fill2(ctx, api.Pair(), 1))...) { @@ -568,36 +268,26 @@ func script() { // The send happens at the call: the future is cancelled before its first poll. cancelled, cancel := context.WithCancel(ctx) cancel() - check(errors.Is(channel.SendLater(cancelled, rt.NewBytes([]byte("eager"))), context.Canceled), "a cancelled call returns its context's error") - fmt.Printf("recv %s\n", must(channel.Recv(ctx)).Copy()) + check(errors.Is(c.SendLater(cancelled, rt.NewBytes([]byte("eager"))), context.Canceled), "a cancelled call returns its context's error") + fmt.Printf("recv %s\n", must(c.Recv(ctx)).Copy()) // The send happens at the call, and the future borrows the channel and the tag. - fmt.Printf("tagged %s\n", must(channel.Tagged(ctx, "tag"))) - fmt.Printf("itemized %d\n", must(channel.Itemized(ctx, &[]uint32{1, 2, 3}))) + fmt.Printf("tagged %s\n", must(c.Tagged(ctx, "tag"))) + fmt.Printf("itemized %d\n", must(c.Itemized(ctx, &[]uint32{1, 2, 3}))) fmt.Printf("byte_len %d\n", must(api.ByteLen(ctx, rt.NewBytes([]byte("abc"))))) - // An eager call whose callback cancels its context while it makes its future is never - // polled: only the eager half logs. - { - inner, cancel := context.WithCancel(ctx) - log := &cancelLog{cancel: cancel} - _, err := api.EmitLater(inner, log, rt.NewBytes([]byte{1, 2})) - check(errors.Is(err, context.Canceled), "an eager call cancelled as it makes its future returns its context's error") - check(log.lines.Load() == 2, "an eager call cancelled as it makes its future is never polled") - } - channel.Send(rt.NewBytes([]byte("sized"))) - sized, size, err := channel.RecvSized(ctx) - check(err == nil, "recv sized") + c.Send(rt.NewBytes([]byte("sized"))) + sized, size := must2(c.RecvSized(ctx)) fmt.Printf("sized %s %d\n", sized.Copy(), size) // The waker moves into Rust, which keeps it until the send wakes it. - channel.Notify(func() { wakes++ }) - channel.Send(rt.NewBytes([]byte("rung"))) + c.Notify(func() { wakes++ }) + c.Send(rt.NewBytes([]byte("rung"))) fmt.Printf("woken %d\n", wakes) // A poll with no async twin is a future. - fmt.Printf("take %s\n", must(channel.PollTake(ctx)).Copy()) - channel.Send(rt.NewBytes([]byte("measured"))) - fmt.Printf("measure %d\n", must(channel.PollMeasure(ctx, 2))) + fmt.Printf("take %s\n", must(c.PollTake(ctx)).Copy()) + c.Send(rt.NewBytes([]byte("measured"))) + fmt.Printf("measure %d\n", must(c.PollMeasure(ctx, 2))) // A context is made of the waker, which Rust keeps until the send wakes it. - channel.Listen(func() { wakes++ }) - channel.Send(rt.NewBytes([]byte("heard"))) + c.Listen(func() { wakes++ }) + c.Send(rt.NewBytes([]byte("heard"))) fmt.Printf("woken %d\n", wakes) // A returned waker wakes the waiter's task through Rust until the GC collects it. waiter := api.NewWaiter(func() { wakes++ }) @@ -605,287 +295,118 @@ func script() { must(waiter.Context())() waiter.Close() fmt.Printf("woken %d\n", wakes) +} - list1 := must(api.NewNode(1, nil)) - ok(list1.Push(2)) - fmt.Printf("node %d\n", must(list1.Sum())) +// must2 is a call's two values, or a panic on its error. +func must2[A, B any](a A, b B, err error) (A, B) { + if err != nil { + panic(err) + } + return a, b +} - tally := api.NewTally() - must(tally.Bump()) - fmt.Printf("tally %d %t\n", must(tally.Bump()), must(tally.Equal(tally))) - fmt.Printf("both %d\n", must(api.BumpBoth(tally, tally))) - fmt.Printf("peek %d\n", must(api.Peek(tally, func(lent *api.Tally) uint32 { return must(lent.Bump()) }))) - - area := must(api.Grow(dep.NewArea(dep.Size{Width: 2, Height: 3}), 1)) - areaSize := must(area.Size()) - fmt.Printf("area %d %d %d\n", areaSize.Width, areaSize.Height, must(area.Pixels())) - - // Generic types, each at the instances it infers, named by their arguments. - pair := api.PairU32{Left: 2, Right: 5} - swapped := pair.Swap() - fmt.Printf("pair %d %d sum %d %s %t\n", swapped.Left, swapped.Right, pair.Sum(), pair.GoString(), pair.Equal(swapped)) - fmt.Printf("even %t %t\n", pair.Even(), api.PairU32{Left: 7, Right: 7}.Even()) - // An instance renamed alone, beside another of `Pair` that keeps its name. - tagged := api.Tag(dep.Size{Width: 1, Height: 2}, 3) - flipped := tagged.Swap() - fmt.Printf("sized %d %d %s\n", flipped.Left, flipped.Right.Width, flipped.GoString()) - beside := api.PairU32{Left: 258, Right: 9}.BesideSize(tagged.Left) - fmt.Printf("beside %d %s\n", beside.Left, beside.GoString()) - // At its default, named as the type itself. - stack := api.NewStack() - for i, n := range []string{"a", "b"} { - ok(stack.Push(must(api.NewCounter(n, uint64(i)+1)))) +// drive is the transcript's: a kept closure, called again at the instant it asks for, then +// once its waiter wakes. +func drive() { + start := *api.NewMoment(0, 1000) + calls := 0 + stopped := must(api.Drive(context.Background(), start, func(now api.Moment, waiter *api.Waiter) (*api.Moment, error) { + calls++ + switch calls { + case 1: + later := now.After(5) + return &later, nil + case 2: + fmt.Printf("drive %d\n", now.Millis()-start.Millis()) + must(waiter.Waker())() + return nil, nil + } + return nil, fmt.Errorf("stopped after %d", calls) + })) + fmt.Printf("drive %s\n", stopped) +} + +// readers is the transcript's: one over bytes, one whose reads fail, and a seek from the +// start past `math.MaxInt64`, which reaches the reader whole, as `Cursor` takes one. +func readers() { + tail(strings.NewReader("hello world")) + tail(brokenReader{}) + if at, err := api.SeekTo(farReader{}, math.MaxUint64); err != nil { + fmt.Printf("sought error %s\n", err) + } else { + fmt.Printf("sought %d\n", at) } - top := must(must(stack.Pop()).Get()) - fmt.Printf("stack %d Some(%d) %t %t\n", must(stack.Depth()), top, must(stack.Pop()) != nil, must(stack.Pop()) == nil) - // Generic functions and methods, at each implementation of the trait bounding them, by - // reference, which leaves Go its handle. - fromPoint := must(api.CounterSeededPoint("p", api.Point{X: -3, Y: 4})) - fromSize := must(api.CounterSeededSize("s", dep.Size{Width: 5, Height: 6})) - fromCounter := must(api.CounterSeededCounter("c", fromPoint)) - fromPolar := must(api.CounterSeededPolarPoint("q", api.PolarPoint{Turns: 1, Distance: 2})) - fmt.Printf("seeded %d %d %d %d past %d seeds %d\n", must(fromPoint.Get()), must(fromSize.Get()), must(fromCounter.Get()), must(fromPolar.Get()), - must(stack.DepthPastPoint(api.Point{X: 1, Y: 2})), api.SeedsPointSize(dep.Size{Width: 2, Height: 3})) - - // A trait implemented for `Point` and `&Point` apart: one instance. - fmt.Printf("weigh %d\n", api.WeighPoint(api.Point{X: -1, Y: 2})) - // A function named as the type it returns, and one named as a type it does not. `area` - // names a type of another crate's package, which leaves its name alone. - polar := api.NewPolarPoint(2) - check(polar != nil, "a point off the origin") - check(api.Span_(1, 4) == 3, "a function named as a type of its package") - fmt.Printf("polar %d %t area %d\n", polar.Distance, api.NewPolarPoint(0) == nil, api.Area(dep.Size{Width: 2, Height: 3})) - // Two types whose paths join alike, the second kept apart where its path splits. - fmt.Printf("wind %d\n", api.Wind(api.PolarTurn{Whole: 2}, api.Polar_Turn{Part: 3})) - // Names that clash in some language, each kept apart there. - clashSpan := api.ClashSpan{Width: 4} - clashStore := api.NewClashStore(7) - clashPair := rt.Tuple2[rt.Tuple2[uint8, uint16], uint32]{V0: rt.Tuple2[uint8, uint16]{V0: 1, V1: 2}, V1: 3} - clashTriple := rt.Tuple3[uint8, uint16, uint32]{V0: 1, V1: 2, V2: 3} - fmt.Printf("clash %s %s %s span %d %s %s store %d %d audio %d %d nested %d\n", - api.ClashTone{Hz: 440}.GoString(), api.ClashTone_{Db: 3}.GoString(), api.Cancelled{Step: 2}.GoString(), - clashSpan.Width_(), clashSpan.ToString(), clashSpan.String(), must(clashStore.Free()), must(clashStore.Close_()), - api.ClashAudioEncoderFinish(), api.ClashAudioEncoderFinish_(), api.ClashNested(&clashPair, &clashTriple)) - clashStore.Close() - // Instances that name each other, and one made only by an impl of it. - crossed := api.Cross(api.LeftRightU8{Value: api.RightU8{Value: 1}}, api.RightLeftU8{Value: api.LeftU8{Value: 2}}) - fmt.Printf("cross %d outer %d\n", crossed, must(api.NewOuterInnerU8(4).Get())) - // A bound that outlives the call takes a value, and an instance only a constant names. - fmt.Printf("kept %d boxed %d\n", api.KeptPoint(api.Point{X: 1, Y: -2}), api.BOXED().Value) - fmt.Printf("keep %d\n", api.KeepPoint(api.Point{X: 1, Y: -2})) - five := api.Point{X: 5, Y: 2} - fmt.Printf("kept or %d %d keeper %d\n", api.KeptOrPoint(&five), api.KeptOrPoint(nil), api.KeeperPoint(five)) - // Inferred instances taking a lent closure and a foreign implementation, and one only - // its impl of a trait names. - sides := api.PairU32{Left: 2, Right: 5} - fmt.Printf("apply %d\n", api.ApplyU32(sides, func(side uint32) uint32 { return side * 3 })) - fmt.Printf("report %d\n", api.ReportU32(sides, printLog{})) - fmt.Printf("wrapped %d\n", api.KeptWrapU32(api.WrapU32{Value: 4})) - fmt.Printf("keeps %d\n", api.Keeps(printLog{}).Value) - - // Its Drop runs when Go closes the handle, not before. - token := api.NewToken(7) - fmt.Printf("token %d dropped %d\n", must(token.IdGet()), api.Dropped()) - token.Close() - fmt.Printf("dropped %d\n", api.Dropped()) - - // A field and the method of its name, each its own member. - retry := api.NewRetry(ptr[uint32](5)) - limit := must(retry.LimitGet()) - isSome := 0 - if limit != nil { - isSome = 1 +} + +// localLater is the transcript's: futures of a value that is not `Send`, each awaited on +// the home that runs it. +func localLater(local *api.Local) { + ctx := context.Background() + fmt.Printf("local later %d\n", must(must(api.LocalOrNewLater(ctx, local)).Bump())) + fmt.Printf("local later fresh %d\n", must(must(api.LocalOrNewLater(ctx, nil)).Bump())) +} + +// checks checks what the transcript does not print, each by an assertion: errors as their +// types, what a refused call leaves, and what only Go's calls can pass. +func checks() { + ctx := context.Background() + // An exported error type is returned as itself. + { + c := must(api.NewCounter("c", 5)) + var e api.Error + _, err := c.Add(2000) + check(errors.As(err, &e) && e.GoString() == "Overflow", "add returns an api.Error") + ok(c.Close()) } - fmt.Printf("retry %d %d %d %d\n", isSome, *limit, must(retry.Limit()), must(retry.Delay())) - // The renamed field's setter, named as its getter. - ok(retry.LimitSet(nil)) - fmt.Printf("retry %d\n", must(retry.Limit())) - fmt.Printf("slot %d\n", must(api.NewSlotU8(200).Value())) - - // Foreign types: a URL parsed from text, socket addresses, OS paths, and slices. - base := must(url.UrlParse("https://example.com/a/b")) - fmt.Printf("url %s host Some(%s)\n", base, quoted(*must(api.Host(base)))) - resolved := must(api.Resolve(must(base.Clone()), "c?d")) - fmt.Printf("resolve %s %t\n", resolved, must(resolved.Equal(base))) - resolved.Close() - var parse rt.StringError - _, err = url.UrlParse("no scheme") - check(errors.As(err, &parse), "parse returns its message") - fmt.Printf("parse err %s\n", parse.Value) - v4 := must(rt.SocketAddrV4Of(netip.MustParseAddrPort("127.0.0.1:8080"))) - v6 := must(rt.SocketAddrV6Of(netip.MustParseAddrPort("[::1%3]:443"))) - fmt.Printf("ports %s\n", list(api.Ports([]rt.SocketAddr{rt.SocketAddrFromV4(v4), rt.SocketAddrFromV6(v6)}), number)) - peer := must(api.Peer{Addr: rt.SocketAddrFromV6(v6), Names: []string{"a", "b"}}.Next("c")) - fmt.Printf("peer %s %s\n", peer.GoString(), list(must(peer.Aliases()), quoted)) - file := must(api.File("dir", "f\\'\"\t")) - fmt.Printf("file %s\n", escaped(file)) - fmt.Printf("parents %s\n", strings.Trim(strings.ReplaceAll(list(must(api.Parents([]string{file, "/"})), func(p *string) string { - if p == nil { - return "none" - } - return escaped(*p) - }), ",", ""), "[]")) + // Refused over a closed mark, the call writes nothing back. + { + noted := api.ScoreOf(2) + by := api.MarkOf(5) + check(must(noted.Note(by)) == 2 && noted.Count() == 7, "a note adds its mark") + ok(by.Close()) + _, refused := noted.Note(by) + check(refused != nil && noted.Count() == 7, "a refused note leaves the score as it was") + } + // An eager call whose callback cancels its context while it makes its future is never + // polled: only the eager half logs. + { + inner, cancel := context.WithCancel(ctx) + log := &cancelLog{cancel: cancel} + _, err := api.EmitLater(inner, log, rt.NewBytes([]byte{1, 2})) + check(errors.Is(err, context.Canceled), "an eager call cancelled as it makes its future returns its context's error") + check(log.lines.Load() == 2, "an eager call cancelled as it makes its future is never polled") + } + // A function named as a type of its package, which `area` names in another's. + check(api.Span_(1, 4) == 3, "a function named as a type of its package") // A path that is no UTF-8 is a Go string all the same. check(api.Stray() == "\xff", "a path that is not UTF-8 crosses as its bytes") var lent string api.VisitStray(func(path string) { lent = path }) check(lent == "\xff", "a path Rust lends that is not UTF-8 crosses as its bytes") // An error Rust returns only boxed is its type. - _, err = api.Refuse("why") + _, err := api.Refuse("why") var refusal *api.Refusal check(errors.As(err, &refusal) && err.Error() == "refused: why", "a boxed error is its type") - words := must(api.Words(" one two three ")) - fmt.Printf("words %d %s\n", len(words), list(words, quoted)) - fmt.Printf("sentence %s %s\n", must(api.Sentence(&words)), must(api.Sentence(nil))) - fmt.Printf("sentence %s|\n", must(api.Sentence(&[]string{}))) - abc := "abc" - fmt.Printf("either %d %d\n", must(api.Either(&abc)), must(api.Either(nil))) - ab := rt.NewBytes([]byte("ab")) - fmt.Printf("prefixed %s %s\n", api.Prefixed(rt.NewBytes([]byte("cd")), &ab).Copy(), api.Prefixed(rt.NewBytes([]byte("cd")), nil).Copy()) - fmt.Printf("coordinates %d %d\n", api.Coordinates(&api.Point{X: 2, Y: 3}), api.Coordinates(nil)) - two, three := must(api.NewCounter("two", 2)), must(api.NewCounter("three", 3)) - fmt.Printf("plus %d %d\n", must(two.Plus(three)), must(two.Plus(nil))) - fmt.Printf("add_to %t %t %d\n", must(two.AddTo(three)), must(two.AddTo(nil)), must(three.Get())) - encoded := rt.NewBytes([]byte("0,")) - api.PutNumber(1, &encoded) - api.PutNumber(23, &encoded) - fmt.Printf("put_number %s\n", encoded.Copy()) - entry := rt.Tuple2[rt.Bytes, uint32]{V0: rt.NewBytes([]byte("ab")), V1: 1} - stamps := api.PushCounted(&entry, 'c') - fmt.Printf("push_counted %d %s %d\n", stamps, entry.V0.Copy(), entry.V1) - digits := rt.NewBytes([]byte("7x9")) - firstDigit := must(api.Digit(&digits)) - _, skipped := api.Digit(&digits) - lastDigit := must(api.Digit(&digits)) - fmt.Printf("digit %d %t %d %d\n", firstDigit, skipped != nil, lastDigit, digits.Len()) - nudged := api.Point{X: 1, Y: 2} - api.Nudge(&nudged, 3) - fmt.Printf("nudge %d %d\n", nudged.X, nudged.Y) - config := must(api.Secure("h3")) - fmt.Printf("secure %s %s\n", must(api.AlpnLent(config)), must(api.Alpn(must(config.Clone())))) - cert := api.Certify(rt.NewBytes([]byte("der"))) - certLen := must(api.CertLen(cert)) - fmt.Printf("cert %d %s %d\n", certLen, must(api.CertDer(cert)).Copy(), must(api.ChainLen([]*tls.Cert{api.Certify(rt.NewBytes([]byte("a"))), api.Certify(rt.NewBytes([]byte("bc")))}))) - // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. - fmt.Printf("resolver %s\n", must(api.Resolved(must(api.Resolver("r1"))))) - codecs := api.NewCodecs() - fmt.Printf("codecs %d\n", must(codecs.Ids())) - listed := must(codecs.ListGet()) - ok(codecs.ListSet([]*tls.Codec{listed[1], listed[0]})) - fmt.Printf("codecs reversed %d\n", must(codecs.Ids())) - codecs.Close() - // A standard library value no type maps, in a handle. - failure := must(api.Failure("boom")) - fmt.Printf("failure %s %s\n", must(api.FailureMessage(failure)), must(api.FailureKind(failure))) - // Iterators, passed as the arrays of their items. - fmt.Printf("sum_all %d\n", api.SumAll([]uint32{1, 2, 3})) - fmt.Printf("weigh_all %d\n", must(api.WeighAllCounter([]*api.Counter{must(api.NewCounter("w", 3))}))) - fmt.Printf("offered_len %d\n", api.OfferedLen([]rt.Bytes{rt.NewBytes([]byte("h3")), rt.NewBytes([]byte("moq-00"))})) - fmt.Printf("join_words %s\n", must(api.JoinWords([]string{"a", "b", "c"}))) - // Bytes that must be `'static`, interned. - for _, label := range []string{"der", "der again"} { - der := api.DerFromSlice(rt.NewBytes([]byte("der"))) - fmt.Printf("%s %s\n", label, must(der.Bytes()).Copy()) - der.Close() - } - session := must(api.Resume("h3", 60)) - fmt.Printf("resume %s %d\n", must(session.Alpn()), must(session.Lifetime()).Seconds) - session.Close() - if _, err := api.Resume("", 60); err != nil { - fmt.Printf("resume err %s\n", err) - } - meters := api.NewMeters() - meter := must(meters.First()) - _ = must(meter.Add(2)) - fmt.Printf("lent %d %d\n", must(meter.Add(3)), must(must(meters.First()).Count())) - ok(meters.Clear()) - fmt.Printf("cleared %d\n", must(must(meters.First()).Count())) - lastMeter := must(meters.LastGet()) - _ = must(lastMeter.Add(4)) - fmt.Printf("field lent %d\n", must(lastMeter.Add(1))) - // An optional field that is not Clone, lent as `Some` of a handle. - fmt.Printf("spare %t\n", must(meters.SpareGet()) != nil) - ok(meters.SpareSet(api.MeterDefault())) - spare := must(meters.SpareGet()) - _ = must(spare.Add(5)) - fmt.Printf("spare lent %d\n", must(spare.Add(1))) - tallies := api.NewTallies() - _ = must(must(tallies.First()).Bump()) - fmt.Printf("tallied %d\n", must(must(tallies.First()).Bump())) - // A draft borrowing its ledger exclusively until it closes, through which its sheet's - // members are reached by Deref and DerefMut: the ledger refuses any other use meanwhile. - ledger := api.NewLedger() - draft := must(ledger.Edit()) - check(draft.TitleSet("minutes") == nil, "a draft's title sets") - check(draft.Write("first") == nil, "a draft writes") - fmt.Printf("draft %s %d %s %t\n", must(draft.TitleGet()), must(draft.Lines()), must(draft.Describe()), must(draft.Edited())) - _, exclusive := ledger.Published() - check( - errors.Is(exclusive, rt.ErrBorrowed) && exclusive.Error() == "api_Ledger_published: a handle is borrowed exclusively", - fmt.Sprintf("a lent ledger refuses a read: %v", exclusive), - ) - fmt.Printf("committed %d\n", must(draft.Commit())) - fmt.Printf("ledger %s %d\n", must(ledger.Title()), must(ledger.Published())) - draft = must(ledger.Edit()) - fmt.Printf("read %d %t\n", must(draft.Lines()), must(draft.Edited())) - check(draft.Close() == nil, "a draft closes") - draft = must(ledger.Edit()) - check(draft.Write("second") == nil, "a draft writes") - check(draft.Close() == nil, "a draft closes") - fmt.Printf("dropped %d\n", must(ledger.Published())) - receipt := must(ledger.Receipt()) - fmt.Printf("receipt %d\n", must(receipt.Count())) - check(receipt.Close() == nil, "a receipt closes") - padSmall, padWide, layered := api.PadU8Small(), api.PadU16Wide(), api.NewLayered() - marker := must(api.NewMarker("m", 3, 5)) - check(marker.YSet(7) == nil, "a marker's point sets") - fmt.Printf("forwarded %d %d %d %d [%s] [%s]\n", must(padWide.Title()), must(layered.Lines()), must(marker.XGet()), must(marker.YGet()), must(padSmall.Describe()), must(padWide.Describe())) - for _, closer := range []interface{ Close() error }{padSmall, padWide, layered, marker} { - check(closer.Close() == nil, "a forwarding handle closes") - } - check(ledger.Seal() == nil, "a ledger seals") - _, sealed := ledger.Edit() - fmt.Printf("sealed %s\n", sealed) - check(ledger.Close() == nil, "a ledger closes") - fmt.Printf("chunks %s\n", list(api.Chunks(rt.NewBytes([]byte("abcde")), 2), func(b rt.Bytes) string { return list(b.Copy(), number) })) - counters := must(api.Counters([]string{"x", "y"})) - fmt.Printf("counters %s\n", strings.Trim(list(counters, func(c *api.Counter) string { - return fmt.Sprintf("%s %d", must(c.Name()), must(c.Get())) - }), "[]")) - // Each counter moves in, so Go closes it. - fmt.Printf("worth %d %d\n", must(api.Worth(&[]*api.Counter{counters[0]}, []*api.Counter{counters[1]})), must(api.Worth(nil, nil))) - held := must(api.NewCounter("h", 4)) - fmt.Print("held") - for _, n := range []*uint64{must(api.HeldCount(&held)), must(api.HeldCount(nil))} { - if n == nil { - fmt.Print(" None") - } else { - fmt.Printf(" Some(%d)", *n) - } - } - fmt.Println() - b := "b" - unnamed := "None" - if s := must(api.BoxedName(nil)); s != nil { - unnamed = *s - } - fmt.Printf("boxed Some(%q) %s %t\n", *must(api.BoxedName(must(api.BoxedCounter(&b)))), unnamed, must(api.BoxedCounter(nil)) == nil) - fmt.Printf("less %d\n", api.Less(5, 2)) - fmt.Printf("sums %s\n", list(api.Sums([][]uint32{{1, 2}, {}, {3}}), number)) - var leastSets []string - for _, set := range api.Least([][]uint32{{3, 1}, {}, {2}}) { - leastSets = append(leastSets, list(set, number)) + // Another crate's error crosses as its message. + var parse rt.StringError + _, err = url.UrlParse("no scheme") + check(errors.As(err, &parse) && parse.Value == "relative URL without a base", "a URL's parse returns its message") + _, err = serdejson.JsonParse(`{"a":`) + check(errors.As(err, &parse), "a JSON parse returns its message") + // A draft borrows its ledger exclusively until it closes: the ledger refuses any other + // use meanwhile. + { + ledger := api.NewLedger() + draft := must(ledger.Edit()) + _, exclusive := ledger.Published() + check( + errors.Is(exclusive, rt.ErrBorrowed) && exclusive.Error() == "api_Ledger_published: a handle is borrowed exclusively", + fmt.Sprintf("a lent ledger refuses a read: %v", exclusive), + ) + check(draft.Close() == nil, "a draft closes") + check(must(ledger.Published()) == 0, "a closed draft frees its ledger") + check(ledger.Close() == nil, "a ledger closes") } - fmt.Printf("least %s\n", strings.Join(leastSets, " ")) - numbers("edges", api.NumbersEdges()) - numbers("reversed", api.NumbersEdges().Reversed()) - floatEdges := api.NumbersEdges() - nan := api.NewMeasure(math.NaN(), false) - fmt.Printf("float equal %t %t %t %t %t\n", floatEdges.Equal(floatEdges), floatEdges.Equal(api.NumbersEdges()), api.NumbersZero(true).Equal(api.NumbersZero(false)), nan.Equal(nan), api.NewMeasure(math.Copysign(0, -1), true).Equal(api.NewMeasure(0, false))) - fmt.Printf("sum u32 %d %d\n", api.SumU32(nil), api.SumU32([]uint32{math.MaxUint32, math.MaxUint32, 2})) - fmt.Printf("doubled i64 %s\n", list(api.DoubledI64([]int64{math.MinInt64, -1, 0, math.MaxInt64}), number)) - floats := api.BoxedFloats([]float64{math.Copysign(0, -1), math.Float64frombits(0x7ff8_0000_0000_0001)}) - fmt.Printf("boxed floats %s\n", list(floats, f64Bits)) // A block lends a sub-slice in place, and Rust's `None` and empty `Some` stay apart. framed := []uint32{9, 1, 2, 9} check(api.SumU32(framed[1:3]) == 3, "a sub-slice lends only its own items") @@ -896,154 +417,10 @@ func script() { check(edges.Reversed().Some != nil && len(*edges.Reversed().Some) == 0, "an empty block in an option is Some") edges.Some = &[]int32{1, 2} check(list(*edges.Reversed().Some, number) == "[2, 1]", "a block in an option crosses whole") - sum := api.Summed([]api.Point{{X: 1, Y: 2}, {X: -4, Y: 6}}) - none := api.Summed(nil) - fmt.Printf("summed %d %d %d %d\n", sum.X, sum.Y, none.X, none.Y) - fmt.Printf("longest %d %d\n", must(api.Longest([]string{"a", "abc"})), must(api.Longest(nil))) - noFirst := "None" - if must(api.FirstOf(nil)) != nil { - noFirst = "Some" - } - fmt.Printf("first of Some(%s) %s\n", quoted(*must(api.FirstOf([]string{"a", "b"}))), noFirst) - limits := api.ByteLimits(rt.NewBytes([]byte("a")), rt.NewBytes([]byte("bc"))) - breadth := api.Breadth(api.LimitsDuration{Low: must(rt.DurationOf(5 * time.Millisecond)), High: must(rt.NewDuration(2, 0))}) - fmt.Printf("limits %s %s breadth %d\n", limits.Low.Copy(), limits.High.Copy(), must(breadth.Std()).Milliseconds()) - parts := []rt.Bytes{rt.NewBytes([]byte("ab")), rt.NewBytes(nil), rt.NewBytes([]byte("c"))} - fmt.Printf("joined %s %d read %d\n", api.Joined(parts).Copy(), len(api.Joined(nil).Copy()), api.ReadLen(rt.NewBytes([]byte("hello")))) - doc := must(serdejson.JsonParse(`{"b": [1, 2.5, null], "a": "é"}`)) - fmt.Printf("json %s\n", must(api.Encode(doc))) - fmt.Printf("timed text %s\n", must(api.TimedText(doc))) - tagged2 := must(api.Tagged(doc, "t")) - fmt.Printf("tagged %s\n", must(tagged2.ToText())) - tagged2.Close() - // A JSON object's entries cross as pairs of a key and its document, each moved in. - jsonEntries := must(api.Entries([]rt.Tuple2[string, *serdejson.Json]{ - {V0: "b", V1: must(serdejson.JsonParse(`[1]`))}, - {V0: "a", V1: must(serdejson.JsonParse(`2`))}, - }, "t")) - fmt.Printf("entries %s\n", strings.Trim(list(jsonEntries, func(r rt.Tuple2[string, *serdejson.Json]) string { - return fmt.Sprintf("%s %s", r.V0, must(r.V1.ToText())) - }), "[]")) - for _, entry := range jsonEntries { - entry.V1.Close() - } - _, err = serdejson.JsonParse(`{"a":`) - check(errors.As(err, &parse), "parse returns its message") - fmt.Printf("json parse err %s\n", err) - site := must(api.NewSite(base)) - fmt.Printf("site %s %s\n", must(site.HomeGet()), must(site.HomeGet())) - - // Slices, passed in and returned as clones, and the socket address of each family. - fmt.Printf("shapes %s greetings %s\n", list(api.ShapeALL(), func(s api.Shape) string { return shapes[s] }), list(api.GREETINGS(), quoted)) - fmt.Printf("both %s primes %s\n", list(api.ShapeBOTH(), func(s api.Shape) string { return shapes[s] }), list(api.PRIMES(), func(n uint32) string { return fmt.Sprint(n) })) - trail := must(api.NewTrail([]api.Point{{X: 1, Y: 2}, {X: 3, Y: 4}}, []string{"a", "b"})) - point := func(p api.Point) string { return p.GoString() } - labeled := func(l api.Label) string { return l.GoString() } - fmt.Printf("trail %s %s\n", list(must(trail.Points()), point), list(must(trail.Labels()), labeled)) - // Returned iterators, each collected at the call: drained labels are gone after. - fmt.Printf("iterated %s %s %s\n", list(must(trail.Iter()), point), list(must(trail.Names()), quoted), list(must(trail.Bytes()).Copy(), number)) - fmt.Printf("drained %s then %s\n", list(must(trail.Drain()), labeled), list(must(trail.Labels()), labeled)) - // A filter, collected at the call. - fmt.Printf("beyond %s\n", strings.Trim(list(must(trail.Beyond(1)), func(p api.Point) string { - return fmt.Sprintf("%d %d", p.X, p.Y) - }), "[]")) - trail.Close() - fmt.Printf("numbered %s\n", strings.Trim(list(must(api.Numbered([]string{"p", "q"})), func(c *api.Counter) string { - return fmt.Sprintf("%s %d", must(c.Name()), must(c.Get())) - }), "[]")) - next4, next6 := api.Nexts(v4, v6) - fmt.Printf("nexts %s %d %d %d\n", next4.IP.Netip(), next4.Port, next6.Port, next6.ScopeID) - nextIp4, nextIp6 := api.NextIps(rt.Ipv4Addr{10, 0, 0, 255}, must(rt.Ipv6AddrOf(netip.MustParseAddr("::ffff")))) - mapped := api.Flip(rt.IpAddrFromV4(rt.Ipv4Addr{127, 0, 0, 1})) - fmt.Printf("ips %x %x %s %s %s\n", nextIp4, nextIp6, ipHex(mapped), ipHex(api.Flip(mapped)), ipHex(api.Flip(must(rt.IpAddrOf(netip.IPv6Loopback()))))) - - // Lossless round trips: each type's edge values, passed through Rust and back. - fmt.Print("lossless duration") - for _, d := range []rt.Duration{ - {}, - must(rt.NewDuration(0, 1)), - must(rt.NewDuration(9_223_372_036, 854_775_808)), - must(rt.NewDuration(math.MaxUint64, 999_999_999)), - } { - d = api.SameDuration(d) - fmt.Printf(" %d.%09d", d.Secs(), d.Nanos()) - } - fmt.Println() - fmt.Printf("lossless u64 %d %d %d\n", api.SameU64(0), api.SameU64(1<<63), api.SameU64(math.MaxUint64)) - fmt.Printf("lossless usize %d %d\n", api.SameUsize(0), api.SameUsize(math.MaxUint)) - fmt.Printf("lossless isize %d %d\n", api.SameIsize(math.MinInt), api.SameIsize(math.MaxInt)) - fmt.Print("lossless u128") - for _, v := range []rt.U128{{}, {Hi: 1}, {Hi: math.MaxUint64, Lo: math.MaxUint64}} { - v = api.SameU128(v) - fmt.Printf(" %016x%016x", v.Hi, v.Lo) - } - fmt.Println() - fmt.Print("lossless char") - for _, c := range []rune{0, 0xd7ff, 0xe000, unicode.MaxRune} { - fmt.Printf(" %x", must(api.SameChar(c))) - } - fmt.Println() - fmt.Printf("lossless path %x %x\n", must(api.SamePath("a/é")), must(api.SamePath(api.Stray()))) - sameV4 := api.SameSocketAddrV4(rt.SocketAddrV4{IP: rt.Ipv4Addr{255, 255, 255, 255}, Port: math.MaxUint16}) - sameV6 := api.SameSocketAddrV6(rt.SocketAddrV6{ - IP: rt.Ipv6Addr{0, 1, 15: 2}, - Port: 3, - FlowInfo: math.MaxUint32, - ScopeID: math.MaxUint32, - }) - fmt.Printf("lossless socket %s %s %s %s\n", socketHex(rt.SocketAddrFromV4(sameV4)), socketHex(rt.SocketAddrFromV6(sameV6)), - socketHex(api.SameSocketAddr(rt.SocketAddrFromV4(sameV4))), socketHex(api.SameSocketAddr(rt.SocketAddrFromV6(sameV6)))) - // A key hashes by Rust's Hash: equal keys alike, and these two apart. - keyA, keyB := must(api.NewKey("a")), must(api.NewKey("b")) - fmt.Printf("key %t %t\n", must(keyA.HashOf()) == must(must(api.NewKey("a")).HashOf()), must(keyA.HashOf()) == must(keyB.HashOf())) - fmt.Printf("lossless ip %s %s\n", ipHex(api.SameIpAddr(rt.IpAddrFromV4(rt.Ipv4Addr{255, 255, 255, 255}))), - ipHex(api.SameIpAddr(rt.IpAddrFromV6(rt.Ipv6Addr{0xff, 0xff, 15: 1})))) - checked() - - // serde_json's map iterator, collected as pairs of a key and its document. - sections := must(api.Sections([]rt.Tuple2[string, *serdejson.Json]{ - {V0: "b", V1: must(serdejson.JsonParse(`[1]`))}, - {V0: "a", V1: must(serdejson.JsonParse(`2`))}, - })) - // Joined by hand: trimming brackets would eat the last document's own. - var sectionTexts []string - for _, section := range sections { - sectionTexts = append(sectionTexts, fmt.Sprintf("%s %s", section.V0, must(section.V1.ToText()))) - section.V1.Close() - } - fmt.Printf("sections %s\n", strings.Join(sectionTexts, ", ")) - // An instant only Rust makes, a handle, as its padding is wherever rustc puts it, which - // each call copies out of, and compares. - var began *std.Instant = api.Now() - ended := must(api.Later(began, must(rt.NewDuration(1, 500_000_000)))) - same := must(api.Later(began, rt.Duration{})) - fmt.Printf("instants %d %d %t %t\n", must(must(api.Since(ended, began)).Std()).Milliseconds(), must(must(api.Since(began, ended)).Std()).Milliseconds(), - must(began.Equal(same)), must(began.Equal(ended))) - fmt.Printf("has_instant %t %t\n", must(api.HasInstant(began)), must(api.HasInstant(nil))) - began.Close() - ended.Close() - same.Close() - // tracing's level, and its filter as an optional level whose nil is `OFF`. - verbosity := api.NewVerbosity(tracingcore.LevelWarn) - fmt.Printf("verbosity %s %s\n", api.Spell(must(verbosity.Filter())), api.Spell(api.Louder(must(verbosity.Filter())))) - ok(verbosity.LevelSet(tracingcore.LevelTrace)) - fmt.Printf("verbosity %t %s %s %s\n", must(verbosity.LevelGet()) == tracingcore.LevelTrace, api.Spell(must(verbosity.Filter())), - api.Spell(api.Louder(must(verbosity.Filter()))), api.Spell(api.Louder(nil))) - verbosity.Close() - - fmt.Printf("made %s\n", api.Made(3, func(n uint32) string { return fmt.Sprintf("%d times", n) })) - // A closure taking and returning `Copy` values copies them, never running their `Clone`. - nine, seven := api.NewTicket(9), api.NewTicket(7) - renewed := api.Reissue(seven, func(t api.Ticket) api.Ticket { return api.NewTicket(t.Number() + 1) }) - copied := api.Reissue(seven, func(api.Ticket) api.Ticket { return nine }) - fmt.Printf("reissued %d %d, cloned %d\n", renewed.Number(), copied.Number(), api.TicketClones()) - // A record's traits borrow the checked handle it holds. - nines := api.MarkOf(9) - front, back := must(api.NewSeat(nines, 1)), must(api.NewSeat(nines, 2)) - fmt.Printf("seat %s %t %t\n", front.GoString(), must(front.Equal(front)), must(front.Equal(back))) // The packages serve wasm32 too: the traits of a type only wasm32 has fail on the host's // library as its functions do. { + nines := api.MarkOf(9) _, err := api.PageDefault() check(errors.Is(err, errors.ErrUnsupported), "a Default off the target is unsupported") _, err = api.Page{Size: 1}.Equal(api.Page{Size: 1}) @@ -1055,54 +432,13 @@ func script() { booth.GoString() == "api_Booth_debug: it is not on this library's target", "a GoString off the target reads as its error", ) + check(nines.Close() == nil, "a mark closes") } - check(nines.Close() == nil, "a mark closes") // A kept closure, called on another thread after the call that took it returned. spawned := must(api.NewSpawned(func() uint32 { return 7 })) check(must(spawned.Join()) == 7, "a kept closure runs on another thread") - // A kept closure: called again at the instant it asks for, then once its waiter wakes. - driven := *api.NewMoment(0, 1000) - calls := 0 - stopped := must(api.Drive(context.Background(), driven, func(now api.Moment, waiter *api.Waiter) (*api.Moment, error) { - calls++ - switch calls { - case 1: - later := now.After(5) - return &later, nil - case 2: - fmt.Printf("drive %d\n", now.Millis()-driven.Millis()) - must(waiter.Waker())() - return nil, nil - } - return nil, fmt.Errorf("stopped after %d", calls) - })) - fmt.Printf("drive %s\n", stopped) - tail(strings.NewReader("hello world")) - tail(brokenReader{}) - // A seek from the start reaches the reader whole, past `math.MaxInt64`, as `Cursor` takes one. - if at, err := api.SeekTo(farReader{}, math.MaxUint64); err != nil { - fmt.Printf("sought error %s\n", err) - } else { - fmt.Printf("sought %d\n", at) - } - fmt.Printf("non zeros %s\n", must(api.DescribeNonZeros(api.NewNonZeros()))) - hopFirst, hopLast := uint64(1), uint64(math.MaxUint64) - for _, hop := range []*uint64{nil, &hopFirst, &hopLast} { - if next := must(api.NextHop(hop)); next != nil { - fmt.Printf("hop Some(%d)\n", *next) - } else { - fmt.Println("hop None") - } - } - fmt.Printf("farther hop %d\n", must(api.FartherHop(api.PairNonZeroU16{Left: 3, Right: math.MaxUint16}))) - local := api.NewLocal() - shared := must(api.LocalOrNew(local)) - bumped := must(local.Bump()) - fmt.Printf("local %d %d\n", bumped, must(shared.Bump())) - fmt.Printf("local fresh %d\n", must(must(api.LocalOrNew(nil)).Bump())) - fmt.Printf("local either %d\n", must(api.BumpEither(nil, shared))) - fmt.Printf("local later %d\n", must(must(api.LocalOrNewLater(ctx, local)).Bump())) - fmt.Printf("local later fresh %d\n", must(must(api.LocalOrNewLater(ctx, nil)).Bump())) + checked() + fmt.Println("checks ok") } // farReader is a reader whose reads fail, which seeks anywhere from its start, as Rust's @@ -2094,6 +1430,8 @@ func main() { bytes() case os.Args[1] == "closures": closures() + case os.Args[1] == "checks": + checks() default: broken(os.Args[1]) } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 9b5eadc00..6e97eb3ce 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -355,6 +355,8 @@ fn api_go_race() { &module, &std::fs::read_to_string(manifest_dir().join("tests").join("api.go")).unwrap(), ); + // The transcript's script, generated beside it in its package. + step::write(&module.join("transcript.go"), transcript::go::emit(transcript())); let exe = dir.join(format!("api-test{EXE_SUFFIX}")); run(go(&module, api, &["build", "-race", "-o"]).arg(&exe)); // Every report fails the run. @@ -365,7 +367,7 @@ fn api_go_race() { api.transcript, "the Go transcript under the race detector differs from the native one" ); - for case in ["futures", "owned", "closed", "bytes", "closures"] { + for case in ["futures", "owned", "closed", "bytes", "closures", "checks"] { run(Command::new(&exe).arg(case).envs(env)); } } @@ -1811,6 +1813,8 @@ fn api_go() { &module, &std::fs::read_to_string(manifest_dir().join("tests").join("api.go")).unwrap(), ); + // The transcript's script, generated beside it in its package. + step::write(&module.join("transcript.go"), transcript::go::emit(transcript())); let export = module.join("export"); for (name, root) in [("vet-export", &export), ("vet", &module)] { let step = Step { @@ -1833,6 +1837,7 @@ fn api_go() { run(Command::new(&exe).arg("closed")); run(Command::new(&exe).arg("bytes")); run(Command::new(&exe).arg("closures")); + run(Command::new(&exe).arg("checks")); for (case, message) in [ ( "lent moved", diff --git a/ffi/tests/fixtures/transcript/go.rs b/ffi/tests/fixtures/transcript/go.rs new file mode 100644 index 000000000..9ad69a84d --- /dev/null +++ b/ffi/tests/fixtures/transcript/go.rs @@ -0,0 +1,1695 @@ +//! The transcript as Go: `transcript.go`, a file of `tests/api.go`'s package `main`, whose +//! `script()` runs it through the generated Go, calling `api.go`'s own functions. +//! +//! Each call is bound to a local before the statement that reads it, so the calls run in +//! Rust's order whatever Go's evaluation order, and an error Rust's call cannot return +//! panics there. A handle a statement makes and only lends, as a receiver or a reference, +//! closes at the statement's end, where Rust drops the temporary. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write; + +use super::ir::{Access, Family, Int, Mutability, Receiver, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Op, Pat, Piece, Spec, Step, Transcript, unref}; + +const LANGUAGE: &str = "Go"; + +/// The module path the export's Go packages are under, as `tests/fixtures.rs` lays it out. +const MODULE: &str = "api"; + +/// Helpers the script calls, each for a value Go shapes apart from Rust, or a check Rust +/// makes that Go does not. +const PRELUDE: &str = r#" +// must_ is v, or a panic on err. +func must_[T any](v T, err error) T { + if err != nil { + panic(err) + } + return v +} + +// done_ panics on err. +func done_(err error) { + if err != nil { + panic(err) + } +} + +// ptr_ is a pointer to a copy of v, as an `Option` holds `Some(v)`. +func ptr_[T any](v T) *T { + return &v +} + +// some_ is what v points to, as `unwrap` of an `Option`. +func some_[T any](v *T) T { + if v == nil { + panic("called `Option::unwrap()` on a `None` value") + } + return *v +} + +// present_ is the handle v, as `unwrap` of an `Option` of one. +func present_[T any](v *T) *T { + if v == nil { + panic("called `Option::unwrap()` on a `None` value") + } + return v +} + +// option_ is v as Rust's Debug prints an `Option`, its value by show. +func option_[T any](v *T, show func(T) string) string { + if v == nil { + return "None" + } + return "Some(" + show(*v) + ")" +} + +// optionHandle_ is v as Rust's Debug prints an `Option` of a handle, by show. +func optionHandle_[T any](v *T, show func(*T) string) string { + if v == nil { + return "None" + } + return "Some(" + show(v) + ")" +} + +// list_ is items as Rust's Debug prints a slice, each by show. +func list_[T any](items []T, show func(T) string) string { + shown := make([]string, len(items)) + for i, item := range items { + shown[i] = show(item) + } + return "[" + strings.Join(shown, ", ") + "]" +} + +// debugBytes_ is b as Rust's Debug prints bytes. +func debugBytes_(b []byte) string { + return list_(b, func(b byte) string { return fmt.Sprint(b) }) +} + +// debugString_ is s as Rust's Debug prints a string. +func debugString_(s string) string { + var out strings.Builder + out.WriteByte('"') + for _, r := range s { + switch { + case r == '"' || r == '\\': + out.WriteByte('\\') + out.WriteRune(r) + case r == '\n': + out.WriteString(`\n`) + case r == '\r': + out.WriteString(`\r`) + case r == '\t': + out.WriteString(`\t`) + case r == 0: + out.WriteString(`\0`) + case !unicode.IsPrint(r) && r != ' ': + fmt.Fprintf(&out, `\u{%x}`, r) + default: + out.WriteRune(r) + } + } + out.WriteByte('"') + return out.String() +} + +// bound_ is a bound as Rust's Debug prints it. +func bound_[T any](kind rt.Bound, value T) string { + switch kind { + case rt.BoundIncluded: + return fmt.Sprintf("Included(%v)", value) + case rt.BoundExcluded: + return fmt.Sprintf("Excluded(%v)", value) + } + return "Unbounded" +} + +// errOf_ is err as the error type T Rust's call returns, or a panic on any other. +func errOf_[T error](err error) T { + var t T + if !errors.As(err, &t) { + panic(fmt.Sprintf("an error other than %T: %v", t, err)) + } + return t +} + +// isErr_ is whether err is one of T, as `is_err`, panicking on any other error. +func isErr_[T error](err error) bool { + if err == nil { + return false + } + errOf_[T](err) + return true +} + +// ignore_ drops an error of T, as `let _ =` drops a `Result`, panicking on any other. +func ignore_[T error](err error) { + if err != nil { + errOf_[T](err) + } +} + +// lossy_ is b as text, as `String::from_utf8_lossy`: each longest prefix of a valid +// sequence that does not complete one is a replacement character. +func lossy_(b []byte) string { + var out strings.Builder + for len(b) > 0 { + r, n := utf8.DecodeRune(b) + if r != utf8.RuneError || n > 1 { + out.Write(b[:n]) + b = b[n:] + continue + } + need := 0 + switch { + case b[0] >= 0xc2 && b[0] <= 0xdf: + need = 1 + case b[0] >= 0xe0 && b[0] <= 0xef: + need = 2 + case b[0] >= 0xf0 && b[0] <= 0xf4: + need = 3 + } + lo, hi := byte(0x80), byte(0xbf) + switch b[0] { + case 0xe0: + lo = 0xa0 + case 0xed: + hi = 0x9f + case 0xf0: + lo = 0x90 + case 0xf4: + hi = 0x8f + } + n = 1 + for n <= need && n < len(b) && b[n] >= lo && b[n] <= hi { + n++ + lo, hi = 0x80, 0xbf + } + out.WriteRune(utf8.RuneError) + b = b[n:] + } + return out.String() +} + +// hex128_ is v in lowercase hex, zero-padded to width digits. +func hex128_(v rt.U128, width int) string { + s := v.Big().Text(16) + return strings.Repeat("0", max(0, width-len(s))) + s +} + +// integer_ is any of Go's integers, each of a Rust integer's. +type integer_ interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 +} + +// add_ is a + b, panicking on overflow as Rust's checked build does. +func add_[T integer_](a, b T) T { + c := a + b + if (b > 0 && c < a) || (b < 0 && c > a) { + panic("attempt to add with overflow") + } + return c +} + +// sub_ is a - b, panicking on overflow as Rust's checked build does. +func sub_[T integer_](a, b T) T { + c := a - b + if (b > 0 && c > a) || (b < 0 && c < a) { + panic("attempt to subtract with overflow") + } + return c +} + +// least_ is whether a is its signed type's least value, never for an unsigned one. +func least_[T integer_](a T) bool { + return a < 0 && a == 0-a +} + +// mul_ is a * b, panicking on overflow as Rust's checked build does. +func mul_[T integer_](a, b T) T { + c := a * b + minus := T(0) - 1 + if a != 0 && (c/a != b || (a < 0 && a == minus && least_(b)) || (b < 0 && b == minus && least_(a))) { + panic("attempt to multiply with overflow") + } + return c +} + +// rem_ is a % b, panicking on overflow as Rust's checked build does. +func rem_[T integer_](a, b T) T { + if b < 0 && b == T(0)-1 && least_(a) { + panic("attempt to calculate the remainder with overflow") + } + return a % b +} +"#; + +/// The Go file of `t`'s script. +pub(crate) fn emit(t: &Transcript) -> String { + let mut e = Emitter { + t, + depth: 1, + fresh: 0, + imports: BTreeSet::new(), + used: BTreeSet::new(), + reserved: BTreeSet::new(), + handles: BTreeMap::new(), + drops: Vec::new(), + }; + let mut used = BTreeSet::new(); + let mut locals = BTreeSet::new(); + for step in &t.steps { + reads(step, &mut used, &mut locals); + } + e.used = used; + e.reserved = RESERVED.iter().map(|s| s.to_string()).collect(); + e.reserved.extend(locals.iter().map(|name| local(name))); + for name in t.names(LANGUAGE).iter().filter_map(|(key, name)| key.strip_prefix("crate ").map(|_| name)) { + e.reserved.insert(name.to_string()); + } + for package in ["fmt", "strings", "errors", "unicode", "utf8", "math", "context", "slices", "rt", "io"] { + e.reserved.insert(package.to_string()); + } + for package in ["errors", "fmt", "strings", "unicode", "unicode/utf8"] { + e.imports.insert(package.to_string()); + } + e.rt(); + let mut body = String::new(); + e.steps(&t.steps, &mut body); + let imports: String = e.imports.iter().map(|i| format!("\t\"{i}\"\n")).collect(); + format!( + "// Code generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript. DO NOT EDIT.\n\npackage main\n\nimport (\n{imports})\n\n// script runs the transcript through the generated Go.\nfunc script() {{\n{body}}}\n{PRELUDE}" + ) +} + +/// The names of locals `step` reads, and of the functions and unit structs of +/// `transcript.rs` it calls or makes. +fn reads(step: &Step, used: &mut BTreeSet, locals: &mut BTreeSet) { + if let Step::Drop(name) = step { + used.insert(name.clone()); + } + each_expr(step, &mut |expr| { + walk(expr, &mut |e| match &e.kind { + Kind::Var(name) => { + used.insert(name.clone()); + } + Kind::Local(name, _) => { + locals.insert(name.clone()); + } + _ => {} + }) + }); + let mut inner = |steps: &[Step]| steps.iter().for_each(|s| reads(s, used, locals)); + if let Step::Match { ok, err, .. } = step { + inner(&ok.steps); + inner(&err.steps); + } +} + +/// Each expression a step holds, its arms' and closures' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) | Kind::Field(e, _) | Kind::Element(e, _) | Kind::Clone(e) | Kind::Unwrap(e) | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => es.iter().for_each(inner), + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +/// Go's keywords and the predeclared names the script calls, which no local may take. +const RESERVED: &[&str] = &[ + "break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough", "for", "func", "go", "goto", "if", "import", "interface", "map", "package", "range", "return", "select", "struct", "switch", "type", "var", "any", "bool", "byte", "error", "false", "float32", "float64", "int", "int8", "int16", "int32", "int64", "len", "nil", "rune", "string", "true", "uint", "uint8", "uint16", "uint32", "uint64", "append", "make", "max", "min", "new", "panic", "script", "main", +]; + +/// The Go name of a function `transcript.rs` defines: in camel case, unexported. A unit +/// struct keeps its name. +fn local(name: &str) -> String { + let mut out = String::new(); + let mut upper = false; + for c in name.chars() { + match c { + '_' => upper = true, + c if upper => { + out.extend(c.to_uppercase()); + upper = false; + } + c => out.push(c), + } + } + out +} + +/// How a call's error is handled where it is bound. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Failure { + /// Any error panics, as Rust's call cannot fail. + Panic, + /// The error is bound beside the values, for the script to read. + Bind, +} + +/// A call, made: its Go values, of each type, and its error, if bound. +struct Made { + values: Vec, + types: Vec, + /// Whether the values are a tuple's elements, as Go returns a tuple, even one of one. + tuple: bool, + error: Option, +} + +struct Emitter<'t> { + t: &'t Transcript, + depth: usize, + fresh: usize, + /// The packages the script imports, by path. + imports: BTreeSet, + /// The locals the script reads, which a binding of any other leaves `_`. + used: BTreeSet, + /// Names no local may take. + reserved: BTreeSet, + /// The temporaries holding a handle no use has taken yet, each whether it is optional. + handles: BTreeMap, + /// What closes each handle the current statement only lent, at its end. + drops: Vec, +} + +impl Emitter<'_> { + fn indent(&self) -> String { + "\t".repeat(self.depth) + } + + fn line(&self, out: &mut String, line: &str) { + for l in line.lines() { + let _ = writeln!(out, "{}{l}", self.indent()); + } + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("_{what}{}", self.fresh) + } + + /// A local's name in Go. + fn ident(&self, name: &str) -> String { + match self.reserved.contains(name) { + true => format!("{name}_"), + false => name.to_string(), + } + } + + /// A package of the standard library, imported. + fn std(&mut self, path: &str) -> String { + self.imports.insert(path.to_string()); + path.rsplit('/').next().unwrap().to_string() + } + + /// The runtime's package, imported. + fn rt(&mut self) -> String { + self.imports.insert(format!("{MODULE}/rt")); + "rt".to_string() + } + + /// The package of `krate`, imported. + fn package(&mut self, krate: &str) -> String { + let name = self.t.named(LANGUAGE, &format!("crate {krate}")).to_string(); + self.imports.insert(format!("{MODULE}/{name}")); + name + } + + fn steps(&mut self, steps: &[Step], out: &mut String) { + for step in steps { + let outer = std::mem::take(&mut self.drops); + self.step(step, out); + let drops = std::mem::replace(&mut self.drops, outer); + for drop in drops.iter().rev() { + self.line(out, drop); + } + } + } + + fn step(&mut self, step: &Step, out: &mut String) { + match step { + Step::Let(pat, value) => { + if let Type::Result(_, err) = &value.ty { + // `let _ =` of a `Result`, which drops its error. + let Pat::Ignore(_) = pat else { panic!("a let binding a Result whole") }; + let made = self.made(value, Failure::Bind, false, out); + let error = self.error_type(err); + self.line(out, &format!("ignore_[{error}]({})", made.error.unwrap())); + return; + } + let made = self.spread(value, out); + self.bind_made(pat, &made, out); + } + Step::Print(pieces) => { + let v = self.pieces(pieces, out); + let fmt = self.std("fmt"); + self.line(out, &format!("{fmt}.Println({v})")); + } + Step::Do(value) => self.discard(value, out), + Step::Drop(name) => match unref(&self.local_type(name)).base() { + Type::Object(_) => self.line(out, &format!("done_({}.Close())", self.ident(name))), + ty if !holds(self.t, ty) => self.line(out, &format!("_ = {}", self.ident(name))), + ty => panic!("a drop of {ty:?}, which holds a handle"), + }, + Step::Match { value, ok, err } => self.matched(value, ok, err, out), + } + } + + /// The type the script binds `name` to. + fn local_type(&self, name: &str) -> Type { + fn find(steps: &[Step], name: &str) -> Option { + let named = |pat: &Pat| { + let mut bound = Vec::new(); + super::bound(pat, &mut bound); + bound.into_iter().find(|(n, _)| n == name).map(|(_, ty)| ty) + }; + steps.iter().find_map(|step| match step { + Step::Let(pat, _) => named(pat), + Step::Match { ok, err, .. } => [ok, err] + .into_iter() + .find_map(|arm| arm.pat.as_ref().and_then(named).or_else(|| find(&arm.steps, name))), + _ => None, + }) + } + find(&self.t.steps, name).unwrap_or_else(|| panic!("no local {name}")) + } + + /// An expression evaluated for its effect: what it returns, dropped, each handle closed. + fn discard(&mut self, value: &Expr, out: &mut String) { + if let Type::Result(_, err) = &value.ty { + let made = self.made(value, Failure::Bind, false, out); + let error = self.error_type(err); + self.line(out, &format!("ignore_[{error}]({})", made.error.unwrap())); + return; + } + match &value.kind { + Kind::Call(..) => { + let made = self.made(value, Failure::Panic, true, out); + for (v, ty) in made.values.iter().zip(&made.types) { + self.dropped(v, ty, out); + } + } + Kind::Local(..) if value.ty == Type::Unit => { + let call = self.local_call(value, out); + self.line(out, &call); + } + _ => { + let v = self.expr(value, out); + self.dropped(&v, &value.ty, out); + } + } + } + + /// The value `v` of `ty`, which nothing reads: a handle closes, as Rust drops it. + fn dropped(&mut self, v: &str, ty: &Type, out: &mut String) { + self.handles.remove(v); + match unref(ty).base() { + Type::Object(_) => self.line(out, &format!("done_({v}.Close())")), + Type::Option(inner) if matches!(inner.base(), Type::Object(_)) => { + self.line(out, &format!("if {v} != nil {{\n\tdone_({v}.Close())\n}}")) + } + _ => self.line(out, &format!("_ = {v}")), + } + } + + /// `v`, a value read only by reference: a temporary handle closes at the statement's end. + fn lent(&mut self, v: &str) { + match self.handles.remove(v) { + Some(false) => self.drops.push(format!("done_({v}.Close())")), + Some(true) => self.drops.push(format!("if {v} != nil {{\n\tdone_({v}.Close())\n}}")), + None => {} + } + } + + /// `v`, a value moved: a temporary handle is the callee's. + fn moved(&mut self, v: &str) { + self.handles.remove(v); + } + + /// `e`'s values: each of a call's, which may be many, or else `e`'s one. + fn spread(&mut self, e: &Expr, out: &mut String) -> Made { + match &e.kind { + Kind::Call(..) => self.made(e, Failure::Panic, true, out), + Kind::Unwrap(inner) if matches!(inner.ty, Type::Result(..)) => self.made(inner, Failure::Panic, true, out), + _ => { + let v = self.expr(e, out); + Made { + values: vec![v], + types: vec![e.ty.clone()], + tuple: false, + error: None, + } + } + } + } + + /// `pat` bound to what `made` holds. + fn bind_made(&mut self, pat: &Pat, made: &Made, out: &mut String) { + match made.values.len() { + 1 if !made.tuple => self.bind(pat, &made.values[0], &made.types[0], out), + _ => match pat { + Pat::Tuple(pats) => { + assert_eq!(pats.len(), made.values.len(), "a tuple pattern of a call's values"); + for ((p, v), ty) in pats.iter().zip(&made.values).zip(&made.types) { + self.bind(p, v, ty, out); + } + } + pat => { + let v = self.pack(&made.values, &made.types); + let ty = Type::Tuple(made.types.clone()); + self.bind(pat, &v, &ty, out); + } + }, + } + } + + /// `pat` bound to `v`, a value of `ty`. + fn bind(&mut self, pat: &Pat, v: &str, ty: &Type, out: &mut String) { + match pat { + Pat::Name(name, _) if self.used.contains(name) => { + let name = self.ident(name); + self.line(out, &format!("{name} := {v}")); + } + Pat::Name(..) | Pat::Ignore(_) => self.dropped(v, ty, out), + Pat::Tuple(pats) => { + let parts = self.parts(v, ty); + assert_eq!(parts.len(), pats.len(), "a tuple pattern of another length"); + for (p, (part, ty)) in pats.iter().zip(parts) { + self.bind(p, &part, &ty, out); + } + } + } + } + + /// The elements of `v`, a tuple or bounds of `ty`. + fn parts(&mut self, v: &str, ty: &Type) -> Vec<(String, Type)> { + match unref(ty).base() { + Type::Bounds(int) => vec![(format!("{v}.Start"), Type::Bound(*int)), (format!("{v}.End"), Type::Bound(*int))], + Type::Tuple(elements) if elements.len() == 1 => vec![(v.to_string(), elements[0].clone())], + Type::Tuple(elements) => (elements.iter().enumerate()).map(|(i, ty)| (format!("{v}.V{i}"), ty.clone())).collect(), + ty => panic!("the elements of {ty:?}"), + } + } + + /// Values of each of `types` as one tuple. + fn pack(&mut self, values: &[String], types: &[Type]) -> String { + match values.len() { + 0 => panic!("no value of a call returning none"), + 1 => values[0].clone(), + n => { + let rt = self.rt(); + let tys: Vec = types.iter().map(|t| self.go(t)).collect(); + let fields: Vec = values.iter().enumerate().map(|(i, v)| format!("V{i}: {v}")).collect(); + format!("{rt}.Tuple{n}[{}]{{{}}}", tys.join(", "), fields.join(", ")) + } + } + } + + fn matched(&mut self, value: &Expr, ok: &Arm, err: &Arm, out: &mut String) { + match unref(&value.ty).base() { + Type::Option(inner) => { + let v = self.expr(value, out); + self.lent(&v); + self.line(out, &format!("if {v} != nil {{")); + self.depth += 1; + if let Some(pat) = &ok.pat { + let some = self.deref(&v, inner); + self.bind(pat, &some, inner, out); + } + self.steps(&ok.steps, out); + self.depth -= 1; + self.line(out, "} else {"); + self.depth += 1; + self.steps(&err.steps, out); + self.depth -= 1; + self.line(out, "}"); + } + Type::Result(_, err_ty) => { + let made = self.made(value, Failure::Bind, true, out); + let error = made.error.clone().unwrap(); + self.line(out, &format!("if {error} == nil {{")); + self.depth += 1; + if let Some(pat) = &ok.pat { + self.bind_made(pat, &made, out); + } + self.steps(&ok.steps, out); + self.depth -= 1; + self.line(out, "} else {"); + self.depth += 1; + if let Some(pat) = &err.pat { + let payload = self.payload(&error, err_ty); + self.bind(pat, &payload, err_ty, out); + } + self.steps(&err.steps, out); + self.depth -= 1; + self.line(out, "}"); + } + ty => panic!("a match on {ty:?}"), + } + } + + /// What `v`, an `Option` of `inner`, holds: a handle is its own pointer. + fn deref(&self, v: &str, inner: &Type) -> String { + match inner.base() { + Type::Object(_) => v.to_string(), + _ => format!("(*{v})"), + } + } + + /// The Go type of the error a call failing with `err` returns. + fn error_type(&mut self, err: &Type) -> String { + match unref(err).base() { + ty @ (Type::Record(_) | Type::Enum(_) | Type::Object(_)) => self.go(ty), + ty => { + let named = self.t.named(LANGUAGE, &format!("error {}", self.key(ty))).to_string(); + let (krate, name) = named.split_once("::").unwrap(); + let package = match krate { + "" => self.rt(), + krate => self.package(krate), + }; + format!("{package}.{name}") + } + } + } + + /// The Rust value of `error`, a Go error of a call failing with `err`. + fn payload(&mut self, error: &str, err: &Type) -> String { + let ty = self.error_type(err); + match unref(err).base() { + Type::Record(_) | Type::Enum(_) | Type::Object(_) => format!("errOf_[{ty}]({error})"), + _ => format!("errOf_[{ty}]({error}).Value"), + } + } + + /// The key the export names a type by, as an error's. + fn key(&self, ty: &Type) -> String { + match unref(ty).base() { + Type::Str | Type::String => "string".to_string(), + Type::Slice | Type::Vec | Type::Bytes => "bytes".to_string(), + Type::Bool => "bool".to_string(), + Type::Int(int) => int.rust().to_string(), + Type::Range(int) => format!("range_{}", int.rust()), + Type::Bound(int) => format!("bound_{}", int.rust()), + Type::Bounds(int) => format!("bounds_{}", int.rust()), + Type::Option(inner) => format!("option_{}", self.key(inner)), + Type::List(_, inner) => format!("vec_{}", self.key(inner)), + ty => panic!("an error of {ty:?}"), + } + } + + /// The Go of a format's pieces: a string expression. + fn pieces(&mut self, pieces: &[Piece], out: &mut String) -> String { + let mut parts = Vec::new(); + for piece in pieces { + match piece { + Piece::Text(text) => parts.push(string(text)), + Piece::Value(e, spec) => { + let v = self.expr(e, out); + let shown = self.show(&v, &e.ty, *spec, out); + self.lent(&v); + parts.push(shown); + } + } + } + match parts.len() { + 0 => "\"\"".to_string(), + _ => parts.join(" + "), + } + } + + /// `v`, a value of `ty`, as a string the way Rust formats it with `spec`. + fn show(&mut self, v: &str, ty: &Type, spec: Spec, out: &mut String) -> String { + let ty = unref(ty).base().clone(); + let fmt = self.std("fmt"); + match spec { + Spec::Hex(width) => { + let width = match width { + 0 => String::new(), + w => format!("0{w}"), + }; + return match &ty { + Type::U128 => format!("hex128_({v}, {})", if width.is_empty() { "0" } else { &width[1..] }), + Type::Int(int) | Type::NonZero(int) if int.signed() => { + format!("{fmt}.Sprintf(\"%{width}x\", uint{}({v}))", int.bits()) + } + Type::Int(_) | Type::NonZero(_) => format!("{fmt}.Sprintf(\"%{width}x\", {v})"), + ty => panic!("hex of {ty:?}"), + }; + } + Spec::Padded(width) => return format!("{fmt}.Sprintf(\"%0{width}d\", {v})"), + Spec::Debug => return self.debug(v, &ty), + Spec::Display => {} + } + match &ty { + Type::Bool | Type::Int(_) | Type::NonZero(_) => format!("{fmt}.Sprint({v})"), + Type::String | Type::Str | Type::Path | Type::PathBuf => v.to_string(), + Type::Char => format!("string({v})"), + Type::U128 => format!("{v}.Big().String()"), + Type::Object(i) if !self.t.api.objects[*i].traits.display => { + let index = (self.t.api.objects[*i].methods.iter()) + .position(|m| m.access == Access::Text) + .unwrap_or_else(|| panic!("Display of {}, which has none", self.t.rust(&ty))); + let id = FnId { + owner: super::Owner::Object(*i), + index, + }; + let made = self.call_with(id, Some(v.to_string()), Vec::new(), Failure::Panic, true, out); + made.values[0].clone() + } + Type::Object(_) | Type::Record(_) | Type::Enum(_) => format!("{v}.String()"), + ty => panic!("Display of {ty:?}"), + } + } + + /// `v` as Rust's `Debug` prints a value of `ty`. + fn debug(&mut self, v: &str, ty: &Type) -> String { + let fmt = self.std("fmt"); + match unref(ty).base() { + Type::Bool | Type::Int(_) | Type::NonZero(_) => format!("{fmt}.Sprint({v})"), + Type::U128 => format!("{v}.Big().String()"), + Type::String | Type::Str | Type::Path | Type::PathBuf => format!("debugString_({v})"), + Type::Option(inner) => { + let x = self.fresh("x"); + let show = self.debug(&x, inner); + let go = self.go(inner); + match inner.base() { + Type::Object(_) => format!("optionHandle_({v}, func({x} {go}) string {{ return {show} }})"), + _ => format!("option_({v}, func({x} {go}) string {{ return {show} }})"), + } + } + Type::Vec | Type::Slice | Type::Bytes => format!("debugBytes_({v}.Copy())"), + Type::Array(_) => format!("debugBytes_({v}[:])"), + Type::List(_, item) => { + let x = self.fresh("x"); + let show = self.debug(&x, item); + let go = self.go(item); + format!("list_({v}, func({x} {go}) string {{ return {show} }})") + } + Type::Tuple(elements) => { + let elements = elements.clone(); + let parts: Vec = match elements.len() { + 1 => vec![self.debug(v, &elements[0])], + _ => (elements.iter().enumerate()).map(|(i, ty)| self.debug(&format!("{v}.V{i}"), ty)).collect(), + }; + let tail = if parts.len() == 1 { ",)" } else { ")" }; + format!("\"(\" + {} + \"{tail}\"", parts.join(" + \", \" + ")) + } + Type::Bound(_) => format!("bound_({v}.Kind, {v}.Value)"), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => format!("{v}.GoString()"), + ty => panic!("Debug of {ty:?}"), + } + } + + fn expr(&mut self, e: &Expr, out: &mut String) -> String { + self.value(e, &e.ty, out) + } + + /// The Go of `e`, passed where `want` is taken: a call's value is bound before the + /// statement, each in Rust's order. + fn value(&mut self, e: &Expr, want: &Type, out: &mut String) -> String { + let base = unref(want).base().clone(); + match &e.kind { + Kind::Unit => panic!("a value of ()"), + Kind::Bool(b) => b.to_string(), + Kind::Int(n) => match &base { + Type::U128 => { + let rt = self.rt(); + let v = n.magnitude; + assert!(!n.negative, "a negative u128"); + format!("{rt}.U128{{Hi: {:#x}, Lo: {:#x}}}", (v >> 64) as u64, v as u64) + } + Type::Int(int) | Type::NonZero(int) => format!("{}({n})", go_int(*int)), + ty => match unref(&e.ty).base() { + Type::Int(int) | Type::NonZero(int) => format!("{}({n})", go_int(*int)), + _ => panic!("an integer as {ty:?}"), + }, + }, + Kind::Float(f) => { + let math = self.std("math"); + match &base { + Type::F32 => format!("{math}.Float32frombits({:#x})", (*f as f32).to_bits()), + _ => format!("{math}.Float64frombits({:#x})", f.to_bits()), + } + } + Kind::Char(c) => format!("rune({:#x})", *c as u32), + Kind::Str(s) => string(s), + Kind::Bytes(b) => match &base { + Type::Array(n) => { + let items: Vec = b.iter().map(|b| format!("{b:#04x}")).collect(); + format!("[{n}]byte{{{}}}", items.join(", ")) + } + _ => { + let rt = self.rt(); + format!("{rt}.NewBytes([]byte({}))", bytes(b)) + } + }, + Kind::Duration(secs, nanos) => { + let rt = self.rt(); + match (secs, nanos) { + (0, 0) => format!("{rt}.Duration{{}}"), + _ => format!("must_({rt}.NewDuration({secs}, {nanos}))"), + } + } + Kind::Socket(addr) => self.socket(addr, &base), + Kind::Ip(ip) => self.ip(ip, &base), + Kind::None => { + let ty = match &base { + Type::Option(_) => base.clone(), + _ => unref(&e.ty).base().clone(), + }; + format!("({})(nil)", self.go(&ty)) + } + Kind::Some(inner) => { + let want = match &base { + Type::Option(inner) => (**inner).clone(), + _ => match unref(&e.ty).base() { + Type::Option(inner) => (**inner).clone(), + ty => panic!("Some as {ty:?}"), + }, + }; + let v = self.value(inner, &want, out); + match want.base() { + Type::Object(_) => v, + _ => format!("ptr_({v})"), + } + } + Kind::Tuple(elements) => self.tuple(e, elements, &base, out), + Kind::List(items) => { + let item = match &base { + Type::List(_, item) => (**item).clone(), + ty => panic!("a list as {ty:?}"), + }; + let go = self.go(&item); + let parts: Vec = items.iter().map(|i| self.value(i, &item, out)).collect(); + for (p, i) in parts.iter().zip(items) { + let _ = i; + self.moved(p); + } + format!("[]{go}{{{}}}", parts.join(", ")) + } + Kind::Record(r, fields) => { + let ty = Type::Record(*r); + let name = self.go(&ty); + let rust = self.t.rust(&ty); + let record = &self.t.api.records[*r]; + let named: Vec<(String, Type)> = (record.fields.iter()) + .map(|f| (self.t.named(LANGUAGE, &format!("type {rust} / field {}", f.name)).to_string(), f.ty.clone())) + .collect(); + let values: Vec = (fields.iter().zip(&named)) + .map(|(f, (name, ty))| { + let v = self.value(f, ty, out); + self.moved(&v); + format!("{name}: {v}") + }) + .collect(); + format!("{name}{{{}}}", values.join(", ")) + } + Kind::Variant(en, v, fields) => { + let ty = Type::Enum(*en); + let rust = self.t.rust(&ty); + let enumeration = &self.t.api.enums[*en]; + let variant = &enumeration.variants[*v]; + let name = self.t.named(LANGUAGE, &format!("type {rust} / variant {}", variant.name)).to_string(); + let package = self.package(&enumeration.home.krate.clone()); + if enumeration.variants.iter().all(|v| v.fields.is_empty()) { + return format!("{package}.{name}"); + } + let named: Vec<(String, Type)> = variant.fields.iter().map(|f| (field_name(&f.name), f.ty.clone())).collect(); + let values: Vec = (fields.iter().zip(&named)) + .map(|(f, (name, ty))| { + let v = self.value(f, ty, out); + self.moved(&v); + format!("{name}: {v}") + }) + .collect(); + format!("{package}.{name}{{{}}}", values.join(", ")) + } + Kind::Bound(kind, value) => { + let Type::Bound(_) = &base else { panic!("a bound as {base:?}") }; + let rt = self.rt(); + let ty = self.go(&base); + match (kind, value) { + (BoundKind::Unbounded, _) => format!("{ty}{{Kind: {rt}.BoundUnbounded}}"), + (BoundKind::Included, Some(v)) => { + let int = bound_int(&base); + let v = self.value(v, &int, out); + format!("{ty}{{Kind: {rt}.BoundIncluded, Value: {v}}}") + } + (BoundKind::Excluded, Some(v)) => { + let int = bound_int(&base); + let v = self.value(v, &int, out); + format!("{ty}{{Kind: {rt}.BoundExcluded, Value: {v}}}") + } + _ => unreachable!(), + } + } + Kind::Default => { + let ty = match &base { + Type::Record(_) | Type::Object(_) => base.clone(), + _ => unref(&e.ty).base().clone(), + }; + let rust = self.t.rust(&ty); + let name = self.t.named(LANGUAGE, &format!("type {rust} / Default")).to_string(); + let krate = self.home(&ty); + let package = self.package(&krate); + let call = format!("{package}.{name}()"); + let made = self.hoist(&call, &[ty], false, Failure::Panic, true, out); + made.values[0].clone() + } + Kind::Const(c) => { + let constant = &self.t.api.constants[*c]; + let name = self.t.named(LANGUAGE, &format!("const {}", constant.path.join("::"))).to_string(); + let package = self.package(&constant.home.krate.clone()); + format!("{package}.{name}") + } + Kind::Closure(params, steps, value) => self.closure(params, steps, value, &base, out), + Kind::Local(..) if e.ty == Type::Unit => panic!("a value of a function returning nothing"), + Kind::Local(name, args) if args.is_empty() && name.starts_with(char::is_uppercase) => format!("{name}{{}}"), + Kind::Format(pieces) => self.pieces(pieces, out), + _ => { + let v = self.computed(e, out); + self.coerce(&v, &e.ty, &base) + } + } + } + + /// The Go of `e`, an expression no literal spells, as a value of its own type. + fn computed(&mut self, e: &Expr, out: &mut String) -> String { + match &e.kind { + Kind::Var(name) => self.ident(name), + Kind::Call(..) => { + let made = self.made(e, Failure::Panic, true, out); + self.pack(&made.values, &made.types) + } + Kind::Local(..) => { + let call = self.local_call(e, out); + let v = self.fresh("t"); + self.line(out, &format!("{v} := {call}")); + v + } + Kind::Field(base, i) => { + let b = self.expr(base, out); + let Type::Record(r) = unref(&base.ty).base() else { panic!("a field of {:?}", base.ty) }; + let rust = self.t.rust(&Type::Record(*r)); + let field = &self.t.api.records[*r].fields[*i].name; + let name = self.t.named(LANGUAGE, &format!("type {rust} / field {field}")).to_string(); + format!("{b}.{name}") + } + Kind::Element(base, i) => { + let b = self.expr(base, out); + match unref(&base.ty).base() { + Type::Range(_) => format!("{b}.{}", if *i == 0 { "Start" } else { "End" }), + ty => self.parts(&b, &ty.clone()).swap_remove(*i).0, + } + } + Kind::Clone(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + Type::Object(_) => { + self.lent(&v); + let made = self.hoist(&format!("{v}.Clone()"), &[inner.ty.clone()], true, Failure::Panic, true, out); + made.values[0].clone() + } + Type::List(..) => format!("{}.Clone({v})", self.std("slices")), + _ => v, + } + } + Kind::Unwrap(inner) => match unref(&inner.ty).base() { + Type::Result(..) => { + let made = self.made(inner, Failure::Panic, true, out); + self.pack(&made.values, &made.types) + } + Type::Option(item) => { + let v = self.expr(inner, out); + match item.base() { + Type::Object(_) => { + self.moved(&v); + let made = self.hoist(&format!("present_({v})"), &[(**item).clone()], false, Failure::Panic, true, out); + made.values[0].clone() + } + _ => format!("some_({v})"), + } + } + ty => panic!("unwrap of {ty:?}"), + }, + Kind::UnwrapErr(inner) => { + let Type::Result(_, err) = &inner.ty else { panic!("unwrap_err of {:?}", inner.ty) }; + let made = self.made(inner, Failure::Bind, false, out); + self.payload(&made.error.unwrap(), err) + } + Kind::IsErr(inner) => { + let Type::Result(_, err) = &inner.ty else { panic!("is_err of {:?}", inner.ty) }; + let made = self.made(inner, Failure::Bind, false, out); + let error = self.error_type(err); + format!("isErr_[{error}]({})", made.error.unwrap()) + } + Kind::IsSome(inner) | Kind::IsNone(inner) => { + let v = self.expr(inner, out); + let test = format!("({v} {} nil)", if matches!(e.kind, Kind::IsSome(_)) { "!=" } else { "==" }); + self.lent(&v); + test + } + Kind::Binary(op, a, b) => self.binary(*op, a, b, out), + Kind::Join { items, pat, body, sep } => { + let items_v = self.expr(items, out); + self.lent(&items_v); + let Type::List(_, item) = unref(&items.ty).base() else { panic!("a join over {:?}", items.ty) }; + let item = (**item).clone(); + let parts = self.fresh("j"); + let x = self.fresh("x"); + self.line(out, &format!("var {parts} []string")); + self.line(out, &format!("for _, {x} := range {items_v} {{")); + self.depth += 1; + let outer = std::mem::take(&mut self.drops); + self.bind(pat, &x, &item, out); + let v = self.expr(body, out); + self.line(out, &format!("{parts} = append({parts}, {v})")); + let drops = std::mem::replace(&mut self.drops, outer); + for drop in drops.iter().rev() { + self.line(out, drop); + } + self.depth -= 1; + self.line(out, "}"); + format!("{}.Join({parts}, {})", self.std("strings"), string(sep)) + } + Kind::MapOr { option, none, pat, some } => { + let option_v = self.expr(option, out); + let Type::Option(inner) = unref(&option.ty).base() else { panic!("map_or of {:?}", option.ty) }; + let inner = (**inner).clone(); + let none_v = self.value(none, &e.ty, out); + let result = self.fresh("m"); + self.line(out, &format!("{result} := {none_v}")); + self.line(out, &format!("if {option_v} != nil {{")); + self.depth += 1; + let outer = std::mem::take(&mut self.drops); + let some_v = self.deref(&option_v, &inner); + self.bind(pat, &some_v, &inner, out); + let v = self.value(some, &e.ty, out); + self.line(out, &format!("{result} = {v}")); + let drops = std::mem::replace(&mut self.drops, outer); + for drop in drops.iter().rev() { + self.line(out, drop); + } + self.depth -= 1; + self.line(out, "}"); + self.lent(&option_v); + result + } + Kind::Utf8(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + Type::Array(_) => format!("lossy_({v}[:])"), + Type::Vec | Type::Slice | Type::Bytes => format!("lossy_({v}.Copy())"), + ty => panic!("text of {ty:?}"), + } + } + Kind::Len(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + Type::Vec | Type::Slice | Type::Bytes => format!("uint({v}.Len())"), + Type::Array(_) | Type::String | Type::Str | Type::List(..) => format!("uint(len({v}))"), + ty => panic!("len of {ty:?}"), + } + } + kind => panic!("{} has no Go for this expression", describe(kind)), + } + } + + /// `v`, a value of `have`, as one of `want`: an address of one family where any is + /// taken, or an array of bytes where bytes are. + fn coerce(&mut self, v: &str, have: &Type, want: &Type) -> String { + match (unref(have).base(), want) { + (Type::SocketAddr(Family::V4), Type::SocketAddr(Family::Any)) => format!("{}.SocketAddrFromV4({v})", self.rt()), + (Type::SocketAddr(Family::V6), Type::SocketAddr(Family::Any)) => format!("{}.SocketAddrFromV6({v})", self.rt()), + (Type::IpAddr(Family::V4), Type::IpAddr(Family::Any)) => format!("{}.IpAddrFromV4({v})", self.rt()), + (Type::IpAddr(Family::V6), Type::IpAddr(Family::Any)) => format!("{}.IpAddrFromV6({v})", self.rt()), + (Type::Array(_), Type::Slice | Type::Vec | Type::Bytes) => format!("{}.NewBytes({v}[:])", self.rt()), + _ => v.to_string(), + } + } + + fn socket(&mut self, addr: &std::net::SocketAddr, want: &Type) -> String { + let rt = self.rt(); + let (value, family) = match addr { + std::net::SocketAddr::V4(a) => { + let ip: Vec = a.ip().octets().iter().map(|o| o.to_string()).collect(); + (format!("{rt}.SocketAddrV4{{IP: {rt}.Ipv4Addr{{{}}}, Port: {}}}", ip.join(", "), a.port()), "V4") + } + std::net::SocketAddr::V6(a) => { + let ip: Vec = a.ip().octets().iter().map(|o| o.to_string()).collect(); + ( + format!( + "{rt}.SocketAddrV6{{IP: {rt}.Ipv6Addr{{{}}}, Port: {}, FlowInfo: {}, ScopeID: {}}}", + ip.join(", "), + a.port(), + a.flowinfo(), + a.scope_id() + ), + "V6", + ) + } + }; + match want { + Type::SocketAddr(Family::Any) => format!("{rt}.SocketAddrFrom{family}({value})"), + _ => value, + } + } + + fn ip(&mut self, ip: &std::net::IpAddr, want: &Type) -> String { + let rt = self.rt(); + let (value, family) = match ip { + std::net::IpAddr::V4(ip) => { + let o: Vec = ip.octets().iter().map(|o| o.to_string()).collect(); + (format!("{rt}.Ipv4Addr{{{}}}", o.join(", ")), "V4") + } + std::net::IpAddr::V6(ip) => { + let o: Vec = ip.octets().iter().map(|o| o.to_string()).collect(); + (format!("{rt}.Ipv6Addr{{{}}}", o.join(", ")), "V6") + } + }; + match want { + Type::IpAddr(Family::Any) => format!("{rt}.IpAddrFrom{family}({value})"), + _ => value, + } + } + + fn tuple(&mut self, e: &Expr, elements: &[Expr], base: &Type, out: &mut String) -> String { + let ty = match base { + Type::Range(_) | Type::Bounds(_) | Type::Tuple(_) => base.clone(), + _ => unref(&e.ty).base().clone(), + }; + match &ty { + Type::Range(int) | Type::Bounds(int) => { + let element = match ty { + Type::Range(_) => Type::Int(*int), + _ => Type::Bound(*int), + }; + let go = self.go(&ty); + let (a, b) = (self.value(&elements[0], &element, out), self.value(&elements[1], &element, out)); + format!("{go}{{Start: {a}, End: {b}}}") + } + Type::Tuple(types) => { + let values: Vec = (elements.iter().zip(types)).map(|(e, t)| self.value(e, t, out)).collect(); + for v in &values { + self.moved(v); + } + self.pack(&values, types) + } + ty => panic!("a tuple as {ty:?}"), + } + } + + fn binary(&mut self, op: Op, a: &Expr, b: &Expr, out: &mut String) -> String { + if op == Op::And { + // `&&` evaluates its right side only once its left holds. + let left = self.expr(a, out); + let result = self.fresh("b"); + self.line(out, &format!("{result} := {left}")); + self.line(out, &format!("if {result} {{")); + self.depth += 1; + let outer = std::mem::take(&mut self.drops); + let right = self.expr(b, out); + self.line(out, &format!("{result} = {right}")); + let drops = std::mem::replace(&mut self.drops, outer); + for drop in drops.iter().rev() { + self.line(out, drop); + } + self.depth -= 1; + self.line(out, "}"); + return result; + } + let ty = unref(&a.ty).base().clone(); + let (x, y) = (self.expr(a, out), self.value(b, &ty, out)); + match op { + Op::Eq | Op::Ne => { + let not = if op == Op::Ne { "!" } else { "" }; + match &ty { + Type::Record(_) | Type::Enum(_) | Type::Object(_) => { + self.lent(&x); + self.lent(&y); + let fails = matches!(ty, Type::Object(_)) || fails(self.t, &ty); + let made = self.hoist(&format!("{x}.Equal({y})"), &[Type::Bool], fails, Failure::Panic, true, out); + format!("{not}{}", made.values[0]) + } + Type::Bool | Type::Int(_) | Type::NonZero(_) | Type::Char | Type::F32 | Type::F64 | Type::String | Type::Str => { + format!("({x} {} {y})", if op == Op::Eq { "==" } else { "!=" }) + } + ty => panic!("== of {ty:?}"), + } + } + Op::Lt => format!("({x} < {y})"), + Op::Gt => format!("({x} > {y})"), + Op::Add | Op::Sub | Op::Mul | Op::Rem => { + let Type::Int(_) = ty else { panic!("arithmetic on {ty:?}") }; + let f = match op { + Op::Add => "add_", + Op::Sub => "sub_", + Op::Mul => "mul_", + _ => "rem_", + }; + format!("{f}({x}, {y})") + } + Op::And => unreachable!(), + } + } + + /// A closure, as a function literal bound before the statement that passes it. + fn closure(&mut self, params: &[Pat], steps: &[Step], value: &Expr, want: &Type, out: &mut String) -> String { + let Type::Closure(closure) = want else { panic!("a closure as {want:?}") }; + if closure.err.is_some() { + panic!("a closure returning a Result, which Go returns beside an error"); + } + let types: Vec = closure.params.iter().map(|ty| self.go_param(ty)).collect(); + let mut body = String::new(); + self.depth += 1; + let mut names = Vec::new(); + for (pat, ty) in params.iter().zip(&closure.params) { + match pat { + Pat::Name(name, _) if self.used.contains(name) => names.push(self.ident(name)), + Pat::Name(..) | Pat::Ignore(_) => names.push("_".to_string()), + Pat::Tuple(_) => { + let p = self.fresh("p"); + self.bind(pat, &p, ty, &mut body); + names.push(p); + } + } + } + let outer = std::mem::take(&mut self.drops); + self.steps(steps, &mut body); + let result = match closure.ok { + Type::Unit => String::new(), + ref ok => { + let ok = ok.clone(); + let v = self.value(value, &ok, &mut body); + let drops = std::mem::take(&mut self.drops); + for drop in drops.iter().rev() { + self.line(&mut body, drop); + } + self.line(&mut body, &format!("return {v}")); + format!(" {}", self.go(&ok)) + } + }; + self.drops = outer; + self.depth -= 1; + let params: Vec = names.iter().zip(&types).map(|(n, t)| format!("{n} {t}")).collect(); + let f = self.fresh("f"); + self.line(out, &format!("{f} := func({}){result} {{", params.join(", "))); + out.push_str(&body); + self.line(out, "}"); + f + } + + /// A call of a function `transcript.rs` defines, each argument as its own type. + fn local_call(&mut self, e: &Expr, out: &mut String) -> String { + let Kind::Local(name, args) = &e.kind else { unreachable!() }; + let args: Vec = args.iter().map(|a| self.expr(a, out)).collect(); + for a in &args { + self.lent(a); + } + format!("{}({})", local(name), args.join(", ")) + } + + /// The crate a record, enum, or object belongs to. + fn home(&self, ty: &Type) -> String { + let api = &self.t.api; + match ty { + Type::Record(i) => api.records[*i].home.krate.clone(), + Type::Enum(i) => api.enums[*i].home.krate.clone(), + Type::Object(i) => api.objects[*i].home.krate.clone(), + Type::Callback(i, _) => api.callbacks[*i].home.krate.clone(), + ty => panic!("{ty:?} belongs to no crate"), + } + } + + /// A call expression `e`, made: bound before the statement, its error handled as + /// `failure` says, its values `kept` or else left `_`. + fn made(&mut self, e: &Expr, failure: Failure, kept: bool, out: &mut String) -> Made { + let Kind::Call(id, receiver, args) = &e.kind else { panic!("{} is no call", describe(&e.kind)) }; + let f = self.t.function(*id); + let receiver = receiver.as_ref().map(|r| { + let v = self.expr(r, out); + match f.receiver { + Some(Receiver::Owned) => self.moved(&v), + _ => self.lent(&v), + } + v + }); + let mut values = Vec::new(); + for (arg, param) in args.iter().zip(&f.params) { + if written(¶m.ty) { + // A value passed for `&mut`, which the call writes back through its pointer. + let Kind::Var(name) = &arg.kind else { panic!("a value passed for &mut that is no local") }; + values.push(format!("&{}", self.ident(name))); + continue; + } + let v = self.value(arg, ¶m.ty, out); + match param.ty { + Type::Ref(..) => self.lent(&v), + _ => self.moved(&v), + } + values.push(v); + } + self.call_with(*id, receiver, values, failure, kept, out) + } + + /// The call of `id` on `receiver` with `args`, each already Go, made. + fn call_with(&mut self, id: FnId, receiver: Option, mut args: Vec, failure: Failure, kept: bool, out: &mut String) -> Made { + let f = self.t.function(id); + let name = self.t.name(LANGUAGE, id).to_string(); + if f.future { + let context = self.std("context"); + args.insert(0, format!("{context}.Background()")); + } + let target = match receiver { + Some(r) => r, + None => self.package(&f.home.krate.clone()), + }; + let call = format!("{target}.{name}({})", args.join(", ")); + let types: Vec = match &f.ok { + Type::Unit => Vec::new(), + Type::Tuple(elements) => elements.clone(), + ok => vec![ok.clone()], + }; + let errs = self.errs(id); + let mut made = self.hoist(&call, &types, errs, failure, kept, out); + made.tuple = matches!(f.ok, Type::Tuple(_)); + made + } + + /// Whether the Go of `id` returns an error beside its values: Rust's own, a future's + /// context's, or a check of what it takes failing, as of a closed handle or text Rust's + /// type does not hold, or of an item the target lacks. + fn errs(&self, id: FnId) -> bool { + let f = self.t.function(id); + let receiver = f.receiver.is_some() && self.t.owner(id).is_some_and(|o| fails(self.t, &o)); + f.err.is_some() + || f.future + || receiver + || f.params.iter().any(|p| fails(self.t, &p.ty)) + || !self.t.api.everywhere(f.on) + } + + /// `call`, of values of `types` and an error if `errs`, bound before the statement. + fn hoist(&mut self, call: &str, types: &[Type], errs: bool, failure: Failure, kept: bool, out: &mut String) -> Made { + let values: Vec = types + .iter() + .map(|_| match kept { + true => self.fresh("t"), + false => "_".to_string(), + }) + .collect(); + let mut made = Made { + values: values.clone(), + types: types.to_vec(), + tuple: false, + error: None, + }; + match (values.len(), errs, failure) { + (0, false, _) => self.line(out, call), + (0, true, Failure::Panic) => self.line(out, &format!("done_({call})")), + (1, true, Failure::Panic) if kept => self.line(out, &format!("{} := must_({call})", values[0])), + (_, false, _) if kept => self.line(out, &format!("{} := {call}", values.join(", "))), + (_, false, _) => self.line(out, &format!("{} = {call}", values.join(", "))), + (_, true, failure) => { + let error = self.fresh("e"); + let mut names = values.clone(); + names.push(error.clone()); + self.line(out, &format!("{} := {call}", names.join(", "))); + match failure { + Failure::Panic => self.line(out, &format!("done_({error})")), + Failure::Bind => made.error = Some(error), + } + } + } + for (v, ty) in made.values.iter().zip(types) { + if v != "_" && holds_handle(ty) { + self.handles.insert(v.clone(), !matches!(unref(ty).base(), Type::Object(_))); + } + } + made + } + + /// The Go type of `ty`, as the export spells it. + fn go(&mut self, ty: &Type) -> String { + match ty { + Type::Bool => "bool".to_string(), + Type::Int(int) | Type::NonZero(int) => go_int(*int).to_string(), + Type::U128 => format!("{}.U128", self.rt()), + Type::F32 => "float32".to_string(), + Type::F64 => "float64".to_string(), + Type::Char => "rune".to_string(), + Type::Str | Type::String | Type::Path | Type::PathBuf => "string".to_string(), + Type::Slice | Type::Vec | Type::Bytes => format!("{}.Bytes", self.rt()), + Type::Array(n) => format!("[{n}]byte"), + Type::Duration => format!("{}.Duration", self.rt()), + Type::SocketAddr(family) => { + let name = match family { + Family::Any => "SocketAddr", + Family::V4 => "SocketAddrV4", + Family::V6 => "SocketAddrV6", + }; + format!("{}.{name}", self.rt()) + } + Type::IpAddr(family) => { + let name = match family { + Family::Any => "IpAddr", + Family::V4 => "Ipv4Addr", + Family::V6 => "Ipv6Addr", + }; + format!("{}.{name}", self.rt()) + } + Type::List(_, inner) => format!("[]{}", self.go(inner)), + Type::Option(inner) => match inner.base() { + Type::Object(_) => self.go(inner), + _ => format!("*{}", self.go(inner)), + }, + Type::Box(inner) | Type::Ref(_, inner) => self.go(inner), + Type::Record(_) | Type::Enum(_) => self.named_type(ty), + Type::Object(_) => format!("*{}", self.named_type(ty)), + Type::Callback(i, _) => { + let path = self.t.api.callbacks[*i].path.join("::"); + let name = self.t.named(LANGUAGE, &format!("type {path}")).to_string(); + let package = self.package(&self.home(ty)); + format!("{package}.{name}") + } + Type::Closure(closure) => { + let params: Vec = closure.params.iter().map(|p| self.go_param(p)).collect(); + let params = params.join(", "); + match (&closure.ok, closure.err.is_some()) { + (Type::Unit, false) => format!("func({params})"), + (Type::Unit, true) => format!("func({params}) error"), + (ok, false) => format!("func({params}) {}", self.go(ok)), + (ok, true) => format!("func({params}) ({}, error)", self.go(ok)), + } + } + Type::Range(int) => format!("{}.Range{}", self.rt(), pascal_int(*int)), + Type::Bound(int) => format!("{}.Bound{}", self.rt(), pascal_int(*int)), + Type::Bounds(int) => format!("{}.Bounds{}", self.rt(), pascal_int(*int)), + Type::Tuple(elements) => match &elements[..] { + [element] => self.go(element), + elements => { + let types: Vec = elements.iter().map(|e| self.go(e)).collect(); + format!("{}.Tuple{}[{}]", self.rt(), elements.len(), types.join(", ")) + } + }, + Type::Waker => "func()".to_string(), + Type::Future => format!("func({}.Context)", self.std("context")), + Type::Reader => format!("{}.ReadSeeker", self.std("io")), + ty => panic!("no Go type is {ty:?}"), + } + } + + /// The Go type of a parameter Rust lends a closure: bytes are a `[]byte`, copied. + fn go_param(&mut self, ty: &Type) -> String { + match ty.base() { + Type::Slice | Type::Vec | Type::Bytes => "[]byte".to_string(), + Type::Option(inner) if matches!(inner.base(), Type::Slice | Type::Vec | Type::Bytes) => "*[]byte".to_string(), + _ => self.go(ty), + } + } + + /// A record's, enum's, or object's name, qualified by its package. + fn named_type(&mut self, ty: &Type) -> String { + let name = self.t.type_name(LANGUAGE, ty).to_string(); + let package = self.package(&self.home(ty)); + format!("{package}.{name}") + } +} + +/// Whether a parameter of `ty` takes a value the call writes back, through a pointer. +fn written(ty: &Type) -> bool { + matches!(ty, Type::Ref(Mutability::Mut, inner) if !matches!(**inner, Type::Object(_) | Type::Reader)) +} + +/// What an expression kind is, for a panic naming it. +fn describe(kind: &Kind) -> String { + let text = format!("{:?}", std::mem::discriminant(kind)); + text +} + +/// Whether a value of `ty` is a handle, or an `Option` of one, which closes once dropped. +fn holds_handle(ty: &Type) -> bool { + match unref(ty).base() { + Type::Object(_) => true, + Type::Option(inner) => matches!(inner.base(), Type::Object(_)), + _ => false, + } +} + +/// Whether a value of `ty` holds a handle anywhere. +fn holds(t: &Transcript, ty: &Type) -> bool { + let api = &t.api; + match ty { + Type::Object(_) => true, + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => holds(t, inner), + Type::Tuple(elements) => elements.iter().any(|e| holds(t, e)), + Type::Record(i) => api.records[*i].fields.iter().any(|f| holds(t, &f.ty)), + Type::Enum(i) => (api.enums[*i].variants.iter()).any(|v| v.fields.iter().any(|f| holds(t, &f.ty))), + _ => false, + } +} + +/// Whether passing a value of `ty` can fail a Go call before it is made: it holds a +/// handle, which may be closed, or text, a char, a path, or a `NonZero`, whose Go types +/// hold values Rust's do not. +fn fails(t: &Transcript, ty: &Type) -> bool { + let api = &t.api; + match ty { + Type::Object(_) | Type::Str | Type::String | Type::Char | Type::Path | Type::PathBuf | Type::NonZero(_) => true, + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => fails(t, inner), + Type::Tuple(elements) => elements.iter().any(|e| fails(t, e)), + Type::Record(i) => api.records[*i].fields.iter().any(|f| fails(t, &f.ty)), + Type::Enum(i) => (api.enums[*i].variants.iter()).any(|v| v.fields.iter().any(|f| fails(t, &f.ty))), + _ => false, + } +} + +/// The integer a bound of `ty` holds. +fn bound_int(ty: &Type) -> Type { + match ty { + Type::Bound(int) => Type::Int(*int), + ty => panic!("a bound as {ty:?}"), + } +} + +fn go_int(int: Int) -> &'static str { + match int { + Int::U8 => "uint8", + Int::U16 => "uint16", + Int::U32 => "uint32", + Int::U64 => "uint64", + Int::Usize => "uint", + Int::I8 => "int8", + Int::I16 => "int16", + Int::I32 => "int32", + Int::I64 => "int64", + Int::Isize => "int", + } +} + +fn pascal_int(int: Int) -> String { + let rust = int.rust(); + let mut chars = rust.chars(); + let first = chars.next().unwrap().to_ascii_uppercase(); + format!("{first}{}", chars.as_str()) +} + +/// A field's Go name, as the export spells a variant's: `V0` for a positional one. +fn field_name(name: &str) -> String { + match name.starts_with(|c: char| c.is_ascii_digit()) { + true => format!("V{name}"), + false => { + let camel = local(name); + let mut chars = camel.chars(); + match chars.next() { + Some(first) => first.to_uppercase().chain(chars).collect(), + None => String::new(), + } + } + } +} + +/// A Go string literal. +fn string(s: &str) -> String { + let mut out = String::from("\""); + for c in s.chars() { + match c { + '"' | '\\' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + let _ = write!(out, "\\x{:02x}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); + out +} + +/// A Go string literal of bytes, any byte escaped. +fn bytes(b: &[u8]) -> String { + let mut out = String::from("\""); + for &byte in b { + match byte { + b'"' | b'\\' => { + out.push('\\'); + out.push(byte as char); + } + 0x20..0x7f => out.push(byte as char), + _ => { + let _ = write!(out, "\\x{byte:02x}"); + } + } + } + out.push('"'); + out +} diff --git a/ffi/tests/fixtures/transcript/ir.rs b/ffi/tests/fixtures/transcript/ir.rs index 58a95d4a0..d06a53227 100644 --- a/ffi/tests/fixtures/transcript/ir.rs +++ b/ffi/tests/fixtures/transcript/ir.rs @@ -20,11 +20,28 @@ pub(crate) struct Api { pub(crate) callbacks: Vec, pub(crate) functions: Vec, pub(crate) constants: Vec, + /// The targets the API serves, each a bit of an item's `on`. + pub(crate) targets: Vec, +} + +impl Api { + /// Whether an item `on` these targets is on every target the API serves. + pub(crate) fn everywhere(&self, on: u64) -> bool { + let all = u64::MAX >> (64 - self.targets.len()); + on & all == all + } +} + +/// The crate an item belongs to, whose package or module a binding puts it in. +#[derive(serde::Deserialize)] +pub(crate) struct Home { + pub(crate) krate: String, } #[derive(serde::Deserialize)] pub(crate) struct Record { pub(crate) path: Vec, + pub(crate) home: Home, /// The path, with any arguments, the API shows the type at, which its keys name it by. #[serde(default)] pub(crate) shown: Option>, @@ -45,6 +62,7 @@ pub(crate) struct Field { #[derive(serde::Deserialize)] pub(crate) struct Enum { pub(crate) path: Vec, + pub(crate) home: Home, /// The path, with any arguments, the API shows the type at, which its keys name it by. #[serde(default)] pub(crate) shown: Option>, @@ -65,6 +83,7 @@ pub(crate) struct Variant { #[derive(serde::Deserialize)] pub(crate) struct Object { pub(crate) path: Vec, + pub(crate) home: Home, /// The path, with any arguments, the API shows the type at, which its keys name it by. #[serde(default)] pub(crate) shown: Option>, @@ -85,6 +104,7 @@ fn yes() -> bool { #[derive(serde::Deserialize)] pub(crate) struct Callback { pub(crate) path: Vec, + pub(crate) home: Home, pub(crate) methods: Vec, } @@ -100,6 +120,9 @@ pub(crate) struct Traits { #[derive(serde::Deserialize)] pub(crate) struct Function { pub(crate) path: Vec, + pub(crate) home: Home, + /// The targets it is on, a bit each of the API's `targets`. + pub(crate) on: u64, pub(crate) receiver: Option, pub(crate) params: Vec, pub(crate) ok: Type, @@ -143,6 +166,7 @@ pub(crate) struct Param { #[derive(serde::Deserialize)] pub(crate) struct Constant { pub(crate) path: Vec, + pub(crate) home: Home, pub(crate) value: Literal, } diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 79879ef50..cad6afd50 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -13,6 +13,7 @@ pub(crate) mod ir; mod parse; +pub(crate) mod go; pub(crate) mod python; use std::collections::BTreeMap; @@ -343,6 +344,11 @@ impl Transcript { self.named(language, &format!("type {}", self.rust(ty))) } + /// `language`'s name for each item, by its key. + pub(crate) fn names(&self, language: &str) -> &BTreeMap { + &self.names[language] + } + /// `language`'s name for the item `key` names, such as `const api::LIMIT`. pub(crate) fn named(&self, language: &str, key: &str) -> &str { let names = &self.names[language]; From 82d1394788c373da9e4ce471ae38767bcecee2d0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 04:46:25 -0800 Subject: [PATCH 08/28] wip: generate the Kotlin transcript Co-Authored-By: Claude Opus 5.5 --- ffi/tests/api.kt | 942 ++++-------------- ffi/tests/fixtures.rs | 22 +- ffi/tests/fixtures/transcript/kotlin.rs | 1170 +++++++++++++++++++++++ ffi/tests/fixtures/transcript/mod.rs | 1 + 4 files changed, 1373 insertions(+), 762 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/kotlin.rs diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index 107ab47fa..c46749630 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -1,8 +1,9 @@ // The api fixture's Kotlin test: the script fixtures/api/examples/transcript.rs runs -// natively, through the generated Kotlin. tests/fixtures.rs compares the transcripts. +// natively, through the Kotlin tests/fixtures/transcript writes from it, which calls the +// functions here that transcript.rs defines. tests/fixtures.rs compares the transcripts. // -// With an argument, it instead checks the futures' semantics, or breaks a contract, which -// must fail. +// With an argument, it instead checks the futures' semantics, what the GC frees, what +// only Kotlin's types bound, or breaks a contract, which must fail. @file:OptIn(ExperimentalUnsignedTypes::class) @@ -27,7 +28,7 @@ import kotlinx.coroutines.withTimeout annotation class OwnFrame // The Log callback: keeps even levels. -class PrintLog : Log, AutoCloseable { +class Print : Log, AutoCloseable { override fun log(level: UByte, line: String): Boolean { println("log $level $line") return level.toInt() % 2 == 0 @@ -51,310 +52,79 @@ fun numbers(what: String, n: Numbers) { println("$what some ${n.some?.let { "Some(${it.contentToString()})" } ?: "None"}") } -fun bound(b: BoundU64): String = when (b.kind) { - Bound.INCLUDED -> "Included(${b.value})" - Bound.EXCLUDED -> "Excluded(${b.value})" - Bound.UNBOUNDED -> "Unbounded" +/** A path's bytes as Rust's `escape_ascii` prints them. */ +fun escaped(path: PathBuf): String = path.toByteArray().joinToString("") { + when (val b = it.toInt() and 0xff) { + '\t'.code -> "\\t" + '\r'.code -> "\\r" + '\n'.code -> "\\n" + '\\'.code, '\''.code, '"'.code -> "\\${b.toChar()}" + in 0x20 until 0x7f -> b.toChar().toString() + else -> "\\x%02x".format(b) + } } -fun script() { - println("limit $LIMIT") +/** Bytes in hex, as transcript.rs prints them. */ +fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) } - val p = Point(1, 2).offset(2, 3) - println("offset ${p.x} ${p.y}") - println("debug ${p.debug()}") - println("eq ${p == Point(3, 5)}") - val d = Point.default() - println("default ${d.x} ${d.y}") +fun hex(array: ArrayU8x4): String = hex(array.toByteArray()) - val c = Counter.new("c", 5u) - println("get ${c.get()}") - println("name ${c.name()}") - println("add ok ${c.add(10u)}") - try { - c.add(2000u) - } catch (e: ErrorException) { - println("add err ${e.message} ${e.error.debug()}") - } - try { - c.sub(20u) - } catch (e: ErrorException) { - println("sub err ${e.message} ${e.error.debug()}") - } - c.rename("d") - println("name ${c.name()}") - println("is d ${c.`is`("d")}") - c.clone().use { copy -> - copy.add(1u) - println("clone ${copy.get()} original ${c.get()}") - } - println("debug ${c.debug()}") - val label = c.intoLabel(p) - println("label ${label.debug()}") - println("note ${hasText(Note(""))} ${hasText(Note(null))}") - - val (below, above) = Counter.new("s", 7u).split(5u) - println("split ${below.name()} ${below.get()} ${above.name()} ${above.get()}") - val (only) = only(Counter.new("o", 3u)) - println("only ${only.name()} ${only.get()}") - val (w8, w16, w32, w64) = widths(98305u) - println("widths $w8 $w16 $w32 $w64") - for (b in listOf(2uL, 0uL)) { - try { - val (q, r) = divide(7u, b) - println("divide $q $r") - } catch (e: ErrorException) { - println("divide err ${e.message}") - } - } - // A tuple inside another type is a Pair, a Triple, or a longer tuple class. - for (n in listOf(98305uL, 0uL)) { - val spread = spread(n) - println(if (spread == null) "spread none" else "spread ${spread.first} ${spread.second} ${spread.third} ${spread.fourth}") - } - for (needle in listOf("lo", "x")) { - val found = find(Bytes("hello".encodeToByteArray()), Bytes(needle.encodeToByteArray())) - println(if (found == null) "find none" else "find ${found.first} ${found.second}") - } - val statRows = rows(listOf(Point(1, 2), Point(3, 3))) - println("rows ${statRows.joinToString(", ") { (name, shape, p) -> "$name ${shape.debug()} ${p.x} ${p.y}" }}") - // Each handle in a tuple moves in, as one taken by value does. - Board.new(listOf(Pair("low", Counter.new("l", 1u)), Pair("high", Counter.new("h", 9u)))).use { board -> - val ranked = board.ranked() - println("ranked ${ranked.joinToString(", ") { (name, counter) -> "$name ${counter.name()} ${counter.get()}" }}") - ranked.forEach { it.second.close() } - board.best().use { println("best ${it.name()} ${it.get()}") } - } - // A map crosses as its pairs and a set as its items, which Rust collects in order, each - // key once, the last kept. - val atlas = Atlas(listOf(Pair("b", Point(1, 1)), Pair("ab", Point(2, 3)), Pair("b", Point(4, 4))), listOf(3u, 1u, 3u)) - .with("c", Point(5, 6)) - val atlasPoints = atlas.points.joinToString(", ") { (name, p) -> "$name ${p.x} ${p.y}" } - println("atlas $atlasPoints; ids ${atlas.ids.joinToString(" ")}") - // Another crate's error crosses as its message. - for (text in listOf("80", "x")) { - try { - println("port ${port(text)}") - } catch (e: StringException) { - println("port err ${e.error}") - } - } - val span = Span(Pair(2u, 10u), Pair("s", Shape.SQUARE)) - val (lowerHalf, upperHalf) = halves(span) - println("halves ${lowerHalf.first} ${lowerHalf.second} ${upperHalf.first} ${upperHalf.second} ${span.debug()}") - val (swappedN, swappedText) = swapped(Pair("t", 4u)) - println("swapped $swappedN $swappedText") - for (value in listOf(null, Tuple1(null), Tuple1(3u))) { - val doubled = doubled(value) - println(if (doubled == null) "doubled None" else "doubled Some((${doubled.first?.let { "Some($it)" } ?: "None"},))") - } - // A borrowed or boxed tuple of one is a tuple, not its element. - val lentOne = lentBack(Tuple1(Bytes(byteArrayOf(1, 2)))).first.toByteArray().toList() - val boxedOne = boxedTuple(Bytes(byteArrayOf(3))).first.toByteArray().toList() - println("lent back $lentOne boxed $boxedOne") - // A borrowed string and an owned one share a tuple struct. - println("title Some((\"${title(true)!!.first}\",)) ${if (title(false) == null) "None" else "Some"} named Some((\"${named("x")!!.first}\",))") - - // Each lent counter is a new handle to a clone. - val registry = Registry.new(Counter.new("first", 1u)) - println("last ${registry.last() != null}") - registry.push(Counter.new("last", 2u)) - val first = registry.firstGet - first.add(10u) - println("first ${registry.firstGet.get()} lent ${first.get()}") - val last = registry.last()!! - last.add(10u) - println("last ${registry.last()!!.get()} lent ${last.get()}") - // A closure lent for the call edits the first counter through a handle. - val by = 5uL - val edited = registry.edit { counter -> - counter.add(by) - counter.edited() && counter.get() == 6uL - } - println("edit $edited ${registry.firstGet.get()}") - // A setter moves an object in, as assignment does, closing its handle. - registry.firstSet(Counter.new("second", 3u)) - println("set first ${registry.firstGet.get()} ${registry.firstGet.name()}") - println("walk ${walk(3u) { cursor -> cursor.at() * 2u }}") - println("each ${each(2u) { at -> println("visit $at") }}") - println("offset ${offset({ 7u }, 3u)}") - println("shift ${shift({ 7u }, 4u)}") - - val name = Name.owned("a") - val joined = name.join(Name.owned("b")) - println("joined ${joined.asStr()} ${joined.debug()} ${joined == name}") - joined.rename("c") - println("renamed ${joined.asStr()}") - val long = longer(joined, Name.owned("dd")) - println("longer ${long.asStr()}") - println("unnamed [${unnamed().asStr()}]") - val lit = Name.borrowed("lit") - println("borrowed ${lit.asStr()} ${lit.shares(Name.borrowed("lit"))} ${lit.shares(Name.borrowed("other"))}") - - println("total ${total(RangeU64(2u, 5u))}") - println("reach ${reach(2u, 5u)}") - val two = java.math.BigInteger.valueOf(2) - val scaled = listOf(scaled(two.pow(128) - java.math.BigInteger.ONE, 1u), scaled(two.pow(64) + java.math.BigInteger.ONE, 1uL shl 63), scaled(two.pow(127), 2u)) - println("scaled " + scaled.joinToString(" ") { it?.toString(16)?.padStart(32, '0') ?: "none" }) - for (v in listOf(two.pow(128), java.math.BigInteger.ONE.negate())) { - check(runCatching { scaled(v, 1u) }.exceptionOrNull() is IllegalArgumentException, "$v is no u128") - } - Digest.new().use { digest -> - digest.sumSet(fingerprint("deadbeef")) - val unparsed = try { - fingerprint("zz").toString() - } catch (e: StringException) { - e.error - } - println("digest ${digest.sumGet} ${digest.flipped(ArrayU8x4(byteArrayOf(-1, 0, -1, 0)))} $unparsed") - check(runCatching { ArrayU8x4(ByteArray(3)) }.exceptionOrNull() is IllegalArgumentException, "3 bytes are no [u8; 4]") - } - Batch.new().use { batch -> - pair().use { batch2 -> - val accepted = (1u..5u).count { batch.push(it) } - val paired = (1u..3u).count { batch2.push(it) } - val emptied = drain4(batch) - println("batch ${batch.capacity()} $accepted $emptied ${drain4(batch)} ${batch2.capacity()} $paired ${drain2(batch2)}") - println("capacities ${capacities42(batch, batch2)} ${capacities22(batch2, batch2)}") - } - } - val wide = widen(RangeU64(2u, 5u), 1u) - println("widen ${wide.start} ${wide.end}") - val counts = listOf( - BoundsU64(BoundU64(Bound.INCLUDED, 2u), BoundU64(Bound.EXCLUDED, 5u)), - BoundsU64(BoundU64(Bound.INCLUDED, 2u), BoundU64(Bound.INCLUDED, 5u)), - BoundsU64(BoundU64(Bound.INCLUDED, 3u), BoundU64(Bound.UNBOUNDED, 0u)), - BoundsU64(BoundU64(Bound.UNBOUNDED, 0u), BoundU64(Bound.UNBOUNDED, 0u)), - BoundsU64(BoundU64(Bound.EXCLUDED, 2u), BoundU64(Bound.INCLUDED, 4u)), - ).map { count(it) } - println("count ${counts.joinToString(" ")}") - println("end ${bound(end(3u))} ${bound(end(0u))}") - val (endsStart, endsEnd) = ends(3u) - println("ends ${bound(endsStart)} ${bound(endsEnd)}") - for (n in listOf(2uL, 5uL)) { - try { - println("below ${below(n, 3u)}") - } catch (e: BoundsU64Exception) { - println("below err ${bound(e.error.start)} ${bound(e.error.end)}") - } - } - val window = Window(RangeU64(2u, 8u), end(5u)) - println("window ${window.contains(4u)} ${window.contains(6u)} ${window.debug()}") - - println(greet("x", Shape.SQUARE)) - println("len ${len(Bytes("abc".encodeToByteArray()))}") - val binary = Bytes(byteArrayOf(0xff.toByte(), 0, 'a'.code.toByte())) - println("hex ${hex(binary)}") - println("timed hex ${timedHex(binary)}") - println("sample hex ${sampleHex(binary)}") - println("queued hex ${queuedHex(binary)}") - println("tick ${tickName(Label("tick", null, null))}") - println("rooted ${rootedName(Label("rooted", null, null))}") - println("stored ${storedText("stored")}") - println("layer ${layerName(Label("layer", null, null))}") - for (event in listOf(Event.Moved(p), Event.Named("n"), Event.Done)) { - println(describe(event)) - } +fun pathHex(path: PathBuf): String = hex(path.toByteArray()) - // A `Copy` handle passed by value is copied, so it stays usable. - val stamp = Stamp.fromMillis(2500u) - println("secs ${stamp.secs()}") - println("later ${Stamp.fromMillis(3000u).later(stamp)}") - println("secs ${stamp.secs()}") - println("whole ${stamp.whole().debug()}") - val message = Message.new(stamp, Bytes("body".encodeToByteArray())) - println("payload ${message.payloadGet.text()}") - println("stamp ${message.stampGet!!.debug()}") - println("sent ${message.sent()}") - // Setters assign in place: the bytes are copied in, and a `Copy` handle copied. - val reset = Stamp.fromMillis(4000u) - message.stampSet(reset) - message.payloadSet(Bytes("edited".encodeToByteArray())) - println("payload ${message.payloadGet.text()}") - println("stamp ${message.stampGet!!.debug()}") - println("secs ${reset.secs()}") - message.stampSet(null) - println("stamp ${message.stampGet != null}") - - // A value past a word, copied across: a closure takes and returns one by value. - val moment = Moment.new(1500u, 1000u)!! - println("moment ${moment.millis()} ${Moment.new(1u, 0u) == null}") - val shifted = shifted(moment) { m -> m.after(500u) } - println("shifted ${shifted.millis()} ${shifted == moment.after(500u)}") - println("wrapped ${moment.after(ULong.MAX_VALUE).millis()} ${moment == shifted}") - // A record holding one crosses as its words, in and out, and a call with no slots - // left for one passes it encoded. - val clocked = clockedAfter(Clocked(moment, 1u), 500u) - check(clocked == Clocked(moment.after(500u), 2u) && clocked.at.millis() == 2000uL, "a record's moment crosses as its words") - check(crammed(moment, shifted, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL) == 1500uL + 2000uL + 124uL, "a crammed call passes its last moment encoded") - // A `Result` of one returns it directly, or throws. - check(momentAt(1500u, 1000u) == moment && stampAt(5u) == Stamp.fromMillis(5u), "a result's value returns directly") - check(runCatching { momentAt(1u, 0u) }.isFailure && runCatching { stampAt(0u) }.isFailure, "a result's error throws") - // One of 128 words is made with no constructor of a parameter each, and passed encoded. - val broad = Wide.new(ULong.MAX_VALUE) - check(broad.sum() == 8001uL - 1uL && broad == Wide.new(ULong.MAX_VALUE) && broad != Wide.new(0u), "a wide value crosses") +/** A duration as its seconds and nine digits of nanoseconds. */ +fun seconds(d: Duration): String = "${d.secs}.${d.nanos.toString().padStart(9, '0')}" + +/** A duration in whole milliseconds. */ +fun millis(d: Duration): ULong = d.secs * 1000uL + d.nanos / 1_000_000u + +/** A char's code point, which Kotlin holds it as. */ +fun code(c: Int): UInt = c.toUInt() + +fun reversed(list: List): List = list.reversed() + +fun f64Bits(floats: DoubleArray): ULongArray = ULongArray(floats.size) { floats[it].toRawBits().toULong() } + +/** An address's octets in hex, so their length shows its family. */ +fun ipHex(ip: IpAddr): String = hex( + when (ip) { + is Ipv4Addr -> ip.octets() + is Ipv6Addr -> ip.octets() + }, +) + +/** A socket address as its IP's octets in hex, its port, flow label, and scope, each IPv6's alone. */ +fun socketHex(addr: SocketAddr): String = when (addr) { + is SocketAddrV4 -> "${hex(addr.ip.octets())}:${addr.port}" + is SocketAddrV6 -> "${hex(addr.ip.octets())}:${addr.port}:${addr.flowinfo}:${addr.scopeId}" +} - // A value with padding, or bytes that vary, is a handle, as no table says where padding is. - val gap = Gap.new(7u, 3u) - println("gap ${gap.sum()} ${gap == Gap.new(7u, 3u)}") - val berth = Berth.new(4u) - println("berth Some(${berth.at()}) ${if (Berth.new(null).at() == null) "None" else "Some"}") - - // A `Copy` type changed in place is a value, which a `&mut self` method returns as the - // call left it, Rust's own return beside it: a change reaches only the copy it replaces. - var score = Score.of(2u) - val step = Score.of(3u) - score = score.add(step) - score = score.add(step) - println("score ${score.count()} ${step.doubled().count()} ${step.count()}") - var scoreCopy = score - val (taken, taken0) = scoreCopy.take() - scoreCopy = taken - println("taken $taken0 ${scoreCopy.count()} ${score.count()}") - val otherScore = Mut(step) - val (absorbed, before0, before1) = scoreCopy.absorb(otherScore) - scoreCopy = absorbed - println("absorbed $before0 $before1 ${scoreCopy.count()} ${otherScore.value.count()} ${step.count()}") - var hits = Hits.of(1u, 2u) - val keptHits = hits - hits = hits.add(Hits.of(10u, 20u)) - hits = hits.hitsSet(7u) - println("hits ${hits.hitsGet} ${hits.missesGet} ${keptHits.hitsGet} ${keptHits.missesGet} ${hits == keptHits}") - val (counted, countedSame) = keptHits.eq(keptHits) - println("counted $countedSame ${counted.hitsGet}") - var extent = Extent.new(5u, 3u) - val extentStart = extent - val (slid, old) = extent.slide(10u) - extent = slid - extent = extent.startSet(extent.startGet + 1u) - println("extent $old ${extent.startGet} ${extent.end()} ${extentStart.startGet} ${extentStart.end()}") - val weighted = Weighted(step, 4u) - println("weighted ${weighted.total()} ${weighted.score.count() + step.count()}") - // A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. - val mark = Mark.of(1uL) - mark.add(2uL) - val parcel = Parcel(mark, Bytes("abc".encodeToByteArray())) - println("heft ${heft(Pair(mark, Bytes("ab".encodeToByteArray())), parcel, Pair(Counter.new("w", 1u), Bytes("abcd".encodeToByteArray())))}") - // A value's `&mut self` beside a checked handle. - val (noted, notedBefore) = Score.of(2uL).note(Mark.of(5uL)) - println("noted $notedBefore ${noted.count()}") - - println("kept ${emit(PrintLog(), Bytes(byteArrayOf(1, 2, 3, 4)))}") - Logger.new(PrintLog()).use { logger -> println("write ${logger.write("hi")}") } - println("dropped") - // Rust calls it on another thread, before the call returns. - val threshold = 2 - val kept = filter(Bytes(byteArrayOf(1, 2, 3, 4))) { level, line -> - println("filter $level $line") - level.toInt() > threshold +/** A path no Rust string spells: bytes that are not UTF-8, or on Windows, WTF-8's lone surrogate. */ +fun unspelled(): PathBuf = when (java.io.File.separatorChar) { + '\\' -> PathBuf(byteArrayOf(0xed.toByte(), 0xa0.toByte(), 0x80.toByte())) + else -> stray() +} + +/** The bytes as text. */ +fun Bytes.text(): String = toByteArray().decodeToString() + +fun check(ok: Boolean, what: String) { + if (!ok) { + System.err.println("failed: $what") + kotlin.system.exitProcess(1) } - println("filtered $kept") +} + +/** Whether [f] throws `IllegalArgumentException`, as a value its Rust type cannot hold does. */ +fun rejects(f: () -> Any?): Boolean = runCatching(f).exceptionOrNull() is IllegalArgumentException + +fun script() = transcript() +// A channel's futures, on a dispatcher the script drains, so it sees the receive pend and +// its wake queue the resume. +fun channel() { val channel = Channel.new() var wakes = 0 val waker = Waker { wakes++ } - // On a dispatcher the script drains, so it sees the receive pend and its wake queue - // the resume. val q = Queue() var got: Bytes? = null CoroutineScope(q.asCoroutineDispatcher()).launch { got = channel.recv() } @@ -406,396 +176,34 @@ fun script() { waiter.context().wake() } println("woken $wakes") +} - val list = Node.new(1u, null) - list.push(2u) - println("node ${list.sum()}") - - val tally = Tally.new() - tally.bump() - println("tally ${tally.bump()} ${tally == tally}") - println("both ${bumpBoth(tally, tally)}") - println("peek ${peek(tally) { lent -> lent.bump() }}") - - val area = grow(Area.new(Size(2u, 3u)), 1u) - val size = area.size() - println("area ${size.width} ${size.height} ${area.pixels()}") - - // Generic types, each at the instances it infers, named by their arguments. - val pair = PairU32(2u, 5u) - val swapped = pair.swap() - println("pair ${swapped.left} ${swapped.right} sum ${pair.sum()} ${pair.debug()} ${pair == swapped}") - println("even ${pair.even()} ${PairU32(7u, 7u).even()}") - // An instance renamed alone, beside another of `Pair` that keeps its name. - val sized: PairSizeU8 = tag(Size(1u, 2u), 3u) - val flipped: PairU8Size = sized.swap() - println("sized ${flipped.left} ${flipped.right.width} ${flipped.debug()}") - val beside = PairU32(258u, 9u).besideSize(sized.left) - println("beside ${beside.left} ${beside.debug()}") - // At its default, named as the type itself. - val stack = Stack.new() - for ((i, n) in listOf("a", "b").withIndex()) { - stack.push(Counter.new(n, i.toULong() + 1u)) - } - val top = stack.pop()!!.get() - println("stack ${stack.depth()} Some($top) ${stack.pop() != null} ${stack.pop() == null}") - // Generic functions and methods, at each implementation of the trait bounding them, by - // reference, which leaves Kotlin its handle. - val fromPoint = Counter.seededPoint("p", Point(-3, 4)) - val fromSize = Counter.seededSize("s", Size(5u, 6u)) - val fromCounter = Counter.seededCounter("c", fromPoint) - val fromPolar = Counter.seededPolarPoint("q", PolarPoint(1u, 2u)) - println( - "seeded ${fromPoint.get()} ${fromSize.get()} ${fromCounter.get()} ${fromPolar.get()} " + - "past ${stack.depthPastPoint(Point(1, 2))} seeds ${seedsPointSize(Size(2u, 3u))}", - ) - - // A trait implemented for `Point` and `&Point` apart: one instance. - println("weigh ${weighPoint(Point(-1, 2))}") - // A function named as the type it returns, and one named as a type it does not. - println("polar ${polarPoint(2u)!!.distance} ${polarPoint(0u) == null} area ${area(Size(2u, 3u))}") - // Two types whose paths join alike, the second kept apart where its path splits. - println("wind ${wind(PolarTurn(2u), Polar_Turn(3u))}") - // Names that clash in some language, each kept apart there. - val clashSpan = ClashSpan(4u) - ClashStore.new(7u).use { clashStore -> - val clashPair = Pair(Pair(1.toUByte(), 2.toUShort()), 3u) - val clashTriple = Tuple1(Triple(1.toUByte(), 2.toUShort(), 3u)) - println( - "clash ${ClashTone(440u).debug()} ${ClashTone_(3u).debug()} ${Cancelled(2u).debug()} " + - "span ${clashSpan.width()} ${clashSpan.toString_()} $clashSpan " + - "store ${clashStore.free()} ${clashStore.close_()} " + - "audio ${clashAudioEncoderFinish()} ${clashAudioEncoderFinish_()} nested ${clashNested(clashPair, clashTriple)}" - ) - } - // Instances that name each other, and one made only by an impl of it. - println("cross ${cross(LeftRightU8(RightU8(1u)), RightLeftU8(LeftU8(2u)))} outer ${OuterInnerU8.new(4u).get()}") - // A bound that outlives the call takes a value, and an instance only a constant names. - println("kept ${keptPoint(Point(1, -2))} boxed ${BOXED.value}") - println("keep ${keepPoint(Point(1, -2))}") - val five = Point(5, 2) - println("kept or ${keptOrPoint(five)} ${keptOrPoint(null)} keeper ${keeperPoint(five)}") - // Inferred instances taking a lent closure and a foreign implementation, and one only - // its impl of a trait names. - val sides = PairU32(2u, 5u) - println("apply ${applyU32(sides) { side -> side * 3u }}") - println("report ${reportU32(sides, PrintLog())}") - println("wrapped ${keptWrapU32(WrapU32(4u))}") - println("keeps ${keeps(PrintLog()).value}") - - // Its Drop runs when Kotlin closes the handle, not before. - val token = Token.new(7u) - println("token ${token.idGet} dropped ${dropped()}") - token.close() - println("dropped ${dropped()}") - - // A field and the method of its name, each its own member. - val retry = Retry.new(5u) - val limit = retry.limitGet - println("retry ${if (limit != null) 1 else 0} ${limit ?: 0u} ${retry.limit()} ${retry.delay()}") - // The renamed field's setter, named as its getter. - retry.limitSet(null) - println("retry ${retry.limit()}") - println("slot ${SlotU8.new(200u).value()}") - - // Foreign types: a URL parsed from text, socket addresses, OS paths, and `Vec`s. - val base = Url.parse("https://example.com/a/b") - println("url $base host ${host(base)?.let { "Some(\"$it\")" } ?: "None"}") - resolve(base.clone(), "c?d").use { url -> println("resolve $url ${url == base}") } - try { - Url.parse("no scheme").close() - } catch (e: StringException) { - println("parse err ${e.error}") - } - val v4 = SocketAddrV4(Ipv4Addr(127u, 0u, 0u, 1u), 8080u) - val loopback = ByteArray(16).also { it[15] = 1 } - val v6 = SocketAddrV6(Ipv6Addr(loopback), 443u, 0u, 3u) - println("ports ${ports(listOf(v4, v6)).contentToString()}") - val peer = Peer(v6, listOf("a", "b")).next("c") - println("peer ${peer.debug()} ${peer.aliases().joinToString(", ", "[", "]") { "\"$it\"" }}") - val file = file(PathBuf("dir"), "f\\'\"\t") - println("file ${escaped(file)}") - println("parents ${parents(listOf(file, PathBuf("/"))).joinToString(" ") { it?.let(::escaped) ?: "none" }}") - val words = words(" one two three ") - println("words ${words.size} ${words.joinToString(", ", "[", "]") { "\"$it\"" }}") - println("sentence ${sentence(words)} ${sentence(null)}") - println("sentence ${sentence(emptyList())}|") - println("either ${either("abc")} ${either(null)}") - val cd = Bytes("cd".encodeToByteArray()) - println("prefixed ${prefixed(cd, Bytes("ab".encodeToByteArray())).toByteArray().decodeToString()} ${prefixed(cd, null).toByteArray().decodeToString()}") - println("coordinates ${coordinates(Point(2, 3))} ${coordinates(null)}") - Counter.new("two", 2u).use { two -> - Counter.new("three", 3u).use { three -> - println("plus ${two.plus(three)} ${two.plus(null)}") - println("add_to ${two.addTo(three)} ${two.addTo(null)} ${three.get()}") - check(two.offset(3u, 4u) == 36uL, "a method's parameters named handle and h are its own") - } - } - check(Counter.new("five", 5u).intoSum(1u) == 6uL, "a consuming method's parameter named close is its own") - // A function taking a JNI env, which Kotlin alone exports, passing its thread's. - val any = Any() - check(sameObject(any, any) && !sameObject(any, Any()) && sameObject(null, null) && !sameObject(any, null), "a JObject crosses as the reference Kotlin passed") - Counter.new("five", 5u).use { five -> - check(five.plusIfString(2u, "s") == 7uL && five.plusIfString(2u, 1) == 5uL, "a method takes the env between parameters Kotlin passes") - check((runCatching { five.plusIfString(2u, null) }.exceptionOrNull() as? StringException)?.error == "the object is null", "a JNI function's error throws") - } - for (fail in listOf(false, true)) { - val thrown = runCatching { thrown(fail) }.exceptionOrNull() - check(thrown is IllegalStateException && thrown.message == "thrown", "an exception the Rust left pending throws, failing or not") - } - var closed = false - val sink = object : Log, AutoCloseable { - override fun log(level: UByte, line: String): Boolean = true - - override fun close() { - closed = true - } - } - val dropped = runCatching { thrownLogger(sink) }.exceptionOrNull() - check(dropped is IllegalStateException && dropped.message == "logger" && closed, "a result dropped for a pending exception closes its callback, then throws it") - check(jniOne() == 1u, "a facade module named jni is the facade's") - val encoded = Mut(Bytes("0,".encodeToByteArray())) - putNumber(1u, encoded) - putNumber(23u, encoded) - println("put_number ${encoded.value.toByteArray().decodeToString()}") - val entry = Mut(Pair(Bytes("ab".encodeToByteArray()), 1u)) - val stamps = pushCounted(entry, 'c'.code.toUByte()) - println("push_counted $stamps ${entry.value.first.toByteArray().decodeToString()} ${entry.value.second}") - val digits = Mut(Bytes("7x9".encodeToByteArray())) - val firstDigit = digit(digits) - val skipped = try { - digit(digits) - false - } catch (e: ErrorException) { - true - } - println("digit $firstDigit $skipped ${digit(digits)} ${digits.value.size}") - val nudged = Mut(Point(1, 2)) - nudge(nudged, 3) - println("nudge ${nudged.value.x} ${nudged.value.y}") - secure("h3").use { config -> println("secure ${alpnLent(config)} ${alpn(config.clone())}") } - val cert = certify(Bytes("der".encodeToByteArray())) - val certLen = certLen(cert) - println("cert $certLen ${certDer(cert).text()} ${chainLen(listOf(certify(Bytes("a".encodeToByteArray())), certify(Bytes("bc".encodeToByteArray()))))}") - // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. - println("resolver ${resolved(resolver("r1"))}") - Codecs.new().use { codecs -> - println("codecs ${codecs.ids()}") - codecs.listSet(codecs.listGet.reversed()) - println("codecs reversed ${codecs.ids()}") - } - // A standard library value no type maps, in a handle. - val failure = failure("boom") - println("failure ${failureMessage(failure)} ${failureKind(failure)}") - // Iterators, passed as the arrays of their items. - println("sum_all ${sumAll(listOf(1u, 2u, 3u))}") - println("weigh_all ${weighAllCounter(listOf(Counter.new("w", 3u)))}") - println("offered_len ${offeredLen(listOf(Bytes("h3".encodeToByteArray()), Bytes("moq-00".encodeToByteArray())))}") - println("join_words ${joinWords(listOf("a", "b", "c"))}") - // Bytes that must be `'static`, interned. - Der.fromSlice(Bytes("der".encodeToByteArray())).use { println("der ${it.bytes().text()}") } - Der.fromSlice(Bytes("der".encodeToByteArray())).use { println("der again ${it.bytes().text()}") } - resume("h3", 60u).use { session -> println("resume ${session.alpn()} ${session.lifetime().seconds}") } - try { - resume("", 60u) - } catch (e: StringException) { - println("resume err ${e.error}") - } - Meters.new().use { meters -> - meters.first().use { first -> - first.add(2uL) - println("lent ${first.add(3uL)} ${meters.first().use { it.count() }}") - } - meters.clear() - println("cleared ${meters.first().use { it.count() }}") - meters.lastGet.use { last -> - last.add(4uL) - println("field lent ${last.add(1uL)}") - } - // An optional field that is not Clone, lent as `Some` of a handle. - println("spare ${meters.spareGet != null}") - meters.spareSet(Meter.default()) - meters.spareGet!!.use { spare -> - spare.add(5uL) - println("spare lent ${spare.add(1uL)}") - } - } - Tallies.new().use { tallies -> - tallies.first().use { it.bump() } - println("tallied ${tallies.first().use { it.bump() }}") - } - // A draft borrowing its ledger exclusively until it closes, through which its sheet's - // members are reached by Deref and DerefMut: the ledger refuses any other use meanwhile. - Ledger.new().use { ledger -> - val draft = ledger.edit() - draft.titleSet("minutes") - draft.write("first") - println("draft ${draft.titleGet} ${draft.lines()} ${draft.describe()} ${draft.edited()}") - val refused = runCatching { ledger.published() }.exceptionOrNull() - check( - refused is IllegalStateException && refused.message == "api_Ledger_published: a handle is borrowed exclusively", - "a lent ledger refuses a read: $refused", - ) - println("committed ${draft.commit()}") - println("ledger ${ledger.title()} ${ledger.published()}") - ledger.edit().use { println("read ${it.lines()} ${it.edited()}") } - ledger.edit().use { it.write("second") } - println("dropped ${ledger.published()}") - println("receipt ${ledger.receipt().use { it.count() }}") - Marker.new("m", 3, 5).use { marker -> - marker.ySet(7) - val title = PadU16.wide().use { it.title() } - val lines = Layered.new().use { it.lines() } - val small = PadU8.small().use { it.describe() } - val wide = PadU16.wide().use { it.describe() } - println("forwarded $title $lines ${marker.xGet} ${marker.yGet} [$small] [$wide]") - } - ledger.seal() - try { - ledger.edit().close() - } catch (e: ErrorException) { - println("sealed ${e.message}") - } - } - println("chunks ${chunks(Bytes("abcde".encodeToByteArray()), 2uL).map { it.toByteArray().toList() }}") - val counters = counters(listOf("x", "y")) - println("counters ${counters.joinToString(", ") { "${it.name()} ${it.get()}" }}") - // Each counter moves in, so Kotlin closes it. - println("worth ${worth(listOf(counters[0]), listOf(counters[1]))} ${worth(null, emptyList())}") - for (counter in counters) { - check(runCatching { counter.get() }.exceptionOrNull() is IllegalStateException, "a counter moved in is closed") - } - println("held ${listOf(heldCount(Tuple1(Counter.new("h", 4u))), heldCount(null)).joinToString(" ") { if (it == null) "None" else "Some($it)" }}") - println("boxed ${boxedName(boxedCounter("b"))?.let { "Some(\"$it\")" }} ${boxedName(null) ?: "None"} ${boxedCounter(null) == null}") - println("less ${less(5u, 2u)}") - println("sums ${sums(listOf(uintArrayOf(1u, 2u), UIntArray(0), uintArrayOf(3u))).contentToString()}") - println("least ${least(listOf(listOf(3u, 1u), listOf(), listOf(2u))).joinToString(" ")}") - check(splitLast(intArrayOf(1, 2, -3)) == splitLast(intArrayOf(1, 2, -3)), "a tuple holding an array compares by contents") - check(splitLast(intArrayOf(1, 2, -3)).hashCode() == splitLast(intArrayOf(1, 2, -3)).hashCode(), "a tuple holding an array hashes by contents") - check(Shadowed(intArrayOf(1), 0u, 0u) == Shadowed(intArrayOf(1), 0u, 0u) && Shadowed(intArrayOf(1), 0u, 0u) != Shadowed(intArrayOf(2), 0u, 0u), "a field named other compares as itself") - check(Builtin.Any(intArrayOf(1)) == Builtin.Any(intArrayOf(1)) && Builtin.Any(intArrayOf(1)).hashCode() == Builtin.Any(intArrayOf(1)).hashCode(), "a variant named Any compares by contents") - check(Builtin.Native(Double.NaN) != Builtin.Native(Double.NaN) && Builtin.Int(-0.0) == Builtin.Int(0.0) && Builtin.Boolean(1.0) != Builtin.Int(1.0), "variants named as Kotlin's builtins compare as Rust's") - check(Qualifiers(-0.0, 1.0) == Qualifiers(0.0, 1.0) && Qualifiers(-0.0, 1.0).hashCode() == Qualifiers(0.0, 1.0).hashCode() && Qualifiers(Double.NaN, 1.0) != Qualifiers(Double.NaN, 1.0), "fields named as the package and kotlin compare as Rust's") - numbers("edges", Numbers.edges()) - numbers("reversed", Numbers.edges().reversed()) - val edges = Numbers.edges() - val nan = Measure.new(Double.NaN, false) - println("float equal ${edges == edges} ${edges == Numbers.edges()} ${Numbers.zero(true) == Numbers.zero(false)} ${nan == nan} ${Measure.new(-0.0, true) == Measure.new(0.0, false)}") - check(Numbers.zero(true).hashCode() == Numbers.zero(false).hashCode(), "a negative zero hashes as zero does") - check(Measure.new(-0.0, true).hashCode() == Measure.new(0.0, false).hashCode(), "a negative zero hashes as zero does in a nested record") - val ints = edges.copy(f32s = FloatArray(0), f64s = DoubleArray(0)) - val alike = Numbers.edges().copy(f32s = FloatArray(0), f64s = DoubleArray(0)) - check(ints == alike && ints.hashCode() == alike.hashCode(), "records of arrays compare by contents") - val back = edges.reversed().reversed() - check(back.copy(f32s = FloatArray(0), f64s = DoubleArray(0)) == ints, "every integer edge value crosses both ways exactly") - check(back.f32s.map { it.toRawBits() } == edges.f32s.map { it.toRawBits() } && back.f64s.map { it.toRawBits() } == edges.f64s.map { it.toRawBits() }, "every float edge value crosses both ways exactly") - check(edges.copy(some = null).reversed().some == null, "a missing array stays missing") - check(edges.copy(some = IntArray(0)).reversed().some?.size == 0, "an empty array is no missing one") - check(edges.copy(some = intArrayOf(Int.MIN_VALUE, 7)).reversed().some.contentEquals(intArrayOf(7, Int.MIN_VALUE)), "an array in an option crosses in a record") - println("sum u32 ${sumU32(UIntArray(0))} ${sumU32(uintArrayOf(UInt.MAX_VALUE, UInt.MAX_VALUE, 2u))}") - println("doubled i64 ${doubledI64(longArrayOf(Long.MIN_VALUE, -1, 0, Long.MAX_VALUE)).contentToString()}") - val floats = boxedFloats(doubleArrayOf(-0.0, Double.fromBits(0x7ff8000000000001L))) - println("boxed floats ${floats.map { it.toRawBits().toULong() }}") - val summed = summed(listOf(Point(1, 2), Point(-4, 6))) - val noneSummed = summed(emptyList()) - println("summed ${summed.x} ${summed.y} ${noneSummed.x} ${noneSummed.y}") - println("longest ${longest(listOf("a", "abc"))} ${longest(emptyList())}") - println("first of Some(\"${firstOf(listOf("a", "b"))}\") ${firstOf(emptyList()) ?: "None"}") - val limits = byteLimits(Bytes("a".encodeToByteArray()), Bytes("bc".encodeToByteArray())) - val waits = breadth(LimitsDuration(Duration(5.milliseconds), Duration(2.seconds))) - println("limits ${limits.low.toByteArray().decodeToString()} ${limits.high.toByteArray().decodeToString()} breadth ${waits.toKotlinDuration().inWholeMilliseconds}") - val parts = joined(listOf(Bytes("ab".encodeToByteArray()), Bytes(ByteArray(0)), Bytes("c".encodeToByteArray()))).toByteArray().decodeToString() - println("joined $parts ${joined(emptyList()).toByteArray().size} read ${readLen(Bytes("hello".encodeToByteArray()))}") - val doc = Json.parse("""{"b": [1, 2.5, null], "a": "\u00e9"}""") - println("json ${encode(doc)}") - println("timed text ${timedText(doc)}") - tagged(doc, "t").use { tagged -> println("tagged ${tagged.toText()}") } - // A JSON object's entries cross as pairs of a key and its document, each moved in. - val jsonEntries = entries(listOf(Pair("b", Json.parse("[1]")), Pair("a", Json.parse("2"))), "t") - println("entries ${jsonEntries.joinToString(", ") { (key, value) -> "$key ${value.toText()}" }}") - jsonEntries.forEach { it.second.close() } - try { - Json.parse("{\"a\":").close() - } catch (e: StringException) { - println("json parse err ${e.error}") - } - val site = Site.new(base) - site.homeGet.use { a -> site.homeGet.use { b -> println("site $a $b") } } - - // Slices, passed in and returned as clones, and the socket address of each family. - println("shapes ${Shape.ALL.joinToString(", ", "[", "]") { it.debug() }} greetings ${GREETINGS.joinToString(", ", "[", "]") { "\"$it\"" }}") - println("both ${Shape.BOTH.joinToString(", ", "[", "]") { it.debug() }} primes ${PRIMES.joinToString(", ", "[", "]")}") - Trail.new(listOf(Point(1, 2), Point(3, 4)), listOf("a", "b")).use { trail -> - println("trail ${trail.points().joinToString(", ", "[", "]") { it.debug() }} ${trail.labels().joinToString(", ", "[", "]") { it.debug() }}") - // Returned iterators, each collected at the call: drained labels are gone after. - println("iterated ${trail.iter().joinToString(", ", "[", "]") { it.debug() }} ${trail.names().joinToString(", ", "[", "]") { "\"$it\"" }} ${trail.bytes().toByteArray().joinToString(", ", "[", "]") { it.toUByte().toString() }}") - println("drained ${trail.drain().joinToString(", ", "[", "]") { it.debug() }} then ${trail.labels().joinToString(", ", "[", "]") { it.debug() }}") - // A filter, collected at the call. - println("beyond ${trail.beyond(1).joinToString(", ") { "${it.x} ${it.y}" }}") - } - val numbered = numbered(listOf("p", "q")) - println("numbered ${numbered.joinToString(", ") { "${it.name()} ${it.get()}" }}") - numbered.forEach { it.close() } - val (next4, next6) = nexts(v4, v6) - println("nexts ${next4.ip} ${next4.port} ${next6.port} ${next6.scopeId}") - val (nextIp4, nextIp6) = nextIps(Ipv4Addr(10u, 0u, 0u, 255u), Ipv6Addr(ByteArray(16).also { it[14] = -1; it[15] = -1 })) - val mapped = flip(Ipv4Addr(127u, 0u, 0u, 1u)) - val ips = listOf(nextIp4, nextIp6, mapped, flip(mapped), flip(Ipv6Addr(loopback))) - println("ips ${ips.joinToString(" ") { ipHex(it) }}") - lossless() - - // serde_json's map iterator, collected as pairs of a key and its document. - val jsonSections = sections(listOf(Pair("b", Json.parse("[1]")), Pair("a", Json.parse("2")))) - println("sections ${jsonSections.joinToString(", ") { (key, value) -> "$key ${value.toText()}" }}") - jsonSections.forEach { it.second.close() } - // An instant only Rust makes, which each call copies out of its handle, and compares. - val began = now() - val ended = later(began, Duration(1500.milliseconds)) - val same = later(began, Duration.ZERO) - println("instants ${since(ended, began).toKotlinDuration().inWholeMilliseconds} ${since(began, ended).toKotlinDuration().inWholeMilliseconds} ${began == same} ${began == ended}") - println("has_instant ${hasInstant(began)} ${hasInstant(null)}") - // tracing's level, and its filter as an optional level whose null is `OFF`. - Verbosity.new(Level.WARN).use { verbosity -> - println("verbosity ${spell(verbosity.filter())} ${spell(louder(verbosity.filter()))}") - verbosity.levelSet(Level.TRACE) - println("verbosity ${verbosity.levelGet == Level.TRACE} ${spell(verbosity.filter())} ${spell(louder(verbosity.filter()))} ${spell(louder(null))}") - } - - println("made ${made(3u) { n -> "$n times" }}") - // A closure taking and returning `Copy` values copies them, never running their `Clone`. - val nine = Ticket.new(9u) - val given = reissue(Ticket.new(7u)) { t -> Ticket.new(t.number() + 1u) }.number() - val held = reissue(Ticket.new(7u)) { nine }.number() - println("reissued $given $held, cloned ${Ticket.clones()}") - // A record's traits borrow the checked handle it holds. - val nines = Mark.of(9uL) - val front = seat(nines, 1u) - val rear = seat(nines, 2u) - println("seat ${front.debug()} ${front == front.copy()} ${front == rear}") - // A kept closure, called on another thread after the call that took it returned. - check(Spawned.new { 7u }.join() == 7u, "a kept closure runs on another thread") - // A kept closure: called again at the instant it asks for, then once its waiter wakes. - Moment.new(0u, 1000u)!!.let { start -> - var calls = 0 - val stopped = runBlocking { - drive(start) { now, waiter -> - calls += 1 - when (calls) { - 1 -> now.after(5u) - 2 -> { - println("drive ${now.millis() - start.millis()}") - waiter.waker().let { waker -> - waker.wake() - (waker as AutoCloseable).close() - } - null +// A kept closure: called again at the instant it asks for, then once its waiter wakes. +fun drive() { + val start = Moment.new(0u, 1000u)!! + var calls = 0 + val stopped = runBlocking { + drive(start) { now, waiter -> + calls += 1 + when (calls) { + 1 -> now.after(5u) + 2 -> { + println("drive ${now.millis() - start.millis()}") + waiter.waker().let { waker -> + waker.wake() + (waker as AutoCloseable).close() } - else -> throw StringException("stopped after $calls") + null } + else -> throw StringException("stopped after $calls") } } - println("drive $stopped") } + println("drive $stopped") +} + +// Readers over bytes, whose reads fail, and that seek past `Long.MAX_VALUE`. +fun readers() { for (file in listOf(Memory("hello world".encodeToByteArray()), Broken())) { try { val (tail, at) = tail(file, 5u) @@ -810,17 +218,10 @@ fun script() { } catch (e: StringException) { println("sought error ${e.error}") } - println("non zeros ${describeNonZeros(nonZeros())}") - for (hop in listOf(null, 1UL, ULong.MAX_VALUE)) { - println("hop ${nextHop(hop)?.let { "Some($it)" } ?: "None"}") - } - println("farther hop ${fartherHop(PairNonZeroU16(3u, UShort.MAX_VALUE))}") - val local = Local.new() - val shared = localOrNew(local) - val bumped = local.bump() - println("local $bumped ${shared.bump()}") - println("local fresh ${localOrNew(null).bump()}") - println("local either ${bumpEither(null, shared)}") +} + +// Futures of a value that is not `Send`, run on this thread. +fun localLater(local: Local) { println("local later ${runBlocking { localOrNewLater(local) }.bump()}") println("local later fresh ${runBlocking { localOrNewLater(null) }.bump()}") } @@ -877,86 +278,111 @@ open class Broken : java.nio.channels.SeekableByteChannel { override fun close() {} } -/** A path's bytes as Rust's `escape_ascii` prints them. */ -fun escaped(path: PathBuf): String = path.toByteArray().joinToString("") { - when (val b = it.toInt() and 0xff) { - '\t'.code -> "\\t" - '\r'.code -> "\\r" - '\n'.code -> "\\n" - '\\'.code, '\''.code, '"'.code -> "\\${b.toChar()}" - in 0x20 until 0x7f -> b.toChar().toString() - else -> "\\x%02x".format(b) +/** + * What the transcript's script says only in Rust: Kotlin's own errors, equality, and + * conversions, each value the Kotlin type holds and Rust's cannot, which throws, and each + * conversion to and from the idiomatic type, which throws where the other cannot hold a + * value exactly. + */ +fun checks() { + val two = java.math.BigInteger.valueOf(2) + for (v in listOf(two.pow(128), java.math.BigInteger.ONE.negate())) { + check(runCatching { scaled(v, 1u) }.exceptionOrNull() is IllegalArgumentException, "$v is no u128") } -} + check(runCatching { ArrayU8x4(ByteArray(3)) }.exceptionOrNull() is IllegalArgumentException, "3 bytes are no [u8; 4]") -/** The bytes as text. */ -fun Bytes.text(): String = toByteArray().decodeToString() + // A record holding a value past a word crosses as its words, in and out, and a call + // with no slots left for one passes it encoded. + val moment = Moment.new(1500u, 1000u)!! + val shifted = moment.after(500u) + val clocked = clockedAfter(Clocked(moment, 1u), 500u) + check(clocked == Clocked(moment.after(500u), 2u) && clocked.at.millis() == 2000uL, "a record's moment crosses as its words") + check(crammed(moment, shifted, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL, 1uL) == 1500uL + 2000uL + 124uL, "a crammed call passes its last moment encoded") + // A `Result` of one returns it directly, or throws. + check(momentAt(1500u, 1000u) == moment && stampAt(5u) == Stamp.fromMillis(5u), "a result's value returns directly") + check(runCatching { momentAt(1u, 0u) }.isFailure && runCatching { stampAt(0u) }.isFailure, "a result's error throws") + // One of 128 words is made with no constructor of a parameter each, and passed encoded. + val broad = Wide.new(ULong.MAX_VALUE) + check(broad.sum() == 8001uL - 1uL && broad == Wide.new(ULong.MAX_VALUE) && broad != Wide.new(0u), "a wide value crosses") -fun check(ok: Boolean, what: String) { - if (!ok) { - System.err.println("failed: $what") - kotlin.system.exitProcess(1) + Counter.new("two", 2u).use { two -> + check(two.offset(3u, 4u) == 36uL, "a method's parameters named handle and h are its own") } -} - -/** Bytes in hex, as transcript.rs prints them. */ -fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) } + check(Counter.new("five", 5u).intoSum(1u) == 6uL, "a consuming method's parameter named close is its own") + // A function taking a JNI env, which Kotlin alone exports, passing its thread's. + val any = Any() + check(sameObject(any, any) && !sameObject(any, Any()) && sameObject(null, null) && !sameObject(any, null), "a JObject crosses as the reference Kotlin passed") + Counter.new("five", 5u).use { five -> + check(five.plusIfString(2u, "s") == 7uL && five.plusIfString(2u, 1) == 5uL, "a method takes the env between parameters Kotlin passes") + check((runCatching { five.plusIfString(2u, null) }.exceptionOrNull() as? StringException)?.error == "the object is null", "a JNI function's error throws") + } + for (fail in listOf(false, true)) { + val thrown = runCatching { thrown(fail) }.exceptionOrNull() + check(thrown is IllegalStateException && thrown.message == "thrown", "an exception the Rust left pending throws, failing or not") + } + var closed = false + val sink = object : Log, AutoCloseable { + override fun log(level: UByte, line: String): Boolean = true -/** An address's octets in hex, so their length shows its family. */ -fun ipHex(ip: IpAddr): String = hex( - when (ip) { - is Ipv4Addr -> ip.octets() - is Ipv6Addr -> ip.octets() - }, -) + override fun close() { + closed = true + } + } + val dropped = runCatching { thrownLogger(sink) }.exceptionOrNull() + check(dropped is IllegalStateException && dropped.message == "logger" && closed, "a result dropped for a pending exception closes its callback, then throws it") + check(jniOne() == 1u, "a facade module named jni is the facade's") -/** A socket address as its IP's octets in hex, its port, flow label, and scope, each IPv6's alone. */ -fun socketHex(addr: SocketAddr): String = when (addr) { - is SocketAddrV4 -> "${hex(addr.ip.octets())}:${addr.port}" - is SocketAddrV6 -> "${hex(addr.ip.octets())}:${addr.port}:${addr.flowinfo}:${addr.scopeId}" -} + // A draft borrows its ledger exclusively until it closes: the ledger refuses any other + // use meanwhile. + Ledger.new().use { ledger -> + ledger.edit().use { draft -> + draft.write("first") + val refused = runCatching { ledger.published() }.exceptionOrNull() + check( + refused is IllegalStateException && refused.message == "api_Ledger_published: a handle is borrowed exclusively", + "a lent ledger refuses a read: $refused", + ) + } + } + // Each counter moves in, so Kotlin closes it. + val counters = counters(listOf("x", "y")) + worth(listOf(counters[0]), listOf(counters[1])) + for (counter in counters) { + check(runCatching { counter.get() }.exceptionOrNull() is IllegalStateException, "a counter moved in is closed") + } + // A kept closure, called on another thread after the call that took it returned. + check(Spawned.new { 7u }.join() == 7u, "a kept closure runs on another thread") -/** Whether [f] throws `IllegalArgumentException`, as a value its Rust type cannot hold does. */ -fun rejects(f: () -> Any?): Boolean = runCatching(f).exceptionOrNull() is IllegalArgumentException + check(splitLast(intArrayOf(1, 2, -3)) == splitLast(intArrayOf(1, 2, -3)), "a tuple holding an array compares by contents") + check(splitLast(intArrayOf(1, 2, -3)).hashCode() == splitLast(intArrayOf(1, 2, -3)).hashCode(), "a tuple holding an array hashes by contents") + check(Shadowed(intArrayOf(1), 0u, 0u) == Shadowed(intArrayOf(1), 0u, 0u) && Shadowed(intArrayOf(1), 0u, 0u) != Shadowed(intArrayOf(2), 0u, 0u), "a field named other compares as itself") + check(Builtin.Any(intArrayOf(1)) == Builtin.Any(intArrayOf(1)) && Builtin.Any(intArrayOf(1)).hashCode() == Builtin.Any(intArrayOf(1)).hashCode(), "a variant named Any compares by contents") + check(Builtin.Native(Double.NaN) != Builtin.Native(Double.NaN) && Builtin.Int(-0.0) == Builtin.Int(0.0) && Builtin.Boolean(1.0) != Builtin.Int(1.0), "variants named as Kotlin's builtins compare as Rust's") + check(Qualifiers(-0.0, 1.0) == Qualifiers(0.0, 1.0) && Qualifiers(-0.0, 1.0).hashCode() == Qualifiers(0.0, 1.0).hashCode() && Qualifiers(Double.NaN, 1.0) != Qualifiers(Double.NaN, 1.0), "fields named as the package and kotlin compare as Rust's") + val edges = Numbers.edges() + check(Numbers.zero(true).hashCode() == Numbers.zero(false).hashCode(), "a negative zero hashes as zero does") + check(Measure.new(-0.0, true).hashCode() == Measure.new(0.0, false).hashCode(), "a negative zero hashes as zero does in a nested record") + val ints = edges.copy(f32s = FloatArray(0), f64s = DoubleArray(0)) + val alike = Numbers.edges().copy(f32s = FloatArray(0), f64s = DoubleArray(0)) + check(ints == alike && ints.hashCode() == alike.hashCode(), "records of arrays compare by contents") + val back = edges.reversed().reversed() + check(back.copy(f32s = FloatArray(0), f64s = DoubleArray(0)) == ints, "every integer edge value crosses both ways exactly") + check(back.f32s.map { it.toRawBits() } == edges.f32s.map { it.toRawBits() } && back.f64s.map { it.toRawBits() } == edges.f64s.map { it.toRawBits() }, "every float edge value crosses both ways exactly") + check(edges.copy(some = null).reversed().some == null, "a missing array stays missing") + check(edges.copy(some = IntArray(0)).reversed().some?.size == 0, "an empty array is no missing one") + check(edges.copy(some = intArrayOf(Int.MIN_VALUE, 7)).reversed().some.contentEquals(intArrayOf(7, Int.MIN_VALUE)), "an array in an option crosses in a record") -/** - * Each type's edge values, passed through Rust and back, as transcript.rs prints them; then - * each value the Kotlin type holds and Rust's cannot, which throws, and each conversion to - * and from the idiomatic type, which throws where the other cannot hold a value exactly. - */ -fun lossless() { - val durations = listOf(Duration.ZERO, Duration(0u, 1u), Duration(9223372036u, 854775808u), Duration.MAX) - .map { sameDuration(it) } - println("lossless duration ${durations.joinToString(" ") { "${it.secs}.${it.nanos.toString().padStart(9, '0')}" }}") - println("lossless u64 ${sameU64(0u)} ${sameU64(1uL shl 63)} ${sameU64(ULong.MAX_VALUE)}") - println("lossless usize ${sameUsize(0u)} ${sameUsize(ULong.MAX_VALUE)}") - println("lossless isize ${sameIsize(Long.MIN_VALUE)} ${sameIsize(Long.MAX_VALUE)}") - val two = java.math.BigInteger.valueOf(2) - val wides = listOf(java.math.BigInteger.ZERO, two.pow(64), two.pow(128) - java.math.BigInteger.ONE) - println("lossless u128 ${wides.joinToString(" ") { sameU128(it).toString(16).padStart(32, '0') }}") - println("lossless char ${listOf(0, 0xd7ff, 0xe000, 0x10ffff).joinToString(" ") { sameChar(it).toString(16) }}") - // A path no Rust string spells: bytes that are not UTF-8, or on Windows, WTF-8's lone surrogate. - val unspelled = when (java.io.File.separatorChar) { - '\\' -> byteArrayOf(0xed.toByte(), 0xa0.toByte(), 0x80.toByte()) - else -> byteArrayOf(-1) - } - println("lossless path ${listOf(PathBuf("a/é"), PathBuf(unspelled)).joinToString(" ") { hex(samePath(it).toByteArray()) }}") - val v4 = sameSocketAddrV4(SocketAddrV4(Ipv4Addr(UInt.MAX_VALUE), UShort.MAX_VALUE)) - val v6 = sameSocketAddrV6(SocketAddrV6(Ipv6Addr(ByteArray(16).also { it[1] = 1; it[15] = 2 }), 3u, UInt.MAX_VALUE, UInt.MAX_VALUE)) - println("lossless socket ${socketHex(v4)} ${socketHex(v6)} ${listOf(v4, v6).joinToString(" ") { socketHex(sameSocketAddr(it)) }}") // Kotlin's own hash of a key is Rust's `Hash`, as its `equals` is Rust's `==`. Key.new("a").use { a -> Key.new("a").use { same -> Key.new("b").use { b -> - println("key ${a.hashCode() == same.hashCode()} ${a.hashCode() == b.hashCode()}") check(a == same && a != b, "keys compare as Rust's") + check(a.hashCode() == same.hashCode() && a.hashCode() != b.hashCode(), "keys hash as Rust's") check(a.hashCode() == a.hashOf().toLong().hashCode(), "a key hashes as Rust's Hash") check(setOf(a, b).contains(same), "a key finds its equal in a set") } } } - val v6Max = Ipv6Addr(ByteArray(16).also { it[0] = -1; it[1] = -1; it[15] = 1 }) - println("lossless ip ${ipHex(sameIpAddr(Ipv4Addr(UInt.MAX_VALUE)))} ${ipHex(sameIpAddr(v6Max))}") // Durations: exact both ways, and checked against kotlin.time's. check(rejects { Duration(0u, 1_000_000_000u) }, "a second of nanoseconds is no Duration's") @@ -975,8 +401,8 @@ fun lossless() { // Text: a lone surrogate throws, passed alone or encoded, before anything moves. check(rejects { sameString("a\ud800") } && rejects { sameString("\udc00b") }, "a lone surrogate is no Rust text") - check(sameString("\ud83d\ude00") == "\ud83d\ude00", "a surrogate pair is one char") - check(sameString("x".repeat(1023) + "\ud83d\ude00") == "x".repeat(1023) + "\ud83d\ude00", "a pair split across chunks is one char") + check(sameString("😀") == "😀", "a surrogate pair is one char") + check(sameString("x".repeat(1023) + "😀") == "x".repeat(1023) + "😀", "a pair split across chunks is one char") check(rejects { joinWords(listOf("a", "\ud800")) }, "a lone surrogate in a list throws") val kept = Counter.new("kept", 1u) check(rejects { Board.new(listOf(Pair("\ud800", kept))) }, "a lone surrogate beside a moved object throws") @@ -986,7 +412,7 @@ fun lossless() { // Paths: any bytes on Unix, and text only where it is UTF-8. val stray = stray() check(stray.toByteArray().contentEquals(byteArrayOf(-1)) && stray == PathBuf(byteArrayOf(-1)), "a path keeps bytes no String holds") - check(rejects { stray.toText() } && rejects { stray.toPath() } && stray.toString() == "\ufffd", "a path that is not UTF-8 has no text") + check(rejects { stray.toText() } && rejects { stray.toPath() } && stray.toString() == "�", "a path that is not UTF-8 has no text") check(rejects { PathBuf("\ud800") }, "a lone surrogate has no path") check(PathBuf("a/é").toText() == "a/é" && PathBuf("a/é").toPath() == java.nio.file.Paths.get("a/é"), "a UTF-8 path converts") check(_wtf8(byteArrayOf(0xed.toByte(), 0xa0.toByte(), 0x80.toByte())) && !_wtf8(byteArrayOf(0xed.toByte(), 0xa0.toByte(), 0x80.toByte(), 0xed.toByte(), 0xb0.toByte(), 0x80.toByte())), "a lone surrogate is WTF-8, a pair encoded apart is not") @@ -1008,6 +434,7 @@ fun lossless() { check(IpAddr.of(java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))) == Ipv4Addr(127u, 0u, 0u, 1u), "an IPv4 address converts") check(Ipv6Addr(ByteArray(16).also { it[1] = 1; it[15] = 2 }).toString() == "1::2" && Ipv6Addr(ByteArray(16)).toString() == "::", "IPv6 prints as Rust's") check(SocketAddrV4(Ipv4Addr(127u, 0u, 0u, 1u), 80u).toString() == "127.0.0.1:80", "IPv4 prints as Rust's") + println("checks ok") } // A queue of jobs that a test runs when it chooses: the dispatcher coroutines resume on. @@ -1792,6 +1219,7 @@ fun main(args: Array) { args[0] == "futures" -> futures() args[0] == "owned" -> owned() args[0] == "clash" -> clash() + args[0] == "checks" -> checks() else -> broken(args[0]) } } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 9b5eadc00..b33be9bcc 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -716,16 +716,18 @@ fn api_kotlin() { let api = api(); let classes = scratch().join("api").join("kotlin"); let jar = PathBuf::from(coroutines()); + let script = kotlin_transcript(); let step = Step { stamp: &step::stamp(&classes), reads: &[ &api.out.join("kotlin").join("api.kt"), &manifest_dir().join("tests").join("api.kt"), + &script, &jar, ], writes: &[&classes], }; - step.run(&mut kotlinc(&api.out, &classes)); + step.run(&mut kotlinc(&api.out, &script, &classes)); let java = |classpath: &[&Path], args: &[&str]| { let mut cmd = Command::new("kotlin"); cmd.arg(format!("-Djava.library.path={}", api.lib.display())) @@ -831,7 +833,7 @@ fn api_android() { // script's functions marked `OwnFrame` are kept too, as R8 would inline them into their // caller, whose frame ART's interpreter keeps reaching what they held. let jar = dir.join("app.jar"); - run(kotlinc(&out, &jar).arg("-include-runtime")); + run(kotlinc(&out, &kotlin_transcript(), &jar).arg("-include-runtime")); run(Command::new("jar") .arg("xf") .arg(coroutines()) @@ -889,13 +891,21 @@ fn api_android() { kotlin(&api.transcript, &art); } -/// kotlinc compiling the generated Kotlin with `tests/api.kt` into `dest`. -fn kotlinc(out: &Path, dest: &Path) -> Command { +/// The transcript as Kotlin, written beside the scratch directory's other files, whose +/// `transcript()` `tests/api.kt`'s script calls. +fn kotlin_transcript() -> PathBuf { + generated("kotlin", "Transcript.kt", &transcript::kotlin::emit(transcript())).join("Transcript.kt") +} + +/// kotlinc compiling the generated Kotlin with `tests/api.kt` and the transcript `script` +/// into `dest`. +fn kotlinc(out: &Path, script: &Path, dest: &Path) -> Command { let mut cmd = Command::new("kotlinc"); cmd.args(["-Werror", "-cp"]) .arg(coroutines()) .arg(out.join("kotlin").join("api.kt")) .arg(manifest_dir().join("tests").join("api.kt")) + .arg(script) .arg("-d") .arg(dest); cmd @@ -923,7 +933,8 @@ fn newest(dir: &Path) -> PathBuf { } /// `tests/api.kt`'s script, run by `vm` with each argument list, prints the native -/// transcript; then its futures, what the GC frees, and each contract it fails loud on. +/// transcript; then its futures, what the GC frees, what only its types bound, and each +/// contract it fails loud on. fn kotlin(native: &str, vm: &dyn Fn(&[&str]) -> Command) { let kt = run(&mut vm(&[])); assert_eq!( @@ -934,6 +945,7 @@ fn kotlin(native: &str, vm: &dyn Fn(&[&str]) -> Command) { run(&mut vm(&["futures"])); run(&mut vm(&["owned"])); run(&mut vm(&["clash"])); + run(&mut vm(&["checks"])); for (case, message) in [ ("moved", "IllegalStateException: Counter is closed"), ("boxed moved", "IllegalStateException: Node is closed"), diff --git a/ffi/tests/fixtures/transcript/kotlin.rs b/ffi/tests/fixtures/transcript/kotlin.rs new file mode 100644 index 000000000..ad19ab9e6 --- /dev/null +++ b/ffi/tests/fixtures/transcript/kotlin.rs @@ -0,0 +1,1170 @@ +//! The transcript as Kotlin: a file whose `transcript()` runs it through the generated +//! Kotlin, calling `tests/api.kt`'s own functions, which share its default package. + +use std::fmt::Write; + +use super::ir::{Access, Collection, Int, Mutability, Receiver, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; + +const LANGUAGE: &str = "Kotlin"; + +/// Helpers the script calls, each for a value Kotlin shapes apart from Rust. +const PRELUDE: &str = r#"// Generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript. Do not edit. + +@file:OptIn(ExperimentalUnsignedTypes::class) + +/** A call's value, or the exception of [exception] it threw, as a `Result`. */ +private fun _try(exception: Class, call: () -> T): Result = try { + Result.success(call()) +} catch (e: Throwable) { + if (!exception.isInstance(e)) throw e + Result.failure(e) +} + +/** The exception of [exception] a call that must fail threw. */ +private fun _thrown(exception: Class, call: () -> Any?): X { + val thrown = _try(exception, call).exceptionOrNull() ?: throw AssertionError("the call did not fail") + return exception.cast(thrown) +} + +/** A string as Rust's `Debug` prints it. */ +private fun _quoted(s: String): String { + val out = StringBuilder("\"") + for (c in s) { + when (c) { + '"', '\\' -> out.append('\\').append(c) + '\n' -> out.append("\\n") + '\t' -> out.append("\\t") + '\r' -> out.append("\\r") + '\u0000' -> out.append("\\0") + else -> if (c.code < 0x20 || c.code == 0x7f) out.append("\\u{${c.code.toString(16)}}") else out.append(c) + } + } + return out.append('"').toString() +} + +/** A char, which Kotlin holds as its code point, as text. */ +private fun _char(c: Int): String = String(Character.toChars(c)) + +private fun _bound(kind: api.Bound, value: Any): String = when (kind) { + api.Bound.INCLUDED -> "Included($value)" + api.Bound.EXCLUDED -> "Excluded($value)" + api.Bound.UNBOUNDED -> "Unbounded" +} + +/** Bytes as Rust's `Debug` prints a list of them. */ +private fun _bytes(bytes: ByteArray): String = bytes.joinToString(", ", "[", "]") { (it.toInt() and 0xff).toString() } + +private fun _option(value: T?, show: (T) -> String): String = if (value == null) "None" else "Some(${show(value)})" +"#; + +/// The Kotlin file of `t`'s script. +pub(crate) fn emit(t: &Transcript) -> String { + let mut hooks = Vec::new(); + for step in &t.steps { + each_expr(step, &mut |e| { + walk(e, &mut |e| { + if let Kind::Local(name, _) = &e.kind + && !hooks.contains(&local(name)) + { + hooks.push(local(name)); + } + }) + }); + } + let mut e = Emitter { + t, + depth: 1, + mutated: Vec::new(), + vars: Vec::new(), + hooks, + fresh: 0, + }; + mutated(&t.steps, t, &mut e.mutated, &mut e.vars); + let mut out = String::from(PRELUDE); + out.push_str("\nfun transcript() {\n"); + let body = e.steps(&t.steps); + out.push_str(&body); + out.push_str("}\n"); + out +} + +/// The locals a call takes `&mut` that are values, not objects, each a `Mut` whose `value` +/// the script reads; and those a value's `&mut self` method is called on, each a `var` the +/// method's return replaces. +fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec, vars: &mut Vec) { + let mut visit = |expr: &Expr| { + walk(expr, &mut |e| { + if let Kind::Call(id, receiver, args) = &e.kind { + let f = t.function(*id); + for (arg, param) in args.iter().zip(params(t, *id)) { + if let Kind::Var(name) = &arg.kind + && written(¶m) && !out.contains(name) + { + out.push(name.clone()); + } + } + if let Some(receiver) = receiver + && let Kind::Var(name) = &receiver.kind + && f.receiver == Some(Receiver::Mut) + && matches!(id.owner, Owner::Record(_)) + && !vars.contains(name) + { + vars.push(name.clone()); + } + } + }) + }; + for step in steps { + each_expr(step, &mut visit); + } +} + +/// The types of `id`'s parameters Kotlin passes: all but a JNI env, which the binding passes. +fn params(t: &Transcript, id: FnId) -> Vec { + (t.function(id).params.iter()) + .filter(|p| !matches!(&p.ty, Type::Jni(v) if v == "Env")) + .map(|p| p.ty.clone()) + .collect() +} + +/// Whether a parameter of `ty` is a `Mut` Rust writes back through. +fn written(ty: &Type) -> bool { + matches!(ty, Type::Ref(Mutability::Mut, inner) if !matches!(**inner, Type::Object(_) | Type::Reader)) +} + +/// Each expression a step holds, its arms' and closures' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +struct Emitter<'t> { + t: &'t Transcript, + depth: usize, + /// The locals each a `Mut`. + mutated: Vec, + /// The locals each a `var`, which a value's `&mut self` method replaces. + vars: Vec, + /// The names of `tests/api.kt`'s functions the script calls, which no local may shadow. + hooks: Vec, + fresh: usize, +} + +/// Kotlin's hard keywords, which no name may be. +const KEYWORDS: &[&str] = &[ + "as", + "break", + "class", + "continue", + "do", + "else", + "false", + "for", + "fun", + "if", + "in", + "interface", + "is", + "null", + "object", + "package", + "return", + "super", + "this", + "throw", + "true", + "try", + "typealias", + "typeof", + "val", + "var", + "when", + "while", +]; + +/// What the script names by its root, which no local may shadow. +const ROOTS: &[&str] = &["api", "kotlin", "kotlinx", "java", "it", "field", "value"]; + +/// The Kotlin name of a function `transcript.rs` defines, or of a unit struct it does. +fn local(name: &str) -> String { + match name.starts_with(|c: char| c.is_ascii_uppercase()) { + true => name.to_string(), + false => camel(name), + } +} + +impl Emitter<'_> { + /// A local's name in Kotlin. + fn ident(&self, name: &str) -> String { + match KEYWORDS.contains(&name) || ROOTS.contains(&name) || self.hooks.iter().any(|h| h == name) { + true => format!("{name}_"), + false => name.to_string(), + } + } + + fn indent(&self) -> String { + "\t".repeat(self.depth) + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("_{what}{}", self.fresh) + } + + fn steps(&mut self, steps: &[Step]) -> String { + let mut out = String::new(); + for step in steps { + self.step(step, &mut out); + } + out + } + + fn line(&self, out: &mut String, line: &str) { + let _ = writeln!(out, "{}{line}", self.indent()); + } + + fn step(&mut self, step: &Step, out: &mut String) { + match step { + Step::Let(pat, value) => { + // A value's `&mut self` returns it as the call left it, before what Rust returns. + if let Some((name, call)) = self.mut_receiver(value) { + return match (unref(&value.ty), pat) { + (Type::Unit, _) => self.line(out, &format!("{name} = {call}")), + (ty, pat) => { + let tmp = self.fresh("t"); + self.line(out, &format!("val {tmp} = {call}")); + self.line(out, &format!("{name} = {tmp}.first")); + let rest = match ty { + Type::Tuple(elements) if elements.len() > 1 => { + let parts: Vec = (0..elements.len()) + .map(|i| format!("{tmp}.{}", ordinal(i + 1))) + .collect(); + let class = self.tuple_class(elements); + format!("{class}({})", parts.join(", ")) + } + _ => format!("{tmp}.second"), + }; + self.bind(pat, &rest, out) + } + }; + } + let v = self.expr(value, out); + match pat { + Pat::Ignore(_) => { + let v = self.dropped(&v, &value.ty); + self.line(out, &v) + } + Pat::Name(name, _) if self.mutated.contains(name) => { + let name = self.ident(name); + self.line(out, &format!("val {name} = api.Mut({v})")) + } + pat => self.bind(pat, &v, out), + } + } + Step::Print(pieces) => { + let v = self.pieces(pieces, out); + self.line(out, &format!("println({v})")); + } + Step::Do(value) => { + if let Some((name, call)) = self.mut_receiver(value) { + return match unref(&value.ty) { + Type::Unit => self.line(out, &format!("{name} = {call}")), + _ => self.line(out, &format!("{name} = {call}.first")), + }; + } + let v = self.expr(value, out); + let v = self.dropped(&v, &value.ty); + self.line(out, &v); + } + Step::Drop(name) => { + let name = self.ident(name); + self.line(out, &format!("{name}.close()")) + } + Step::Match { value, ok, err } => self.matched(value, ok, err, out), + } + } + + /// `v`, a value of `ty` the script drops: a `Result`'s error too, which Kotlin throws. + fn dropped(&self, v: &str, ty: &Type) -> String { + match ty { + Type::Result(_, err) => format!("_try({}::class.java) {{ {v} }}", self.exception(err)), + _ => v.to_string(), + } + } + + /// A call of a method taking a value's `&mut self` on a local: the local's name, and + /// the call, which Kotlin returns the value from as the call left it. + fn mut_receiver(&mut self, value: &Expr) -> Option<(String, String)> { + let Kind::Call(id, Some(receiver), args) = &value.kind else { + return None; + }; + let f = self.t.function(*id); + if f.receiver != Some(Receiver::Mut) || !matches!(id.owner, Owner::Record(_)) { + return None; + } + let Kind::Var(name) = &receiver.kind else { + panic!("a value's &mut self method on anything but a local") + }; + let mut scratch = String::new(); + let call = self.call(*id, Some(receiver), args, &mut scratch); + assert!( + scratch.is_empty(), + "a value's &mut self method taking a closure of steps" + ); + Some((self.ident(name), call)) + } + + /// `pat` bound to `v`: a name, a `var` if a method replaces it, or a tuple's elements, + /// destructured where Kotlin can and read one by one where it nests. + fn bind(&mut self, pat: &Pat, v: &str, out: &mut String) { + match pat { + Pat::Name(name, _) => { + let keyword = if self.vars.contains(name) { "var" } else { "val" }; + let name = self.ident(name); + self.line(out, &format!("{keyword} {name} = {v}")); + } + Pat::Ignore(_) => self.line(out, v), + Pat::Tuple(pats) if pats.iter().all(|p| self.flat(p)) => { + let names: Vec = pats.iter().map(|p| self.pat(p)).collect(); + self.line(out, &format!("val ({}) = {v}", names.join(", "))); + } + Pat::Tuple(pats) => { + let tmp = self.fresh("t"); + self.line(out, &format!("val {tmp} = {v}")); + for (i, p) in pats.iter().enumerate() { + if !matches!(p, Pat::Ignore(_)) { + self.bind(p, &format!("{tmp}.component{}()", i + 1), out); + } + } + } + } + } + + /// Whether `pat` binds in a destructuring declaration: a name no method replaces, or `_`. + fn flat(&self, pat: &Pat) -> bool { + match pat { + Pat::Name(name, _) => !self.vars.contains(name) && !self.mutated.contains(name), + Pat::Ignore(_) => true, + Pat::Tuple(_) => false, + } + } + + fn pat(&self, pat: &Pat) -> String { + match pat { + Pat::Name(name, _) => self.ident(name), + Pat::Ignore(_) => "_".to_string(), + Pat::Tuple(pats) => { + let parts: Vec = pats.iter().map(|p| self.pat(p)).collect(); + format!("({})", parts.join(", ")) + } + } + } + + /// A lambda's parameter binding `pat`, and the statements its body begins with to bind + /// what Kotlin cannot destructure there. + fn param(&mut self, pat: &Pat) -> (String, String) { + match pat { + Pat::Tuple(pats) if !pats.iter().all(|p| self.flat(p)) => { + let tmp = self.fresh("p"); + let mut body = String::new(); + self.depth += 1; + self.bind(pat, &tmp, &mut body); + self.depth -= 1; + (tmp, body) + } + pat => (self.pat(pat), String::new()), + } + } + + fn matched(&mut self, value: &Expr, ok: &Arm, err: &Arm, out: &mut String) { + match &value.ty { + Type::Option(_) => { + let v = self.expr(value, out); + let tmp = self.fresh("o"); + self.line(out, &format!("val {tmp} = {v}")); + self.line(out, &format!("if ({tmp} != null) {{")); + self.arm(ok, &tmp, out); + self.line(out, "} else {"); + self.arm(err, "null", out); + self.line(out, "}"); + } + Type::Result(_, err_ty) => { + let exception = self.exception(err_ty); + let v = self.expr(value, out); + let tmp = self.fresh("r"); + self.line(out, &format!("val {tmp} = _try({exception}::class.java) {{ {v} }}")); + self.line(out, &format!("if ({tmp}.isSuccess) {{")); + self.arm(ok, &format!("{tmp}.getOrThrow()"), out); + self.line(out, "} else {"); + self.arm(err, &format!("({tmp}.exceptionOrNull() as {exception}).error"), out); + self.line(out, "}"); + } + ty => panic!("a match on {ty:?}"), + } + } + + fn arm(&mut self, arm: &Arm, payload: &str, out: &mut String) { + self.depth += 1; + if let Some(pat) = &arm.pat { + self.bind(pat, payload, out); + } + let body = self.steps(&arm.steps); + out.push_str(&body); + self.depth -= 1; + } + + /// The exception a call failing with `err` throws. + fn exception(&self, err: &Type) -> String { + let name = match unref(err).base() { + Type::String | Type::Str => self.t.named(LANGUAGE, "error string").to_string(), + Type::Bounds(int) => self + .t + .named(LANGUAGE, &format!("error bounds_{}", int.rust())) + .to_string(), + ty @ (Type::Record(_) | Type::Enum(_) | Type::Object(_)) => { + format!("{}Exception", self.t.type_name(LANGUAGE, ty)) + } + ty => panic!("an error of {ty:?}"), + }; + format!("api.{name}") + } + + /// The Kotlin of a format's pieces: a string template. + fn pieces(&mut self, pieces: &[Piece], out: &mut String) -> String { + let mut template = String::from("\""); + for piece in pieces { + match piece { + Piece::Text(text) => template.push_str(&escape(text)), + Piece::Value(e, spec) => { + let v = self.expr(e, out); + let shown = self.show(&v, &e.ty, *spec); + let _ = write!(template, "${{{shown}}}"); + } + } + } + template.push('"'); + template + } + + /// `v`, a value of `ty`, as Kotlin shows it the way Rust formats it with `spec`. + fn show(&mut self, v: &str, ty: &Type, spec: Spec) -> String { + let ty = unref(ty).base(); + match spec { + Spec::Hex(width) => { + assert!( + matches!(ty, Type::Int(int) | Type::NonZero(int) if !int.signed()) || *ty == Type::U128, + "hex of {ty:?}" + ); + let hex = format!("{v}.toString(16)"); + return match width { + 0 => hex, + width => format!("{hex}.padStart({width}, '0')"), + }; + } + Spec::Padded(width) => { + assert!( + matches!(ty, Type::Int(int) | Type::NonZero(int) if !int.signed()) || *ty == Type::U128, + "zero-padded {ty:?}" + ); + return format!("{v}.toString().padStart({width}, '0')"); + } + Spec::Debug => return self.debug(v, ty), + Spec::Display => {} + } + match ty { + Type::Bool | Type::String | Type::Str | Type::Int(_) | Type::U128 | Type::NonZero(_) => v.to_string(), + Type::Char => format!("_char({v})"), + Type::Object(_) | Type::Record(_) | Type::Enum(_) => match self.text_of(ty) { + Some(text) => format!("{v}.{text}()"), + None => v.to_string(), + }, + ty => panic!("Display of {ty:?}"), + } + } + + /// The name of a type's `Access::Text` method, which Kotlin names apart from `toString`. + fn text_of(&self, ty: &Type) -> Option<&str> { + let Type::Object(i) = ty else { return None }; + let o = &self.t.api.objects[*i]; + let index = o.methods.iter().position(|m| m.access == Access::Text)?; + Some(self.t.name( + LANGUAGE, + FnId { + owner: Owner::Object(*i), + index, + }, + )) + } + + /// `v` as Rust's `Debug` prints a value of `ty`. + fn debug(&mut self, v: &str, ty: &Type) -> String { + match unref(ty).base() { + Type::Bool | Type::Int(_) | Type::U128 | Type::NonZero(_) => format!("{v}.toString()"), + Type::String | Type::Str => format!("_quoted({v})"), + Type::Option(inner) => { + let x = self.fresh("x"); + let show = self.debug(&x, inner); + format!("_option({v}) {{ {x} -> {show} }}") + } + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => format!("_bytes({v}.toByteArray())"), + Type::List(_, item) => { + let x = self.fresh("x"); + let show = self.debug(&x, item); + format!("{v}.joinToString(\", \", \"[\", \"]\") {{ {x} -> {show} }}") + } + Type::Tuple(elements) => { + let x = self.fresh("x"); + let parts: Vec = (0..elements.len()) + .map(|i| { + let shown = self.debug(&format!("{x}.{}", ordinal(i)), &elements[i]); + format!("${{{shown}}}") + }) + .collect(); + let tail = if parts.len() == 1 { ",)" } else { ")" }; + format!("{v}.let {{ {x} -> \"({}{tail}\" }}", parts.join(", ")) + } + Type::Bound(_) => format!("{v}.let {{ _bound(it.kind, it.value) }}"), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => format!("{v}.debug()"), + ty => panic!("Debug of {ty:?}"), + } + } + + fn expr(&mut self, e: &Expr, out: &mut String) -> String { + self.value(e, &e.ty, out) + } + + /// The Kotlin of `e`, passed where `want` is taken. + fn value(&mut self, e: &Expr, want: &Type, out: &mut String) -> String { + match &e.kind { + Kind::Unit => "Unit".to_string(), + Kind::Bool(b) => b.to_string(), + Kind::Int(n) => { + let ty = match unref(&e.ty).base() { + ty @ (Type::Int(_) | Type::NonZero(_) | Type::U128) => ty, + _ => unref(want).base(), + }; + int(*n, ty) + } + Kind::Float(f) => match unref(want).base() { + Type::F32 => float32(*f as f32), + _ => float64(*f), + }, + Kind::Char(c) => format!("0x{:x}", *c as u32), + Kind::Str(s) => match unref(want).base() { + Type::Path | Type::PathBuf => format!("api.PathBuf({})", string(s)), + _ => string(s), + }, + Kind::Bytes(b) => match unref(want).base() { + Type::Array(n) => format!("api.ArrayU8x{n}({})", byte_array(b)), + _ => format!("api.Bytes({})", byte_array(b)), + }, + Kind::Duration(secs, nanos) => format!("api.Duration({secs}uL, {nanos}u)"), + Kind::Socket(std::net::SocketAddr::V4(a)) => { + format!( + "api.SocketAddrV4({}, {})", + ipv4(a.ip()), + int(Num::new(a.port().into()), &Type::Int(Int::U16)) + ) + } + Kind::Socket(std::net::SocketAddr::V6(a)) => format!( + "api.SocketAddrV6({}, {}, {}u, {}u)", + ipv6(a.ip()), + int(Num::new(a.port().into()), &Type::Int(Int::U16)), + a.flowinfo(), + a.scope_id() + ), + Kind::Ip(std::net::IpAddr::V4(ip)) => ipv4(ip), + Kind::Ip(std::net::IpAddr::V6(ip)) => ipv6(ip), + Kind::None => "null".to_string(), + Kind::Some(inner) => { + let want = match unref(want).base() { + Type::Option(inner) => (**inner).clone(), + _ => inner.ty.clone(), + }; + self.value(inner, &want, out) + } + Kind::Tuple(elements) => self.tuple(e, elements, want, out), + Kind::List(items) => self.list(items, want, out), + Kind::Record(r, fields) => { + let name = self.t.type_name(LANGUAGE, &Type::Record(*r)).to_string(); + let field_types: Vec = self.t.api.records[*r].fields.iter().map(|f| f.ty.clone()).collect(); + let args: Vec = fields + .iter() + .zip(&field_types) + .map(|(f, ty)| self.value(f, ty, out)) + .collect(); + format!("api.{name}({})", args.join(", ")) + } + Kind::Variant(en, v, fields) => { + let name = self.t.type_name(LANGUAGE, &Type::Enum(*en)).to_string(); + let enumeration = &self.t.api.enums[*en]; + let variant = &enumeration.variants[*v]; + if enumeration.variants.iter().all(|v| v.fields.is_empty()) { + return format!("api.{name}.{}", upper(&variant.name)); + } + if variant.fields.is_empty() { + return format!("api.{name}.{}", variant.name); + } + let field_types: Vec = variant.fields.iter().map(|f| f.ty.clone()).collect(); + let variant_name = variant.name.clone(); + let args: Vec = fields + .iter() + .zip(&field_types) + .map(|(f, ty)| self.value(f, ty, out)) + .collect(); + format!("api.{name}.{variant_name}({})", args.join(", ")) + } + Kind::Bound(kind, value) => { + let Type::Bound(int_ty) = unref(&e.ty) else { + panic!("a bound of {:?}", e.ty) + }; + let (kind, v) = match (kind, value) { + (BoundKind::Unbounded, _) => ("UNBOUNDED", int(Num::new(0), &Type::Int(*int_ty))), + (BoundKind::Included, Some(v)) => ("INCLUDED", self.value(v, &Type::Int(*int_ty), out)), + (BoundKind::Excluded, Some(v)) => ("EXCLUDED", self.value(v, &Type::Int(*int_ty), out)), + _ => unreachable!(), + }; + format!("api.Bound{}(api.Bound.{kind}, {v})", int_name(*int_ty)) + } + Kind::Default => { + let name = self.t.type_name(LANGUAGE, unref(&e.ty).base()).to_string(); + format!("api.{name}.default()") + } + Kind::Var(name) => match self.mutated.contains(name) { + // Passed `&mut`, the `Mut` itself; read, its value. + true if written(want) => self.ident(name), + true => format!("{}.value", self.ident(name)), + false => self.ident(name), + }, + Kind::Const(c) => format!( + "api.{}", + self.t + .named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::"))) + ), + Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args, out), + Kind::Field(base, i) => { + let b = self.expr(base, out); + let Type::Record(r) = unref(&base.ty).base() else { + panic!("a field of {:?}", base.ty) + }; + format!("{b}.{}", field_name(&self.t.api.records[*r].fields[*i].name)) + } + Kind::Element(base, i) => { + let b = self.expr(base, out); + match unref(&base.ty).base() { + Type::Range(_) | Type::Bounds(_) => format!("{b}.{}", if *i == 0 { "start" } else { "end" }), + Type::Tuple(_) => format!("{b}.{}", ordinal(*i)), + ty => panic!("an element of {ty:?}"), + } + } + Kind::Clone(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + Type::Object(_) => format!("{v}.clone()"), + Type::List(..) if block(unref(&inner.ty).base()).is_none() => format!("{v}.toList()"), + // Records, bytes, and the rest are immutable, so the value is its clone. + Type::Record(_) | Type::Enum(_) | Type::Bytes | Type::String | Type::Int(_) | Type::Bool => v, + ty => panic!("a clone of {ty:?}"), + } + } + Kind::Unwrap(inner) => { + let v = self.expr(inner, out); + match &inner.ty { + Type::Result(..) => v, + _ => format!("{v}!!"), + } + } + Kind::UnwrapErr(inner) => { + let Type::Result(_, err) = &inner.ty else { + panic!("unwrap_err of {:?}", inner.ty) + }; + let exception = self.exception(err); + let v = self.expr(inner, out); + format!("_thrown({exception}::class.java) {{ {v} }}.error") + } + Kind::IsErr(inner) => { + let Type::Result(_, err) = &inner.ty else { + panic!("is_err of {:?}", inner.ty) + }; + let exception = self.exception(err); + let v = self.expr(inner, out); + format!("_try({exception}::class.java) {{ {v} }}.isFailure") + } + Kind::IsSome(inner) => format!("({} != null)", self.expr(inner, out)), + Kind::IsNone(inner) => format!("({} == null)", self.expr(inner, out)), + Kind::Binary(op, a, b) => { + let ty = unref(&a.ty).base().clone(); + let (a, b) = (self.value(a, &ty, out), self.value(b, &ty, out)); + let sym = match op { + Op::Eq => "==", + Op::Ne => "!=", + Op::Lt => "<", + Op::Gt => ">", + Op::Add => "+", + Op::Sub => "-", + Op::Mul => "*", + Op::Rem => "%", + Op::And => "&&", + }; + let v = format!("({a} {sym} {b})"); + // Kotlin widens arithmetic on a byte or a short to an `Int`, which Rust keeps. + match (op, &ty) { + (Op::Add | Op::Sub | Op::Mul | Op::Rem, Type::Int(int)) => match narrow(*int) { + Some(to) => format!("{v}.{to}()"), + None => v, + }, + _ => v, + } + } + Kind::Closure(params, steps, value) => self.closure(params, steps, value), + Kind::Local(name, args) => { + let args: Vec = args.iter().map(|a| self.expr(a, out)).collect(); + format!("{}({})", local(name), args.join(", ")) + } + Kind::Format(pieces) => self.pieces(pieces, out), + Kind::Join { items, pat, body, sep } => { + let items = self.expr(items, out); + let (param, bound) = self.param(pat); + let body = self.lambda_body(&bound, body); + format!("{items}.joinToString({}) {{ {param} ->{body}}}", string(sep)) + } + Kind::MapOr { + option, + none, + pat, + some, + } => { + let option = self.expr(option, out); + let none = self.expr(none, out); + let Pat::Name(..) = pat else { + panic!("map_or binding a pattern") + }; + let param = self.pat(pat); + let some = self.expr(some, out); + format!("{option}.let {{ {param} -> if ({param} == null) {none} else {some} }}") + } + Kind::Utf8(inner) => format!("{}.toByteArray().decodeToString()", self.expr(inner, out)), + Kind::Len(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + Type::String | Type::Str => format!("{v}.encodeToByteArray().size.toULong()"), + _ => format!("{v}.size.toULong()"), + } + } + } + } + + /// A lambda's body after its parameters: the statements `bound` binds, then `value`. + fn lambda_body(&mut self, bound: &str, value: &Expr) -> String { + let mut pre = String::new(); + self.depth += 1; + let v = self.expr(value, &mut pre); + self.depth -= 1; + match (bound.is_empty() && pre.is_empty(), &value.kind) { + (true, _) => format!(" {v} "), + (false, Kind::Unit) => format!("\n{bound}{pre}{}", self.indent()), + (false, _) => format!("\n{bound}{pre}{}\t{v}\n{}", self.indent(), self.indent()), + } + } + + fn tuple(&mut self, e: &Expr, elements: &[Expr], want: &Type, out: &mut String) -> String { + match unref(&e.ty).base() { + Type::Range(int_ty) => { + let ty = Type::Int(*int_ty); + let (a, b) = (self.value(&elements[0], &ty, out), self.value(&elements[1], &ty, out)); + format!("api.Range{}({a}, {b})", int_name(*int_ty)) + } + Type::Bounds(int_ty) => { + let ty = Type::Bound(*int_ty); + let (a, b) = (self.value(&elements[0], &ty, out), self.value(&elements[1], &ty, out)); + format!("api.Bounds{}({a}, {b})", int_name(*int_ty)) + } + _ => { + let wants: Vec = match unref(want).base() { + Type::Tuple(ts) => ts.clone(), + _ => elements.iter().map(|e| e.ty.clone()).collect(), + }; + let parts: Vec = elements + .iter() + .zip(&wants) + .map(|(e, t)| self.value(e, t, out)) + .collect(); + let class = self.tuple_class(&wants); + format!("{class}({})", parts.join(", ")) + } + } + } + + /// The Kotlin class of a tuple of `elements`: `Pair` and `Triple`, unless an element + /// compares by its contents, which theirs cannot, else the binding's `TupleN`. + fn tuple_class(&self, elements: &[Type]) -> String { + let contents = elements.iter().any(|e| holds_block(e) || self.holds_float(e)); + match elements.len() { + 2 | 3 if contents => format!("api.Tuple{}", elements.len()), + 2 => "Pair".to_string(), + 3 => "Triple".to_string(), + n => format!("api.Tuple{n}"), + } + } + + fn holds_float(&self, ty: &Type) -> bool { + self.floats(ty, &mut Vec::new()) + } + + fn floats(&self, ty: &Type, seen: &mut Vec<(bool, usize)>) -> bool { + match ty { + Type::F32 | Type::F64 => true, + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => { + self.floats(inner, seen) + } + Type::Tuple(elements) => elements.iter().any(|e| self.floats(e, seen)), + Type::Record(i) if !seen.contains(&(false, *i)) => { + seen.push((false, *i)); + self.t.api.records[*i].fields.iter().any(|f| self.floats(&f.ty, seen)) + } + Type::Enum(i) if !seen.contains(&(true, *i)) => { + seen.push((true, *i)); + (self.t.api.enums[*i].variants.iter()) + .flat_map(|v| &v.fields) + .any(|f| self.floats(&f.ty, seen)) + } + _ => false, + } + } + + fn list(&mut self, items: &[Expr], want: &Type, out: &mut String) -> String { + let list = unref(want).base(); + let Type::List(_, item) = list else { + panic!("a list as {list:?}") + }; + let item = (**item).clone(); + let parts: Vec = items.iter().map(|e| self.value(e, &item, out)).collect(); + match block(list) { + Some(element) => format!("{}({})", array_of(element), parts.join(", ")), + None => format!("listOf({})", parts.join(", ")), + } + } + + /// A closure as a lambda, its steps before the value it returns. + fn closure(&mut self, params: &[Pat], steps: &[Step], value: &Expr) -> String { + let mut bound = String::new(); + let mut names = Vec::new(); + for p in params { + let (name, binds) = self.param(p); + names.push(name); + bound.push_str(&binds); + } + self.depth += 1; + bound.push_str(&self.steps(steps)); + self.depth -= 1; + let body = self.lambda_body(&bound, value); + match names.is_empty() { + true => format!("{{{body}}}"), + false => format!("{{ {} ->{body}}}", names.join(", ")), + } + } + + /// A call of `id`: a function of the package, an associated function of a type, a + /// method, or a field's getter or setter. + fn call(&mut self, id: FnId, receiver: Option<&Expr>, args: &[Expr], out: &mut String) -> String { + let f = self.t.function(id); + let name = self.t.name(LANGUAGE, id).to_string(); + let (access, future) = (f.access, f.future); + let params = params(self.t, id); + assert_eq!( + args.len(), + params.len(), + "a call of {} with {} arguments", + self.t.key(id), + args.len() + ); + let args: Vec = args.iter().zip(¶ms).map(|(a, ty)| self.value(a, ty, out)).collect(); + let target = match (receiver, self.t.owner(id)) { + (Some(r), _) => self.expr(r, out), + (None, Some(ty)) => format!("api.{}", self.t.type_name(LANGUAGE, &ty)), + (None, None) => "api".to_string(), + }; + // A handle made for the call is a temporary, which Rust drops once the statement + // ends, ending any borrow it holds: Kotlin closes it once the call returns. + let temporary = receiver.is_some_and(|r| temporary(r)) && f.receiver != Some(Receiver::Owned); + let (target, close) = match temporary { + true => { + let tmp = self.fresh("h"); + (tmp.clone(), Some((target, tmp))) + } + false => (target, None), + }; + let call = match access { + Access::Field { set: false, .. } | Access::Const => format!("{target}.{name}"), + _ => format!("{target}.{name}({})", args.join(", ")), + }; + let call = match close { + Some((handle, tmp)) => format!("{handle}.use {{ {tmp} -> {call} }}"), + None => call, + }; + match future { + true => format!("kotlinx.coroutines.runBlocking {{ {call} }}"), + false => call, + } + } +} + +/// Whether `e` is a handle no local holds: an object a call returned, unwrapped or not. +fn temporary(e: &Expr) -> bool { + let called = match &e.kind { + Kind::Call(..) => true, + Kind::Unwrap(inner) => matches!(inner.kind, Kind::Call(..)), + _ => false, + }; + called && matches!(unref(&e.ty).base(), Type::Object(_)) +} + +/// Whether `ty` holds a list Kotlin keeps as a primitive array anywhere but in a record or +/// an enum, which compare their own. +fn holds_block(ty: &Type) -> bool { + match ty { + _ if block(ty).is_some() => true, + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => holds_block(inner), + Type::Tuple(elements) => elements.iter().any(holds_block), + _ => false, + } +} + +/// The element of a list Kotlin holds as a primitive array: a `Vec`, slice, boxed slice, +/// or array of a fixed-width integer or a float. +fn block(ty: &Type) -> Option<&Type> { + match ty { + Type::List(Collection::Vec | Collection::Slice | Collection::Box | Collection::Array(_), inner) => { + match &**inner { + Type::Int(Int::Usize | Int::Isize) => None, + Type::Int(_) | Type::F32 | Type::F64 => Some(inner), + _ => None, + } + } + _ => None, + } +} + +/// The function making a primitive array of `element`s. +fn array_of(element: &Type) -> &'static str { + match element { + Type::Int(Int::U8) => "ubyteArrayOf", + Type::Int(Int::I8) => "byteArrayOf", + Type::Int(Int::U16) => "ushortArrayOf", + Type::Int(Int::I16) => "shortArrayOf", + Type::Int(Int::U32) => "uintArrayOf", + Type::Int(Int::I32) => "intArrayOf", + Type::Int(Int::U64) => "ulongArrayOf", + Type::Int(Int::I64) => "longArrayOf", + Type::F32 => "floatArrayOf", + Type::F64 => "doubleArrayOf", + ty => panic!("an array of {ty:?}"), + } +} + +/// An integer literal of `ty`, typed as Kotlin holds it wherever it stands. +fn int(n: Num, ty: &Type) -> String { + let int = match ty { + Type::Int(int) | Type::NonZero(int) => *int, + Type::U128 => return format!("java.math.BigInteger(\"{n}\")"), + ty => panic!("an integer as {ty:?}"), + }; + match int { + Int::U8 => format!("{n}.toUByte()"), + Int::U16 => format!("{n}.toUShort()"), + Int::U32 => format!("{n}u"), + Int::U64 | Int::Usize => format!("{n}uL"), + Int::I8 => format!("({n}).toByte()"), + Int::I16 => format!("({n}).toShort()"), + Int::I32 if n == Num::new(i32::MIN.into()) => "Int.MIN_VALUE".to_string(), + Int::I32 => format!("({n})"), + Int::I64 | Int::Isize if n == Num::new(i64::MIN.into()) => "Long.MIN_VALUE".to_string(), + Int::I64 | Int::Isize => format!("({n}L)"), + } +} + +/// What Kotlin's arithmetic on `int`, which it widens, converts back with. +fn narrow(int: Int) -> Option<&'static str> { + match int { + Int::U8 => Some("toUByte"), + Int::U16 => Some("toUShort"), + Int::I8 => Some("toByte"), + Int::I16 => Some("toShort"), + _ => None, + } +} + +fn float64(f: f64) -> String { + match f.is_finite() && !(f == 0.0 && f.is_sign_negative()) { + true => format!("{f:?}"), + false => format!("Double.fromBits(0x{:x}uL.toLong())", f.to_bits()), + } +} + +fn float32(f: f32) -> String { + match f.is_finite() && !(f == 0.0 && f.is_sign_negative()) { + true => format!("{f:?}f"), + false => format!("Float.fromBits(0x{:x}u.toInt())", f.to_bits()), + } +} + +fn ipv4(ip: &std::net::Ipv4Addr) -> String { + format!("api.Ipv4Addr({}u)", u32::from(*ip)) +} + +fn ipv6(ip: &std::net::Ipv6Addr) -> String { + format!("api.Ipv6Addr({})", byte_array(&ip.octets())) +} + +/// A field's Kotlin name: in camel case, quoted if a keyword. +fn field_name(name: &str) -> String { + let name = camel(name); + match KEYWORDS.contains(&name.as_str()) { + true => format!("`{name}`"), + false => name, + } +} + +/// A snake-case name in camel case: `into_label` is `intoLabel`, and `0` is `_0`. +fn camel(name: &str) -> String { + if name.starts_with(|c: char| c.is_ascii_digit()) { + return format!("_{name}"); + } + let mut out = String::new(); + let mut up = false; + for c in name.chars() { + match c { + '_' if !out.is_empty() => up = true, + c if up => { + out.extend(c.to_uppercase()); + up = false; + } + c => out.push(c), + } + } + out +} + +/// The tuple element `k` names, from 0. +fn ordinal(k: usize) -> String { + const ORDINALS: [&str; 12] = [ + "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", + "twelfth", + ]; + ORDINALS + .get(k) + .map_or_else(|| format!("item{}", k + 1), |o| o.to_string()) +} + +/// A plain enum's entry: its variant's name in upper snake case. +fn upper(name: &str) -> String { + let mut out = String::new(); + for (i, c) in name.chars().enumerate() { + if c.is_uppercase() && i > 0 { + out.push('_'); + } + out.push(c.to_ascii_uppercase()); + } + out +} + +fn int_name(int: Int) -> String { + let rust = int.rust(); + let mut chars = rust.chars(); + let first = chars.next().unwrap().to_ascii_uppercase(); + format!("{first}{}", chars.as_str()) +} + +/// Text escaped for a Kotlin string literal or template. +fn escape(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + match c { + '"' | '\\' | '$' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + let _ = write!(out, "\\u{:04x}", c as u32); + } + c => out.push(c), + } + } + out +} + +/// A Kotlin string literal. +fn string(s: &str) -> String { + format!("\"{}\"", escape(s)) +} + +/// A Kotlin `ByteArray` of `b`: its text encoded where it is printable UTF-8. +fn byte_array(b: &[u8]) -> String { + match std::str::from_utf8(b) { + Ok(text) if !text.is_empty() && text.chars().all(|c| (' '..='~').contains(&c)) => { + format!("{}.encodeToByteArray()", string(text)) + } + _ => { + let parts: Vec = b.iter().map(|&byte| (byte as i8).to_string()).collect(); + format!("byteArrayOf({})", parts.join(", ")) + } + } +} diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 79879ef50..34bf79c60 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -13,6 +13,7 @@ pub(crate) mod ir; mod parse; +pub(crate) mod kotlin; pub(crate) mod python; use std::collections::BTreeMap; From 6c21bf9ed064cc205aeb4e1dbb3e1f54b68a7e17 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 04:51:35 -0800 Subject: [PATCH 09/28] wip: generate the TypeScript transcript Co-Authored-By: Claude Opus 5.5 --- ffi/tests/api.ts | 974 ++------------ ffi/tests/fixtures.rs | 10 +- ffi/tests/fixtures/transcript/mod.rs | 1 + ffi/tests/fixtures/transcript/typescript.rs | 1336 +++++++++++++++++++ 4 files changed, 1481 insertions(+), 840 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/typescript.rs diff --git a/ffi/tests/api.ts b/ffi/tests/api.ts index 9d0b4d8ec..682cfe262 100644 --- a/ffi/tests/api.ts +++ b/ffi/tests/api.ts @@ -1,90 +1,46 @@ // The api fixture's web test: the script fixtures/api/examples/transcript.rs runs as -// native Rust does on wasm32-wasip1, through the generated TypeScript on Node or Deno, from -// beside the binding's `web` directory, or in a browser, through tests/browser.ts's -// `process`. RUST2_WASM is the path of the module, built with the crate's `web` feature. -// tests/fixtures.rs compares the transcripts. +// native Rust does on wasm32-wasip1, through the TypeScript tests/fixtures/transcript +// writes from it, transcript.ts, which calls the functions exported here that +// transcript.rs defines. It runs on Node or Deno, from beside the binding's `web` +// directory, or in a browser, through tests/browser.ts's `process`. RUST2_WASM is the path +// of the module, built with the crate's `web` feature. tests/fixtures.rs compares the +// transcripts. // // With an argument, it instead checks the futures' semantics, what disposing and the -// garbage collector free, what a closed object refuses, how returned bytes cross, or what -// a call lent bytes or text reads once memory grows, or breaks a contract, which must fail. +// garbage collector free, what a closed object refuses, how returned bytes cross, what a +// call lent bytes or text reads once memory grows, or the binding's own errors the +// transcript cannot say, or breaks a contract, which must fail. +import * as transcript from "./transcript.ts"; import * as api from "./web/index.ts"; import * as rt from "./web/rt.ts"; import * as g from "./web/glue.ts"; -import * as Area from "./web/Area.ts"; -import * as Atlas from "./web/Atlas.ts"; import * as Batch from "./web/Batch.ts"; -import * as Batch2 from "./web/Batch2.ts"; -import * as Berth from "./web/Berth.ts"; import * as Board from "./web/Board.ts"; -import * as Cancelled from "./web/Cancelled.ts"; import * as Channel from "./web/Channel.ts"; -import * as ClashSpan from "./web/ClashSpan.ts"; -import * as ClashStore from "./web/ClashStore.ts"; -import * as ClashTone from "./web/ClashTone.ts"; -import * as ClashTone_ from "./web/ClashTone_.ts"; -import * as Codecs from "./web/Codecs.ts"; import * as Counter from "./web/Counter.ts"; -import * as Cursor from "./web/Cursor.ts"; -import * as Der from "./web/Der.ts"; import * as Digest from "./web/Digest.ts"; -import * as Draft from "./web/Draft.ts"; import * as Error_ from "./web/Error_.ts"; import type * as Event from "./web/Event.ts"; -import * as Extent from "./web/Extent.ts"; -import * as Gap from "./web/Gap.ts"; -import * as Hits from "./web/Hits.ts"; -import * as Instant from "./web/Instant.ts"; -import * as Json from "./web/Json.ts"; import * as Key from "./web/Key.ts"; -import * as Label from "./web/Label.ts"; import * as Labelled from "./web/Labelled.ts"; -import * as Layered from "./web/Layered.ts"; import * as Ledger from "./web/Ledger.ts"; import * as Local from "./web/Local.ts"; import type { Log } from "./web/Log.ts"; import * as Logger from "./web/Logger.ts"; -import * as Mark from "./web/Mark.ts"; -import * as Marker from "./web/Marker.ts"; -import * as Measure from "./web/Measure.ts"; -import * as Message from "./web/Message.ts"; import * as Meter from "./web/Meter.ts"; import * as Meters from "./web/Meters.ts"; import * as Moment from "./web/Moment.ts"; -import * as Name from "./web/Name.ts"; import * as Node from "./web/Node.ts"; import * as Numbers from "./web/Numbers.ts"; -import * as OuterInnerU8 from "./web/OuterInnerU8.ts"; -import * as PadU16 from "./web/PadU16.ts"; -import * as PadU8 from "./web/PadU8.ts"; -import * as PairSizeU8 from "./web/PairSizeU8.ts"; -import * as PairU32 from "./web/PairU32.ts"; -import * as PairU8Size from "./web/PairU8Size.ts"; -import * as Peer from "./web/Peer.ts"; import * as Point from "./web/Point.ts"; -import * as Receipt from "./web/Receipt.ts"; import * as Registry from "./web/Registry.ts"; -import * as Retry from "./web/Retry.ts"; import * as Score from "./web/Score.ts"; -import * as Seat from "./web/Seat.ts"; import * as Shape from "./web/Shape.ts"; -import * as Site from "./web/Site.ts"; -import * as SlotU8 from "./web/SlotU8.ts"; -import * as Span from "./web/Span.ts"; -import * as Stack from "./web/Stack.ts"; -import * as Stamp from "./web/Stamp.ts"; -import * as Tallies from "./web/Tallies.ts"; import * as Tally from "./web/Tally.ts"; -import * as Ticket from "./web/Ticket.ts"; -import * as TlsConfig from "./web/TlsConfig.ts"; -import * as TlsSession from "./web/TlsSession.ts"; import * as Token from "./web/Token.ts"; -import * as Trail from "./web/Trail.ts"; import * as Url from "./web/Url.ts"; -import * as Verbosity from "./web/Verbosity.ts"; import * as Waiter from "./web/Waiter.ts"; -import * as Weighted from "./web/Weighted.ts"; -import * as Window from "./web/Window.ts"; // Node's globals, which the binding's types leave out. declare const process: { @@ -110,11 +66,6 @@ function num(v: rt.u64): number { const U64_MAX = rt.u64FromBig(0xffffffffffffffffn); -/** A `u128` in hex, as transcript.rs prints it. */ -function hex128(v: rt.u128): string { - return rt.u128ToBig(v).toString(16).padStart(32, "0"); -} - const encoder = new TextEncoder(); const decoder = new TextDecoder(); const enc = (text: string) => encoder.encode(text); @@ -126,70 +77,18 @@ function list(values: Iterable): string { return `[${[...values].map((v) => `${v}`).join(", ")}]`; } -/** Bytes in hex, as transcript.rs prints them. */ -function hex(data: Uint8Array): string { - return [...data].map((b) => b.toString(16).padStart(2, "0")).join(""); -} - -/** A socket address as its IP's bytes in hex, its port, flow label, and scope, each IPv6's alone. */ -function socketHex(addr: rt.SocketAddr): string { - if (addr.tag === "V4") return `${hex(addr._0.ip.octets)}:${addr._0.port}`; - const v6 = addr._0; - return `${hex(v6.ip.octets)}:${v6.port}:${v6.flowinfo}:${v6.scopeId}`; -} - -const quoted = (values: string[]) => `[${values.map((v) => `"${v}"`).join(", ")}]`; - -/** A path's bytes as Rust's `escape_ascii` prints them. */ -function escaped(path: rt.PathBuf): string { - let out = ""; - for (const b of path.bytes) { - if (b === 0x09) out += "\\t"; - else if (b === 0x0d) out += "\\r"; - else if (b === 0x0a) out += "\\n"; - else if (b === 0x5c || b === 0x27 || b === 0x22) out += `\\${String.fromCharCode(b)}`; - else if (b >= 0x20 && b < 0x7f) out += String.fromCharCode(b); - else out += `\\x${b.toString(16).padStart(2, "0")}`; - } - return out; -} - -type Bound = ReturnType; - -function bound(b: Bound): string { - return b.tag === "Unbounded" ? "Unbounded" : `${b.tag}(${dec(b._0)})`; -} - /** Each float's bits, as transcript.rs prints them. */ const bits32 = (v: Float32Array) => list(new Uint32Array(v.buffer, v.byteOffset, v.length)); const bits64 = (v: Float64Array) => list(new BigUint64Array(v.buffer, v.byteOffset, v.length)); -/** The floats of `bits`, each never a JavaScript number, whose NaN an engine may make its - * own: Deno's V8 does, storing one in an array literal. */ -const floats64 = (...bits: bigint[]) => new Float64Array(new BigUint64Array(bits).buffer); - -/** Print each of `n`'s lists, its floats as their bits, as transcript.rs does. */ -function numbers(what: string, n: Numbers.Numbers): void { - print(`${what} u16 ${list(n.u16s)}`); - print(`${what} u32 ${list(n.u32s)}`); - print(`${what} u64 ${list(n.u64s)}`); - print(`${what} i8 ${list(n.i8s)}`); - print(`${what} i16 ${list(n.i16s)}`); - print(`${what} i32 ${list(n.i32s)}`); - print(`${what} i64 ${list(n.i64s)}`); - print(`${what} f32 ${bits32(n.f32s)}`); - print(`${what} f64 ${bits64(n.f64s)}`); - print(`${what} some ${n.some === undefined ? "None" : `Some(${list(n.some)})`}`); -} - /** The value of a result that must be `Ok`. */ function unwrap(r: rt.Result): T { if (!r.ok) throw new Error(`an unexpected Err: ${String(r.error)}`); return r.value; } -/** The Log callback: keeps even levels. */ -class PrintLog implements Log { +/** The Log callback: keeps even levels, as transcript.rs's does. */ +export class Print implements Log { log(level: number, line: string): boolean { print(`log ${level} ${line}`); return level % 2 === 0; @@ -345,310 +244,14 @@ class Far implements rt.Reader { } } +/** The transcript, through the TypeScript tests/fixtures/transcript writes from it, which + * calls the functions below that transcript.rs defines. */ async function script(): Promise { - print(`limit ${dec(api.LIMIT)}`); - check(`${rt.i64ToBig(api.FAR)}` === "9223372036854775807", "a constant past a safe integer keeps its type"); - - const p = Point.offset({ x: 1, y: 2 }, 2, 3); - print(`offset ${p.x} ${p.y}`); - print(`debug ${Point.debug(p)}`); - print(`eq ${Point.eq(p, { x: 3, y: 5 })}`); - const d = Point.default(); - print(`default ${d.x} ${d.y}`); - - const c = Counter.new("c", 5); - print(`get ${dec(Counter.get(c))}`); - print(`name ${Counter.name(c)}`); - print(`add ok ${dec(unwrap(Counter.add(c, 10)))}`); - const over = Counter.add(c, 2000); - if (!over.ok) print(`add err ${Error_.toString(over.error)} ${Error_.debug(over.error)}`); - const under = Counter.sub(c, 20); - if (!under.ok) print(`sub err ${Error_.toString(under.error)} ${Error_.debug(under.error)}`); - Counter.rename(c, "d"); - print(`name ${Counter.name(c)}`); - print(`is d ${Counter.is(c, "d")}`); - const copy = Counter.clone(c); - Counter.add(copy, 1); - print(`clone ${dec(Counter.get(copy))} original ${dec(Counter.get(c))}`); - close(copy); - print(`debug ${Counter.debug(c)}`); - const label = Counter.intoLabel(c, p); - print(`label ${Label.debug(label)}`); - print(`note ${api.hasText({ text: "" })} ${api.hasText({ text: undefined })}`); - - const [below, above] = Counter.split(Counter.new("s", 7), 5); - print(`split ${Counter.name(below)} ${dec(Counter.get(below))} ${Counter.name(above)} ${dec(Counter.get(above))}`); - const [only] = api.only(Counter.new("o", 3)); - print(`only ${Counter.name(only)} ${dec(Counter.get(only))}`); - const [w8, w16, w32, w64] = api.widths(98305); - print(`widths ${w8} ${w16} ${w32} ${dec(w64)}`); - for (const b of [2, 0]) { - const r = api.divide(7, b); - print(r.ok ? `divide ${dec(r.value[0])} ${dec(r.value[1])}` : `divide err ${Error_.toString(r.error)}`); - } - for (const n of [98305, 0]) { - const spread = api.spread(n); - print(spread === undefined ? "spread none" : `spread ${spread[0]} ${spread[1]} ${spread[2]} ${dec(spread[3])}`); - } - for (const needle of ["lo", "x"]) { - const found = api.find(enc("hello"), enc(needle)); - print(found === undefined ? "find none" : `find ${found[0]} ${found[1]}`); - } - const statRows = api.rows([ - { x: 1, y: 2 }, - { x: 3, y: 3 }, - ]); - print(`rows ${statRows.map(([n, s, at]) => `${n} ${Shape.debug(s)} ${at.x} ${at.y}`).join(", ")}`); - // Each handle in a tuple moves in, as one taken by value does, and the counters a board - // returns build another, each moved back in. - const first = Board.new([ - ["low", Counter.new("l", 1)], - ["high", Counter.new("h", 9)], - ]); - const board = Board.new(Board.intoCounters(first)); - const ranked = Board.ranked(board); - print(`ranked ${ranked.map(([n, r]) => `${n} ${Counter.name(r)} ${dec(Counter.get(r))}`).join(", ")}`); - const best = Board.best(board); - print(`best ${Counter.name(best)} ${dec(Counter.get(best))}`); - close(best); - close(board); - // A map crosses as its pairs and a set as its items, which Rust collects in order, each - // key once, the last kept. - const atlas = Atlas.with( - { - points: [ - ["b", { x: 1, y: 1 }], - ["ab", { x: 2, y: 3 }], - ["b", { x: 4, y: 4 }], - ], - ids: [3, 1, 3], - }, - "c", - { x: 5, y: 6 }, - ); - print(`atlas ${atlas.points.map(([n, at]) => `${n} ${at.x} ${at.y}`).join(", ")}; ids ${atlas.ids.join(" ")}`); - // Another crate's error crosses as its message. - for (const t of ["80", "x"]) { - const r = api.port(t); - print(r.ok ? `port ${r.value}` : `port err ${r.error}`); - } - const span: Span.Span = { bounds: [2, 10], named: ["s", "Square"] }; - const [lowerHalf, upperHalf] = api.halves(span); - print(`halves ${lowerHalf[0]} ${lowerHalf[1]} ${upperHalf[0]} ${upperHalf[1]} ${Span.debug(span)}`); - const [swappedN, swappedText] = api.swapped(["t", 4]); - print(`swapped ${swappedN} ${swappedText}`); - for (const value of [undefined, [undefined], [3]] as ([number | undefined] | undefined)[]) { - const doubled = api.doubled(value); - if (doubled === undefined) print("doubled None"); - else print(`doubled Some((${doubled[0] === undefined ? "None" : `Some(${doubled[0]})`},))`); - } - // A borrowed or boxed tuple of one is a tuple, not its element. - const [lentOne] = api.lentBack([bytes(1, 2)]); - const [boxedOne] = api.boxedTuple(bytes(3)); - print(`lent back ${list(lentOne)} boxed ${list(boxedOne)}`); - // A borrowed string and an owned one share a tuple struct. - print( - `title Some(("${api.title(true)![0]}",)) ${api.title(false) === undefined ? "None" : "Some"} ` + - `named Some(("${api.named("x")![0]}",))`, - ); - - // Each lent counter is a new handle to a clone. - const registry = Registry.new(Counter.new("first", 1)); - print(`last ${Registry.last(registry) !== undefined}`); - Registry.push(registry, Counter.new("last", 2)); - const lentFirst = Registry.firstGet(registry); - Counter.add(lentFirst, 10); - print(`first ${dec(Counter.get(Registry.firstGet(registry)))} lent ${dec(Counter.get(lentFirst))}`); - const last = Registry.last(registry)!; - Counter.add(last, 10); - print(`last ${dec(Counter.get(Registry.last(registry)!))} lent ${dec(Counter.get(last))}`); - // A closure lent for the call edits the first counter through a handle. - const by = 5; - const edited = Registry.edit(registry, (counter) => { - Counter.add(counter, by); - return Counter.edited(counter) && Counter.get(counter) === 6; - }); - print(`edit ${edited} ${dec(Counter.get(Registry.firstGet(registry)))}`); - // A setter moves an object in, as assignment does, closing it. - Registry.firstSet(registry, Counter.new("second", 3)); - print(`set first ${dec(Counter.get(Registry.firstGet(registry)))} ${Counter.name(Registry.firstGet(registry))}`); - print(`walk ${dec(api.walk(3, (cursor) => num(Cursor.at(cursor)) * 2))}`); - print(`each ${api.each(2, (at) => print(`visit ${at}`))}`); - print(`offset ${api.offset(() => 7, 3)}`); - print(`shift ${api.shift(() => 7, 4)}`); - - const name = Name.owned("a"); - const joined = Name.join(name, Name.owned("b")); - print(`joined ${Name.asStr(joined)} ${Name.debug(joined)} ${Name.eq(joined, name)}`); - Name.rename(joined, "c"); - print(`renamed ${Name.asStr(joined)}`); - const long = api.longer(joined, Name.owned("dd")); - print(`longer ${Name.asStr(long)}`); - print(`unnamed [${Name.asStr(api.unnamed())}]`); - const lit = Name.borrowed("lit"); - print(`borrowed ${Name.asStr(lit)} ${Name.shares(lit, Name.borrowed("lit"))} ${Name.shares(lit, Name.borrowed("other"))}`); - - print(`total ${dec(api.total({ start: 2, end: 5 }))}`); - print(`reach ${api.reach(2, 5)}`); - const scaled = [ - api.scaled(rt.u128FromBig((1n << 128n) - 1n), 1), - api.scaled(rt.u128FromBig((1n << 64n) + 1n), rt.u64FromBig(1n << 63n)), - api.scaled(rt.u128FromBig(1n << 127n), 2), - ]; - print(`scaled ${scaled.map((v) => (v === undefined ? "none" : hex128(v))).join(" ")}`); - const digest = Digest.new(); - Digest.sumSet(digest, unwrap(api.fingerprint("deadbeef"))); - const unparsed = api.fingerprint("zz"); - print( - `digest ${hex(Digest.sumGet(digest))} ${hex(Digest.flipped(digest, bytes(0xff, 0, 0xff, 0)))} ` + - `${unparsed.ok ? "" : unparsed.error}`, - ); - close(digest); - const batch = Batch.new(); - const batch2 = api.pair(); - let accepted = 0; - for (let v = 1; v <= 5; v++) if (Batch.push(batch, v)) accepted++; - let paired = 0; - for (let v = 1; v <= 3; v++) if (Batch2.push(batch2, v)) paired++; - const emptied = api.drain4(batch); - print( - `batch ${Batch.capacity(batch)} ${accepted} ${dec(emptied)} ${dec(api.drain4(batch))} ` + - `${Batch2.capacity(batch2)} ${paired} ${dec(api.drain2(batch2))}`, - ); - print(`capacities ${api.capacities42(batch, batch2)} ${api.capacities22(batch2, batch2)}`); - close(batch); - close(batch2); - const wide = api.widen({ start: 2, end: 5 }, 1); - print(`widen ${dec(wide.start)} ${dec(wide.end)}`); - const counts = ( - [ - [{ tag: "Included", _0: 2 }, { tag: "Excluded", _0: 5 }], - [{ tag: "Included", _0: 2 }, { tag: "Included", _0: 5 }], - [{ tag: "Included", _0: 3 }, { tag: "Unbounded" }], - [{ tag: "Unbounded" }, { tag: "Unbounded" }], - [{ tag: "Excluded", _0: 2 }, { tag: "Included", _0: 4 }], - ] as [Bound, Bound][] - ).map(([start, end]) => api.count({ start, end })); - print(`count ${counts.map(dec).join(" ")}`); - print(`end ${bound(api.end(3))} ${bound(api.end(0))}`); - const [endsStart, endsEnd] = api.ends(3); - print(`ends ${bound(endsStart)} ${bound(endsEnd)}`); - for (const n of [2, 5]) { - const r = api.below(n, 3); - print(r.ok ? `below ${dec(r.value)}` : `below err ${bound(r.error.start)} ${bound(r.error.end)}`); - } - const window: Window.Window = { range: { start: 2, end: 8 }, end: api.end(5) }; - print(`window ${Window.contains(window, 4)} ${Window.contains(window, 6)} ${Window.debug(window)}`); - - print(api.greet("x", "Square")); - print(`len ${api.len(enc("abc"))}`); - const binary = bytes(0xff, 0, 0x61); - print(`hex ${api.hex(binary)}`); - print(`timed hex ${api.timedHex(binary)}`); - print(`sample hex ${api.sampleHex(binary)}`); - print(`queued hex ${api.queuedHex(binary)}`); - print(`tick ${api.tickName({ name: "tick", at: undefined, ttl: undefined })}`); - print(`rooted ${api.rootedName({ name: "rooted", at: undefined, ttl: undefined })}`); - print(`stored ${api.storedText("stored")}`); - print(`layer ${api.layerName({ name: "layer", at: undefined, ttl: undefined })}`); - for (const event of [{ tag: "Moved", _0: p }, { tag: "Named", name: "n" }, { tag: "Done" }] as const) { - print(api.describe(event)); - } - - // A `Copy` value passed by value is copied, so it stays usable. - const stamp = Stamp.fromMillis(2500); - print(`secs ${dec(Stamp.secs(stamp))}`); - print(`later ${Stamp.later(Stamp.fromMillis(3000), stamp)}`); - print(`secs ${dec(Stamp.secs(stamp))}`); - print(`whole ${Stamp.debug(Stamp.whole(stamp))}`); - const message = Message.new(stamp, enc("body")); - print(`payload ${text(Message.payloadGet(message))}`); - print(`stamp ${Stamp.debug(Message.stampGet(message)!)}`); - print(`sent ${Message.sent(message)}`); - // Setters assign in place: the bytes are copied in, and a `Copy` value copied. - const reset = Stamp.fromMillis(4000); - Message.stampSet(message, reset); - Message.payloadSet(message, enc("edited")); - print(`payload ${text(Message.payloadGet(message))}`); - print(`stamp ${Stamp.debug(Message.stampGet(message)!)}`); - print(`secs ${dec(Stamp.secs(reset))}`); - Message.stampSet(message, undefined); - print(`stamp ${Message.stampGet(message) !== undefined}`); - - // A value past a word, copied across: a closure takes and returns one by value. - const moment = Moment.new(1500, 1000)!; - const Forged = rt.Opaque as unknown as new (bytes: Uint8Array) => Moment.Moment; - throws(() => new Forged(new Uint8Array(16)), TypeError, "a caller's opaque value"); - throws(() => Moment.millis({ bytes: new Uint8Array(16) } as unknown as Moment.Moment), RangeError, "a lookalike"); - print(`moment ${dec(Moment.millis(moment))} ${Moment.new(1, 0) === undefined}`); - const shifted = api.shifted(moment, (m) => Moment.after(m, 500)); - print(`shifted ${dec(Moment.millis(shifted))} ${Moment.eq(shifted, Moment.after(moment, 500))}`); - print(`wrapped ${dec(Moment.millis(Moment.after(moment, U64_MAX)))} ${Moment.eq(moment, shifted)}`); - - // A value with padding, or bytes that vary, is a handle, as no table says where padding is. - const gap = Gap.new(7, 3); - print(`gap ${dec(Gap.sum(gap))} ${Gap.eq(gap, Gap.new(7, 3))}`); - const berth = Berth.new(4); - print(`berth Some(${Berth.at(berth)}) ${Berth.at(Berth.new(undefined)) === undefined ? "None" : "Some"}`); - - // A `Copy` type changed in place is a value, which a `&mut self` method returns as the - // call left it, Rust's own return beside it: a change reaches only the copy it replaces. - let score = Score.of(2); - const increment = Score.of(3); - score = Score.add(score, increment); - score = Score.add(score, increment); - print(`score ${dec(Score.count(score))} ${dec(Score.count(Score.doubled(increment)))} ${dec(Score.count(increment))}`); - let [scoreCopy, taken] = Score.take(score); - print(`taken ${dec(taken)} ${dec(Score.count(scoreCopy))} ${dec(Score.count(score))}`); - const otherScore = { v: increment }; - const [absorbed, before0, before1] = Score.absorb(scoreCopy, otherScore); - scoreCopy = absorbed; - print( - `absorbed ${dec(before0)} ${dec(before1)} ${dec(Score.count(scoreCopy))} ` + - `${dec(Score.count(otherScore.v))} ${dec(Score.count(increment))}`, - ); - let hits = Hits.of(1, 2); - const keptHits = hits; - hits = Hits.add(hits, Hits.of(10, 20)); - hits = Hits.hitsSet(hits, 7); - print( - `hits ${dec(Hits.hitsGet(hits))} ${dec(Hits.missesGet(hits))} ${dec(Hits.hitsGet(keptHits))} ` + - `${dec(Hits.missesGet(keptHits))} ${Hits.eq(hits, keptHits)}`, - ); - const [counted, countedSame] = Hits.eq_(keptHits, keptHits); - print(`counted ${countedSame} ${dec(Hits.hitsGet(counted))}`); - let extent = Extent.new(5, 3); - const extentStart = extent; - const [slid, old] = Extent.slide(extent, 10); - extent = slid; - extent = Extent.startSet(extent, num(Extent.startGet(extent)) + 1); - print( - `extent ${dec(old)} ${dec(Extent.startGet(extent))} ${dec(Extent.end(extent))} ` + - `${dec(Extent.startGet(extentStart))} ${dec(Extent.end(extentStart))}`, - ); - const weighted = { score: increment, weight: 4 }; - print(`weighted ${dec(Weighted.total(weighted))} ${num(Score.count(weighted.score)) + num(Score.count(increment))}`); - // A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. - const mark = Mark.of(1); - Mark.add(mark, 2); - const parcel = { mark, payload: bytes(97, 98, 99) }; - print(`heft ${dec(api.heft([mark, bytes(97, 98)], parcel, [Counter.new("w", 1), bytes(97, 98, 99, 100)]))}`); - // A value's `&mut self` beside a checked handle. - const [noted, notedBefore] = Score.note(Score.of(2), Mark.of(5)); - print(`noted ${dec(notedBefore)} ${dec(Score.count(noted))}`); - - print(`kept ${api.emit(new PrintLog(), bytes(1, 2, 3, 4))}`); - const logger = Logger.new(new PrintLog()); - print(`write ${Logger.write(logger, "hi")}`); - close(logger); - print("dropped"); - const threshold = 2; - const filtered = api.filter(bytes(1, 2, 3, 4), (level, line) => { - print(`filter ${level} ${line}`); - return level > threshold; - }); - print(`filtered ${filtered}`); + await transcript.script(); +} +/** A channel's futures, as promises: what transcript.rs polls by hand. */ +export async function channel(): Promise { const channel = Channel.new(); let wakes = 0; // Polled at the call, it pends, and the wake the send posts resumes it from the event loop. @@ -709,416 +312,12 @@ async function script(): Promise { throws(() => waker.wake(), Error, "a closed waker throws", (m) => m === "Waker is closed"); await until(() => wakes === 5, "a returned waker wakes the waiter"); print(`woken ${wakes}`); + close(channel); +} - const nodes = Node.new(1, undefined); - Node.push(nodes, 2); - print(`node ${dec(Node.sum(nodes))}`); - - const tally = Tally.new(); - Tally.bump(tally); - print(`tally ${Tally.bump(tally)} ${Tally.eq(tally, tally)}`); - print(`both ${api.bumpBoth(tally, tally)}`); - print(`peek ${api.peek(tally, (lent) => Tally.bump(lent))}`); - - const area = api.grow(Area.new({ width: 2, height: 3 }), 1); - const areaSize = Area.size(area); - print(`area ${areaSize.width} ${areaSize.height} ${dec(Area.pixels(area))}`); - - // Generic types, each at the instances it infers, named by their arguments. - const pair = { left: 2, right: 5 }; - const swapped = PairU32.swap(pair); - print(`pair ${swapped.left} ${swapped.right} sum ${PairU32.sum(pair)} ${PairU32.debug(pair)} ${PairU32.eq(pair, swapped)}`); - print(`even ${PairU32.even(pair)} ${PairU32.even({ left: 7, right: 7 })}`); - // An instance renamed alone, beside another of `Pair` that keeps its name. - const sized = api.tag({ width: 1, height: 2 }, 3); - const flipped = PairSizeU8.swap(sized); - print(`sized ${flipped.left} ${flipped.right.width} ${PairU8Size.debug(flipped)}`); - const beside = PairU32.besideSize({ left: 258, right: 9 }, sized.left); - print(`beside ${beside.left} ${PairU8Size.debug(beside)}`); - // At its default, named as the type itself. - const stack = Stack.new(); - ["a", "b"].forEach((n, i) => Stack.push(stack, Counter.new(n, i + 1))); - const top = dec(Counter.get(Stack.pop(stack)!)); - print(`stack ${Stack.depth(stack)} Some(${top}) ${Stack.pop(stack) !== undefined} ${Stack.pop(stack) === undefined}`); - // Generic functions and methods, at each implementation of the trait bounding them, by - // reference, which leaves JavaScript its object. - const fromPoint = Counter.seededPoint("p", { x: -3, y: 4 }); - const fromSize = Counter.seededSize("s", { width: 5, height: 6 }); - const fromCounter = Counter.seededCounter("c", fromPoint); - const fromPolar = Counter.seededPolarPoint("q", { turns: 1, distance: 2 }); - print( - `seeded ${dec(Counter.get(fromPoint))} ${dec(Counter.get(fromSize))} ${dec(Counter.get(fromCounter))} ` + - `${dec(Counter.get(fromPolar))} past ${dec(Stack.depthPastPoint(stack, { x: 1, y: 2 }))} ` + - `seeds ${dec(api.seedsPointSize({ width: 2, height: 3 }))}`, - ); - - // A trait implemented for `Point` and `&Point` apart: one instance. - print(`weigh ${api.weighPoint({ x: -1, y: 2 })}`); - // A function named as the type it returns, and one named as a type it does not. - print( - `polar ${api.polarPoint(2)!.distance} ${api.polarPoint(0) === undefined} ` + - `area ${dec(api.area({ width: 2, height: 3 }))}`, - ); - // Two types whose paths join alike, the second kept apart where its path splits. - print(`wind ${api.wind({ whole: 2 }, { part: 3 })}`); - // Names that clash in some language, each kept apart there. - const clashSpan = { width: 4 }; - const clashStore = ClashStore.new(7); - print( - `clash ${ClashTone.debug({ hz: 440 })} ${ClashTone_.debug({ db: 3 })} ${Cancelled.debug({ step: 2 })} ` + - `span ${ClashSpan.width(clashSpan)} ${ClashSpan.toString_(clashSpan)} ${ClashSpan.toString(clashSpan)} ` + - `store ${ClashStore.free(clashStore)} ${ClashStore.close(clashStore)} ` + - `audio ${api.clashAudioEncoderFinish()} ${api.clashAudioEncoderFinish_()} ` + - `nested ${api.clashNested([[1, 2], 3], [[1, 2, 3]])}`, - ); - close(clashStore); - // Instances that name each other, and one made only by an impl of it. - const cross = api.cross({ value: { value: 1 } }, { value: { value: 2 } }); - print(`cross ${cross} outer ${OuterInnerU8.get(OuterInnerU8.new(4))}`); - // A bound that outlives the call takes a value, and an instance only a constant names. - print(`kept ${dec(api.keptPoint({ x: 1, y: -2 }))} boxed ${api.BOXED().value}`); - print(`keep ${api.keepPoint({ x: 1, y: -2 })}`); - const five = { x: 5, y: 2 }; - print(`kept or ${api.keptOrPoint(five)} ${api.keptOrPoint(undefined)} keeper ${api.keeperPoint(five)}`); - // Inferred instances taking a lent closure and a foreign implementation, and one only its - // impl of a trait names. - const sides = { left: 2, right: 5 }; - print(`apply ${api.applyU32(sides, (side) => side * 3)}`); - print(`report ${api.reportU32(sides, new PrintLog())}`); - print(`wrapped ${dec(api.keptWrapU32({ value: 4 }))}`); - print(`keeps ${api.keeps(new PrintLog()).value}`); - - // Its Drop runs when JavaScript disposes it, not before. - const token = Token.new(7); - print(`token ${Token.idGet(token)} dropped ${api.dropped()}`); - close(token); - print(`dropped ${api.dropped()}`); - - // A field and the method of its name, each its own member. - const retry = Retry.new(5); - const limit = Retry.limitGet(retry); - print(`retry ${limit === undefined ? 0 : 1} ${limit ?? 0} ${Retry.limit(retry)} ${Retry.delay(retry)}`); - // The renamed field's setter, named as its getter. - Retry.limitSet(retry, undefined); - print(`retry ${Retry.limit(retry)}`); - print(`slot ${SlotU8.value(SlotU8.new(200))}`); - - // Foreign types: a URL parsed from text, socket addresses, OS paths, and lists. - const base = unwrap(Url.parse("https://example.com/a/b")); - const host = api.host(base); - print(`url ${Url.toString(base)} host ${host === undefined ? "None" : `Some("${host}")`}`); - const url = unwrap(api.resolve(Url.clone(base), "c?d")); - print(`resolve ${Url.toString(url)} ${Url.eq(url, base)}`); - close(url); - const unparsedUrl = Url.parse("no scheme"); - if (!unparsedUrl.ok) print(`parse err ${unparsedUrl.error}`); - const v4: rt.SocketAddrV4 = { ip: { octets: bytes(127, 0, 0, 1) }, port: 8080 }; - const v6: rt.SocketAddrV6 = { ip: { octets: ipv6(1) }, port: 443, flowinfo: 0, scopeId: 3 }; - print(`ports ${list(api.ports([{ tag: "V4", _0: v4 }, { tag: "V6", _0: v6 }]))}`); - const peer = Peer.next({ addr: { tag: "V6", _0: v6 }, names: ["a", "b"] }, "c"); - print(`peer ${Peer.debug(peer)} ${quoted(Peer.aliases(peer))}`); - const file = api.file(rt.pathFrom("dir"), "f\\'\"\t"); - print(`file ${escaped(file)}`); - print(`parents ${api.parents([file, rt.pathFrom("/")]).map((at) => (at === undefined ? "none" : escaped(at))).join(" ")}`); - const words = api.words(" one two three "); - print(`words ${words.length} ${quoted(words)}`); - print(`sentence ${api.sentence(words)} ${api.sentence(undefined)}`); - print(`sentence ${api.sentence([])}|`); - print(`either ${api.either("abc")} ${api.either(undefined)}`); - print(`prefixed ${text(api.prefixed(enc("cd"), enc("ab")))} ${text(api.prefixed(enc("cd"), undefined))}`); - print(`coordinates ${api.coordinates({ x: 2, y: 3 })} ${api.coordinates(undefined)}`); - const two = Counter.new("two", 2); - const three = Counter.new("three", 3); - print(`plus ${dec(Counter.plus(two, three))} ${dec(Counter.plus(two, undefined))}`); - print(`add_to ${Counter.addTo(two, three)} ${Counter.addTo(two, undefined)} ${dec(Counter.get(three))}`); - close(two); - close(three); - const encoded = { v: enc("0,") }; - api.putNumber(1, encoded); - api.putNumber(23, encoded); - print(`put_number ${text(encoded.v)}`); - const entry: rt.Place<[Uint8Array, number]> = { v: [enc("ab"), 1] }; - const stamps = api.pushCounted(entry, 0x63); - print(`push_counted ${stamps} ${text(entry.v[0])} ${entry.v[1]}`); - const digits = { v: enc("7x9") }; - const firstDigit = unwrap(api.digit(digits)); - const skipped = !api.digit(digits).ok; - print(`digit ${firstDigit} ${skipped} ${unwrap(api.digit(digits))} ${digits.v.length}`); - const nudged = { v: { x: 1, y: 2 } }; - api.nudge(nudged, 3); - print(`nudge ${nudged.v.x} ${nudged.v.y}`); - const config = api.secure("h3"); - print(`secure ${api.alpnLent(config)} ${api.alpn(TlsConfig.clone(config))}`); - const cert = api.certify(enc("der")); - const certLen = api.certLen(cert); - print(`cert ${certLen} ${text(api.certDer(cert))} ${api.chainLen([api.certify(enc("a")), api.certify(enc("bc"))])}`); - close(config); - // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. - print(`resolver ${api.resolved(api.resolver("r1"))}`); - const codecs = Codecs.new(); - print(`codecs ${Codecs.ids(codecs)}`); - Codecs.listSet(codecs, Codecs.listGet(codecs).reverse()); - print(`codecs reversed ${Codecs.ids(codecs)}`); - close(codecs); - // A standard library value no type maps, in a handle. - const failure = api.failure("boom"); - print(`failure ${api.failureMessage(failure)} ${api.failureKind(failure)}`); - // Iterators, passed as the arrays of their items. - print(`sum_all ${api.sumAll([1, 2, 3])}`); - print(`weigh_all ${dec(api.weighAllCounter([Counter.new("w", 3)]))}`); - print(`offered_len ${api.offeredLen([enc("h3"), enc("moq-00")])}`); - print(`join_words ${api.joinWords(["a", "b", "c"])}`); - // Bytes that must be `'static`, interned. - for (const what of ["der", "der again"]) { - const der = Der.fromSlice(enc("der")); - print(`${what} ${text(Der.bytes(der))}`); - close(der); - } - const session = unwrap(api.resume("h3", 60)); - print(`resume ${TlsSession.alpn(session)} ${TlsSession.lifetime(session).seconds}`); - close(session); - const unresumed = api.resume("", 60); - if (!unresumed.ok) print(`resume err ${unresumed.error}`); - const meters = Meters.new(); - const lentMeter = Meters.first(meters); - Meter.add(lentMeter, 2); - print(`lent ${dec(Meter.add(lentMeter, 3))} ${dec(Meter.count(Meters.first(meters)))}`); - close(lentMeter); - Meters.clear(meters); - print(`cleared ${dec(Meter.count(Meters.first(meters)))}`); - const lastMeter = Meters.lastGet(meters); - Meter.add(lastMeter, 4); - print(`field lent ${dec(Meter.add(lastMeter, 1))}`); - close(lastMeter); - // An optional field that is not Clone, lent as a handle. - print(`spare ${Meters.spareGet(meters) !== undefined}`); - Meters.spareSet(meters, Meter.default()); - const spare = Meters.spareGet(meters)!; - Meter.add(spare, 5); - print(`spare lent ${dec(Meter.add(spare, 1))}`); - close(spare); - close(meters); - const tallies = Tallies.new(); - Tally.bump(Tallies.first(tallies)); - print(`tallied ${Tally.bump(Tallies.first(tallies))}`); - close(tallies); - // A draft the ledger's `edit` lends holds the ledger borrowed exclusively until it closes, - // and its sheet's members are reached by Deref and DerefMut: the ledger refuses any other - // use meanwhile. - const ledger = Ledger.new(); - const edit = (): Draft.Draft => { - const edited = Ledger.edit(ledger); - if (!edited.ok) throw new Error("an unsealed ledger lends a draft"); - return edited.value; - }; - let draft = edit(); - Draft.titleSet(draft, "minutes"); - Draft.write(draft, "first"); - print(`draft ${Draft.titleGet(draft)} ${Draft.lines(draft)} ${Draft.describe(draft)} ${Draft.edited(draft)}`); - borrowed(() => Ledger.published(ledger), "api_Ledger_published: a handle is borrowed exclusively", "a lent ledger refuses a read"); - print(`committed ${Draft.commit(draft)}`); - close(draft); - print(`ledger ${Ledger.title(ledger)} ${Ledger.published(ledger)}`); - draft = edit(); - print(`read ${Draft.lines(draft)} ${Draft.edited(draft)}`); - close(draft); - draft = edit(); - Draft.write(draft, "second"); - close(draft); - print(`dropped ${Ledger.published(ledger)}`); - const receipt = Ledger.receipt(ledger); - print(`receipt ${Receipt.count(receipt)}`); - close(receipt); - { - const small = PadU8.small(); - const wide = PadU16.wide(); - const layered = Layered.new$(); - const marker = Marker.new$("m", 3, 5); - Marker.ySet(marker, 7); - print( - `forwarded ${PadU16.title(wide)} ${Layered.lines(layered)} ${Marker.xGet(marker)} ${Marker.yGet(marker)} ` + - `[${PadU8.describe(small)}] [${PadU16.describe(wide)}]`, - ); - for (const handle of [small, wide, layered, marker]) close(handle); - } - Ledger.seal(ledger); - const sealed = Ledger.edit(ledger); - if (!sealed.ok) print(`sealed ${Error_.toString(sealed.error)}`); - close(ledger); - print(`chunks ${list(api.chunks(enc("abcde"), 2).map(list))}`); - const counters = api.counters(["x", "y"]); - print(`counters ${counters.map((n) => `${Counter.name(n)} ${dec(Counter.get(n))}`).join(", ")}`); - // Each counter moves in, so a later call throws. - print(`worth ${dec(api.worth([counters[0]], [counters[1]]))} ${dec(api.worth(undefined, []))}`); - for (const counter of counters) closed(() => Counter.get(counter), "Counter", "a counter moved in is closed"); - const held = [api.heldCount([Counter.new("h", 4)]), api.heldCount(undefined)]; - print(`held ${held.map((n) => (n === undefined ? "None" : `Some(${dec(n)})`)).join(" ")}`); - print( - `boxed Some("${api.boxedName(api.boxedCounter("b"))}") ` + - `${api.boxedName(undefined) === undefined ? "None" : "Some"} ${api.boxedCounter(undefined) === undefined}`, - ); - print(`less ${api.less(5, 2)}`); - print(`sums ${list(api.sums([new Uint32Array([1, 2]), new Uint32Array(0), new Uint32Array([3])]))}`); - print(`least ${api.least([[3, 1], [], [2]]).map(list).join(" ")}`); - numbers("edges", Numbers.edges()); - numbers("reversed", Numbers.reversed(Numbers.edges())); - const edges = Numbers.edges(); - const nan = Measure.new(NaN, false); - print( - `float equal ${Numbers.eq(edges, edges)} ${Numbers.eq(edges, Numbers.edges())} ` + - `${Numbers.eq(Numbers.zero(true), Numbers.zero(false))} ${Measure.eq(nan, nan)} ` + - `${Measure.eq(Measure.new(-0, true), Measure.new(0, false))}`, - ); - print(`sum u32 ${dec(api.sumU32(new Uint32Array(0)))} ${dec(api.sumU32(new Uint32Array([0xffffffff, 0xffffffff, 2])))}`); - print(`doubled i64 ${list(api.doubledI64(new BigInt64Array([-(1n << 63n), -1n, 0n, (1n << 63n) - 1n])))}`); - const floats = api.boxedFloats(floats64(1n << 63n, 0x7ff8000000000001n)); - print(`boxed floats ${bits64(floats)}`); - const summed = api.summed([ - { x: 1, y: 2 }, - { x: -4, y: 6 }, - ]); - const noneSummed = api.summed([]); - print(`summed ${summed.x} ${summed.y} ${noneSummed.x} ${noneSummed.y}`); - print(`longest ${api.longest(["a", "abc"])} ${api.longest([])}`); - print(`first of Some("${api.firstOf(["a", "b"])}") ${api.firstOf([]) ?? "None"}`); - const limits = api.byteLimits(enc("a"), enc("bc")); - const waits = api.breadth({ low: { secs: 0, nanos: 5_000_000 }, high: { secs: 2, nanos: 0 } }); - print(`limits ${text(limits.low)} ${text(limits.high)} breadth ${num(waits.secs) * 1000 + Math.floor(waits.nanos / 1e6)}`); - const parts = text(api.joined([enc("ab"), new Uint8Array(0), enc("c")])); - print(`joined ${parts} ${api.joined([]).length} read ${dec(api.readLen(enc("hello")))}`); - const doc = unwrap(Json.parse('{"b": [1, 2.5, null], "a": "é"}')); - print(`json ${api.encode(doc)}`); - print(`timed text ${api.timedText(doc)}`); - const tagged = api.tagged(doc, "t"); - print(`tagged ${Json.toText(tagged)}`); - close(tagged); - // A JSON object's entries cross as pairs of a key and its document, each moved in. - const entries = api.entries( - [ - ["b", unwrap(Json.parse("[1]"))], - ["a", unwrap(Json.parse("2"))], - ], - "t", - ); - print(`entries ${entries.map(([k, v]) => `${k} ${Json.toText(v)}`).join(", ")}`); - for (const [, v] of entries) close(v); - const unparsedJson = Json.parse('{"a":'); - if (!unparsedJson.ok) print(`json parse err ${unparsedJson.error}`); - const site = Site.new(base); - print(`site ${Url.toString(Site.homeGet(site))} ${Url.toString(Site.homeGet(site))}`); - - // Slices, passed in and returned as clones, and the socket address of each family. - const shapes = (values: Shape.Shape[]) => list(values.map(Shape.debug)); - const points = (values: Point.Point[]) => list(values.map(Point.debug)); - const labels = (values: Label.Label[]) => list(values.map(Label.debug)); - print(`shapes ${shapes(Shape.ALL())} greetings ${quoted(api.GREETINGS())}`); - print(`both ${shapes(Shape.BOTH())} primes ${list(api.PRIMES())}`); - const trail = Trail.new( - [ - { x: 1, y: 2 }, - { x: 3, y: 4 }, - ], - ["a", "b"], - ); - print(`trail ${points(Trail.points(trail))} ${labels(Trail.labels(trail))}`); - // Returned iterators, each collected at the call: drained labels are gone after. - print(`iterated ${points(Trail.iter(trail))} ${quoted(Trail.names(trail))} ${list(Trail.bytes(trail))}`); - print(`drained ${labels(Trail.drain(trail))} then ${labels(Trail.labels(trail))}`); - // A filter, collected at the call. - print(`beyond ${Trail.beyond(trail, 1).map((at) => `${at.x} ${at.y}`).join(", ")}`); - close(trail); - const numbered = api.numbered(["p", "q"]); - print(`numbered ${numbered.map((n) => `${Counter.name(n)} ${dec(Counter.get(n))}`).join(", ")}`); - const [next4, next6] = api.nexts(v4, v6); - print(`nexts ${next4.ip.octets.join(".")} ${next4.port} ${next6.port} ${next6.scopeId}`); - const [nextIp4, nextIp6] = api.nextIps({ octets: bytes(10, 0, 0, 255) }, { octets: ipv6(0xffff) }); - const mapped = api.flip({ tag: "V4", _0: { octets: bytes(127, 0, 0, 1) } }); - const ips = [nextIp4, nextIp6, mapped._0, api.flip(mapped)._0, api.flip({ tag: "V6", _0: { octets: ipv6(1) } })._0]; - print(`ips ${ips.map((ip) => hex(ip.octets)).join(" ")}`); - - // Lossless round trips: each type's edge values, passed through Rust and back. - const durations = ( - [ - { secs: 0, nanos: 0 }, - { secs: 0, nanos: 1 }, - { secs: 9223372036, nanos: 854775808 }, - { secs: U64_MAX, nanos: 999999999 }, - ] as rt.Duration[] - ).map(api.sameDuration); - print(`lossless duration ${durations.map((t) => `${dec(t.secs)}.${`${t.nanos}`.padStart(9, "0")}`).join(" ")}`); - const u64s = [0, rt.u64FromBig(1n << 63n), U64_MAX]; - print(`lossless u64 ${u64s.map((v) => dec(api.sameU64(v))).join(" ")}`); - // wasm32's `usize` and `isize` are 32 bits. - print(`lossless usize ${[0, 0xffffffff].map(api.sameUsize).join(" ")}`); - print(`lossless isize ${api.sameIsize(-0x80000000)} ${api.sameIsize(0x7fffffff)}`); - const u128s = [0n, 1n << 64n, (1n << 128n) - 1n].map(rt.u128FromBig); - print(`lossless u128 ${u128s.map((v) => hex128(api.sameU128(v))).join(" ")}`); - print(`lossless char ${[0, 0xd7ff, 0xe000, 0x10ffff].map((v) => api.sameChar(v).toString(16)).join(" ")}`); - // A path no Rust string spells: bytes that are not UTF-8. - const paths = [rt.pathFrom("a/é"), { bytes: bytes(0xff) }]; - print(`lossless path ${paths.map((at) => hex(api.samePath(at).bytes)).join(" ")}`); - const sockV4 = api.sameSocketAddrV4({ ip: { octets: bytes(255, 255, 255, 255) }, port: 65535 }); - const sockV6 = api.sameSocketAddrV6({ - ip: { octets: bytes(0, 1, ...new Array(13).fill(0), 2) }, - port: 3, - flowinfo: 0xffffffff, - scopeId: 0xffffffff, - }); - const socks = [api.sameSocketAddr({ tag: "V4", _0: sockV4 }), api.sameSocketAddr({ tag: "V6", _0: sockV6 })]; - print( - `lossless socket ${socketHex({ tag: "V4", _0: sockV4 })} ${socketHex({ tag: "V6", _0: sockV6 })} ` + - `${socks.map(socketHex).join(" ")}`, - ); - // A key hashes by Rust's `Hash`: equal keys alike, and these two apart. - const hash = (n: string) => dec(Key.hash(Key.new(n))); - print(`key ${hash("a") === hash("a")} ${hash("a") === hash("b")}`); - const sameIps = [ - api.sameIpAddr({ tag: "V4", _0: { octets: bytes(255, 255, 255, 255) } }), - api.sameIpAddr({ tag: "V6", _0: { octets: bytes(0xff, 0xff, ...new Array(13).fill(0), 1) } }), - ]; - print(`lossless ip ${sameIps.map((ip) => hex(ip._0.octets)).join(" ")}`); - - // serde_json's map iterator, collected as pairs of a key and its document. - const sections = api.sections([ - ["b", unwrap(Json.parse("[1]"))], - ["a", unwrap(Json.parse("2"))], - ]); - print(`sections ${sections.map(([k, v]) => `${k} ${Json.toText(v)}`).join(", ")}`); - for (const [, v] of sections) close(v); - // An instant only Rust makes, which each call copies out of its handle, and compares. - const began = api.now(); - const ended = api.later(began, { secs: 1, nanos: 500_000_000 }); - const same = api.later(began, { secs: 0, nanos: 0 }); - const millis = (t: rt.Duration) => num(t.secs) * 1000 + Math.floor(t.nanos / 1e6); - print( - `instants ${millis(api.since(ended, began))} ${millis(api.since(began, ended))} ` + - `${Instant.eq(began, same)} ${Instant.eq(began, ended)}`, - ); - print(`has_instant ${api.hasInstant(began)} ${api.hasInstant(undefined)}`); - // tracing's level, and its filter as an optional level whose undefined is `OFF`. - const verbosity = Verbosity.new("Warn"); - print(`verbosity ${api.spell(Verbosity.filter(verbosity))} ${api.spell(api.louder(Verbosity.filter(verbosity)))}`); - Verbosity.levelSet(verbosity, "Trace"); - print( - `verbosity ${Verbosity.levelGet(verbosity) === "Trace"} ${api.spell(Verbosity.filter(verbosity))} ` + - `${api.spell(api.louder(Verbosity.filter(verbosity)))} ${api.spell(api.louder(undefined))}`, - ); - close(verbosity); - - // A closure's string, which Rust takes. - print(`made ${api.made(3, (n) => `${n} times`)}`); - // A closure taking and returning `Copy` values copies them, never running their `Clone`. - const nine = Ticket.new(9); - const renewed = Ticket.number(api.reissue(Ticket.new(7), (t) => Ticket.new(Ticket.number(t) + 1))); - const copied = Ticket.number(api.reissue(Ticket.new(7), () => nine)); - print(`reissued ${renewed} ${copied}, cloned ${Ticket.clones()}`); - // A record's traits borrow the checked handle it holds. - const nines = Mark.of(9); - const front = api.seat(nines, 1); - const back = api.seat(nines, 2); - print(`seat ${Seat.debug(front)} ${Seat.eq(front, api.seat(nines, 1))} ${Seat.eq(front, back)}`); - // A kept closure: called again at the instant it asks for, then once its waiter wakes, - // failing with Rust's error. +/** A kept closure: called again at the instant it asks for, then once its waiter wakes, + * failing with Rust's error. */ +export async function drive(): Promise { const start = Moment.new(0, 1000)!; let calls = 0; const stopped = await within( @@ -1137,30 +336,127 @@ async function script(): Promise { "a kept closure wakes its future", ); print(`drive ${stopped}`); - // A reader the caller implements, then one whose reads fail. +} + +/** Readers JavaScript implements: one over bytes, one whose reads fail, and a seek from the + * start past `i64::MAX`, which reaches the reader whole, as `Cursor` takes one. */ +export function readers(): void { for (const reader of [new BytesReader(enc("hello world")), new Broken()]) { const r = api.tail(reader, 5); print(r.ok ? `tail ${text(r.value[0])} ${dec(r.value[1])}` : `tail error ${r.error}`); } - // A seek from the start reaches the reader whole, past `i64::MAX`, as `Cursor` takes one. const sought = api.seekTo(new Far(), U64_MAX); print(sought.ok ? `sought ${dec(sought.value)}` : `sought error ${sought.error}`); - print(`non zeros ${api.describeNonZeros(api.nonZeros())}`); - for (const hop of [undefined, 1, U64_MAX]) { - const next = api.nextHop(hop); - print(next === undefined ? "hop None" : `hop Some(${dec(next)})`); - } - print(`farther hop ${api.fartherHop({ left: 3, right: 0xffff })}`); - const local = Local.new(); - const shared = api.localOrNew(local); - const bumped = Local.bump(local); - print(`local ${bumped} ${Local.bump(shared)}`); - print(`local fresh ${Local.bump(api.localOrNew(undefined))}`); - print(`local either ${api.bumpEither(undefined, shared)}`); +} + +/** Futures of a value that is not `Send`, awaited on JavaScript's one thread. */ +export async function localLater(local: Local.Local): Promise { print(`local later ${Local.bump(await api.localOrNewLater(local))}`); print(`local later fresh ${Local.bump(await api.localOrNewLater(undefined))}`); } +/** A path no Rust string spells: on wasm32, as on Unix, bytes that are not UTF-8. */ +export function unspelled(): rt.PathBuf { + return api.stray(); +} + +/** Lowercase hex of `data`, two digits each. */ +export function hex(data: Uint8Array | rt.Bytes): string { + return [...data.slice()].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +/** A path's bytes as Rust's `escape_ascii` prints them. */ +export function escaped(path: rt.PathBuf): string { + let out = ""; + for (const b of path.bytes) { + if (b === 0x09) out += "\\t"; + else if (b === 0x0d) out += "\\r"; + else if (b === 0x0a) out += "\\n"; + else if (b === 0x5c || b === 0x27 || b === 0x22) out += `\\${String.fromCharCode(b)}`; + else if (b >= 0x20 && b < 0x7f) out += String.fromCharCode(b); + else out += `\\x${b.toString(16).padStart(2, "0")}`; + } + return out; +} + +/** A path's bytes in hex. */ +export function pathHex(path: rt.PathBuf): string { + return hex(path.bytes); +} + +/** A duration as its seconds and nine digits of nanoseconds. */ +export function seconds(d: rt.Duration): string { + return `${dec(d.secs)}.${`${d.nanos}`.padStart(9, "0")}`; +} + +/** A duration in whole milliseconds. */ +export function millis(d: rt.Duration): rt.u64 { + return rt.u64FromBig(rt.u64ToBig(d.secs) * 1000n + BigInt(Math.floor(d.nanos / 1e6))); +} + +/** A char's code point, which is how the binding holds one. */ +export function code(c: number): number { + return c; +} + +/** The list reversed. */ +export function reversed(list: T[]): T[] { + return [...list].reverse(); +} + +/** Each float's bits. */ +export function f64Bits(floats: Float64Array): BigUint64Array { + return new BigUint64Array(floats.buffer, floats.byteOffset, floats.length); +} + +/** A socket address as its IP's bytes in hex, its port, flow label, and scope, each IPv6's + * alone, apart by colons. */ +export function socketHex(addr: rt.SocketAddr | rt.SocketAddrV4 | rt.SocketAddrV6): string { + const one: rt.SocketAddrV4 | rt.SocketAddrV6 = "tag" in addr ? addr._0 : addr; + if (one.ip.octets.length === 4) return `${hex(one.ip.octets)}:${one.port}`; + const v6 = one as rt.SocketAddrV6; + return `${hex(v6.ip.octets)}:${v6.port}:${v6.flowinfo}:${v6.scopeId}`; +} + +/** An address's bytes in hex, so the length shows its family. */ +export function ipHex(ip: rt.IpAddr | rt.Ipv4Addr | rt.Ipv6Addr): string { + return hex("tag" in ip ? ip._0.octets : ip.octets); +} + +/** Print each of `n`'s lists, its floats as their bits, as transcript.rs does. */ +export function numbers(what: string, n: Numbers.Numbers): void { + print(`${what} u16 ${list(n.u16s)}`); + print(`${what} u32 ${list(n.u32s)}`); + print(`${what} u64 ${list(n.u64s)}`); + print(`${what} i8 ${list(n.i8s)}`); + print(`${what} i16 ${list(n.i16s)}`); + print(`${what} i32 ${list(n.i32s)}`); + print(`${what} i64 ${list(n.i64s)}`); + print(`${what} f32 ${bits32(n.f32s)}`); + print(`${what} f64 ${bits64(n.f64s)}`); + print(`${what} some ${n.some === undefined ? "None" : `Some(${list(n.some)})`}`); +} + +/** What the transcript's script says only in Rust: the binding's own errors. */ +function checks(): void { + check(`${rt.i64ToBig(api.FAR)}` === "9223372036854775807", "a constant past a safe integer keeps its type"); + // Only Rust makes an opaque value: a caller's throws, and so does a lookalike passed in. + const Forged = rt.Opaque as unknown as new (bytes: Uint8Array) => Moment.Moment; + throws(() => new Forged(new Uint8Array(16)), TypeError, "a caller's opaque value"); + throws(() => Moment.millis({ bytes: new Uint8Array(16) } as unknown as Moment.Moment), RangeError, "a lookalike"); + // A draft borrows its ledger exclusively: the ledger refuses any other use meanwhile. + const ledger = Ledger.new(); + const draft = unwrap(Ledger.edit(ledger)); + borrowed(() => Ledger.published(ledger), "api_Ledger_published: a handle is borrowed exclusively", "a lent ledger refuses a read"); + close(draft); + close(ledger); + // Each counter moves in, so a later call throws. + const counters = api.counters(["x", "y"]); + api.worth([counters[0]!], [counters[1]!]); + for (const counter of counters) closed(() => Counter.get(counter), "Counter", "a counter moved in is closed"); + print("checks ok"); +} + /** The IPv6 address whose last 16 bits are `last`. */ function ipv6(last: number): Uint8Array { const octets = new Uint8Array(16); @@ -1943,6 +1239,8 @@ async function main(): Promise { return bounds(); case "grown": return grown(); + case "checks": + return checks(); default: return broken(which); } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 9b5eadc00..684cba8ff 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1369,6 +1369,12 @@ fn web() -> &'static Web { .env("RUSTFLAGS", "-D warnings")); step::mirror(&api.out.join("web"), &dir.join("web")); step::copy(&manifest_dir().join("tests").join("api.ts"), &dir.join("api.ts")); + let scripts = generated( + "typescript", + "transcript.ts", + &transcript::typescript::emit(transcript()), + ); + step::copy(&scripts.join("transcript.ts"), &dir.join("transcript.ts")); step::write(&dir.join("tsconfig.json"), TSCONFIG); run(Command::new("tsc").arg("-p").arg(&dir)); Web { @@ -1398,7 +1404,7 @@ impl From for Ran { /// The cases of `tests/api.ts` that must pass, after its transcript: `owned` and `bytes` /// check what the garbage collector frees, so only a runtime exposing it runs them. -const WEB_CASES: [&str; 6] = ["futures", "owned", "closed", "bytes", "bounds", "grown"]; +const WEB_CASES: [&str; 7] = ["futures", "owned", "closed", "bytes", "bounds", "grown", "checks"]; /// The cases of `tests/api.ts` that break a contract, each failing with its message. const WEB_BROKEN: [(&str, &str); 9] = [ @@ -1583,7 +1589,7 @@ const TSCONFIG: &str = r#"{ "skipLibCheck": true, "types": [] }, - "include": ["api.ts", "web/*.ts"] + "include": ["api.ts", "transcript.ts", "web/*.ts"] } "#; diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 79879ef50..069da01f4 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -14,6 +14,7 @@ pub(crate) mod ir; mod parse; pub(crate) mod python; +pub(crate) mod typescript; use std::collections::BTreeMap; use std::path::Path; diff --git a/ffi/tests/fixtures/transcript/typescript.rs b/ffi/tests/fixtures/transcript/typescript.rs new file mode 100644 index 000000000..1c3a44c75 --- /dev/null +++ b/ffi/tests/fixtures/transcript/typescript.rs @@ -0,0 +1,1336 @@ +//! The transcript as TypeScript: a module whose `script()` runs it through the web binding, +//! calling `tests/api.ts`'s own exports, which it imports as `hook`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write; + +use super::ir::{Access, Collection, Family, Int, Mutability, Receiver, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, bound, unref}; + +const LANGUAGE: &str = "TypeScript"; + +/// Helpers the script calls, each for a value TypeScript shapes apart from Rust. Each is +/// exported, so one a script leaves unused is no unused local. +const PRELUDE: &str = r#" +const _decoder = new TextDecoder(); + +/** Bytes as UTF-8 text, what is not replaced. */ +export function _text(data: Uint8Array | rt.Bytes): string { + return _decoder.decode(data.slice()); +} + +/** A string's length in UTF-8 bytes, as Rust's `len`. */ +export function _utf8Len(text: string): number { + return rt.encoded(text).length; +} + +/** A string as Rust's `Debug` prints it. */ +export function _quoted(s: string): string { + let out = '"'; + for (const c of s) { + switch (c) { + case '"': + case "\\": + out += "\\" + c; + break; + case "\n": + out += "\\n"; + break; + case "\t": + out += "\\t"; + break; + case "\r": + out += "\\r"; + break; + default: + out += c; + } + } + return out + '"'; +} + +export function _list(items: Iterable, show: (item: T) => string): string { + return `[${Array.from(items, show).join(", ")}]`; +} + +export function _option(value: T | undefined, show: (value: T) => string): string { + return value === undefined ? "None" : `Some(${show(value)})`; +} + +export function _bound( + b: { readonly tag: "Included"; readonly _0: T } | { readonly tag: "Excluded"; readonly _0: T } | { readonly tag: "Unbounded" }, + show: (value: T) => string, +): string { + return b.tag === "Unbounded" ? "Unbounded" : `${b.tag}(${show(b._0)})`; +} + +/** A `u64` in decimal: its form, or a block's `bigint`. */ +export function _u64(v: rt.u64 | bigint): string { + return typeof v === "bigint" ? `${v}` : `${rt.u64ToBig(v)}`; +} + +export function _i64(v: rt.i64 | bigint): string { + return typeof v === "bigint" ? `${v}` : `${rt.i64ToBig(v)}`; +} + +export function _u128(v: rt.u128): string { + return `${rt.u128ToBig(v)}`; +} + +/** An integer in hex, zero-padded to `width` digits. */ +export function _hex(v: bigint, width: number): string { + return v.toString(16).padStart(width, "0"); +} + +/** The value of a result that must be `Ok`. */ +export function _ok(r: rt.Result): T { + if (!r.ok) throw new Error(`an unexpected Err: ${String(r.error)}`); + return r.value; +} + +/** The error of a result that must be `Err`. */ +export function _err(r: rt.Result): E { + if (r.ok) throw new Error("an unexpected Ok"); + return r.error; +} + +/** The value of an option that must be `Some`. */ +export function _some(value: T | undefined): T { + if (value === undefined) throw new Error("an unwrap of None"); + return value; +} + +export function _mapOr(value: T | undefined, none: U, some: (value: T) => U): U { + return value === undefined ? none : some(value); +} + +/** Its elements as a tuple, not an array. */ +export function _tuple(...items: T): T { + return items; +} + +/** The floats of `bits`, each never a JavaScript number, whose NaN an engine may make its + * own: Deno's V8 does, storing one in an array literal. */ +export function _f64s(bits: bigint[]): Float64Array { + return new Float64Array(new BigUint64Array(bits).buffer); +} + +export function _f32s(bits: number[]): Float32Array { + return new Float32Array(new Uint32Array(bits).buffer); +} + +export function _f64(bits: bigint): number { + return _f64s([bits])[0]!; +} + +/** The objects a statement made and lent, which Rust drops as the statement ends. */ +const _temps: Disposable[] = []; + +/** `value`, a temporary, disposed once its statement ends. */ +export function _tmp(value: T): T { + _temps.push(value); + return value; +} + +/** Dispose the statement's temporaries, the last made first, as Rust drops them. */ +export function _free(): void { + for (let value = _temps.pop(); value !== undefined; value = _temps.pop()) value[Symbol.dispose](); +} +"#; + +/// The TypeScript module of `t`'s script. +pub(crate) fn emit(t: &Transcript) -> String { + let mut e = Emitter { + t, + depth: 1, + mutated: Vec::new(), + fresh: 0, + closures: 0, + modules: BTreeSet::new(), + vars: BTreeMap::new(), + temps: false, + }; + mutated(&t.steps, t, &mut e.mutated); + let body = e.steps(&t.steps); + let mut out = String::from( + "// Generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript.\n\n\ + import * as api from \"./web/index.ts\";\n\ + import * as rt from \"./web/rt.ts\";\n\ + import * as hook from \"./api.ts\";\n", + ); + for module in &e.modules { + let _ = writeln!(out, "import * as {module} from \"./web/{module}.ts\";"); + } + out.push_str(PRELUDE); + out.push_str("\nexport async function script(): Promise {\n"); + out.push_str(&body); + out.push_str("}\n"); + out +} + +/// The locals a call takes `&mut` that are values, not objects: each is an `rt.Place`, +/// whose `v` the script reads. +fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec) { + let mut visit = |expr: &Expr| { + walk(expr, &mut |e| { + if let Kind::Call(id, _, args) = &e.kind { + for (arg, param) in args.iter().zip(&t.function(*id).params) { + if let (Kind::Var(name), Type::Ref(Mutability::Mut, inner)) = (&arg.kind, ¶m.ty) + && !matches!(**inner, Type::Object(_) | Type::Reader) + && !out.contains(name) + { + out.push(name.clone()); + } + } + } + }) + }; + for step in steps { + each_expr(step, &mut visit); + } +} + +/// Each expression a step holds, its arms' and closures' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +struct Emitter<'t> { + t: &'t Transcript, + depth: usize, + /// The locals each an `rt.Place`. + mutated: Vec, + fresh: usize, + /// How many closures the expression being written is inside, where nothing awaits. + closures: usize, + /// The binding's type modules the script names, each imported. + modules: BTreeSet, + /// Each local's type. + vars: BTreeMap, + /// Whether the statement being written made a temporary to dispose as it ends. + temps: bool, +} + +/// JavaScript's reserved words, and what the script itself names, which no local may be. +const RESERVED: &str = "\ + break case catch class const continue debugger default delete do else enum export extends false \ + finally for function if import in instanceof new null return super switch this throw true try \ + typeof var void while with yield let static implements interface package private protected \ + public await arguments eval undefined NaN Infinity api rt hook console Array String Number \ + BigInt Symbol Math Error Uint8Array Uint16Array Uint32Array Int8Array Int16Array Int32Array \ + BigUint64Array BigInt64Array Float32Array Float64Array TextDecoder"; + +/// A local's name in TypeScript. +fn ident(name: &str) -> String { + match RESERVED.split_whitespace().any(|r| r == name) { + true => format!("{name}_"), + false => name.to_string(), + } +} + +/// A Rust name in camel case, as the binding names a field or a function: `into_label` is +/// `intoLabel`, and `0` is `_0`. +fn camel(name: &str) -> String { + if name.starts_with(|c: char| c.is_ascii_digit()) { + return format!("_{name}"); + } + let mut out = String::new(); + for (i, part) in name.split('_').filter(|p| !p.is_empty()).enumerate() { + let mut chars = part.chars(); + let first = chars.next().unwrap(); + match i { + 0 => out.extend(first.to_lowercase()), + _ => out.extend(first.to_uppercase()), + } + out.push_str(chars.as_str()); + } + out +} + +/// Names each distinct, as the binding keeps a record's fields apart: `foo` and `foo_`, +/// both `foo` in camel case, are `foo` and `foo2`. +fn distinct(names: Vec) -> Vec { + let mut taken = BTreeSet::new(); + (names.iter()) + .map(|name| { + let mut unique = name.clone(); + let mut n = 2; + while taken.contains(&unique) || (unique != *name && names.contains(&unique)) { + unique = format!("{name}{n}"); + n += 1; + } + taken.insert(unique.clone()); + unique + }) + .collect() +} + +/// A list of `ty` held as a typed array: its item, if so. +fn block(ty: &Type) -> Option<&Type> { + match ty { + Type::List(Collection::Vec | Collection::Slice | Collection::Box | Collection::Array(_), inner) => { + match &**inner { + Type::Int(Int::Usize | Int::Isize) => None, + Type::Int(_) | Type::F32 | Type::F64 => Some(inner), + _ => None, + } + } + _ => None, + } +} + +/// Whether `ty` is an integer the binding holds as `rt.u64`, `rt.i64`, or `rt.u128`, each +/// with its `bigint` conversion. +fn wide(ty: &Type) -> Option<&'static str> { + match ty { + Type::Int(Int::U64) | Type::NonZero(Int::U64) => Some("u64"), + Type::Int(Int::I64) | Type::NonZero(Int::I64) => Some("i64"), + Type::U128 => Some("u128"), + _ => None, + } +} + +/// Whether `expr` is a literal, whose type TypeScript would infer wider than the binding's. +fn literal(expr: &Expr) -> bool { + !matches!( + expr.kind, + Kind::Var(_) + | Kind::Const(_) + | Kind::Call(..) + | Kind::Field(..) + | Kind::Element(..) + | Kind::Clone(_) + | Kind::Unwrap(_) + | Kind::UnwrapErr(_) + | Kind::Local(..) + | Kind::Binary(..) + | Kind::IsSome(_) + | Kind::IsNone(_) + | Kind::IsErr(_) + | Kind::Format(_) + | Kind::Join { .. } + | Kind::MapOr { .. } + | Kind::Utf8(_) + | Kind::Len(_) + | Kind::Default + ) +} + +impl Emitter<'_> { + fn indent(&self) -> String { + "\t".repeat(self.depth) + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("${what}{}", self.fresh) + } + + fn line(&self, out: &mut String, line: &str) { + let _ = writeln!(out, "{}{line}", self.indent()); + } + + /// The binding's module of the type `ty`, imported. + fn module(&mut self, ty: &Type) -> String { + let name = self.t.type_name(LANGUAGE, unref(ty).base()).to_string(); + self.modules.insert(name.clone()); + name + } + + fn steps(&mut self, steps: &[Step]) -> String { + let mut out = String::new(); + for step in steps { + self.step(step, &mut out); + // A closure's statements leave theirs to the statement that called it, whose own + // the closure may still lend. + if self.temps && self.closures == 0 { + self.line(&mut out, "_free();"); + self.temps = false; + } + } + out + } + + /// `v`, the TypeScript of `e`, which a call lends: a temporary object disposed as the + /// statement ends, as Rust drops it. + fn lent(&mut self, e: &Expr, v: String) -> String { + let fresh = matches!( + e.kind, + Kind::Call(..) | Kind::Default | Kind::Clone(_) | Kind::Unwrap(_) | Kind::Local(..) + ); + match (fresh, unref(&e.ty).base()) { + (true, Type::Object(_)) => { + self.temps = true; + format!("_tmp({v})") + } + _ => v, + } + } + + fn step(&mut self, step: &Step, out: &mut String) { + match step { + Step::Let(pat, value) => { + // A value's `&mut self` returns it as the call left it, before what Rust returns. + if let Some((place, call)) = self.mut_receiver(value) { + let ret = unref(&value.ty).clone(); + match (&ret, pat) { + (Type::Unit, Pat::Ignore(_)) => self.line(out, &format!("{place} = {call};")), + (Type::Unit, _) => panic!("a let of a value's &mut self method returning ()"), + _ => { + let t = self.fresh("t"); + self.line(out, &format!("const {t} = {call};")); + self.line(out, &format!("{place} = {t}[0];")); + let rest = match &ret { + Type::Tuple(elements) if elements.len() > 1 => { + let parts: Vec = + (1..=elements.len()).map(|i| format!("{t}[{i}]")).collect(); + format!("_tuple({})", parts.join(", ")) + } + _ => format!("{t}[1]"), + }; + self.bind(pat, &rest, &ret, false, out); + } + } + return; + } + let v = self.expr(value); + match pat { + Pat::Name(name, ty) if self.mutated.contains(name) => { + self.vars.insert(name.clone(), ty.clone()); + let ty = self.ts(ty); + self.line(out, &format!("let {}: rt.Place<{ty}> = {{ v: {v} }};", ident(name))); + } + pat => { + let annotate = literal(value); + self.bind(pat, &v, &value.ty, annotate, out); + } + } + } + Step::Print(pieces) => { + let v = self.pieces(pieces); + self.line(out, &format!("console.log({v});")); + } + Step::Do(value) => { + if let Some((place, call)) = self.mut_receiver(value) { + return match unref(&value.ty) { + Type::Unit => self.line(out, &format!("{place} = {call};")), + _ => self.line(out, &format!("{place} = {call}[0];")), + }; + } + let v = self.expr(value); + // What a language's own function does for its effect may be async, as a + // language's futures are. + let v = match (&value.kind, &value.ty, self.closures) { + (Kind::Local(..), Type::Unit, 0) => format!("await {v}"), + _ => v, + }; + self.line(out, &format!("{v};")); + } + Step::Drop(name) => match self.vars.get(name).map(|ty| unref(ty).base()) { + Some(Type::Object(_)) => self.line(out, &format!("{}[Symbol.dispose]();", ident(name))), + ty => panic!("a drop of {name}, a {ty:?}"), + }, + Step::Match { value, ok, err } => self.matched(value, ok, err, out), + } + } + + /// A call of a method taking a value's `&mut self` on a local: the local's place, and the + /// call, which TypeScript returns the value from as the call left it. + fn mut_receiver(&mut self, value: &Expr) -> Option<(String, String)> { + let Kind::Call(id, Some(receiver), args) = &value.kind else { + return None; + }; + let f = self.t.function(*id); + if f.receiver != Some(Receiver::Mut) || !matches!(id.owner, Owner::Record(_)) { + return None; + } + let Kind::Var(name) = &receiver.kind else { + panic!("a value's &mut self method on anything but a local") + }; + let place = match self.mutated.contains(name) { + true => format!("{}.v", ident(name)), + false => ident(name), + }; + let call = self.call(*id, Some(receiver), args); + Some((place, call)) + } + + /// `let pat = v`, of a value of `ty`, annotated with its type if `annotate`. + fn bind(&mut self, pat: &Pat, v: &str, ty: &Type, annotate: bool, out: &mut String) { + let mut names = Vec::new(); + bound(pat, &mut names); + self.vars.extend(names); + match pat { + Pat::Ignore(_) => self.line(out, &format!("{v};")), + Pat::Name(name, ty) if annotate => { + let ty = self.ts(ty); + self.line(out, &format!("let {}: {ty} = {v};", ident(name))); + } + pat => { + let target = self.pat(pat, ty); + self.line(out, &format!("let {target} = {v};")); + } + } + } + + /// A pattern binding a value of `ty`: a `Bounds`'s by its start and end. + fn pat(&mut self, pat: &Pat, ty: &Type) -> String { + match pat { + Pat::Name(name, ty) => { + self.vars.insert(name.clone(), ty.clone()); + ident(name) + } + Pat::Ignore(_) => String::new(), + Pat::Tuple(pats) => match unref(ty).base() { + Type::Bounds(int) => { + let bound = Type::Bound(*int); + let parts: Vec = (pats.iter().zip(["start", "end"])) + .filter(|(p, _)| !matches!(p, Pat::Ignore(_))) + .map(|(p, key)| format!("{key}: {}", self.pat(p, &bound))) + .collect(); + format!("{{ {} }}", parts.join(", ")) + } + Type::Tuple(elements) => { + let elements = elements.clone(); + let parts: Vec = pats.iter().zip(&elements).map(|(p, ty)| self.pat(p, ty)).collect(); + format!("[{}]", parts.join(", ")) + } + ty => panic!("a tuple pattern of {ty:?}"), + }, + } + } + + fn matched(&mut self, value: &Expr, ok: &Arm, err: &Arm, out: &mut String) { + let v = self.expr(value); + let (test, ok_value, ok_ty, err_value, err_ty) = match &value.ty { + Type::Option(inner) => { + if undefinable(inner) { + panic!("a match on an Option of {inner:?}, whose None is rt.None"); + } + let o = self.fresh("o"); + self.line(out, &format!("const {o} = {v};")); + ( + format!("{o} !== undefined"), + o, + (**inner).clone(), + String::new(), + Type::Unit, + ) + } + Type::Result(ok_ty, err_ty) => { + let r = self.fresh("r"); + self.line(out, &format!("const {r} = {v};")); + ( + format!("{r}.ok"), + format!("{r}.value"), + (**ok_ty).clone(), + format!("{r}.error"), + (**err_ty).clone(), + ) + } + ty => panic!("a match on {ty:?}"), + }; + self.line(out, &format!("if ({test}) {{")); + self.depth += 1; + if let Some(pat) = &ok.pat { + self.bind(pat, &ok_value, &ok_ty, false, out); + } + let body = self.steps(&ok.steps); + out.push_str(&body); + self.depth -= 1; + self.line(out, "} else {"); + self.depth += 1; + if let Some(pat) = &err.pat { + self.bind(pat, &err_value, &err_ty, false, out); + } + let body = self.steps(&err.steps); + out.push_str(&body); + self.depth -= 1; + self.line(out, "}"); + } + + /// The TypeScript type of a value of `ty`, as a literal of it takes it. + fn ts(&mut self, ty: &Type) -> String { + if let Some(item) = block(ty) { + return typed_array(item).to_string(); + } + match ty { + Type::Unit => "undefined".to_string(), + Type::Bool => "boolean".to_string(), + ty if wide(ty).is_some() => format!("rt.{}", wide(ty).unwrap()), + Type::Int(_) | Type::NonZero(_) | Type::F32 | Type::F64 | Type::Char => "number".to_string(), + Type::Str | Type::String => "string".to_string(), + Type::Slice | Type::Vec | Type::Bytes | Type::Array(_) => "Uint8Array".to_string(), + Type::Path | Type::PathBuf => "rt.PathBuf".to_string(), + Type::Duration => "rt.Duration".to_string(), + Type::SocketAddr(Family::Any) => "rt.SocketAddr".to_string(), + Type::SocketAddr(Family::V4) => "rt.SocketAddrV4".to_string(), + Type::SocketAddr(Family::V6) => "rt.SocketAddrV6".to_string(), + Type::IpAddr(Family::Any) => "rt.IpAddr".to_string(), + Type::IpAddr(Family::V4) => "rt.Ipv4Addr".to_string(), + Type::IpAddr(Family::V6) => "rt.Ipv6Addr".to_string(), + Type::List(_, item) => { + let item = self.ts(item); + match item.contains(' ') { + true => format!("({item})[]"), + false => format!("{item}[]"), + } + } + Type::Option(inner) if undefinable(inner) => format!("{} | rt.None", self.ts(inner)), + Type::Option(inner) => format!("{} | undefined", self.ts(inner)), + Type::Box(inner) | Type::Ref(_, inner) => self.ts(inner), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => { + let module = self.module(ty); + format!("{module}.{module}") + } + Type::Range(int) => { + let int = self.ts(&Type::Int(*int)); + format!("{{ start: {int}; end: {int} }}") + } + Type::Bound(int) => { + let int = self.ts(&Type::Int(*int)); + format!( + "{{ readonly tag: \"Included\"; readonly _0: {int} }} | {{ readonly tag: \"Excluded\"; readonly _0: {int} }} | {{ readonly tag: \"Unbounded\" }}" + ) + } + Type::Bounds(int) => { + let bound = self.ts(&Type::Bound(*int)); + format!("{{ start: {bound}; end: {bound} }}") + } + Type::Tuple(elements) => { + let elements: Vec = elements.iter().map(|e| self.ts(e)).collect(); + format!("[{}]", elements.join(", ")) + } + Type::Result(ok, err) => { + let (ok, err) = (self.ts(ok), self.ts(err)); + format!("rt.Result<{ok}, {err}>") + } + ty => panic!("the TypeScript type of {ty:?}"), + } + } + + /// A template literal of a format's pieces. + fn pieces(&mut self, pieces: &[Piece]) -> String { + let mut out = String::from("`"); + for piece in pieces { + match piece { + Piece::Text(text) => out.push_str(&template(text)), + Piece::Value(e, spec) => { + let v = self.expr(e); + let v = self.lent(e, v); + let shown = self.show(&v, &e.ty, *spec); + let _ = write!(out, "${{{shown}}}"); + } + } + } + out.push('`'); + out + } + + /// `v`, a value of `ty`, as a string the way Rust formats it with `spec`. + fn show(&mut self, v: &str, ty: &Type, spec: Spec) -> String { + let ty = unref(ty).base().clone(); + match spec { + Spec::Hex(width) => return format!("_hex({}, {width})", big(v, &ty)), + Spec::Padded(width) => { + return format!("String({}).padStart({width}, \"0\")", self.show(v, &ty, Spec::Display)); + } + Spec::Debug => return self.debug(v, &ty), + Spec::Display => {} + } + match &ty { + Type::Bool => v.to_string(), + Type::String | Type::Str => v.to_string(), + Type::Char => format!("String.fromCodePoint({v})"), + ty if wide(ty).is_some() => format!("_{}({v})", wide(ty).unwrap()), + Type::Int(_) | Type::NonZero(_) => v.to_string(), + Type::Object(_) | Type::Record(_) | Type::Enum(_) => self.text(v, &ty), + ty => panic!("Display of {ty:?}"), + } + } + + /// A type's `Display`: its `Access::Text` method, else its `toString`. + fn text(&mut self, v: &str, ty: &Type) -> String { + let (owner, methods, traits) = match ty { + Type::Record(i) => ( + Owner::Record(*i), + &self.t.api.records[*i].methods, + self.t.api.records[*i].traits, + ), + Type::Enum(i) => ( + Owner::Enum(*i), + &self.t.api.enums[*i].methods, + self.t.api.enums[*i].traits, + ), + Type::Object(i) => ( + Owner::Object(*i), + &self.t.api.objects[*i].methods, + self.t.api.objects[*i].traits, + ), + ty => panic!("Display of {ty:?}"), + }; + let module = self.module(ty); + if let Some(index) = methods.iter().position(|m| m.access == Access::Text) { + let name = self.t.name(LANGUAGE, FnId { owner, index }); + return format!("{module}.{name}({v})"); + } + if !traits.display { + panic!("Display of {}, which has none", self.t.rust(ty)); + } + format!("{module}.toString({v})") + } + + /// `v` as Rust's `Debug` prints a value of `ty`. + fn debug(&mut self, v: &str, ty: &Type) -> String { + let ty = unref(ty).base().clone(); + if let Some(item) = block(&ty) { + let shown = match item { + Type::Int(_) => "`${x}`", + ty => panic!("Debug of a block of {ty:?}"), + }; + return format!("_list({v}, (x) => {shown})"); + } + match &ty { + Type::Bool => format!("`${{{v}}}`"), + ty if wide(ty).is_some() => format!("_{}({v})", wide(ty).unwrap()), + Type::Int(_) | Type::NonZero(_) => format!("`${{{v}}}`"), + Type::String | Type::Str => format!("_quoted({v})"), + Type::Option(inner) => { + if undefinable(inner) { + panic!("Debug of an Option of {inner:?}, whose None is rt.None"); + } + let x = self.fresh("x"); + let show = self.debug(&x, inner); + format!("_option({v}, ({x}) => {show})") + } + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => format!("_list({v}, (x) => `${{x}}`)"), + Type::List(_, item) => { + let x = self.fresh("x"); + let show = self.debug(&x, item); + format!("_list({v}, ({x}) => {show})") + } + Type::Tuple(elements) => { + let parts: Vec = (elements.iter().enumerate()) + .map(|(i, e)| self.debug(&format!("{v}[{i}]"), e)) + .collect(); + let parts: Vec = parts.iter().map(|p| format!("${{{p}}}")).collect(); + let tail = if parts.len() == 1 { ",)" } else { ")" }; + format!("`({}{tail}`", parts.join(", ")) + } + Type::Bound(int) => { + let x = self.fresh("x"); + let show = self.debug(&x, &Type::Int(*int)); + format!("_bound({v}, ({x}) => {show})") + } + Type::Record(_) | Type::Enum(_) | Type::Object(_) => { + let traits = match &ty { + Type::Record(i) => self.t.api.records[*i].traits, + Type::Enum(i) => self.t.api.enums[*i].traits, + Type::Object(i) => self.t.api.objects[*i].traits, + _ => unreachable!(), + }; + if !traits.debug { + panic!("Debug of {}, which has none", self.t.rust(&ty)); + } + let module = self.module(&ty); + format!("{module}.debug({v})") + } + ty => panic!("Debug of {ty:?}"), + } + } + + fn expr(&mut self, e: &Expr) -> String { + self.value(e, &e.ty) + } + + /// The TypeScript of `e`, passed where `want` is taken. + fn value(&mut self, e: &Expr, want: &Type) -> String { + let v = self.bare(e, want); + // An address of one family, where either is taken, is its variant. + match (unref(&e.ty).base(), unref(want).base()) { + (Type::SocketAddr(Family::V4), Type::SocketAddr(Family::Any)) + | (Type::IpAddr(Family::V4), Type::IpAddr(Family::Any)) => { + format!("{{ tag: \"V4\", _0: {v} }}") + } + (Type::SocketAddr(Family::V6), Type::SocketAddr(Family::Any)) + | (Type::IpAddr(Family::V6), Type::IpAddr(Family::Any)) => { + format!("{{ tag: \"V6\", _0: {v} }}") + } + _ => v, + } + } + + fn bare(&mut self, e: &Expr, want: &Type) -> String { + match &e.kind { + Kind::Unit => "undefined".to_string(), + Kind::Bool(b) => b.to_string(), + Kind::Int(n) => int(*n, unref(&e.ty).base()), + Kind::Float(f) => float(*f), + Kind::Char(c) => (*c as u32).to_string(), + Kind::Str(s) => match unref(&e.ty).base() { + Type::Path | Type::PathBuf => format!("rt.pathFrom({})", string(s)), + _ => string(s), + }, + Kind::Bytes(b) => bytes(b), + Kind::Duration(secs, nanos) => { + let secs = int(Num::new(i128::from(*secs)), &Type::Int(Int::U64)); + format!("{{ secs: {secs}, nanos: {nanos} }}") + } + Kind::Socket(addr) => { + let inner = match addr { + std::net::SocketAddr::V4(a) => { + format!("{{ ip: {}, port: {} }}", octets(&a.ip().octets()), a.port()) + } + std::net::SocketAddr::V6(a) => format!( + "{{ ip: {}, port: {}, flowinfo: {}, scopeId: {} }}", + octets(&a.ip().octets()), + a.port(), + a.flowinfo(), + a.scope_id() + ), + }; + match unref(&e.ty).base() { + Type::SocketAddr(Family::Any) => format!("{{ tag: \"{}\", _0: {inner} }}", family(addr.is_ipv4())), + _ => inner, + } + } + Kind::Ip(ip) => { + let inner = match ip { + std::net::IpAddr::V4(v4) => octets(&v4.octets()), + std::net::IpAddr::V6(v6) => octets(&v6.octets()), + }; + match unref(&e.ty).base() { + Type::IpAddr(Family::Any) => format!("{{ tag: \"{}\", _0: {inner} }}", family(ip.is_ipv4())), + _ => inner, + } + } + Kind::None => match unref(want).base() { + Type::Option(inner) if undefinable(inner) => "rt.None".to_string(), + _ => "undefined".to_string(), + }, + Kind::Some(inner) => { + let want = match unref(want).base() { + Type::Option(inner) => (**inner).clone(), + _ => inner.ty.clone(), + }; + self.value(inner, &want) + } + Kind::Tuple(elements) => self.tuple(e, elements, want), + Kind::List(items) => self.list(items, want), + Kind::Record(r, fields) => { + let record = &self.t.api.records[*r]; + let names = distinct(record.fields.iter().map(|f| camel(&f.name)).collect()); + let types: Vec = record.fields.iter().map(|f| f.ty.clone()).collect(); + let parts: Vec = (fields.iter().zip(&types).zip(&names)) + .map(|((f, ty), name)| format!("{name}: {}", self.value(f, ty))) + .collect(); + format!("{{ {} }}", parts.join(", ")) + } + Kind::Variant(en, v, fields) => { + let enumeration = &self.t.api.enums[*en]; + let variant = &enumeration.variants[*v]; + if enumeration.variants.iter().all(|v| v.fields.is_empty()) { + return string(&variant.name); + } + let names = distinct( + (variant.fields.iter()) + .map(|f| match camel(&f.name) { + name if name == "tag" => "tag$".to_string(), + name => name, + }) + .collect(), + ); + let types: Vec = variant.fields.iter().map(|f| f.ty.clone()).collect(); + let mut parts = vec![format!("tag: {}", string(&variant.name))]; + for ((f, ty), name) in fields.iter().zip(&types).zip(&names) { + parts.push(format!("{name}: {}", self.value(f, ty))); + } + format!("{{ {} }}", parts.join(", ")) + } + Kind::Bound(kind, value) => match (kind, value) { + (BoundKind::Unbounded, _) => "{ tag: \"Unbounded\" }".to_string(), + (BoundKind::Included, Some(v)) => format!("{{ tag: \"Included\", _0: {} }}", self.expr(v)), + (BoundKind::Excluded, Some(v)) => format!("{{ tag: \"Excluded\", _0: {} }}", self.expr(v)), + _ => unreachable!(), + }, + Kind::Default => { + let module = self.module(&e.ty); + format!("{module}.default()") + } + Kind::Var(name) => match self.mutated.contains(name) { + // Passed `&mut`, the place itself; read, its value. + true if matches!(want, Type::Ref(Mutability::Mut, _)) => ident(name), + true => format!("{}.v", ident(name)), + false => ident(name), + }, + Kind::Const(c) => { + let key = format!("const {}", self.t.api.constants[*c].path.join("::")); + format!("api.{}", self.t.named(LANGUAGE, &key)) + } + Kind::Call(id, receiver, args) => { + let call = self.call(*id, receiver.as_deref(), args); + match self.t.function(*id).future { + true if self.closures == 0 => format!("(await {call})"), + true => panic!("a call of {} in a closure, which cannot await it", self.t.key(*id)), + false => call, + } + } + Kind::Field(base, i) => { + let b = self.expr(base); + let Type::Record(r) = unref(&base.ty).base() else { + panic!("a field of {:?}", base.ty) + }; + let names = distinct(self.t.api.records[*r].fields.iter().map(|f| camel(&f.name)).collect()); + format!("{b}.{}", names[*i]) + } + Kind::Element(base, i) => { + let b = self.expr(base); + match unref(&base.ty).base() { + Type::Range(_) => format!("{b}.{}", if *i == 0 { "start" } else { "end" }), + _ => format!("{b}[{i}]"), + } + } + Kind::Clone(inner) => { + let v = self.expr(inner); + match unref(&inner.ty).base() { + ty @ Type::Object(_) => { + let module = self.module(ty); + format!("{module}.clone({v})") + } + ty @ Type::List(..) if block(ty).is_some() => format!("{v}.slice()"), + Type::List(..) => format!("[...{v}]"), + // A value, which nothing changes in place. + _ => v, + } + } + Kind::Unwrap(inner) => { + let v = self.expr(inner); + match &inner.ty { + Type::Result(..) => format!("_ok({v})"), + _ => format!("_some({v})"), + } + } + Kind::UnwrapErr(inner) => format!("_err({})", self.expr(inner)), + Kind::IsErr(inner) => format!("!{}.ok", self.expr(inner)), + Kind::IsSome(inner) => format!("({} !== undefined)", self.expr(inner)), + Kind::IsNone(inner) => format!("({} === undefined)", self.expr(inner)), + Kind::Binary(op, a, b) => self.binary(*op, a, b), + Kind::Closure(params, steps, value) => { + let Type::Closure(closure) = unref(&e.ty).base() else { + panic!("a closure of {:?}", e.ty) + }; + let types = closure.params.clone(); + self.closure(params, &types, steps, value) + } + Kind::Local(name, args) => { + let args: Vec = args.iter().map(|a| self.expr(a)).collect(); + match name.starts_with(|c: char| c.is_ascii_uppercase()) { + // A unit struct: a value of the language's own class. + true => format!("new hook.{name}({})", args.join(", ")), + false => format!("hook.{}({})", camel(name), args.join(", ")), + } + } + Kind::Format(pieces) => self.pieces(pieces), + Kind::Join { items, pat, body, sep } => { + let Type::List(_, item) = unref(&items.ty).base() else { + panic!("a join over {:?}", items.ty) + }; + let item = (**item).clone(); + let items = self.expr(items); + let target = self.pat(pat, &item); + self.closures += 1; + let body = self.expr(body); + self.closures -= 1; + format!("Array.from({items}, ({target}) => {body}).join({})", string(sep)) + } + Kind::MapOr { + option, + none, + pat, + some, + } => { + let Type::Option(inner) = unref(&option.ty).base() else { + panic!("a map_or of {:?}", option.ty) + }; + let inner = (**inner).clone(); + let option = self.expr(option); + let none = self.expr(none); + let target = self.pat(pat, &inner); + self.closures += 1; + let some = self.expr(some); + self.closures -= 1; + format!("_mapOr({option}, {none}, ({target}) => {some})") + } + Kind::Utf8(inner) => format!("_text({})", self.expr(inner)), + Kind::Len(inner) => { + let v = self.expr(inner); + match unref(&inner.ty).base() { + Type::String | Type::Str => format!("_utf8Len({v})"), + _ => format!("{v}.length"), + } + } + } + } + + fn binary(&mut self, op: Op, a: &Expr, b: &Expr) -> String { + let ty = unref(&a.ty).base().clone(); + let (x, y) = (self.expr(a), self.expr(b)); + let (x, y) = (self.lent(a, x), self.lent(b, y)); + match op { + Op::Eq => self.equal(&x, &y, &ty), + Op::Ne => format!("!{}", self.equal(&x, &y, &ty)), + Op::And => format!("({x} && {y})"), + Op::Lt | Op::Gt | Op::Add | Op::Sub | Op::Mul | Op::Rem => { + let symbol = match op { + Op::Lt => "<", + Op::Gt => ">", + Op::Add => "+", + Op::Sub => "-", + Op::Mul => "*", + Op::Rem => "%", + _ => unreachable!(), + }; + match wide(&ty) { + Some(_) => { + let joined = format!("{} {symbol} {}", big(&x, &ty), big(&y, &ty)); + match op { + Op::Lt | Op::Gt => format!("({joined})"), + _ => format!("rt.{}FromBig({joined})", wide(&ty).unwrap()), + } + } + None if matches!(ty, Type::Int(_) | Type::NonZero(_) | Type::F32 | Type::F64) => { + format!("({x} {symbol} {y})") + } + None => panic!("{op:?} of {ty:?}"), + } + } + } + } + + /// Whether `x` equals `y`, each a value of `ty`, as Rust's `==` says. + fn equal(&mut self, x: &str, y: &str, ty: &Type) -> String { + if wide(ty).is_some() { + return format!("({} === {})", big(x, ty), big(y, ty)); + } + match ty { + Type::Enum(i) if self.t.api.enums[*i].variants.iter().all(|v| v.fields.is_empty()) => { + format!("({x} === {y})") + } + Type::Record(_) | Type::Enum(_) | Type::Object(_) => { + let module = self.module(ty); + format!("{module}.eq({x}, {y})") + } + Type::Bool | Type::Int(_) | Type::NonZero(_) | Type::Char | Type::String | Type::Str => { + format!("({x} === {y})") + } + ty => panic!("== of {ty:?}"), + } + } + + fn tuple(&mut self, e: &Expr, elements: &[Expr], want: &Type) -> String { + match unref(&e.ty).base() { + Type::Range(_) | Type::Bounds(_) => { + let (a, b) = (self.expr(&elements[0]), self.expr(&elements[1])); + format!("{{ start: {a}, end: {b} }}") + } + _ => { + let wants: Vec = match unref(want).base() { + Type::Tuple(ts) => ts.clone(), + _ => elements.iter().map(|e| e.ty.clone()).collect(), + }; + let parts: Vec = elements.iter().zip(&wants).map(|(e, t)| self.value(e, t)).collect(); + format!("[{}]", parts.join(", ")) + } + } + } + + fn list(&mut self, items: &[Expr], want: &Type) -> String { + let ty = unref(want).base().clone(); + let Type::List(_, item) = &ty else { + panic!("a list as {ty:?}") + }; + let item = (**item).clone(); + let Some(element) = block(&ty) else { + let parts: Vec = items.iter().map(|e| self.value(e, &item)).collect(); + return format!("[{}]", parts.join(", ")); + }; + // A block's items: integers past 32 bits as `bigint`s, and floats as their bits. + let each = |f: &dyn Fn(&Kind) -> Option| -> Vec { + (items.iter()) + .map(|e| f(&e.kind).unwrap_or_else(|| panic!("an item of a block of {element:?} other than a literal"))) + .collect() + }; + match element { + Type::Int(int @ (Int::U64 | Int::I64)) => { + let parts = each(&|k| match k { + Kind::Int(n) => Some(format!("{n}n")), + _ => None, + }); + format!("new {}([{}])", typed_array(&Type::Int(*int)), parts.join(", ")) + } + Type::F64 => { + let parts = each(&|k| match k { + Kind::Float(f) => Some(format!("{:#x}n", f.to_bits())), + _ => None, + }); + format!("_f64s([{}])", parts.join(", ")) + } + Type::F32 => { + let parts = each(&|k| match k { + Kind::Float(f) => Some(format!("{:#x}", (*f as f32).to_bits())), + _ => None, + }); + format!("_f32s([{}])", parts.join(", ")) + } + element => { + let parts: Vec = items.iter().map(|e| self.value(e, &item)).collect(); + format!("new {}([{}])", typed_array(element), parts.join(", ")) + } + } + } + + /// An arrow function: its parameters, of `types`, the steps it runs, and what it returns. + fn closure(&mut self, params: &[Pat], types: &[Type], steps: &[Step], value: &Expr) -> String { + let params: Vec = params.iter().zip(types).map(|(p, ty)| self.pat(p, ty)).collect(); + let params = params.join(", "); + self.closures += 1; + let arrow = match steps.is_empty() { + true => { + let v = self.expr(value); + match v.starts_with('{') { + true => format!("({params}) => ({v})"), + false => format!("({params}) => {v}"), + } + } + false => { + self.depth += 1; + let mut body = self.steps(steps); + if !matches!(value.kind, Kind::Unit) { + let v = self.expr(value); + self.line(&mut body, &format!("return {v};")); + } + self.depth -= 1; + format!("({params}) => {{\n{body}{}}}", self.indent()) + } + }; + self.closures -= 1; + arrow + } + + /// A call of `id`: a function of the module, an associated function of a type, a + /// method, or a field's getter or setter. + fn call(&mut self, id: FnId, receiver: Option<&Expr>, args: &[Expr]) -> String { + let f = self.t.function(id); + let name = self.t.name(LANGUAGE, id).to_string(); + let params: Vec = f.params.iter().map(|p| p.ty.clone()).collect(); + let access = f.access; + let owner = match self.t.owner(id) { + Some(ty) => self.module(&ty), + None => "api".to_string(), + }; + let by_ref = matches!(f.receiver, Some(Receiver::Ref | Receiver::Mut)); + let mut values = Vec::new(); + if let Some(r) = receiver { + let v = self.expr(r); + values.push(if by_ref { self.lent(r, v) } else { v }); + } + for (a, ty) in args.iter().zip(¶ms) { + let v = self.value(a, ty); + values.push(if matches!(ty, Type::Ref(..)) { + self.lent(a, v) + } else { + v + }); + } + match access { + Access::Const => format!("{owner}.{name}()"), + _ => format!("{owner}.{name}({})", values.join(", ")), + } + } +} + +/// Whether a value of `ty` can be `undefined`, so its `Option` keeps `None` apart as `rt.None`. +fn undefinable(ty: &Type) -> bool { + matches!(ty.base(), Type::Unit | Type::Option(_)) +} + +/// The typed array holding a block's elements exactly. +fn typed_array(elem: &Type) -> &'static str { + match elem { + Type::Int(Int::U8) => "Uint8Array", + Type::Int(Int::U16) => "Uint16Array", + Type::Int(Int::U32) => "Uint32Array", + Type::Int(Int::U64) => "BigUint64Array", + Type::Int(Int::I8) => "Int8Array", + Type::Int(Int::I16) => "Int16Array", + Type::Int(Int::I32) => "Int32Array", + Type::Int(Int::I64) => "BigInt64Array", + Type::F32 => "Float32Array", + Type::F64 => "Float64Array", + other => panic!("{other:?} is no block"), + } +} + +/// `v`, a value of the integer type `ty`, as a `bigint`. +fn big(v: &str, ty: &Type) -> String { + match wide(ty) { + Some(wide) => format!("rt.{wide}ToBig({v})"), + None => format!("BigInt({v})"), + } +} + +/// An integer literal of `ty`: a number while it is a safe integer, else its type's form. +fn int(n: Num, ty: &Type) -> String { + const SAFE: u128 = (1 << 53) - 1; + match ty { + ty if wide(ty).is_some() => match n.magnitude <= SAFE { + true => n.to_string(), + false => format!("rt.{}FromBig({n}n)", wide(ty).unwrap()), + }, + // The web binding's target is wasm32, whose pointer is 32 bits: a literal past them, + // which no Rust for wasm32 spells, is the bound `MAX` or `MIN` is on a 64-bit host. + Type::Int(Int::Usize) | Type::NonZero(Int::Usize) => match (n.negative, n.magnitude) { + (false, m) if m <= u128::from(u32::MAX) => n.to_string(), + (false, m) if m == u128::from(u64::MAX) => u32::MAX.to_string(), + _ => panic!("{n} as wasm32's usize"), + }, + Type::Int(Int::Isize) | Type::NonZero(Int::Isize) => { + let v = if n.negative { + -(n.magnitude as i128) + } else { + n.magnitude as i128 + }; + match v { + v if i32::try_from(v).is_ok() => v.to_string(), + v if v == i128::from(i64::MAX) => i32::MAX.to_string(), + v if v == i128::from(i64::MIN) => i32::MIN.to_string(), + _ => panic!("{n} as wasm32's isize"), + } + } + Type::Int(_) | Type::NonZero(_) => n.to_string(), + ty => panic!("an integer literal as {ty:?}"), + } +} + +/// A float literal: a NaN other than JavaScript's own, by its bits. +fn float(f: f64) -> String { + match f { + f if f.is_nan() && f.to_bits() != f64::NAN.to_bits() => format!("_f64({:#x}n)", f.to_bits()), + f if f.is_nan() => "NaN".to_string(), + f if f == f64::INFINITY => "Infinity".to_string(), + f if f == f64::NEG_INFINITY => "-Infinity".to_string(), + f => format!("{f:?}"), + } +} + +fn family(v4: bool) -> &'static str { + if v4 { "V4" } else { "V6" } +} + +/// An IP address's octets, as the binding holds one. +fn octets(b: &[u8]) -> String { + format!("{{ octets: {} }}", bytes(b)) +} + +fn bytes(b: &[u8]) -> String { + let parts: Vec = b.iter().map(u8::to_string).collect(); + format!("new Uint8Array([{}])", parts.join(", ")) +} + +/// A JavaScript string literal. +fn string(s: &str) -> String { + let mut out = String::from("\""); + for c in s.chars() { + match c { + '"' | '\\' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 => { + let _ = write!(out, "\\u{:04x}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); + out +} + +/// Text inside a template literal. +fn template(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + match c { + '`' | '\\' | '$' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 => { + let _ = write!(out, "\\u{:04x}", c as u32); + } + c => out.push(c), + } + } + out +} From a90015db7c723f1800082209f27f54a58ccd3909 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:07:23 -0800 Subject: [PATCH 10/28] wip: generate the Swift transcript Co-Authored-By: Claude Opus 5.5 --- ffi/tests/api.swift | 913 +++---------- ffi/tests/fixtures.rs | 11 +- ffi/tests/fixtures/transcript/ir.rs | 39 +- ffi/tests/fixtures/transcript/mod.rs | 1 + ffi/tests/fixtures/transcript/swift.rs | 1633 ++++++++++++++++++++++++ 5 files changed, 1831 insertions(+), 766 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/swift.rs diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index 2e680c490..e2e5872ac 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -1,8 +1,10 @@ // The api fixture's Swift test: the script fixtures/api/examples/transcript.rs runs -// natively, through the generated Swift. tests/fixtures.rs compares the transcripts. +// natively, through the generated Swift, which tests/fixtures/transcript writes as +// transcript.swift's `transcript()`. tests/fixtures.rs compares the transcripts. Each +// function transcript.rs defines is this file's, by the same name. // -// With an argument, it instead checks the futures' semantics, what releasing frees, or -// breaks a contract, which must fail. +// With an argument, it instead checks what only Swift says, the futures' semantics, what +// releasing frees, or breaks a contract, which must fail. import Api import BasicContainers @@ -12,7 +14,7 @@ import NoDump #endif // The Log callback: keeps even levels. -final class PrintLog: Log { +final class Print: Log { func log(_ level: UInt8, _ line: String) -> Bool { print("log \(level) \(line)") return level % 2 == 0 @@ -24,6 +26,7 @@ final class PrintLog: Log { } } + /// A Log that counts its frees. final class DropLog: Log { let drops: Cell @@ -57,18 +60,6 @@ final class CancelLog: Log, @unchecked Sendable { } } -func bound(_ b: BoundU64) -> String { - switch b { - case .included(let n): return "Included(\(n))" - case .excluded(let n): return "Excluded(\(n))" - case .unbounded: return "Unbounded" - } -} - -func debug(_ value: T) -> String { - String(reflecting: value) -} - func text(_ data: Bytes) -> String { String(decoding: data, as: UTF8.self) } @@ -120,15 +111,6 @@ func refusal(_ reason: String) -> Refusal { fatalError("refuse returned") } -/// Each of `items` as `each` prints it, joined by commas. -func listed(_ items: borrowing UniqueArray, _ each: (borrowing T) -> String) -> String { - var out: [String] = [] - for i in 0.. String { var out = "" @@ -251,322 +233,11 @@ func block(_ body: @escaping @Sendable () async throws -> T) -> T { return try! value.get() } -func script() { - print("limit \(LIMIT)") - - let p = Point(x: 1, y: 2).offset(2, 3) - print("offset \(p.x) \(p.y)") - print("debug \(debug(p))") - print("eq \(p == Point(x: 3, y: 5))") - let d = Point.default() - print("default \(d.x) \(d.y)") - - var c = Counter.new("c", 5) - print("get \(try! c.get())") - print("name \(try! c.name())") - print("add ok \(try! c.add(10))") - do { - _ = try c.add(2000) - } catch let e as Api.Error { - print("add err \(e) \(debug(e))") - } catch { - check(false, "add throws an Error") - } - do { - _ = try c.sub(20) - } catch let e as Api.Error { - print("sub err \(e) \(debug(e))") - } catch { - check(false, "sub throws an Error") - } - try! c.rename("d") - print("name \(try! c.name())") - print("is d \(try! c.`is`("d"))") - var copy = try! c.clone() - _ = try! copy.add(1) - print("clone \(try! copy.get()) original \(try! c.get())") - print("debug \(try! c.debugDescription)") - let label = try! c.intoLabel(p) - print("label \(debug(label))") - print("note \(hasText(Note(text: ""))) \(hasText(Note(text: nil)))") - - // A tuple holding a handle is a struct of its elements. - let split = try! Counter.new("s", 7).split(5) - print("split \(try! split._0.name()) \(try! split._0.get()) \(try! split._1.name()) \(try! split._1.get())") - let one = try! only(Counter.new("o", 3)) - print("only \(try! one.name()) \(try! one.get())") - let (w8, w16, w32, w64) = widths(98305) - print("widths \(w8) \(w16) \(w32) \(w64)") - for b: UInt64 in [2, 0] { - do { - let (q, r) = try divide(7, b) - print("divide \(q) \(r)") - } catch { - print("divide err \(error)") - } - } - for n: UInt64 in [98305, 0] { - if let s = spread(n) { - print("spread \(s.0) \(s.1) \(s.2) \(s.3)") - } else { - print("spread none") - } - } - for needle in ["lo", "x"] { - if let found = find(Bytes("hello".utf8), Bytes(needle.utf8)) { - print("find \(found.0) \(found.1)") - } else { - print("find none") - } - } - let statRows = rows([Point(x: 1, y: 2), Point(x: 3, y: 3)]) - print("rows \(statRows.map { "\($0.0) \(debug($0.1)) \($0.2.x) \($0.2.y)" }.joined(separator: ", "))") - // Each handle in a tuple moves in, as one taken by value does, and an array of them is a - // `UniqueArray`. - var ranks = UniqueArray() - ranks.append(TupleStringCounter("low", Counter.new("l", 1))) - ranks.append(TupleStringCounter("high", Counter.new("h", 9))) - let board = try! Board.new(ranks) - let ranked = try! board.ranked() - print("ranked \(listed(ranked) { "\($0._0) \(try! $0._1.name()) \(try! $0._1.get())" })") - let best = try! board.best() - print("best \(try! best.name()) \(try! best.get())") - // A map crosses as its pairs and a set as its items, which Rust collects in order, each - // key once, the last kept. - let atlas = Atlas(points: [("b", Point(x: 1, y: 1)), ("ab", Point(x: 2, y: 3)), ("b", Point(x: 4, y: 4))], ids: [3, 1, 3]) - .with("c", Point(x: 5, y: 6)) - let atlasPoints = atlas.points.map { "\($0.0) \($0.1.x) \($0.1.y)" }.joined(separator: ", ") - print("atlas \(atlasPoints); ids \(atlas.ids.map { "\($0)" }.joined(separator: " "))") - // Another crate's error crosses as its message. - for text in ["80", "x"] { - do { - print("port \(try port(text))") - } catch let e as StringError { - print("port err \(e.error)") - } catch { - check(false, "port throws its message") - } - } - let span = Span(bounds: (2, 10), named: ("s", .square)) - let (lowerHalf, upperHalf) = halves(span) - print("halves \(lowerHalf.0) \(lowerHalf.1) \(upperHalf.0) \(upperHalf.1) \(debug(span))") - let (swappedN, swappedText) = swapped(("t", 4)) - print("swapped \(swappedN) \(swappedText)") - // A tuple of one is its element, so `Option<(Option,)>` nests two optionals. - for value: UInt32?? in [.none, .some(nil), .some(3)] { - switch doubled(value) { - case .none: print("doubled None") - case .some(let inner): print("doubled Some((\(inner.map { "Some(\($0))" } ?? "None"),))") - } - } - print("lent back \(Array(lentBack(Bytes([1, 2])))) boxed \(Array(boxedTuple(Bytes([3]))))") - // A borrowed string and an owned one share a tuple struct. - print("title Some((\"\(title(true)!)\",)) \(title(false) == nil ? "None" : "Some") named Some((\"\(named("x")!)\",))") - - // Each lent counter is a new handle to a clone. - var registry = try! Registry.new(Counter.new("first", 1)) - print("last \(try! registry.last() != nil)") - try! registry.push(Counter.new("last", 2)) - var first = try! registry.firstGet() - _ = try! first.add(10) - print("first \(try! registry.firstGet().get()) lent \(try! first.get())") - var last = try! registry.last()! - _ = try! last.add(10) - print("last \(try! registry.last()!.get()) lent \(try! last.get())") - // A closure lent for the call edits the first counter through a handle. - let by: UInt64 = 5 - let edited = try! registry.edit { counter in - _ = try! counter.add(by) - return try! counter.edited() && counter.get() == 6 - } - print("edit \(edited) \(try! registry.firstGet().get())") - // A setter moves an object in, as assignment does, closing its handle. - try! registry.firstSet(Counter.new("second", 3)) - print("set first \(try! registry.firstGet().get()) \(try! registry.firstGet().name())") - print("walk \(walk(3) { cursor in try! cursor.at() * 2 })") - print("each \(each(2) { at in print("visit \(at)") })") - print("offset \(offset({ 7 }, 3))") - print("shift \(shift({ 7 }, 4))") - - let name = Name.owned("a") - var joined = try! name.join(Name.owned("b")) - print("joined \(try! joined.asStr()) \(try! joined.debugDescription) \(try! joined == name)") - try! joined.rename("c") - print("renamed \(try! joined.asStr())") - let long = try! longer(joined, Name.owned("dd")) - print("longer \(try! long.asStr())") - print("unnamed [\(try! unnamed().asStr())]") - let lit = Name.borrowed("lit") - print("borrowed \(try! lit.asStr()) \(try! lit.shares(Name.borrowed("lit"))) \(try! lit.shares(Name.borrowed("other")))") - - print("total \(total(RangeU64(start: 2, end: 5)))") - print("reach \(reach(2, 5))") - let scaledHex = [ - scaled(U128(high: .max, low: .max), 1), scaled(U128(high: 1, low: 1), 1 << 63), scaled(U128(high: 1 << 63, low: 0), 2), - ].map { v in - v.map { v in [v.high, v.low].map { h in Swift.String(repeating: "0", count: 16 - Swift.String(h, radix: 16).count) + Swift.String(h, radix: 16) }.joined() } ?? "none" - } - print("scaled \(scaledHex.joined(separator: " "))") - check(U128(high: .max, low: .max).description == "340282366920938463463374607431768211455", "a u128's decimal digits") - let sumHex = { (sum: ArrayU8x4) in sum.map { Swift.String(format: "%02x", $0) }.joined() } - var digest = Digest.new() - try! digest.sumSet(try! fingerprint("deadbeef")) - var unparsed = "" - do { - _ = try fingerprint("zz") - } catch let e as StringError { - unparsed = e.error - } catch { - check(false, "fingerprint throws its message") - } - print("digest \(sumHex(try! digest.sumGet)) \(sumHex(try! digest.flipped(ArrayU8x4([0xff, 0, 0xff, 0])!))) \(unparsed)") - check(ArrayU8x4([1, 2, 3]) == nil, "3 bytes are no [u8; 4]") - var batch = Batch.new(), batch2 = pair() - let accepted = (1...5).filter { try! batch.push($0) }.count - let paired = (1...3).filter { try! batch2.push($0) }.count - let emptied = try! drain4(&batch) - print("batch \(try! batch.capacity()) \(accepted) \(emptied) \(try! drain4(&batch)) \(try! batch2.capacity()) \(paired) \(try! drain2(&batch2))") - print("capacities \(try! capacities42(batch, batch2)) \(try! capacities22(batch2, batch2))") - let wide = widen(RangeU64(start: 2, end: 5), 1) - print("widen \(wide.start) \(wide.end)") - let counts = [ - BoundsU64(start: .included(2), end: .excluded(5)), - BoundsU64(start: .included(2), end: .included(5)), - BoundsU64(start: .included(3), end: .unbounded), - BoundsU64(start: .unbounded, end: .unbounded), - BoundsU64(start: .excluded(2), end: .included(4)), - ].map { count($0) } - print("count \(counts.map(String.init).joined(separator: " "))") - print("end \(bound(end(3))) \(bound(end(0)))") - let (endsStart, endsEnd) = ends(3) - print("ends \(bound(endsStart)) \(bound(endsEnd))") - for n: UInt64 in [2, 5] { - do { - print("below \(try Api.below(n, 3))") - } catch let e as BoundsU64Error { - print("below err \(bound(e.error.start)) \(bound(e.error.end))") - } catch { - check(false, "below throws its bounds") - } - } - let window = Window(range: RangeU64(start: 2, end: 8), end: end(5)) - print("window \(window.contains(4)) \(window.contains(6)) \(debug(window))") - - print(greet("x", .square)) - print("len \(len(Bytes("abc".utf8)))") - let binary = Bytes([0xff, 0, 0x61]) - print("hex \(hex(binary))") - print("timed hex \(timedHex(binary))") - print("sample hex \(sampleHex(binary))") - print("queued hex \(queuedHex(binary))") - print("tick \(tickName(Label(name: "tick", at: nil, ttl: nil)))") - print("rooted \(rootedName(Label(name: "rooted", at: nil, ttl: nil)))") - print("stored \(storedText("stored"))") - print("layer \(layerName(Label(name: "layer", at: nil, ttl: nil)))") - for event: Event in [.moved(p), .named(name: "n"), .done] { - print(describe(event)) - } - check(advance(.init_(1)) == .init_(0) && advance(.init_(0)) == .done, "a variant named init crosses") - // Rust's seconds are a u64, past Int64's. - let rustMax = try! RustDuration(secs: .max, nanos: 999_999_999) - let past = RustDuration.seconds(UInt64(Int64.max) + 1) - check( - extended(past, try! RustDuration(secs: UInt64(Int64.max), nanos: 999_999_999)) == rustMax, - "a duration past Int64's seconds crosses") - check(extended(try! RustDuration(secs: .max, nanos: 999_999_996), .nanoseconds(3)) == rustMax, "Rust's longest duration crosses") - check(extended(rustMax, .nanoseconds(1)) == nil, "Rust refuses a duration past its longest") - durations(rustMax) - - // A `Copy` handle passed by value is copied, so it stays usable. - let stamp = Stamp.fromMillis(2500) - print("secs \(stamp.secs())") - print("later \(Stamp.fromMillis(3000).later(stamp))") - print("secs \(stamp.secs())") - print("whole \(debug(stamp.whole()))") - var message = Message.new(stamp, Bytes("body".utf8)) - print("payload \(text(try! message.payloadGet))") - print("stamp \(debug(try! message.stampGet!))") - print("sent \(try! message.sent())") - // Setters assign in place: the bytes are copied in, and a `Copy` handle copied. - let reset = Stamp.fromMillis(4000) - try! message.stampSet(reset) - try! message.payloadSet(Bytes("edited".utf8)) - print("payload \(text(try! message.payloadGet))") - print("stamp \(debug(try! message.stampGet!))") - print("secs \(reset.secs())") - try! message.stampSet(nil) - print("stamp \(try! message.stampGet != nil)") - - // A value past a word, copied across: a closure takes and returns one by value. - let moment = Moment.new(1500, 1000)! - print("moment \(moment.millis()) \(Moment.new(1, 0) == nil)") - let shifted = shifted(moment) { $0.after(500) } - print("shifted \(shifted.millis()) \(shifted == moment.after(500))") - print("wrapped \(moment.after(UInt64.max).millis()) \(moment == shifted)") - - // A value with padding, or bytes that vary, is a handle, as no table says where padding is. - let gap = Gap.new(7, 3) - print("gap \(gap.sum()) \(gap == Gap.new(7, 3))") - let berth = Berth.new(4) - print("berth Some(\(berth.at()!)) \(Berth.new(nil).at() == nil ? "None" : "Some")") - - // A `Copy` type changed in place is a value, whose change reaches only the copy changed. - var score = Score.of(2) - let step = Score.of(3) - score.add(step) - score.add(step) - print("score \(score.count()) \(step.doubled().count()) \(step.count())") - var scoreCopy = score - let taken = scoreCopy.take() - print("taken \(taken) \(scoreCopy.count()) \(score.count())") - var otherScore = step - let before = scoreCopy.absorb(&otherScore) - print("absorbed \(before.0) \(before.1) \(scoreCopy.count()) \(otherScore.count()) \(step.count())") - var hits = Hits.of(1, 2) - let keptHits = hits - hits.add(Hits.of(10, 20)) - hits.hitsSet(7) - print("hits \(hits.hitsGet) \(hits.missesGet) \(keptHits.hitsGet) \(keptHits.missesGet) \(hits == keptHits)") - var counted = keptHits - let countedSame = counted.eq(keptHits) - print("counted \(countedSame) \(counted.hitsGet)") - var extent = Extent.new(5, 3) - let extentStart = extent - let old = extent.slide(10) - extent.startSet(extent.startGet + 1) - print("extent \(old) \(extent.startGet) \(extent.end()) \(extentStart.startGet) \(extentStart.end())") - let weighted = Weighted(score: step, weight: 4) - print("weighted \(weighted.total()) \(weighted.score.count() + step.count())") - // A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. - let mark = Mark.of(1) - try! mark.add(2) - let parcel = Parcel(mark: mark, payload: Bytes("abc".utf8)) - print("heft \(try! heft((mark, Bytes("ab".utf8)), parcel, TupleCounterBytes(Counter.new("w", 1), Bytes("abcd".utf8))))") - // A value's `&mut self` beside a checked handle. - var noted = Score.of(2) - let notedBefore = try! noted.note(Mark.of(5)) - print("noted \(notedBefore) \(noted.count())") - - // Bound first, so Swift's reference is gone before the print. - let kept = emit(PrintLog(), Bytes([1, 2, 3, 4])) - print("kept \(kept)") - do { - let logger = Logger.new(PrintLog()) - print("write \(logger.write("hi"))") - } - print("dropped") - // Rust calls it on another thread, before the call returns. - let threshold: UInt8 = 2 - let filtered = filter(Bytes([1, 2, 3, 4])) { level, line in - print("filter \(level) \(line)") - return level > threshold - } - print("filtered \(filtered)") - +/// A channel's futures, on an executor the script drains, so it sees each wait and the +/// wake that queues its resume. +func channel() { let channel = Channel.new() let wakes = Cell(0) - // On an executor the script drains, so it sees the receive wait and its wake queue - // the resume. let q = Queue() let got = Cell(nil) q.launch { got.value = try await channel.recv() } @@ -621,134 +292,115 @@ func script() { try! waiter.context()() } print("woken \(wakes.value)") +} - var list = try! Node.new(1, nil) - try! list.push(2) - print("node \(try! list.sum())") - - let tally = Tally.new() - _ = try! tally.bump() - print("tally \(try! tally.bump()) \(try! tally == tally)") - print("both \(try! bumpBoth(tally, tally))") - print("peek \(try! peek(tally) { lent in try! lent.bump() })") - - let grown = grow(Area.new(Size(width: 2, height: 3)), 1) - let size = grown.size() - print("area \(size.width) \(size.height) \(grown.pixels())") - - // Generic types, each at the instances it infers, named by their arguments. - let pair = PairU32(left: 2, right: 5) - let swappedPair = pair.swap() - print("pair \(swappedPair.left) \(swappedPair.right) sum \(pair.sum()) \(debug(pair)) \(pair == swappedPair)") - print("even \(pair.even()) \(PairU32(left: 7, right: 7).even())") - // An instance renamed alone, beside another of `Pair` that keeps its name. - let sized: PairSizeU8 = tag(Size(width: 1, height: 2), 3) - let flipped: PairU8Size = sized.swap() - print("sized \(flipped.left) \(flipped.right.width) \(debug(flipped))") - let beside = PairU32(left: 258, right: 9).besideSize(sized.left) - print("beside \(beside.left) \(debug(beside))") - // At its default, named as the type itself. - var stack = Stack.new() - for (i, n) in ["a", "b"].enumerated() { - try! stack.push(Counter.new(n, UInt64(i) + 1)) - } - let top = try! stack.pop()!.get() - print("stack \(try! stack.depth()) Some(\(top)) \(try! stack.pop() != nil) \(try! stack.pop() == nil)") - // Generic functions and methods, at each implementation of the trait bounding them, by - // reference, which leaves Swift its handle. - let fromPoint = Counter.seededPoint("p", Point(x: -3, y: 4)) - let fromSize = Counter.seededSize("s", Size(width: 5, height: 6)) - let fromCounter = try! Counter.seededCounter("c", fromPoint) - let fromPolar = Counter.seededPolarPoint("q", PolarPoint(turns: 1, distance: 2)) - print( - "seeded \(try! fromPoint.get()) \(try! fromSize.get()) \(try! fromCounter.get()) \(try! fromPolar.get()) " - + "past \(try! stack.depthPastPoint(Point(x: 1, y: 2))) seeds \(seedsPointSize(Size(width: 2, height: 3)))") - - // A trait implemented for `Point` and `&Point` apart: one instance. - print("weigh \(weighPoint(Point(x: -1, y: 2)))") - // A function named as the type it returns, and one named as a type it does not. - print("polar \(polarPoint(2)!.distance) \(polarPoint(0) == nil) area \(area(Size(width: 2, height: 3)))") - // Two types whose paths join alike, the second kept apart where its path splits. - print("wind \(wind(PolarTurn(whole: 2), Polar_Turn(part: 3)))") - // Names that clash in some language, each kept apart there. - let clashSpan = ClashSpan(width: 4) - let clashStore = ClashStore.new(7) - print( - "clash \(debug(ClashTone(hz: 440))) \(debug(ClashTone_(db: 3))) \(debug(Cancelled(step: 2))) " - + "span \(clashSpan.width_()) \(clashSpan.toString()) \(clashSpan) " - + "store \(clashStore.free()) \(clashStore.close()) " - + "audio \(clashAudioEncoderFinish()) \(clashAudioEncoderFinish_()) " - + "nested \(clashNested(((1, 2), 3), (1, 2, 3)))" - ) - // Instances that name each other, and one made only by an impl of it. - let crossed = cross(LeftRightU8(value: RightU8(value: 1)), RightLeftU8(value: LeftU8(value: 2))) - print("cross \(crossed) outer \(OuterInnerU8.new(4).get())") - // A bound that outlives the call takes a value, and an instance only a constant names. - print("kept \(keptPoint(Point(x: 1, y: -2))) boxed \(BOXED.value)") - print("keep \(keepPoint(Point(x: 1, y: -2)))") - let five = Point(x: 5, y: 2) - print("kept or \(keptOrPoint(five)) \(keptOrPoint(nil)) keeper \(keeperPoint(five))") - // Inferred instances taking a lent closure and a foreign implementation, and one only - // its impl of a trait names. - let sides = PairU32(left: 2, right: 5) - print("apply \(applyU32(sides) { side in side * 3 })") - let report = reportU32(sides, PrintLog()) - print("report \(report)") - print("wrapped \(keptWrapU32(WrapU32(value: 4)))") - let keptLog = keeps(PrintLog()) - print("keeps \(keptLog.value)") - - // Its Drop runs when Swift releases the last reference, not before. - do { - let token = Token.new(7) - withExtendedLifetime(token) { print("token \(try! token.idGet) dropped \(dropped())") } - } - print("dropped \(dropped())") - - // A field and the method of its name, each its own member. - var retry = Retry.new(5) - let limit = try! retry.limitGet - print("retry \(limit != nil ? 1 : 0) \(limit ?? 0) \(try! retry.limit()) \(try! retry.delay())") - // The renamed field's setter, named as its getter. - try! retry.limitSet(nil) - print("retry \(try! retry.limit())") - print("slot \(SlotU8.new(200).value())") - - // Foreign types: a URL parsed from text, socket addresses, OS paths, and `Vec`s. - let base = try! Url.parse("https://example.com/a/b") - print("url \(try! base.description) host \(try! host(base).map { "Some(\"\($0)\")" } ?? "None")") - let url = try! resolve(try! base.clone(), "c?d") - print("resolve \(try! url.description) \(try! url == base)") +/// A kept closure: called again at the instant it asks for, then once its waiter wakes. +func drive() { + let start = Moment.new(0, 1000)! + let calls = Cell(0) + let stopped = block { + try await Api.drive(start) { now, waiter in + calls.value += 1 + switch calls.value { + case 1: return now.after(5) + case 2: + print("drive \(now.millis() - start.millis())") + try! waiter.waker()() + return nil + default: throw StringError(error: "stopped after \(calls.value)") + } + } + } + print("drive \(stopped)") +} + +/// Readers over bytes, whose reads fail, and that seek past `Int64.max`. +func readers() { + var memory = Memory(Data("hello world".utf8)) + printTail { try tail(&memory, 5) } + check(memory.at == 6, "a reader's seeks stay once the call returns") + var broken = Broken() + printTail { try tail(&broken, 5) } + // A seek from the start reaches the reader whole, past `Int64.max`, as `Cursor` takes one. + var far = Far() do { - _ = try Url.parse("no scheme") + print("sought \(try seekTo(&far, UInt64.max))") } catch let e as StringError { - print("parse err \(e.error)") + print("sought error \(e.error)") } catch { - check(false, "parse throws its message") - } - let v4 = SocketAddr.v4(SocketAddrV4(ip: Ipv4Addr(127, 0, 0, 1), port: 8080)) - let loopback = Ipv6Addr(bits: U128(1)) - let v6 = SocketAddr.v6(SocketAddrV6(ip: loopback, port: 443, scopeId: 3)) - print("ports \(ports([v4, v6]))") - let peer = Peer(addr: v6, names: ["a", "b"]).next("c") - print("peer \(debug(peer)) \(peer.aliases())") - let file = file("dir", "f\\'\"\t") - print("file \(escaped(file))") - print("parents \(parents([file, "/"]).map { $0.map(escaped) ?? "none" }.joined(separator: " "))") - let words = words(" one two three ") - print("words \(words.count) \(words)") - print("sentence \(sentence(words)) \(sentence(nil))") - print("sentence \(sentence([]))|") - print("either \(either("abc")) \(either(nil))") - print("prefixed \(String(decoding: prefixed(Bytes("cd".utf8), Bytes("ab".utf8)), as: UTF8.self)) \(String(decoding: prefixed(Bytes("cd".utf8), nil), as: UTF8.self))") - print("coordinates \(coordinates(Point(x: 2, y: 3))) \(coordinates(nil))") + check(false, "seekTo throws its io::Error's message") + } +} + +/// Futures of a value that is not Send, made on this thread, so awaited on an executor the +/// script drains on it. +func localLater(_ local: consuming Local) { + let held = Held(local) + let later = Cell(0) + let q = Queue() + q.launch { later.value = try await localOrNewLater(local: held.local).bump() } + q.drain() + print("local later \(later.value)") + print("local later fresh \(block { try await localOrNewLater().bump() })") +} + +/// A path no Rust string spells: bytes that are not UTF-8. +func unspelled() -> PathBuf { + stray() +} + +/// A path's bytes in hex. +func pathHex(_ path: PathBuf) -> String { + hex(path.bytes) +} + +/// A duration as its seconds and nine digits of nanoseconds. +func seconds(_ d: RustDuration) -> String { + "\(d.secs).\(String(d.nanos).leftPadded(9))" +} + +/// A duration in whole milliseconds. +func millis(_ d: RustDuration) -> UInt64 { + d.secs * 1000 + UInt64(d.nanos) / 1_000_000 +} + +/// A char's code point. +func code(_ c: Unicode.Scalar) -> UInt32 { + c.value +} + +/// The list reversed. +func reversed(_ list: consuming UniqueArray) -> UniqueArray { + var out = UniqueArray() + while list.count > 0 { + out.append(list.remove(at: list.count - 1)) + } + return out +} + +/// Each float's bits. +func f64Bits(_ floats: [Double]) -> [UInt64] { + floats.map(\.bitPattern) +} + +/// What the transcript's script says only in Rust, or Swift alone has: its own types' +/// conversions, the errors and checks it throws, and its protocols. +func checks() { + check(U128(high: .max, low: .max).description == "340282366920938463463374607431768211455", "a u128's decimal digits") + check(ArrayU8x4([1, 2, 3]) == nil, "3 bytes are no [u8; 4]") + check(advance(.init_(1)) == .init_(0) && advance(.init_(0)) == .done, "a variant named init crosses") + // Rust's seconds are a u64, past Int64's. + let rustMax = try! RustDuration(secs: .max, nanos: 999_999_999) + let past = RustDuration.seconds(UInt64(Int64.max) + 1) + check( + extended(past, try! RustDuration(secs: UInt64(Int64.max), nanos: 999_999_999)) == rustMax, + "a duration past Int64's seconds crosses") + check(extended(try! RustDuration(secs: .max, nanos: 999_999_996), .nanoseconds(3)) == rustMax, "Rust's longest duration crosses") + check(extended(rustMax, .nanoseconds(1)) == nil, "Rust refuses a duration past its longest") + durations(rustMax) do { - // An optional borrowed handle is an overload with it and one without; one borrowed - // mutably is an optional `inout`. let two = Counter.new("two", 2) - var three: Counter? = Counter.new("three", 3) - var none: Counter? = nil - print("plus \(try! two.plus(other: three!)) \(try! two.plus())") + let three = Counter.new("three", 3) // A list and an option holding a struct beside a class, whose handle each moves. var pairs = UniqueArray() pairs.append(TupleCounterRefusal(Counter.new("a", 1), refusal("x"))) @@ -802,105 +454,16 @@ func script() { // Each optional borrowed parameter is an overload with and without its label. let one = Counter.new("one", 1) check( - try! two.clamped() == 2 && two.clamped(low: three!) == 3 && two.clamped(high: one) == 1 - && two.clamped(low: one, high: three!) == 2, + try! two.clamped() == 2 && two.clamped(low: three) == 3 && two.clamped(high: one) == 1 + && two.clamped(low: one, high: three) == 2, "clamped overloads each optional borrow" ) - print("add_to \(try! two.addTo(&three)) \(try! two.addTo(&none)) \(try! three!.get())") - } - do { - var encoded = Bytes("0,".utf8) - putNumber(1, &encoded) - putNumber(23, &encoded) - print("put_number \(String(decoding: encoded, as: UTF8.self))") - var entry = (Bytes("ab".utf8), UInt32(1)) - let stamps = pushCounted(&entry, UInt8(ascii: "c")) - print("push_counted \(stamps) \(String(decoding: entry.0, as: UTF8.self)) \(entry.1)") - var digits = Bytes("7x9".utf8) - let firstDigit = try! digit(&digits) - let skipped = (try? digit(&digits)) == nil - let lastDigit = try! digit(&digits) - print("digit \(firstDigit) \(skipped) \(lastDigit) \(digits.count)") - var nudged = Point(x: 1, y: 2) - nudge(&nudged, 3) - print("nudge \(nudged.x) \(nudged.y)") } do { - let config = secure("h3") - print("secure \(try! alpnLent(config)) \(try! alpn(config.clone()))") - let cert = certify(Bytes("der".utf8)) - let certLength = try! certLen(cert) - let der = text(try! certDer(cert)) - var chain = UniqueArray() - chain.append(certify(Bytes("a".utf8))) - chain.append(certify(Bytes("bc".utf8))) - print("cert \(certLength) \(der) \(try! chainLen(chain))") - // Another crate's trait objects: an `Arc`, taken back, and `'static` ones, held by value. - print("resolver \(try! resolved(resolver("r1")))") - var codecs = Codecs.new() - print("codecs \(try! codecs.ids())") - var listed = try! codecs.listGet() - var reversed = UniqueArray() - reversed.append(listed.remove(at: 1)) - reversed.append(listed.remove(at: 0)) - try! codecs.listSet(reversed) - print("codecs reversed \(try! codecs.ids())") - // A standard library value no type maps, in a handle. - let failed = failure("boom") - let message = try! failureMessage(failed) - print("failure \(message) \(try! failureKind(failed))") - // Iterators, passed as the arrays of their items. - print("sum_all \(sumAll([1, 2, 3]))") - var weighed = UniqueArray() - weighed.append(Counter.new("w", 3)) - print("weigh_all \(try! weighAllCounter(weighed))") - print("offered_len \(offeredLen([Bytes("h3".utf8), Bytes("moq-00".utf8)]))") - print("join_words \(joinWords(["a", "b", "c"]))") - // Bytes that must be `'static`, interned. - print("der \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") - print("der again \(text(Der.fromSlice(Bytes("der".utf8)).bytes()))") - let session = try! resume("h3", 60) - print("resume \(session.alpn()) \(session.lifetime().seconds)") - do { - _ = try resume("", 60) - } catch let e as StringError { - print("resume err \(e.error)") - } catch { - check(false, "resume throws its message") - } - var meters = Meters.new() - let first = try! meters.first() - _ = try! first.add(2) - print("lent \(try! first.add(3)) \(try! meters.first().count())") - try! meters.clear() - print("cleared \(try! meters.first().count())") - let last = try! meters.lastGet() - _ = try! last.add(4) - print("field lent \(try! last.add(1))") - // An optional field that is not Clone, lent as `Some` of a handle. - var hasSpare = false - if let _ = try! meters.spareGet() { - hasSpare = true - } - print("spare \(hasSpare)") - try! meters.spareSet(Meter.default()) - if let spare = try! meters.spareGet() { - _ = try! spare.add(5) - print("spare lent \(try! spare.add(1))") - } - let tallies = Tallies.new() - _ = try! tallies.first().bump() - print("tallied \(try! tallies.first().bump())") - } - do { - // A draft borrowing its ledger exclusively until it is consumed, through which its - // sheet's members are reached by Deref and DerefMut: the ledger refuses any other use - // meanwhile. + // A draft borrows its ledger exclusively until it is consumed: the ledger refuses any + // other use meanwhile. var ledger = Ledger.new() - var draft = try! ledger.edit() - try! draft.titleSet("minutes") - try! draft.write("first") - print("draft \(try! draft.titleGet) \(try! draft.lines()) \(try! draft.describe()) \(try! draft.edited())") + let draft = try! ledger.edit() do { _ = try ledger.published() check(false, "a lent ledger refuses a read") @@ -912,187 +475,10 @@ func script() { } catch { check(false, "a lent ledger threw \(error)") } - print("committed \(try! draft.commit())") - print("ledger \(try! ledger.title()) \(try! ledger.published())") - let read = try! ledger.edit() - print("read \(try! read.lines()) \(try! read.edited())") - _ = consume read - var second = try! ledger.edit() - try! second.write("second") - _ = consume second - print("dropped \(try! ledger.published())") - print("receipt \(try! ledger.receipt().count())") - var marker = Marker.new("m", 3, 5) - try! marker.ySet(7) - print("forwarded \(PadU16.wide().title()) \(Layered.new().lines()) \(try! marker.xGet) \(try! marker.yGet) [\(PadU8.small().describe())] [\(PadU16.wide().describe())]") - _ = consume marker - try! ledger.seal() - do { - _ = try ledger.edit() - check(false, "a sealed ledger refuses a draft") - } catch let e as Api.Error { - print("sealed \(e)") - } catch { - check(false, "a sealed ledger throws an Error") - } + _ = consume draft } - print("chunks \(chunks(Bytes("abcde".utf8), 2).map { Array($0) })") - var counters = counters(["x", "y"]) - print("counters \(listed(counters) { "\(try! $0.name()) \(try! $0.get())" })") - // Each counter moves in. - var some = UniqueArray() - some.append(counters.remove(at: 0)) - var boxed = UniqueArray() - boxed.append(counters.remove(at: 0)) - print("worth \(try! worth(some, boxed)) \(try! worth(nil, UniqueArray()))") - print("held \([try! heldCount(Counter.new("h", 4)), try! heldCount(nil)].map { $0.map { "Some(\($0))" } ?? "None" }.joined(separator: " "))") - print("boxed \(try! boxedName(boxedCounter("b")).map { "Some(\"\($0)\")" } ?? "None") \(try! boxedName(nil) ?? "None") \(boxedCounter(nil) == nil)") - print("less \(less(5, 2))") - print("sums \(sums([[1, 2], [], [3]]))") - print("least \(least([[3, 1], [], [2]]).map { "\($0)" }.joined(separator: " "))") - numbers("edges", Numbers.edges()) - numbers("reversed", Numbers.edges().reversed()) - let edges = Numbers.edges() - let nan = Measure.new(Double.nan, false) - print("float equal \(edges == edges) \(edges == Numbers.edges()) \(Numbers.zero(true) == Numbers.zero(false)) \(nan == nan) \(Measure.new(-0.0, true) == Measure.new(0.0, false))") - print("sum u32 \(sumU32([])) \(sumU32([UInt32.max, UInt32.max, 2]))") - print("doubled i64 \(doubledI64([Int64.min, -1, 0, Int64.max]))") - print("boxed floats \(boxedFloats([-0.0, Double(bitPattern: 0x7ff8_0000_0000_0001)]).map(\.bitPattern))") - let sum = summed([Point(x: 1, y: 2), Point(x: -4, y: 6)]) - let noneSum = summed([]) - print("summed \(sum.x) \(sum.y) \(noneSum.x) \(noneSum.y)") - print("longest \(longest(["a", "abc"])) \(longest([]))") - print("first of Some(\"\(firstOf(["a", "b"])!)\") \(firstOf([]) ?? "None")") - let limits = byteLimits(Bytes("a".utf8), Bytes("bc".utf8)) - let waits = breadth(LimitsDuration(low: .milliseconds(5), high: .seconds(2))) - let low = String(decoding: limits.low, as: UTF8.self) - let high = String(decoding: limits.high, as: UTF8.self) - print("limits \(low) \(high) breadth \(waits.secs * 1000 + UInt64(waits.nanos) / 1_000_000)") - let parts = String(decoding: Api.joined([Bytes("ab".utf8), Bytes(), Bytes("c".utf8)]), as: UTF8.self) - print("joined \(parts) \(Api.joined([]).count) read \(readLen(Bytes("hello".utf8)))") - let doc = try! Json.parse(#"{"b": [1, 2.5, null], "a": "é"}"#) - print("json \(try! encode(doc))") - print("timed text \(try! timedText(doc))") - let tagged = try! tagged(doc, "t") - print("tagged \(try! tagged.toText())") - // A JSON object's entries cross as pairs of a key and its document, each moved in. - var pairs = UniqueArray() - pairs.append(TupleStringJson("b", try! Json.parse("[1]"))) - pairs.append(TupleStringJson("a", try! Json.parse("2"))) - let jsonEntries = try! entries(pairs, "t") - print("entries \(listed(jsonEntries) { "\($0._0) \(try! $0._1.toText())" })") - do { - _ = try Json.parse("{\"a\":") - } catch let e as StringError { - print("json parse err \(e.error)") - } catch { - check(false, "parse throws its message") - } - let site = try! Site.new(base) - print("site \(try! site.homeGet().description) \(try! site.homeGet().description)") - - // Slices, passed in and returned as clones, and the socket address of each family. - print("shapes \(Shape.ALL) greetings \(GREETINGS)") - print("both \(Shape.BOTH) primes \(PRIMES)") - var trail = Trail.new([Point(x: 1, y: 2), Point(x: 3, y: 4)], ["a", "b"]) - print("trail \(try! trail.points()) \(try! trail.labels())") - // Returned iterators, each collected at the call: drained labels are gone after. - print("iterated \(try! trail.iter()) \(try! trail.names()) \(Array(try! trail.bytes()))") - print("drained \(try! trail.drain()) then \(try! trail.labels())") - // A filter, collected at the call. - print("beyond \(try! trail.beyond(1).map { "\($0.x) \($0.y)" }.joined(separator: ", "))") - let numbered = numbered(["p", "q"]) - print("numbered \(listed(numbered) { "\(try! $0.name()) \(try! $0.get())" })") - let (next4, next6) = nexts(SocketAddrV4(ip: Ipv4Addr(127, 0, 0, 1), port: 8080), SocketAddrV6(ip: loopback, port: 443, scopeId: 3)) - print("nexts \(next4.ip.octets.map(String.init).joined(separator: ".")) \(next4.port) \(next6.port) \(next6.scopeId)") - let (nextIp4, nextIp6) = nextIps(Ipv4Addr(10, 0, 0, 255), Ipv6Addr(bits: U128(0xffff))) - let mapped = flip(.v4(Ipv4Addr(127, 0, 0, 1))) - let ips = [IpAddr.v4(nextIp4), .v6(nextIp6), mapped, flip(mapped), flip(.v6(loopback))] - print("ips \(ips.map(ipHex).joined(separator: " "))") - lossless() - - // serde_json's map iterator, collected as pairs of a key and its document. - var sectionPairs = UniqueArray() - sectionPairs.append(TupleStringJson("b", try! Json.parse("[1]"))) - sectionPairs.append(TupleStringJson("a", try! Json.parse("2"))) - let jsonSections = try! sections(sectionPairs) - print("sections \(listed(jsonSections) { "\($0._0) \(try! $0._1.toText())" })") - // An instant only Rust makes, which each call copies out of its handle, and compares. - let millis = { (d: RustDuration) in d.secs * 1000 + UInt64(d.nanos) / 1_000_000 } - let began = now() - let ended = later(began, .milliseconds(1500)) - print("instants \(millis(since(ended, began))) \(millis(since(began, ended))) \(began == later(began, .seconds(0))) \(began == ended)") - print("has_instant \(hasInstant(began)) \(hasInstant(nil))") - // tracing's level, and its filter as an optional level whose nil is `OFF`. - var verbosity = Verbosity.new(.warn) - print("verbosity \(spell(try! verbosity.filter())) \(spell(louder(try! verbosity.filter())))") - try! verbosity.levelSet(.trace) - print("verbosity \(try! verbosity.levelGet == .trace) \(spell(try! verbosity.filter())) \(spell(louder(try! verbosity.filter()))) \(spell(louder(nil)))") - - print("made \(made(3) { "\($0) times" })") - // A closure taking and returning `Copy` objects copies them, never running their `Clone`. - let nine = Ticket.new(9) - let given = reissue(Ticket.new(7)) { Ticket.new($0.number() + 1) }.number() - let held = reissue(Ticket.new(7)) { _ in nine }.number() - print("reissued \(given) \(held), cloned \(Ticket.clones())") - // A record's traits borrow the checked handle it holds. - let nines = Mark.of(9) - let front = try! seat(nines, 1) - let back = try! seat(nines, 2) - print("seat \(try! front.debugDescription) \(try! front == front) \(try! front == back)") // A kept closure, called on another thread after the call that took it returned. check(try! Spawned.new { 7 }.join() == 7, "a kept closure runs on another thread") - // A kept closure: called again at the instant it asks for, then once its waiter wakes. - let start = Moment.new(0, 1000)! - let calls = Cell(0) - let stopped = block { - try await drive(start) { now, waiter in - calls.value += 1 - switch calls.value { - case 1: return now.after(5) - case 2: - print("drive \(now.millis() - start.millis())") - try! waiter.waker()() - return nil - default: throw StringError(error: "stopped after \(calls.value)") - } - } - } - print("drive \(stopped)") - var memory = Memory(Data("hello world".utf8)) - printTail { try tail(&memory, 5) } - check(memory.at == 6, "a reader's seeks stay once the call returns") - var broken = Broken() - printTail { try tail(&broken, 5) } - // A seek from the start reaches the reader whole, past `Int64.max`, as `Cursor` takes one. - var far = Far() - do { - print("sought \(try seekTo(&far, UInt64.max))") - } catch let e as StringError { - print("sought error \(e.error)") - } catch { - check(false, "seekTo throws its io::Error's message") - } - print("non zeros \(describeNonZeros(nonZeros()))") - for hop in [nil, 1, UInt64.max] as [UInt64?] { - print("hop \(nextHop(hop.map { try! NonZero($0) }).map { "Some(\($0))" } ?? "None")") - } - print("farther hop \(fartherHop(PairNonZeroU16(left: try! NonZero(3), right: try! NonZero(.max))))") - do { - let local = Local.new() - let shared = try! localOrNew(local: local) - let bumped = try! local.bump() - print("local \(bumped) \(try! shared.bump())") - print("local fresh \(try! localOrNew().bump())") - print("local either \(try! bumpEither(shared))") - // Made on this thread, so awaited on the executor the script drains on it. - let held = Held(local) - let later = Cell(0) - q.launch { later.value = try await localOrNewLater(local: held.local).bump() } - q.drain() - print("local later \(later.value)") - print("local later fresh \(block { try await localOrNewLater().bump() })") - } // A zero, which Swift's integer holds and Rust's `NonZero` does not, makes none, and a // record holding one keeps the protocols its traits give. check(refused("NonZero(_:)") { _ = try NonZero(0) }, "a zero makes no NonZero") @@ -1100,7 +486,9 @@ func script() { check(try! NonZero(.min) < NonZero(1), "a NonZero compares as its integer") let debuggable: any CustomDebugStringConvertible = nonZeros() check(debuggable.debugDescription == describeNonZeros(nonZeros()), "a record of NonZero is Debug") + lossless() targets() + print("checks ok") } /// Print each of `n`'s lists, its floats as their bits, as transcript.rs does. @@ -1611,28 +999,44 @@ func lentKept() { } #endif -/// `bytes` in hex, two digits each. -func hexBytes(_ bytes: some Sequence) -> String { +/// `bytes` in lowercase hex, two digits each. +func hex(_ bytes: some Sequence) -> String { bytes.map { String($0, radix: 16).leftPadded(2) }.joined() } /// An IP address's octets in hex, so their length shows its family. func ipHex(_ ip: IpAddr) -> String { switch ip { - case .v4(let ip): return hexBytes(ip.octets) - case .v6(let ip): return hexBytes(ip.octets) + case .v4(let ip): return ipHex(ip) + case .v6(let ip): return ipHex(ip) } } +func ipHex(_ ip: Ipv4Addr) -> String { + hex(ip.octets) +} + +func ipHex(_ ip: Ipv6Addr) -> String { + hex(ip.octets) +} + /// A socket address as its IP's octets in hex, its port, flow label, and scope, each /// IPv6's alone, apart by colons. func socketHex(_ addr: SocketAddr) -> String { switch addr { - case .v4(let v4): return "\(hexBytes(v4.ip.octets)):\(v4.port)" - case .v6(let v6): return "\(hexBytes(v6.ip.octets)):\(v6.port):\(v6.flowinfo):\(v6.scopeId)" + case .v4(let v4): return socketHex(v4) + case .v6(let v6): return socketHex(v6) } } +func socketHex(_ v4: SocketAddrV4) -> String { + "\(hex(v4.ip.octets)):\(v4.port)" +} + +func socketHex(_ v6: SocketAddrV6) -> String { + "\(hex(v6.ip.octets)):\(v6.port):\(v6.flowinfo):\(v6.scopeId)" +} + /// Whether `body` throws a `CheckError` from `function`. func refused(_ function: String, _ body: () throws -> Void) -> Bool { do { @@ -1664,41 +1068,24 @@ func durations(_ rustMax: RustDuration) { check(refused("RustDuration(_:)") { _ = try RustDuration(swiftMax + .nanoseconds(1) / 2) }, "past the longest by less than a nanosecond throws") } -/// Each type's edge values, passed through Rust and back, as transcript.rs prints them, -/// and the conversions to and from each runtime type, which throw or return nil for a -/// value Rust's type cannot hold. + +/// The conversions to and from each runtime type, which throw or return nil for a value +/// Rust's type cannot hold, and its protocols, which agree with Rust's. func lossless() { - let spans = [ - RustDuration.seconds(0), .nanoseconds(1), .nanoseconds(UInt64(Int64.max) + 1), - try! RustDuration(secs: .max, nanos: 999_999_999), - ].map { sameDuration($0) } - print("lossless duration \(spans.map { "\($0.secs).\(String($0.nanos).leftPadded(9))" }.joined(separator: " "))") - print("lossless u64 \(sameU64(0)) \(sameU64(1 << 63)) \(sameU64(.max))") - print("lossless usize \(sameUsize(0)) \(sameUsize(.max))") - print("lossless isize \(sameIsize(.min)) \(sameIsize(.max))") - let wides = [U128(0), U128(high: 1, low: 0), U128(high: .max, low: .max)].map { sameU128($0) } - print("lossless u128 \(wides.map { hexBytes(withUnsafeBytes(of: ($0.high.bigEndian, $0.low.bigEndian)) { Array($0) }) }.joined(separator: " "))") - let chars: [Unicode.Scalar] = ["\0", "\u{d7ff}", "\u{e000}", "\u{10ffff}"] - print("lossless char \(chars.map { String(sameChar($0).value, radix: 16) }.joined(separator: " "))") check(sameString("a\u{0}é\u{10ffff}") == "a\u{0}é\u{10ffff}", "text crosses") // A path that is not UTF-8, which no String holds, keeps its bytes. let strayPath = stray() check(strayPath.string == nil && PathBuf("a/é").string == "a/é", "a path's text is nil unless UTF-8") - print("lossless path \(hexBytes(samePath("a/é").bytes)) \(hexBytes(samePath(strayPath).bytes))") check(samePath(strayPath) == strayPath, "a path that is not UTF-8 crosses back") visitStray { path in check(path == strayPath, "a lent path that is not UTF-8 keeps its bytes") } check(samePath(PathBuf(bytes: Bytes([0xff]))) == strayPath, "a caller's bytes make a path") - let v4 = sameSocketAddrV4(SocketAddrV4(ip: Ipv4Addr(bits: .max), port: .max)) let ip6 = Ipv6Addr(bits: U128(high: 1 << 48, low: 2)) - let v6 = sameSocketAddrV6(SocketAddrV6(ip: ip6, port: 3, flowinfo: .max, scopeId: .max)) - let addrs = [SocketAddr.v4(v4), .v6(v6)] - print("lossless socket \(addrs.map(socketHex).joined(separator: " ")) \(addrs.map { socketHex(sameSocketAddr($0)) }.joined(separator: " "))") + let addrs = [SocketAddr.v4(SocketAddrV4(ip: Ipv4Addr(bits: .max), port: .max)), .v6(SocketAddrV6(ip: ip6, port: 3))] // A key hashes by Rust's `Hash`, which agrees with its `==`. let a = Key.new("a") let b = Key.new("b") - print("key \(hashed(a) == hashed(Key.new("a"))) \(hashed(a) == hashed(b))") + check(hashed(a) == hashed(Key.new("a")) && hashed(a) != hashed(b), "a key hashes as Rust's Hash does") let edge6 = Ipv6Addr(octets: [0xff, 0xff] + Array(repeating: 0, count: 13) + [1])! - print("lossless ip \(ipHex(sameIpAddr(.v4(Ipv4Addr(255, 255, 255, 255))))) \(ipHex(sameIpAddr(.v6(edge6))))") // Octets convert both ways, and only exactly as many as the family holds. check(Ipv4Addr(octets: [1, 2, 3, 4]) == Ipv4Addr(1, 2, 3, 4) && Ipv4Addr(1, 2, 3, 4).bits == 0x0102_0304, "IPv4 octets convert") check(Ipv6Addr(octets: edge6.octets) == edge6 && edge6.bits == U128(high: 0xffff << 48, low: 1), "IPv6 octets convert") @@ -1706,6 +1093,7 @@ func lossless() { check(SocketAddr(ip: .v6(ip6), port: 3) == .v6(SocketAddrV6(ip: ip6, port: 3)) && addrs[1].ip == .v6(ip6) && addrs[0].port == .max, "a socket address is its IP and port") } + /// `key`'s hash by Swift's own hasher, which `Hashable` uses. func hashed(_ key: borrowing Key) -> Int { var hasher = Swift.Hasher() @@ -1753,7 +1141,8 @@ struct Main { static func main() { let args = CommandLine.arguments.dropFirst() switch args.first { - case nil: script() + case nil: transcript() + case "checks": checks() case "futures": futures() case "owned": owned() case "shared": shared() diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 9b5eadc00..c826089ad 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1184,12 +1184,14 @@ fn api_swift() { // The test's executor preference is macOS 15's. let exe = dir.join("api-test"); let test = manifest_dir().join("tests").join("api.swift"); + let script = generated("swift", "transcript.swift", &transcript::swift::emit(transcript())).join("transcript.swift"); // The Clang module the test and the contract program import on Linux. let nodump = manifest_dir().join("tests").join("nodump"); let step = Step { stamp: &step::stamp(&exe), reads: &[ &test, + &script, &nodump, &module, &include, @@ -1205,6 +1207,7 @@ fn api_swift() { .args(["-parse-as-library", "-I"]) .arg(&dir) .arg(&test) + .arg(&script) .arg(&lib) .args(&collections) .arg(api.staticlib()) @@ -1218,6 +1221,7 @@ fn api_swift() { api.transcript, "the Swift transcript differs from the native one" ); + run(Command::new(&exe).arg("checks")); run(Command::new(&exe).arg("futures")); run(Command::new(&exe).arg("owned")); run(Command::new(&exe).arg("shared")); @@ -1234,17 +1238,18 @@ fn api_swift() { ] { let step = Step { stamp: &dir.join(format!("{case}.stamp")), - reads: &[&test, &nodump, &module, &include, &built, &swiftmodule], + reads: &[&test, &script, &nodump, &module, &include, &built, &swiftmodule], writes: &[], }; let output = step.output( swiftc(&module, 15) - .args(["-parse-as-library", "-emit-sil", "-o"]) + .args(["-parse-as-library", "-wmo", "-emit-sil", "-o"]) .arg(dir.join("broken.sil")) .args(["-I"]) .arg(&dir) .arg(format!("-D{case}")) - .arg(&test), + .arg(&test) + .arg(&script), ); assert!(!output.status.success(), "Swift {case} compiled"); let stderr = String::from_utf8_lossy(&output.stderr); diff --git a/ffi/tests/fixtures/transcript/ir.rs b/ffi/tests/fixtures/transcript/ir.rs index 58a95d4a0..04ddf7d6b 100644 --- a/ffi/tests/fixtures/transcript/ir.rs +++ b/ffi/tests/fixtures/transcript/ir.rs @@ -20,6 +20,34 @@ pub(crate) struct Api { pub(crate) callbacks: Vec, pub(crate) functions: Vec, pub(crate) constants: Vec, + /// The targets the API serves, which each item's `on` holds a bit of. + pub(crate) targets: Vec, +} + +impl Api { + /// Whether an item on `on` is on every target the API serves. + pub(crate) fn everywhere(&self, on: u64) -> bool { + let all = u64::MAX >> (64 - self.targets.len()); + on & all == all + } + + /// The objects a value of `ty` holds, its records' and enums' fields included. + pub(crate) fn handles(&self, ty: &Type, out: &mut Vec, seen: &mut Vec<(bool, usize)>) { + match ty { + Type::Object(i) => out.push(*i), + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => self.handles(inner, out, seen), + Type::Tuple(elements) => elements.iter().for_each(|ty| self.handles(ty, out, seen)), + Type::Record(i) if !seen.contains(&(false, *i)) => { + seen.push((false, *i)); + (self.records[*i].fields.iter()).for_each(|f| self.handles(&f.ty, out, seen)); + } + Type::Enum(i) if !seen.contains(&(true, *i)) => { + seen.push((true, *i)); + (self.enums[*i].variants.iter().flat_map(|v| &v.fields)).for_each(|f| self.handles(&f.ty, out, seen)); + } + _ => {} + } + } } #[derive(serde::Deserialize)] @@ -34,6 +62,8 @@ pub(crate) struct Record { pub(crate) methods: Vec, pub(crate) traits: Traits, pub(crate) opaque: Option, + /// The targets it is on. + pub(crate) on: u64, } #[derive(serde::Deserialize)] @@ -53,6 +83,8 @@ pub(crate) struct Enum { pub(crate) methods: Vec, pub(crate) traits: Traits, pub(crate) foreign: bool, + /// The targets it is on. + pub(crate) on: u64, } #[derive(serde::Deserialize)] @@ -71,11 +103,14 @@ pub(crate) struct Object { pub(crate) args: Vec, #[serde(default = "yes")] pub(crate) send: bool, + pub(crate) sync: bool, pub(crate) copy: bool, pub(crate) shared: bool, pub(crate) methods: Vec, pub(crate) traits: Traits, pub(crate) foreign: bool, + /// The targets it is on. + pub(crate) on: u64, } fn yes() -> bool { @@ -111,6 +146,8 @@ pub(crate) struct Function { pub(crate) lends_mut: bool, pub(crate) access: Access, pub(crate) instance: Option, + /// The targets it is on. + pub(crate) on: u64, } #[derive(serde::Deserialize)] @@ -238,7 +275,7 @@ pub(crate) enum Dyn { Arc, } -#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, serde::Deserialize)] pub(crate) enum Int { U8, U16, diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 79879ef50..560e18507 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -14,6 +14,7 @@ pub(crate) mod ir; mod parse; pub(crate) mod python; +pub(crate) mod swift; use std::collections::BTreeMap; use std::path::Path; diff --git a/ffi/tests/fixtures/transcript/swift.rs b/ffi/tests/fixtures/transcript/swift.rs new file mode 100644 index 000000000..3db556e94 --- /dev/null +++ b/ffi/tests/fixtures/transcript/swift.rs @@ -0,0 +1,1633 @@ +//! The transcript as Swift: a file of the test's own module whose `transcript()` runs it +//! through the generated Swift, calling `tests/api.swift`'s own functions. +//! +//! Swift's binding shapes a call by rules the exporter applies, which this mirrors from the +//! IR alone: which calls throw, which objects are noncopyable structs, which methods mutate, +//! and which getters are properties. A call that can throw is `try!`, as the script expects +//! each to succeed; a `match` on a `Result` catches the error it throws. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write; + +use super::ir::{Access, Api, Family, Int, Mutability, Receiver, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Op, Owner, Pat, Piece, Spec, Step, Transcript, bound, unref}; + +const LANGUAGE: &str = "Swift"; + +/// Helpers the script calls, each for a value Swift prints apart from Rust. +const PRELUDE: &str = r#"// Generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript. + +import Api +import BasicContainers + +/// A string as Rust's `Debug` prints it. +func _quoted(_ s: String) -> String { + var out = "\"" + for c in s.unicodeScalars { + switch c { + case "\"": out += "\\\"" + case "\\": out += "\\\\" + case "\n": out += "\\n" + case "\t": out += "\\t" + case "\r": out += "\\r" + case "\0": out += "\\0" + case _ where c.value < 0x20 || c.value == 0x7f: out += "\\u{\(String(c.value, radix: 16))}" + default: out.unicodeScalars.append(c) + } + } + return out + "\"" +} + +/// An optional as Rust's `Debug` prints it, its value as `show` does. +func _option(_ value: T?, _ show: (T) -> String) -> String { + switch value { + case .some(let value): return "Some(\(show(value)))" + case .none: return "None" + } +} + +/// A list as Rust's `Debug` prints it, each item as `show` does. +func _list(_ items: [T], _ show: (T) -> String) -> String { + "[" + items.map(show).joined(separator: ", ") + "]" +} + +/// Each of `items`, borrowed, as `show` prints it. +func _each(_ items: borrowing UniqueArray, _ show: (borrowing T) -> String) -> [String] { + var out: [String] = [] + for i in 0..(_ value: T, _ body: (T) -> R) -> R { + body(value) +} + +/// An integer's lowercase hex digits, zero-padded to `width`. +func _hex(_ value: T, _ width: Int) -> String { + let digits = String(value, radix: 16) + return String(repeating: "0", count: max(0, width - digits.count)) + digits +} + +/// A `U128`'s lowercase hex digits, zero-padded to `width`. +func _hex(_ value: U128, _ width: Int) -> String { + let low = String(value.low, radix: 16) + let digits = value.high == 0 ? low : String(value.high, radix: 16) + String(repeating: "0", count: 16 - low.count) + low + return String(repeating: "0", count: max(0, width - digits.count)) + digits +} + +/// An integer's decimal digits, zero-padded to `width`. +func _padded(_ value: T, _ width: Int) -> String { + let digits = String(value) + return String(repeating: "0", count: max(0, width - digits.count)) + digits +} + +/// The error of a call that must fail with an `E`. +func _err(_: E.Type, _ body: () throws -> T) -> E { + do { + _ = try body() + } catch let error as E { + return error + } catch { + fatalError("\(error)") + } + fatalError("the call did not fail") +} + +/// Whether a call fails with an `E`. +func _fails(_: E.Type, _ body: () throws -> T) -> Bool { + do { + _ = try body() + return false + } catch is E { + return true + } catch { + fatalError("\(error)") + } +} +"#; + +/// The Swift file of `t`'s script. +pub(crate) fn emit(t: &Transcript) -> String { + let model = Model::new(&t.api); + let mut e = Emitter { + t, + model, + depth: 1, + fresh: 0, + threw: false, + at_root: false, + mutated: BTreeSet::new(), + optional: BTreeSet::new(), + aliases: BTreeMap::new(), + bounds: BTreeSet::new(), + }; + for step in &t.steps { + e.mutations(step); + } + let body = e.steps(&t.steps); + let mut out = String::from(PRELUDE); + for int in &e.bounds { + let name = format!("Bound{}", int_name(*int)); + let _ = write!( + out, + "\n/// A `Bound` as Rust's `Debug` prints it.\nfunc _bound{0}(_ b: Api.{name}) -> String {{\n\tswitch b {{\n\tcase .included(let v): return \"Included(\\(v))\"\n\tcase .excluded(let v): return \"Excluded(\\(v))\"\n\tcase .unbounded: return \"Unbounded\"\n\t}}\n}}\n", + int_name(*int) + ); + } + out.push_str("\n/// The transcript's script, through the generated Swift.\nfunc transcript() {\n"); + out.push_str(&body); + out.push_str("}\n"); + out +} + +/// How Swift's binding shapes the API, by the exporter's rules. +struct Model { + /// The objects that are noncopyable structs: each but those `Copy` or thrown. + structs: BTreeSet, + /// The objects whose handles a call can fail a check of. + checked: Vec, +} + +impl Model { + fn new(api: &Api) -> Model { + let functions = || { + (api.records.iter().flat_map(|r| &r.methods)) + .chain(api.enums.iter().flat_map(|e| &e.methods)) + .chain(api.objects.iter().flat_map(|o| &o.methods)) + .chain(&api.functions) + }; + let thrown: BTreeSet = functions() + .filter_map(|f| match f.err.as_ref().map(Type::base) { + Some(Type::Object(i)) => Some(*i), + _ => None, + }) + .collect(); + let structs = (0..api.objects.len()) + .filter(|i| !api.objects[*i].copy && !thrown.contains(i)) + .collect(); + Model { + structs, + checked: checked(api), + } + } + + /// Whether Swift's value of `ty` is noncopyable: it holds an object's struct. + fn unique(&self, ty: &Type) -> bool { + match ty { + Type::Object(i) => self.structs.contains(i), + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => self.unique(inner), + Type::Tuple(elements) => elements.iter().any(|e| self.unique(e)), + _ => false, + } + } + + /// Whether `ty` is an `Option<&T>` of a struct, which Swift passes by an overload with it + /// and one without. + fn lent_option(&self, ty: &Type) -> bool { + matches!(ty, Type::Option(inner) if matches!(&**inner, Type::Ref(Mutability::Not, object) if self.unique(object))) + } + + /// Whether a parameter of `ty` is `inout`: a value Rust writes back, a reader, or a struct + /// borrowed mutably. + fn inout(&self, ty: &Type) -> bool { + let written = matches!(ty, Type::Ref(Mutability::Mut, inner) if !matches!(**inner, Type::Object(_) | Type::Reader)); + let reader = matches!(ty, Type::Ref(_, inner) if **inner == Type::Reader); + let lent = self.unique(ty) + && match ty { + Type::Ref(Mutability::Mut, _) => true, + Type::Option(inner) => matches!(**inner, Type::Ref(Mutability::Mut, _)), + _ => false, + }; + written || reader || lent + } + + /// Whether the std traits of `ty` can fail a check, so throw. + fn traits_throw(&self, api: &Api, ty: &Type) -> bool { + match ty { + Type::Object(i) => self.checked[*i], + ty => { + let mut handles = Vec::new(); + api.handles(ty, &mut handles, &mut Vec::new()); + handles.iter().any(|&i| self.checked[i]) + } + } + } + + /// Whether a call of `id` can fail a check of a handle it borrows or moves. + fn status(&self, t: &Transcript, id: FnId) -> bool { + let f = t.function(id); + let mut handles = Vec::new(); + let mut seen = Vec::new(); + if f.receiver.is_some() { + match id.owner { + Owner::Object(i) => handles.push(i), + Owner::Record(i) => t.api.handles(&Type::Record(i), &mut handles, &mut seen), + Owner::Enum(i) => t.api.handles(&Type::Enum(i), &mut handles, &mut seen), + Owner::Free => {} + } + } + for param in &f.params { + t.api.handles(¶m.ty, &mut handles, &mut seen); + } + handles.iter().any(|&i| self.checked[i]) + } + + /// Whether a call of `id` throws: a future, a `Result`, a check that can fail, or a + /// target the library may lack. + fn throws(&self, t: &Transcript, id: FnId) -> bool { + let f = t.function(id); + f.future || f.err.is_some() || self.status(t, id) || !t.api.everywhere(f.on) + } + + /// Whether `id` is a `mutating` method: a value's or a struct's `&mut self`. + fn mutating(&self, t: &Transcript, id: FnId) -> bool { + match (t.function(id).receiver, id.owner) { + (Some(Receiver::Mut), Owner::Record(_) | Owner::Enum(_)) => true, + (Some(Receiver::Mut), Owner::Object(i)) => self.structs.contains(&i), + _ => false, + } + } + + /// Whether `id` is a property rather than a method. + fn property(&self, t: &Transcript, id: FnId) -> bool { + let f = t.function(id); + let throws = self.throws(t, id); + match (f.access, f.receiver) { + (Access::Field { set: false, .. }, Some(_)) => { + let ok = match &f.ok { + Type::Tuple(elements) if elements.len() == 1 => &elements[0], + ok => ok, + }; + let getter = !f.future && f.err.is_none() && t.api.everywhere(f.on) && !self.unique(ok); + f.params.is_empty() && !self.mutating(t, id) && (!throws || getter) + } + (Access::Const, None) => f.params.is_empty() && !throws, + _ => false, + } + } +} + +/// Whether a call can fail a check of each object's handle, as the exporter's `checked` +/// decides: its value is not `Sync`, a call borrows it exclusively or moves it, or a handle +/// to it is lent. +fn checked(api: &Api) -> Vec { + fn param(api: &Api, ty: &Type, owned: bool, checked: &mut [bool]) { + match ty { + Type::Object(i) if owned && !api.objects[*i].copy => checked[*i] = true, + Type::Ref(Mutability::Mut, inner) => { + if let Type::Object(i) = inner.base() { + checked[*i] = true; + } + param(api, inner, true, checked); + } + Type::Ref(Mutability::Not, inner) => param(api, inner, false, checked), + Type::Option(inner) | Type::Box(inner) | Type::List(_, inner) => param(api, inner, owned, checked), + Type::Tuple(elements) => elements.iter().for_each(|ty| param(api, ty, owned, checked)), + Type::Closure(closure) => closure.params.iter().for_each(|ty| lent(api, ty, checked)), + Type::Record(_) | Type::Enum(_) if owned => lent(api, ty, checked), + _ => {} + } + } + fn lent(api: &Api, ty: &Type, checked: &mut [bool]) { + let mut handles = Vec::new(); + api.handles(ty, &mut handles, &mut Vec::new()); + handles.into_iter().for_each(|i| checked[i] = true); + } + let mut checked: Vec = api.objects.iter().map(|o| !o.sync).collect(); + let functions = (api.records.iter().flat_map(|r| &r.methods)) + .chain(api.enums.iter().flat_map(|e| &e.methods)) + .chain(&api.functions) + .map(|f| (None, f)) + .chain((api.objects.iter().enumerate()).flat_map(|(i, o)| o.methods.iter().map(move |f| (Some(i), f)))); + for (owner, f) in functions { + match (owner, f.receiver) { + (Some(i), Some(Receiver::Mut)) => checked[i] = true, + (Some(i), Some(Receiver::Owned)) if !api.objects[i].copy => checked[i] = true, + _ => {} + } + f.params.iter().for_each(|p| param(api, &p.ty, true, &mut checked)); + if f.lends { + lent(api, &f.ok, &mut checked); + } + if f.lends_mut + && let Type::Object(j) = f.ok + { + checked[j] = true; + } + } + for method in api.callbacks.iter().flat_map(|c| &c.methods) { + method.params.iter().for_each(|p| lent(api, &p.ty, &mut checked)); + lent(api, &method.ok, &mut checked); + method.err.iter().for_each(|err| lent(api, err, &mut checked)); + } + checked +} + +struct Emitter<'t> { + t: &'t Transcript, + model: Model, + depth: usize, + fresh: usize, + /// Whether the expression being written throws, so its root is `try!`. + threw: bool, + /// Whether the call about to be written is a statement's whole value. + at_root: bool, + /// The locals Swift changes, each a `var`. + mutated: BTreeSet, + /// The locals Swift holds optional, each read unwrapped: a class Rust drops early, or a + /// struct passed as an optional `inout`. + optional: BTreeSet, + /// The names a closure's tuple pattern binds, each read as the element it names. + aliases: BTreeMap, + /// The integers whose `Bound` the script prints. + bounds: BTreeSet, +} + +/// Swift's keywords, which a local's name is quoted as. +const KEYWORDS: &[&str] = &[ + "as", "break", "case", "catch", "class", "continue", "default", "defer", "do", "else", "enum", "extension", "fallthrough", + "false", "for", "func", "guard", "if", "import", "in", "init", "inout", "internal", "is", "let", "nil", "operator", + "private", "protocol", "public", "repeat", "rethrows", "return", "self", "static", "struct", "subscript", "super", + "switch", "throw", "throws", "true", "try", "var", "where", "while", +]; + +/// A name as Swift spells it, quoted if a keyword. +fn kw(name: &str) -> String { + match KEYWORDS.contains(&name) { + true => format!("`{name}`"), + false => name.to_string(), + } +} + +impl Emitter<'_> { + fn indent(&self) -> String { + "\t".repeat(self.depth) + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("_{what}{}", self.fresh) + } + + fn line(&self, out: &mut String, line: &str) { + for l in line.lines() { + let _ = writeln!(out, "{}{l}", self.indent()); + } + } + + /// Record which locals Swift changes or holds optional. + fn mutations(&mut self, step: &Step) { + let visit = |e: &Expr, this: &mut Self| { + walk(e, &mut |e| { + let Kind::Call(id, receiver, args) = &e.kind else { return }; + if this.model.mutating(this.t, *id) + && let Some(Kind::Var(name)) = receiver.as_ref().map(|r| &r.kind) + { + this.mutated.insert(name.clone()); + } + for (arg, param) in args.iter().zip(&this.t.function(*id).params) { + if !this.model.inout(¶m.ty) { + continue; + } + match &arg.kind { + Kind::Var(name) => { + this.mutated.insert(name.clone()); + } + Kind::Some(inner) => match &inner.kind { + Kind::Var(name) => { + this.mutated.insert(name.clone()); + this.optional.insert(name.clone()); + } + _ => panic!("an optional &mut of anything but a local"), + }, + _ => {} + } + } + }) + }; + match step { + Step::Drop(name) => { + // A class goes once Swift's last reference does, so Rust's early drop is Swift's + // release of an optional's. + if !self.dropped_struct(name) { + self.optional.insert(name.clone()); + self.mutated.insert(name.clone()); + } + } + Step::Let(_, e) | Step::Do(e) => visit(e, self), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + visit(e, self) + } + }), + Step::Match { value, ok, err } => { + visit(value, self); + ok.steps.iter().chain(&err.steps).for_each(|s| self.mutations(s)); + } + } + // The steps of each closure. + let mut closures = Vec::new(); + each_expr(step, &mut |e| { + walk(e, &mut |e| { + if let Kind::Closure(_, steps, _) = &e.kind { + closures.extend(steps.iter().cloned()); + } + }) + }); + for step in &closures { + self.mutations(step); + } + } + + /// Whether the local `name` Rust drops early is a struct, which Swift consumes. + fn dropped_struct(&self, name: &str) -> bool { + let mut types = Vec::new(); + let mut find = |steps: &[Step]| { + for step in steps { + let mut bound_names = Vec::new(); + if let Step::Let(pat, _) = step { + bound(pat, &mut bound_names); + } + types.extend(bound_names.into_iter().filter(|(n, _)| n == name).map(|(_, ty)| ty)); + } + }; + find(&self.t.steps); + let ty = types.first().unwrap_or_else(|| panic!("a drop of {name}, which no let binds")); + self.model.unique(ty) + } + + fn steps(&mut self, steps: &[Step]) -> String { + let mut out = String::new(); + for step in steps { + self.step(step, &mut out); + } + out + } + + fn step(&mut self, step: &Step, out: &mut String) { + match step { + Step::Let(pat, value) => { + let literal = matches!(&value.kind, Kind::Tuple(_)) && !matches!(unref(&value.ty).base(), Type::Range(_) | Type::Bounds(_)); + match (pat, &value.kind) { + // A tuple literal binds each element, so each may be its own `let` or `var`. + (Pat::Tuple(pats), Kind::Tuple(elements)) if literal => { + for (pat, element) in pats.iter().zip(elements) { + self.step(&Step::Let(pat.clone(), element.clone()), out); + } + } + (Pat::Name(name, _), _) => { + self.at_root = matches!(value.kind, Kind::Call(..)); + let v = self.root(value, &value.ty, out); + self.at_root = false; + let typed = match self.optional.contains(name) { + true => format!(": {}?", self.sw(&value.ty)), + false if literalish(value) => format!(": {}", self.sw(&value.ty)), + false => String::new(), + }; + let keyword = self.keyword(name); + self.line(out, &format!("{keyword} {}{typed} = {v}", kw(name))); + } + (pat, _) => { + self.at_root = matches!(value.kind, Kind::Call(..)); + let v = self.root(value, &value.ty, out); + self.at_root = false; + self.bind(pat, &v, &value.ty, out); + } + } + } + Step::Print(pieces) => { + let v = self.pieces(pieces, out); + self.line(out, &format!("print({v})")); + } + Step::Do(value) => { + self.at_root = matches!(value.kind, Kind::Call(..)); + let v = self.root(value, &value.ty, out); + self.at_root = false; + match unref(&value.ty) { + Type::Unit => self.line(out, &v), + _ => self.line(out, &format!("_ = {v}")), + } + } + Step::Drop(name) => match self.optional.contains(name) { + true => self.line(out, &format!("{} = nil", kw(name))), + false => self.line(out, &format!("_ = consume {}", kw(name))), + }, + Step::Match { value, ok, err } => self.matched(value, ok, err, out), + } + } + + /// The keyword declaring the local `name`. + fn keyword(&self, name: &str) -> &'static str { + match self.mutated.contains(name) || self.optional.contains(name) { + true => "var", + false => "let", + } + } + + /// `pat` bound to `v`, a value of `ty`. + fn bind(&mut self, pat: &Pat, v: &str, ty: &Type, out: &mut String) { + match pat { + Pat::Name(name, _) => { + let keyword = self.keyword(name); + let typed = match self.optional.contains(name) { + true => format!(": {}?", self.sw(ty)), + false => String::new(), + }; + self.line(out, &format!("{keyword} {}{typed} = {v}", kw(name))); + } + Pat::Ignore(_) => self.line(out, &format!("_ = {v}")), + Pat::Tuple(pats) => { + let parts = self.parts(pats, ty); + // A tuple of one is its element. + if let [(pat, _, _)] = &parts[..] { + return self.bind(pat, v, &parts[0].2, out); + } + let tmp = self.fresh("t"); + self.line(out, &format!("let {tmp} = {v}")); + for (pat, element, ty) in parts { + self.bind(&pat, &format!("{tmp}{element}"), &ty, out); + } + } + } + } + + /// The parts of a tuple pattern of `ty`: each pattern, the member that reads its value, + /// and its type. + fn parts(&self, pats: &[Pat], ty: &Type) -> Vec<(Pat, String, Type)> { + match unref(ty).base() { + Type::Bounds(int) => vec![ + (pats[0].clone(), ".start".to_string(), Type::Bound(*int)), + (pats[1].clone(), ".end".to_string(), Type::Bound(*int)), + ], + Type::Tuple(elements) => { + let unique = self.model.unique(unref(ty).base()); + (pats.iter().zip(elements).enumerate()) + .map(|(n, (p, ty))| { + let member = match unique { + true => format!("._{n}"), + false => format!(".{n}"), + }; + (p.clone(), member, ty.clone()) + }) + .collect() + } + ty => panic!("a tuple pattern of {ty:?}"), + } + } + + /// `pat`, the parameter of a closure, as Swift names it, each name a tuple pattern binds + /// read as the element it names. + fn param(&mut self, pat: &Pat) -> String { + match pat { + Pat::Name(name, _) => kw(name), + Pat::Ignore(_) => "_".to_string(), + Pat::Tuple(_) => { + let tmp = self.fresh("p"); + self.alias(pat, &tmp); + tmp + } + } + } + + fn alias(&mut self, pat: &Pat, v: &str) { + match pat { + Pat::Name(name, _) => { + self.aliases.insert(name.clone(), v.to_string()); + } + Pat::Ignore(_) => {} + Pat::Tuple(pats) => { + let ty = pat_type(pat); + let parts = self.parts(pats, &ty); + if let [(pat, _, _)] = &parts[..] { + return self.alias(pat, v); + } + for (pat, element, _) in parts { + self.alias(&pat, &format!("{v}{element}")); + } + } + } + } + + /// The Swift of `e` as a whole expression: `try!` if any call it makes throws. + fn root(&mut self, e: &Expr, want: &Type, out: &mut String) -> String { + self.rooted("try! ", out, |this, out| this.value(e, want, out)) + } + + /// `write`'s expression, prefixed with `prefix` if it throws. + fn rooted(&mut self, prefix: &str, out: &mut String, write: impl FnOnce(&mut Self, &mut String) -> String) -> String { + let saved = std::mem::replace(&mut self.threw, false); + let v = write(self, out); + match std::mem::replace(&mut self.threw, saved) { + true => format!("{prefix}{v}"), + false => v, + } + } + + fn matched(&mut self, value: &Expr, ok: &Arm, err: &Arm, out: &mut String) { + match &value.ty { + Type::Option(inner) => { + let v = self.root(value, &value.ty, out); + self.line(out, &format!("switch {v} {{")); + let binding = match &ok.pat { + Some(Pat::Name(name, _)) => format!("{} {}", self.keyword(name), kw(name)), + Some(Pat::Ignore(_)) | None => "_".to_string(), + Some(Pat::Tuple(_)) => format!("let {}", self.fresh("o")), + }; + self.line(out, &format!("case .some({binding}):")); + self.depth += 1; + let mut body = String::new(); + if let Some(pat @ Pat::Tuple(_)) = &ok.pat { + let tmp = binding.trim_start_matches("let ").to_string(); + self.bind(pat, &tmp, inner, &mut body); + } + body.push_str(&self.steps(&ok.steps)); + self.body(body, out); + self.depth -= 1; + self.line(out, "case .none:"); + self.depth += 1; + let body = self.steps(&err.steps); + self.body(body, out); + self.depth -= 1; + self.line(out, "}"); + } + Type::Result(ok_ty, err_ty) => { + let (exception, wrapped) = self.exception(err_ty); + self.line(out, "do {"); + self.depth += 1; + let mut body = String::new(); + let v = self.rooted("try ", &mut body, |this, out| this.value(value, &value.ty, out)); + match (&ok.pat, unref(ok_ty)) { + (_, Type::Unit) => self.line(&mut body, &v), + (Some(pat), _) => self.bind(pat, &v, ok_ty, &mut body), + (None, _) => self.line(&mut body, &format!("_ = {v}")), + } + body.push_str(&self.steps(&ok.steps)); + out.push_str(&body); + self.depth -= 1; + let e = self.fresh("e"); + self.line(out, &format!("}} catch let {e} as {exception} {{")); + self.depth += 1; + let mut body = String::new(); + if let Some(pat) = &err.pat { + let error = match wrapped { + true => format!("{e}.error"), + false => e.clone(), + }; + self.bind(pat, &error, err_ty, &mut body); + } + body.push_str(&self.steps(&err.steps)); + self.body(body, out); + self.depth -= 1; + self.line(out, "} catch {"); + self.depth += 1; + self.line(out, "fatalError(\"\\(error)\")"); + self.depth -= 1; + self.line(out, "}"); + } + ty => panic!("a match on {ty:?}"), + } + } + + /// A case's body, which Swift requires hold a statement. + fn body(&self, body: String, out: &mut String) { + match body.is_empty() { + true => self.line(out, "break"), + false => out.push_str(&body), + } + } + + /// The type a call failing with `err` throws, and whether it wraps the error in its + /// `error`. + fn exception(&self, err: &Type) -> (String, bool) { + match unref(err).base() { + ty @ (Type::Record(_) | Type::Enum(_) | Type::Object(_)) => (self.type_name(ty), false), + _ => { + let key = format!("error {}", self.spell(&owned(err))); + (format!("Api.{}", self.t.named(LANGUAGE, &key)), true) + } + } + } + + /// A type as the export keys it: its C name, past the prefix, which C++ names it by. + fn key(&self, ty: &Type) -> String { + match ty { + Type::Unit => "unit".to_string(), + Type::Bool => "bool".to_string(), + Type::Str | Type::String => "string".to_string(), + Type::Slice | Type::Vec | Type::Bytes => "bytes".to_string(), + Type::Path | Type::PathBuf => "path".to_string(), + Type::Int(int) => int.rust().to_string(), + Type::NonZero(int) => format!("non_zero_{}", int.rust()), + Type::F32 => "f32".to_string(), + Type::F64 => "f64".to_string(), + Type::Char => "char".to_string(), + Type::U128 => "u128".to_string(), + Type::Duration => "duration".to_string(), + Type::Array(n) => format!("array_u8_{n}"), + Type::Option(inner) => format!("option_{}", self.key(inner)), + Type::List(_, inner) => format!("vec_{}", self.key(inner)), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => self.t.type_name("C++", ty).to_string(), + Type::Range(int) => format!("range_{}", int.rust()), + Type::Bound(int) => format!("bound_{}", int.rust()), + Type::Bounds(int) => format!("bounds_{}", int.rust()), + Type::Ref(_, inner) | Type::Box(inner) => self.key(inner), + other => panic!("no key spells {other:?}"), + } + } + + /// A type by its key, each tuple spelled as Rust spells it. + fn spell(&self, ty: &Type) -> String { + match ty { + Type::Tuple(elements) => { + let elements: Vec = elements.iter().map(|e| self.spell(e)).collect(); + match elements.len() { + 1 => format!("({},)", elements[0]), + _ => format!("({})", elements.join(", ")), + } + } + ty => self.key(ty), + } + } + + /// The Swift name of a record, enum, or object, qualified by the module. + fn type_name(&self, ty: &Type) -> String { + format!("Api.{}", self.t.type_name(LANGUAGE, ty)) + } + + /// The Swift type of `ty`. + fn sw(&self, ty: &Type) -> String { + match ty { + Type::Unit => "Void".to_string(), + Type::Bool => "Bool".to_string(), + Type::Int(int) => sw_int(*int).to_string(), + Type::NonZero(int) => format!("NonZero<{}>", sw_int(*int)), + Type::U128 => "U128".to_string(), + Type::F32 => "Float".to_string(), + Type::F64 => "Double".to_string(), + Type::Char => "Unicode.Scalar".to_string(), + Type::Str | Type::String => "String".to_string(), + Type::Slice | Type::Vec | Type::Bytes => "Bytes".to_string(), + Type::Array(n) => format!("Api.ArrayU8x{n}"), + Type::Path | Type::PathBuf => "PathBuf".to_string(), + Type::Duration => "RustDuration".to_string(), + Type::SocketAddr(Family::Any) => "SocketAddr".to_string(), + Type::SocketAddr(Family::V4) => "SocketAddrV4".to_string(), + Type::SocketAddr(Family::V6) => "SocketAddrV6".to_string(), + Type::IpAddr(Family::Any) => "IpAddr".to_string(), + Type::IpAddr(Family::V4) => "Ipv4Addr".to_string(), + Type::IpAddr(Family::V6) => "Ipv6Addr".to_string(), + Type::List(_, item) if self.model.unique(item) => format!("UniqueArray<{}>", self.sw(item)), + Type::List(_, item) => format!("[{}]", self.sw(item)), + Type::Option(inner) => format!("{}?", self.sw(inner)), + Type::Box(inner) | Type::Ref(_, inner) => self.sw(inner), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => self.type_name(ty), + Type::Callback(..) => panic!("a local of a callback"), + Type::Range(int) => format!("Api.Range{}", int_name(*int)), + Type::Bound(int) => format!("Api.Bound{}", int_name(*int)), + Type::Bounds(int) => format!("Api.Bounds{}", int_name(*int)), + Type::Tuple(elements) => match &elements[..] { + [element] => self.sw(element), + _ if self.model.unique(ty) => self.tuple_name(elements), + elements => { + let elements: Vec = elements.iter().map(|e| self.sw(e)).collect(); + format!("({})", elements.join(", ")) + } + }, + ty => panic!("a local of {ty:?}"), + } + } + + /// The struct of a tuple holding a struct, which a Swift tuple cannot. + fn tuple_name(&self, elements: &[Type]) -> String { + let key = format!("tuple {}", self.spell(&owned(&Type::Tuple(elements.to_vec())))); + format!("Api.{}", self.t.named(LANGUAGE, &key)) + } + + /// The Swift of a format's pieces: a string literal. A piece that needs statements first + /// has each piece before it written to a local, so they run in order. + fn pieces(&mut self, pieces: &[Piece], out: &mut String) -> String { + let mut parts = String::new(); + for piece in pieces { + match piece { + Piece::Text(text) => parts.push_str(&escape(text)), + Piece::Value(e, spec) => { + let mut pre = String::new(); + let mut v = self.rooted("try! ", &mut pre, |this, pre| { + let v = this.value(e, &e.ty, pre); + this.show(&v, &e.ty, *spec) + }); + // A string's interpolation is one line: a closure of several is a local's. + if v.contains('\n') { + let tmp = self.fresh("v"); + self.line(&mut pre, &format!("let {tmp} = {v}")); + v = tmp; + } + if !pre.is_empty() && !parts.is_empty() { + let tmp = self.fresh("s"); + self.line(out, &format!("let {tmp} = \"{parts}\"")); + parts = format!("\\({tmp})"); + } + out.push_str(&pre); + let _ = write!(parts, "\\({v})"); + } + } + } + format!("\"{parts}\"") + } + + /// `v`, a value of `ty`, as Swift interpolates it the way Rust formats it with `spec`. + fn show(&mut self, v: &str, ty: &Type, spec: Spec) -> String { + let ty = unref(ty).base(); + match (spec, ty) { + (Spec::Hex(width), Type::Int(int)) if !int.signed() => return format!("_hex({v}, {width})"), + (Spec::Hex(width), Type::U128) => return format!("_hex({v}, {width})"), + (Spec::Padded(width), Type::Int(_)) => return format!("_padded({v}, {width})"), + (Spec::Debug, _) => return self.debug(v, ty), + (Spec::Display, _) => {} + (spec, ty) => panic!("{spec:?} of {ty:?}"), + } + match ty { + Type::Bool | Type::Int(_) | Type::U128 | Type::NonZero(_) | Type::String | Type::Str | Type::Char => v.to_string(), + Type::Object(i) if !self.t.api.objects[*i].traits.display => { + let o = &self.t.api.objects[*i]; + let Some(index) = o.methods.iter().position(|m| m.access == Access::Text) else { + panic!("Display of {}, which has none", self.t.rust(ty)) + }; + let id = FnId { + owner: Owner::Object(*i), + index, + }; + self.threw |= self.model.throws(self.t, id); + format!("{}.{}()", postfix(v), self.t.name(LANGUAGE, id)) + } + Type::Object(_) | Type::Record(_) | Type::Enum(_) => { + self.threw |= self.model.traits_throw(&self.t.api, ty); + format!("{}.description", postfix(v)) + } + ty => panic!("Display of {ty:?}"), + } + } + + /// `x` as Rust's `Debug` prints a value of `ty`, in a closure of its own: `try!` if it + /// throws. + fn debug_in(&mut self, x: &str, ty: &Type) -> String { + let mut pre = String::new(); + self.rooted("try! ", &mut pre, |this, _| this.debug(x, ty)) + } + + /// `v` as Rust's `Debug` prints a value of `ty`. + fn debug(&mut self, v: &str, ty: &Type) -> String { + match unref(ty).base() { + Type::Bool | Type::Int(_) | Type::U128 | Type::NonZero(_) => v.to_string(), + Type::String | Type::Str => format!("_quoted({v})"), + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => format!("Array({v})"), + Type::Option(inner) => { + let x = self.fresh("x"); + let show = self.debug_in(&x, inner); + format!("_option({v}) {{ {x} in \"\\({show})\" }}") + } + Type::List(_, item) if self.model.unique(item) => { + let x = self.fresh("x"); + let show = self.debug_in(&x, item); + format!("\"[\" + _each({v}) {{ {x} in \"\\({show})\" }}.joined(separator: \", \") + \"]\"") + } + Type::List(_, item) => { + let x = self.fresh("x"); + let show = self.debug_in(&x, item); + format!("_list({v}) {{ {x} in \"\\({show})\" }}") + } + Type::Tuple(elements) if elements.len() == 1 => format!("\"(\\({}),)\"", self.debug(v, &elements[0])), + Type::Tuple(elements) => { + let x = self.fresh("x"); + let unique = self.model.unique(ty); + let parts: Vec = (elements.iter().enumerate()) + .map(|(n, ty)| { + let element = match unique { + true => format!("{x}._{n}"), + false => format!("{x}.{n}"), + }; + format!("\\({})", self.debug_in(&element, ty)) + }) + .collect(); + format!("_with({v}) {{ {x} in \"({})\" }}", parts.join(", ")) + } + Type::Bound(int) => { + self.bounds.insert(*int); + format!("_bound{}({v})", int_name(*int)) + } + ty @ (Type::Record(_) | Type::Enum(_) | Type::Object(_)) => { + self.threw |= self.model.traits_throw(&self.t.api, ty); + format!("{}.debugDescription", postfix(v)) + } + ty => panic!("Debug of {ty:?}"), + } + } + + /// The Swift of `e`, passed where `want` is taken: an address of one family widened to + /// either's, as Rust's `into` does. + fn value(&mut self, e: &Expr, want: &Type, out: &mut String) -> String { + let v = self.value_of(e, want, out); + match (unref(&e.ty).base(), unref(want).base()) { + (Type::SocketAddr(Family::V4), Type::SocketAddr(Family::Any)) => format!("SocketAddr.v4({v})"), + (Type::SocketAddr(Family::V6), Type::SocketAddr(Family::Any)) => format!("SocketAddr.v6({v})"), + (Type::IpAddr(Family::V4), Type::IpAddr(Family::Any)) => format!("IpAddr.v4({v})"), + (Type::IpAddr(Family::V6), Type::IpAddr(Family::Any)) => format!("IpAddr.v6({v})"), + _ => v, + } + } + + fn value_of(&mut self, e: &Expr, want: &Type, out: &mut String) -> String { + match &e.kind { + Kind::Unit => "()".to_string(), + Kind::Bool(b) => b.to_string(), + Kind::Int(n) => match unref(want).base() { + Type::U128 => { + let v = n.magnitude; + format!("U128(high: {}, low: {})", (v >> 64) as u64, v as u64) + } + Type::NonZero(int) => { + self.threw = true; + format!("NonZero<{}>({n})", sw_int(*int)) + } + _ => n.to_string(), + }, + Kind::Float(f) => { + let f32 = matches!(unref(want).base(), Type::F32); + match (f32, f.is_finite() && !(*f == 0.0 && f.is_sign_negative())) { + (false, true) => format!("{f:?}"), + (true, true) => format!("Float({f:?})"), + (false, false) => format!("Double(bitPattern: {:#x})", f.to_bits()), + (true, false) => format!("Float(bitPattern: {:#x})", (*f as f32).to_bits()), + } + } + Kind::Char(c) => format!("Unicode.Scalar({:#x} as UInt32)!", *c as u32), + Kind::Str(s) => match unref(want).base() { + Type::Path | Type::PathBuf => format!("PathBuf(\"{}\")", escape(s)), + _ => format!("\"{}\"", escape(s)), + }, + Kind::Bytes(b) => match unref(want).base() { + Type::Array(n) => format!("Api.ArrayU8x{n}({})!", byte_list(b)), + _ => format!("Bytes({})", byte_list(b)), + }, + Kind::Duration(secs, nanos) => { + self.threw = true; + format!("RustDuration(secs: {secs}, nanos: {nanos})") + } + Kind::Socket(addr) => { + let (v4, v6) = match addr { + std::net::SocketAddr::V4(a) => (Some(format!("SocketAddrV4(ip: {}, port: {})", ipv4(*a.ip()), a.port())), None), + std::net::SocketAddr::V6(a) => ( + None, + Some(format!( + "SocketAddrV6(ip: {}, port: {}, flowinfo: {}, scopeId: {})", + ipv6(*a.ip()), + a.port(), + a.flowinfo(), + a.scope_id() + )), + ), + }; + match (unref(want).base(), v4, v6) { + (Type::SocketAddr(Family::Any), Some(v), _) => format!("SocketAddr.v4({v})"), + (Type::SocketAddr(Family::Any), _, Some(v)) => format!("SocketAddr.v6({v})"), + (Type::SocketAddr(Family::V4), Some(v), _) | (Type::SocketAddr(Family::V6), _, Some(v)) => v, + (ty, ..) => panic!("a socket address as {ty:?}"), + } + } + Kind::Ip(ip) => { + let (v, family) = match ip { + std::net::IpAddr::V4(ip) => (ipv4(*ip), "v4"), + std::net::IpAddr::V6(ip) => (ipv6(*ip), "v6"), + }; + match unref(want).base() { + Type::IpAddr(Family::Any) => format!("IpAddr.{family}({v})"), + _ => v, + } + } + Kind::None => "nil".to_string(), + Kind::Some(inner) => { + let inner_want = match unref(want).base() { + Type::Option(inner) => (**inner).clone(), + _ => inner.ty.clone(), + }; + let v = self.value(inner, &inner_want, out); + // Some of what Swift holds optional already nests, else a nil would be its none. + match optional(&inner_want) { + true => format!(".some({v})"), + false => v, + } + } + Kind::Tuple(elements) => self.tuple(e, elements, want, out), + Kind::List(items) => self.list(items, want, out), + Kind::Record(r, fields) => { + let record = &self.t.api.records[*r]; + let name = self.type_name(&Type::Record(*r)); + let labels: Vec> = (record.fields.iter()) + .map(|f| (!record.tuple).then(|| field_name(&f.name))) + .collect(); + let types: Vec = record.fields.iter().map(|f| f.ty.clone()).collect(); + let args = self.labelled(fields, &types, &labels, out); + format!("{name}({args})") + } + Kind::Variant(en, v, fields) => { + let name = self.type_name(&Type::Enum(*en)); + let variant = &self.t.api.enums[*en].variants[*v]; + let case = member(&snake(&variant.name)); + if variant.fields.is_empty() { + return format!("{name}.{case}"); + } + let labels: Vec> = (variant.fields.iter()) + .map(|f| (!variant.tuple).then(|| field_name(&f.name))) + .collect(); + let types: Vec = variant.fields.iter().map(|f| f.ty.clone()).collect(); + let args = self.labelled(fields, &types, &labels, out); + format!("{name}.{case}({args})") + } + Kind::Bound(kind, value) => match (kind, value) { + (BoundKind::Unbounded, _) => format!("{}.unbounded", self.sw(unref(&e.ty))), + (BoundKind::Included, Some(v)) => format!("{}.included({})", self.sw(unref(&e.ty)), self.expr(v, out)), + (BoundKind::Excluded, Some(v)) => format!("{}.excluded({})", self.sw(unref(&e.ty)), self.expr(v, out)), + _ => unreachable!(), + }, + Kind::Default => { + let ty = unref(&e.ty).base(); + let on = match ty { + Type::Record(i) => self.t.api.records[*i].on, + Type::Enum(i) => self.t.api.enums[*i].on, + Type::Object(i) => self.t.api.objects[*i].on, + ty => panic!("a default of {ty:?}"), + }; + self.threw |= !self.t.api.everywhere(on); + format!("{}.default()", self.type_name(ty)) + } + Kind::Var(name) => self.var(name), + Kind::Const(c) => format!( + "Api.{}", + self.t.named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::"))) + ), + Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args, out), + Kind::Field(base, i) => { + let b = self.expr(base, out); + let Type::Record(r) = unref(&base.ty).base() else { panic!("a field of {:?}", base.ty) }; + format!("{}.{}", postfix(&b), field_name(&self.t.api.records[*r].fields[*i].name)) + } + Kind::Element(base, i) => { + let b = self.expr(base, out); + match unref(&base.ty).base() { + Type::Range(_) => format!("{}.{}", postfix(&b), if *i == 0 { "start" } else { "end" }), + Type::Tuple(elements) if elements.len() == 1 => b, + ty if self.model.unique(ty) => format!("{}._{i}", postfix(&b)), + _ => format!("{}.{i}", postfix(&b)), + } + } + Kind::Clone(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + ty @ Type::Object(i) if self.t.api.objects[*i].traits.clone => { + self.threw |= self.model.traits_throw(&self.t.api, ty); + format!("{}.clone()", postfix(&v)) + } + // What a call returns is the caller's own already. + ty if self.model.unique(ty) && matches!(inner.kind, Kind::Call(..)) => v, + ty if self.model.unique(ty) => panic!("a clone of {ty:?}, which Swift cannot copy"), + _ => v, + } + } + Kind::Unwrap(inner) => { + let v = self.expr(inner, out); + match &inner.ty { + Type::Result(..) => v, + _ => format!("{}!", postfix(&v)), + } + } + Kind::UnwrapErr(inner) => { + let Type::Result(_, err) = &inner.ty else { panic!("unwrap_err of {:?}", inner.ty) }; + let (exception, wrapped) = self.exception(err); + let call = self.attempt(inner); + match wrapped { + true => format!("_err({exception}.self) {{ {call} }}.error"), + false => format!("_err({exception}.self) {{ {call} }}"), + } + } + Kind::IsErr(inner) => { + let Type::Result(_, err) = &inner.ty else { panic!("is_err of {:?}", inner.ty) }; + let (exception, _) = self.exception(err); + let call = self.attempt(inner); + format!("_fails({exception}.self) {{ {call} }}") + } + Kind::IsSome(inner) => format!("({} != nil)", self.expr(inner, out)), + Kind::IsNone(inner) => format!("({} == nil)", self.expr(inner, out)), + Kind::Binary(op, a, b) => { + if matches!(op, Op::Eq | Op::Ne) { + let ty = unref(&a.ty).base(); + if matches!(ty, Type::Record(_) | Type::Enum(_) | Type::Object(_)) { + self.threw |= self.model.traits_throw(&self.t.api, ty); + } + } + let (a, b) = (self.expr(a, out), self.expr(b, out)); + let op = match op { + Op::Eq => "==", + Op::Ne => "!=", + Op::Lt => "<", + Op::Gt => ">", + Op::Add => "+", + Op::Sub => "-", + Op::Mul => "*", + Op::Rem => "%", + Op::And => "&&", + }; + format!("({a} {op} {b})") + } + Kind::Closure(params, steps, value) => self.closure(params, steps, value), + Kind::Local(name, args) => { + let args: Vec = args.iter().map(|a| self.expr(a, out)).collect(); + match name.starts_with(|c: char| c.is_uppercase()) { + true => format!("{name}({})", args.join(", ")), + false => format!("{}({})", camel(name), args.join(", ")), + } + } + Kind::Format(pieces) => self.pieces(pieces, out), + Kind::Join { items, pat, body, sep } => { + let item = match unref(&items.ty).base() { + Type::List(_, item) => (**item).clone(), + ty => panic!("a join over {ty:?}"), + }; + let v = self.expr(items, out); + let x = self.param(pat); + let body = self.closure_value(body); + match self.model.unique(&item) { + true => format!("_each({v}) {{ {x} in {body} }}.joined(separator: \"{}\")", escape(sep)), + false => format!("{}.map {{ {x} in {body} }}.joined(separator: \"{}\")", postfix(&v), escape(sep)), + } + } + Kind::MapOr { option, none, pat, some } => { + let option = self.expr(option, out); + let none = self.expr(none, out); + let x = self.param(pat); + let some = self.closure_value(some); + format!("({}.map {{ {x} in {some} }} ?? {none})", postfix(&option)) + } + Kind::Utf8(inner) => format!("String(decoding: {}, as: UTF8.self)", self.expr(inner, out)), + Kind::Len(inner) => { + let v = self.expr(inner, out); + match unref(&inner.ty).base() { + Type::String | Type::Str => format!("{}.utf8.count", postfix(&v)), + _ => format!("{}.count", postfix(&v)), + } + } + } + } + + fn expr(&mut self, e: &Expr, out: &mut String) -> String { + self.value(e, &e.ty, out) + } + + /// A local, read: unwrapped if Swift holds it optional, or the element a tuple pattern + /// names. + fn var(&self, name: &str) -> String { + if let Some(alias) = self.aliases.get(name) { + return alias.clone(); + } + match self.optional.contains(name) { + true => format!("{}!", kw(name)), + false => kw(name), + } + } + + /// The call `inner` makes, which throws its error, for a closure that catches it. + fn attempt(&mut self, inner: &Expr) -> String { + let mut pre = String::new(); + let call = self.rooted("try ", &mut pre, |this, pre| this.expr(inner, pre)); + assert!(pre.is_empty(), "a failing call needing statements first"); + call + } + + /// Arguments labelled as `labels` say, each passed where its type is taken. + fn labelled(&mut self, values: &[Expr], types: &[Type], labels: &[Option], out: &mut String) -> String { + let args: Vec = (values.iter().zip(types).zip(labels)) + .map(|((v, ty), label)| { + let v = self.value(v, ty, out); + match label { + Some(label) => format!("{}: {v}", unquote(label)), + None => v, + } + }) + .collect(); + args.join(", ") + } + + fn tuple(&mut self, e: &Expr, elements: &[Expr], want: &Type, out: &mut String) -> String { + match unref(&e.ty).base() { + Type::Range(_) | Type::Bounds(_) => { + let name = self.sw(unref(&e.ty).base()); + let (a, b) = (self.expr(&elements[0], out), self.expr(&elements[1], out)); + format!("{name}(start: {a}, end: {b})") + } + _ => { + let wants: Vec = match unref(want).base() { + Type::Tuple(ts) => ts.clone(), + _ => elements.iter().map(|e| e.ty.clone()).collect(), + }; + let parts: Vec = elements.iter().zip(&wants).map(|(e, t)| self.value(e, t, out)).collect(); + match parts.len() { + 1 => parts.into_iter().next().unwrap(), + _ if self.model.unique(&Type::Tuple(wants.clone())) => { + format!("{}({})", self.tuple_name(&wants), parts.join(", ")) + } + _ => format!("({})", parts.join(", ")), + } + } + } + } + + fn list(&mut self, items: &[Expr], want: &Type, out: &mut String) -> String { + let item = match unref(want).base() { + Type::List(_, item) => (**item).clone(), + ty => panic!("a list as {ty:?}"), + }; + if !self.model.unique(&item) { + let parts: Vec = items.iter().map(|e| self.value(e, &item, out)).collect(); + return format!("[{}]", parts.join(", ")); + } + let sw = self.sw(&item); + if items.is_empty() { + return format!("UniqueArray<{sw}>()"); + } + // A `UniqueArray` has no literal: each item is appended, in order. + let list = self.fresh("a"); + self.line(out, &format!("var {list} = UniqueArray<{sw}>()")); + for e in items { + let mut pre = String::new(); + let v = self.rooted("try! ", &mut pre, |this, pre| this.value(e, &item, pre)); + out.push_str(&pre); + self.line(out, &format!("{list}.append({v})")); + } + list + } + + /// A closure's value, as its own root. + fn closure_value(&mut self, value: &Expr) -> String { + let mut pre = String::new(); + let v = self.root(value, &value.ty, &mut pre); + assert!(pre.is_empty(), "a closure's value needing statements first"); + v + } + + fn closure(&mut self, params: &[Pat], steps: &[Step], value: &Expr) -> String { + let params: Vec = params.iter().map(|p| self.param(p)).collect(); + let head = match params.is_empty() { + true => String::new(), + false => format!(" {} in", params.join(", ")), + }; + self.depth += 1; + let mut body = self.steps(steps); + if !matches!(value.kind, Kind::Unit) { + let v = self.root(value, &value.ty, &mut body); + match body.is_empty() { + true => { + self.depth -= 1; + return format!("{{{head} {v} }}"); + } + false => self.line(&mut body, &format!("return {v}")), + } + } + self.depth -= 1; + format!("{{{head}\n{body}{}}}", self.indent()) + } + + /// A call of `id`: a function of the module, an associated function of a type, a method, + /// or a field's getter or setter. + fn call(&mut self, id: FnId, receiver: Option<&Expr>, args: &[Expr], out: &mut String) -> String { + let at_root = std::mem::take(&mut self.at_root); + let f = self.t.function(id); + let key = self.t.key(id); + assert!(!f.future, "a call of the future {key}, which only a hook awaits"); + // A fresh implementation of a callback, passed to a call within an expression: the call + // is its own statement, so Swift's reference to it goes before the rest runs. + let fresh = args.iter().zip(&f.params).any(|(a, p)| matches!(p.ty.base(), Type::Callback(..)) && matches!(a.kind, Kind::Local(..))); + if fresh && !at_root { + let call = self.rooted("try! ", out, |this, out| { + this.at_root = true; + this.call(id, receiver, args, out) + }); + let tmp = self.fresh("h"); + self.line(out, &format!("let {tmp} = {call}")); + return tmp; + } + self.threw |= self.model.throws(self.t, id); + let omitted: Vec = (args.iter().zip(&f.params).enumerate()) + .filter(|(_, (a, p))| self.model.lent_option(&p.ty) && matches!(a.kind, Kind::None)) + .map(|(k, _)| k) + .collect(); + let omitted_list: Vec = omitted.iter().map(usize::to_string).collect(); + let name = self + .t + .named(LANGUAGE, &format!("{key} / omitted {}", omitted_list.join(","))) + .to_string(); + let target = match receiver { + Some(r) => { + let v = self.expr(r, out); + let lvalue = matches!(r.kind, Kind::Var(_)) && !self.aliases.contains_key(var_name(r)); + match self.model.mutating(self.t, id) && !lvalue { + // A mutating method of a value no local holds: one holds it for the call. + true => { + let tmp = self.fresh("m"); + let sw = self.sw(&r.ty); + self.line(out, &format!("var {tmp}: {sw} = {v}")); + tmp + } + false => postfix(&v), + } + } + None => match self.t.owner(id) { + Some(ty) => self.type_name(&ty), + None => "Api".to_string(), + }, + }; + let labels: Vec = f.params.iter().map(|p| camel(&p.name)).collect(); + let params: Vec<_> = f.params.iter().map(|p| p.ty.clone()).collect(); + let mut parts = Vec::new(); + for (k, (arg, ty)) in args.iter().zip(¶ms).enumerate() { + if omitted.contains(&k) { + continue; + } + if self.model.lent_option(ty) { + let (Type::Option(inner), Kind::Some(value)) = (ty, &arg.kind) else { + panic!("an optional borrow passed for {key} other than Some or None") + }; + let v = self.value(value, inner, out); + parts.push(format!("{}: {v}", labels[k])); + } else if self.model.inout(ty) { + parts.push(self.inout(arg, ty, out)); + } else { + parts.push(self.value(arg, ty, out)); + } + } + let property = self.model.property(self.t, id); + match f.access { + Access::Field { set: false, .. } | Access::Const if property => format!("{target}.{name}"), + _ => format!("{target}.{name}({})", parts.join(", ")), + } + } + + /// An argument passed `inout`: a local, or a nil one holds. + fn inout(&mut self, arg: &Expr, ty: &Type, out: &mut String) -> String { + match &arg.kind { + Kind::Var(name) => format!("&{}", kw(name)), + Kind::Some(inner) => match &inner.kind { + Kind::Var(name) => format!("&{}", kw(name)), + _ => panic!("an optional &mut of anything but a local"), + }, + Kind::None => { + let tmp = self.fresh("n"); + let sw = self.sw(ty); + self.line(out, &format!("var {tmp}: {sw} = nil")); + format!("&{tmp}") + } + _ => panic!("a &mut of anything but a local"), + } + } +} + +/// The local `e` reads. +fn var_name(e: &Expr) -> &str { + match &e.kind { + Kind::Var(name) => name, + _ => "", + } +} + +/// Whether `e`'s Swift is a literal whose type Swift would infer apart from Rust's, so its +/// local is annotated. +fn literalish(e: &Expr) -> bool { + match &e.kind { + Kind::Int(_) | Kind::Float(_) | Kind::None | Kind::Some(_) | Kind::List(_) | Kind::Str(_) => true, + Kind::Tuple(elements) => elements.iter().any(literalish), + _ => false, + } +} + +/// Whether Swift's value of `ty` is optional: an `Option`, or a tuple of one of one. +fn optional(ty: &Type) -> bool { + match unref(ty).base() { + Type::Option(_) => true, + Type::Tuple(elements) if elements.len() == 1 => optional(&elements[0]), + _ => false, + } +} + +/// The type a pattern binds, as its names' types say. +fn pat_type(pat: &Pat) -> Type { + match pat { + Pat::Name(_, ty) | Pat::Ignore(ty) => ty.clone(), + Pat::Tuple(pats) => Type::Tuple(pats.iter().map(pat_type).collect()), + } +} + +/// `ty` without its references, as a key names it. +fn owned(ty: &Type) -> Type { + match ty { + Type::Ref(_, inner) => owned(inner), + Type::Tuple(elements) => Type::Tuple(elements.iter().map(owned).collect()), + Type::Option(inner) => Type::Option(Box::new(owned(inner))), + Type::Box(inner) => Type::Box(Box::new(owned(inner))), + Type::List(c, inner) => Type::List(*c, Box::new(owned(inner))), + ty => ty.clone(), + } +} + +/// `v` as the receiver of a member: parenthesized unless a postfix expression already. +fn postfix(v: &str) -> String { + let mut depth = 0i32; + let mut quoted = false; + let mut escaped = false; + for c in v.chars() { + match c { + _ if escaped => escaped = false, + '\\' if quoted => escaped = true, + '"' => quoted = !quoted, + '(' | '[' | '{' if !quoted => depth += 1, + ')' | ']' | '}' if !quoted => depth -= 1, + ' ' if !quoted && depth == 0 => return format!("({v})"), + _ => {} + } + } + match v.starts_with(['&', '-']) { + true => format!("({v})"), + false => v.to_string(), + } +} + +/// Each expression a step holds, its arms' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it, but not a closure's steps. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) | Kind::Field(e, _) | Kind::Element(e, _) | Kind::Clone(e) | Kind::Unwrap(e) | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => es.iter().for_each(inner), + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, _, value) => walk(value, f), + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +/// The Swift integer type of `int`. +fn sw_int(int: Int) -> &'static str { + match int { + Int::U8 => "UInt8", + Int::U16 => "UInt16", + Int::U32 => "UInt32", + Int::U64 => "UInt64", + Int::Usize => "UInt", + Int::I8 => "Int8", + Int::I16 => "Int16", + Int::I32 => "Int32", + Int::I64 => "Int64", + Int::Isize => "Int", + } +} + +/// An integer's name in a type's: `U64`. +fn int_name(int: Int) -> String { + let rust = int.rust(); + let mut chars = rust.chars(); + let first = chars.next().unwrap().to_ascii_uppercase(); + format!("{first}{}", chars.as_str()) +} + +/// A Rust name split at its case changes, in snake case: `NotFound` is `not_found`. +fn snake(name: &str) -> String { + let chars: Vec = name.chars().collect(); + let mut out = String::new(); + for (i, &c) in chars.iter().enumerate() { + if c.is_uppercase() { + let prev = i.checked_sub(1).map(|j| chars[j]); + let next = chars.get(i + 1); + let boundary = match prev { + Some(p) if p.is_lowercase() || p.is_ascii_digit() => true, + Some(p) if p.is_uppercase() => next.is_some_and(|n| n.is_lowercase()), + _ => false, + }; + if boundary && !out.ends_with('_') { + out.push('_'); + } + out.extend(c.to_lowercase()); + } else { + out.push(c); + } + } + out +} + +/// A snake-case name in camel case: `into_label` is `intoLabel`, and `0` is `_0`. +fn camel(name: &str) -> String { + if name.starts_with(|c: char| c.is_ascii_digit()) { + return format!("_{name}"); + } + let mut out = String::new(); + for (i, word) in snake(name).split('_').filter(|s| !s.is_empty()).enumerate() { + let mut chars = word.chars(); + match (i, chars.next()) { + (0, Some(first)) => out.extend(first.to_lowercase().chain(chars)), + (_, Some(first)) => out.extend(first.to_uppercase().chain(chars)), + _ => {} + } + } + out +} + +/// A member's Swift name: in camel case, quoted if a keyword, and `init` taking `_`. +fn member(snake: &str) -> String { + let name = camel(snake); + match name.as_str() { + "init" => "init_".to_string(), + name => kw(name), + } +} + +/// A field's Swift name. +fn field_name(name: &str) -> String { + member(name) +} + +/// A name without the backticks quoting a keyword. +fn unquote(name: &str) -> String { + name.trim_matches('`').to_string() +} + +fn ipv4(ip: std::net::Ipv4Addr) -> String { + let [a, b, c, d] = ip.octets(); + format!("Ipv4Addr({a}, {b}, {c}, {d})") +} + +fn ipv6(ip: std::net::Ipv6Addr) -> String { + let bits = u128::from(ip); + format!("Ipv6Addr(bits: U128(high: {:#x}, low: {:#x}))", (bits >> 64) as u64, bits as u64) +} + +/// Bytes as a Swift array literal. +fn byte_list(b: &[u8]) -> String { + let items: Vec = b.iter().map(|b| format!("{b:#04x}")).collect(); + format!("[{}] as [UInt8]", items.join(", ")) +} + +/// Text as the inside of a Swift string literal. +fn escape(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + match c { + '"' | '\\' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + let _ = write!(out, "\\u{{{:x}}}", c as u32); + } + c => out.push(c), + } + } + out +} From 5e1c2a0f9e64c277bf65aa6886d080cb8577804f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:08:58 -0800 Subject: [PATCH 11/28] wip: generate the C++ transcript tests/fixtures/transcript/cpp.rs writes the transcript as transcript.hpp, which tests/api.cpp includes after its `hook` namespace: the functions transcript.rs defines. A local moves at its last use, and a line's values are a braced list, so C++ evaluates them in Rust's order. What the old script checked beyond the transcript moved into a `checks` case. Co-Authored-By: Claude Opus 5.5 --- ffi/tests/api.cpp | 1838 ++++++-------------------- ffi/tests/fixtures.rs | 67 +- ffi/tests/fixtures/shapes.rs | 1 + ffi/tests/fixtures/transcript/cpp.rs | 1595 ++++++++++++++++++++++ ffi/tests/fixtures/transcript/mod.rs | 1 + 5 files changed, 2066 insertions(+), 1436 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/cpp.rs diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index f8019fd8e..435194d51 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -1,22 +1,32 @@ // The api fixture's C++ test: the script fixtures/api/examples/transcript.rs runs -// natively, through the generated C++ header. tests/fixtures.rs compares the transcripts. +// natively, through the C++ tests/fixtures/transcript writes from it, transcript.hpp, which +// calls the functions in `hook` here that transcript.rs defines. tests/fixtures.rs compares +// the transcripts. // -// With an argument, it instead checks the futures' semantics, or breaks a contract of the -// ABI, which must abort. +// With an argument, it instead checks the futures' semantics, who owns what, or what the +// transcript says only in Rust, or breaks a contract of the ABI, which must abort. #include +#include #include #include #include #include +#include #include #include #include +#include +#include #include #include #include #include +#include #include +#include +#include +#include #include #include #if __has_include() @@ -42,1553 +52,539 @@ namespace { +// The functions transcript.rs defines, each C++'s own: what tests its idiom, such as its +// futures and readers, or prints a value no two bindings shape alike. +namespace hook { + // Print a returned buffer. void print(const char *before, const api::buf &buf, const char *after) { std::printf("%s%.*s%s", before, static_cast(buf.size()), reinterpret_cast(buf.data()), after); } -// Print a list as Rust's `{:?}` does, each item as `show` spells it. -template static void print_list(const std::vector &list, F show) { - std::printf("["); - for (size_t i = 0; i < list.size(); i++) { - std::printf(i ? ", %s" : "%s", show(list[i]).c_str()); - } - std::printf("]"); -} - -static uint64_t f64_bits(double f) { - uint64_t bits; - std::memcpy(&bits, &f, sizeof bits); - return bits; -} - -static double f64_from(uint64_t bits) { - double f; - std::memcpy(&f, &bits, sizeof f); - return f; -} - -static uint32_t f32_bits(float f) { - uint32_t bits; - std::memcpy(&bits, &f, sizeof bits); - return bits; +const char *yes(bool b) { + return b ? "true" : "false"; } -// Print each of `n`'s lists, its floats as their bits, as transcript.rs does. -static void numbers(const char *what, const api::Numbers &n) { - auto line = [&](const char *name, const auto &list, auto show) { - std::printf("%s %s ", what, name); - print_list(list, show); - std::printf("\n"); - }; - auto num = [](auto v) { return std::to_string(v); }; - line("u16", n.u16s, num); - line("u32", n.u32s, num); - line("u64", n.u64s, num); - line("i8", n.i8s, [](int8_t v) { return std::to_string(int(v)); }); - line("i16", n.i16s, num); - line("i32", n.i32s, num); - line("i64", n.i64s, num); - line("f32", n.f32s, [](float v) { return std::to_string(f32_bits(v)); }); - line("f64", n.f64s, [](double v) { return std::to_string(f64_bits(v)); }); - if (n.some) { - std::printf("%s some Some(", what); - print_list(*n.some, num); - std::printf(")\n"); - } else { - std::printf("%s some None\n", what); - } +unsigned long long ull(std::uint64_t v) { + return static_cast(v); } -// A reader of bytes in memory, which Rust reads and seeks. -struct memory { - std::string bytes; - std::size_t at = 0; - - api::result read(std::uint8_t *buf, std::size_t len) { - std::size_t n = std::min(len, bytes.size() - at); - std::memcpy(buf, bytes.data() + at, n); - at += n; - return api::result::ok(n); - } - api::result seek(std::int64_t offset, std::ios_base::seekdir dir) { - std::int64_t base = dir == std::ios_base::beg ? 0 : static_cast(dir == std::ios_base::cur ? at : bytes.size()); - if (base + offset < 0) { - return api::result::err("before the start"); - } - at = static_cast(base + offset); - return api::result::ok(at); - } -}; - -// A reader whose reads fail, as the transcript's: each seek lands at 0. -struct broken_reader { - api::result read(std::uint8_t *, std::size_t) { - return api::result::err("broken"); - } - api::result seek(std::int64_t, std::ios_base::seekdir) { - return api::result::ok(0); +// The Log callback: keeps even levels. +class Print final : public api::Log { +public: + bool log(std::uint8_t level, api::view line) const override { + std::printf("log %u %.*s\n", level, static_cast(line.size()), reinterpret_cast(line.data())); + return level % 2 == 0; } -}; - -// A reader whose reads fail, which seeks anywhere from its start, as Rust's `Cursor` does. -struct far_reader : broken_reader { - api::result seek_start(std::uint64_t offset) { - return api::result::ok(offset); + ~Print() override { + std::printf("freed\n"); } }; -// Print what `tail` read of `file`. -template -void tail(R &file) { - auto read = api::tail(file, 5); - if (read) { - print("tail ", std::get<0>(*read), ""); - std::printf(" %llu\n", static_cast(std::get<1>(*read))); - } else { - print("tail error ", read.error(), "\n"); +// Lowercase hex of `bytes`, two digits each. +std::string hex(api::view bytes) { + std::string out; + char digits[3]; + for (std::uint8_t b : bytes) { + std::snprintf(digits, sizeof digits, "%02x", b); + out += digits; } + return out; } -// Bytes as Rust's `escape_ascii` prints those of a path. -void print_escaped(const char *before, const api::buf &buf, const char *after) { - std::printf("%s", before); - for (std::uint8_t b : buf) { +// A path's bytes as Rust's `escape_ascii` prints them. +std::string escaped(api::view path) { + std::string out; + for (std::uint8_t b : path) { switch (b) { case '\t': - std::printf("\\t"); + out += "\\t"; break; case '\r': - std::printf("\\r"); + out += "\\r"; break; case '\n': - std::printf("\\n"); + out += "\\n"; break; case '\\': case '\'': case '"': - std::printf("\\%c", b); + out += '\\'; + out += static_cast(b); break; default: if (b >= 0x20 && b < 0x7f) { - std::putchar(b); + out += static_cast(b); } else { - std::printf("\\x%02x", b); + char escape[5]; + std::snprintf(escape, sizeof escape, "\\x%02x", b); + out += escape; } } } - std::printf("%s", after); + return out; } -// Strings as Rust's Debug prints a list of them. -void print_strings(const std::vector &strings) { - std::printf("["); - for (std::size_t i = 0; i < strings.size(); i++) { - print(i == 0 ? "\"" : ", \"", strings[i], "\""); - } - std::printf("]"); +std::string path_hex(api::view path) { + return hex(path); } -int wakes = 0; +// A duration as its seconds and nine digits of nanoseconds. +std::string seconds(api::duration d) { + char out[40]; + std::snprintf(out, sizeof out, "%llu.%09u", ull(d.secs), d.nanos); + return out; +} -// The Log callback: keeps even levels. -class print_log final : public api::Log { -public: - bool log(std::uint8_t level, api::view line) const override { - std::printf("log %u %.*s\n", level, static_cast(line.size()), reinterpret_cast(line.data())); - return level % 2 == 0; - } - ~print_log() override { - std::printf("freed\n"); - } -}; +// A duration in whole milliseconds. +std::uint64_t millis(api::duration d) { + return d.secs * 1000 + d.nanos / 1000000; +} + +std::uint32_t code(char32_t c) { + return static_cast(c); +} -// A bound, as Rust's Debug prints it. -void print_bound(api::bound_u64 bound) { - switch (bound.kind) { - case API_BOUND_INCLUDED: - std::printf("Included(%llu)", static_cast(bound.value)); - break; - case API_BOUND_EXCLUDED: - std::printf("Excluded(%llu)", static_cast(bound.value)); - break; - case API_BOUND_UNBOUNDED: - std::printf("Unbounded"); - break; +std::vector reversed(std::vector list) { + std::reverse(list.begin(), list.end()); + return list; +} + +std::vector f64_bits(const std::vector &floats) { + std::vector out; + for (double f : floats) { + std::uint64_t bits; + std::memcpy(&bits, &f, sizeof bits); + out.push_back(bits); } + return out; } -const char *yes(bool b) { - return b ? "true" : "false"; +// An address's bytes in hex, so the length shows its family. +std::string ip_hex(const api::ip_addr &ip) { + return ip.v6 ? hex(api::view(ip.ip.v6.octets, sizeof ip.ip.v6.octets)) : hex(api::view(ip.ip.v4.octets, sizeof ip.ip.v4.octets)); } -unsigned long long ull(std::uint64_t v) { - return static_cast(v); +std::string ip_hex(const api::ipv4_addr &v4) { + api::ip_addr ip{}; + ip.ip.v4 = v4; + return ip_hex(ip); } -// A queue of jobs that a test runs when it chooses: the executor futures run on. -struct queue { - std::mutex mutex; - std::deque> jobs; +std::string ip_hex(const api::ipv6_addr &v6) { + api::ip_addr ip{}; + ip.v6 = true; + ip.ip.v6 = v6; + return ip_hex(ip); +} - auto executor() { - return [this](std::function job) { - std::lock_guard lock(mutex); - jobs.push_back(std::move(job)); - }; +// A socket address as its IP's bytes in hex, its port, flow label, and scope, each IPv6's +// alone, apart by colons. +std::string socket_hex(const api::socket_addr &addr) { + if (addr.v6) { + const api::socket_addr_v6 &v6 = addr.addr.v6; + return hex(api::view(v6.ip.octets, sizeof v6.ip.octets)) + ":" + std::to_string(v6.port) + ":" + + std::to_string(v6.flowinfo) + ":" + std::to_string(v6.scope_id); } + return hex(api::view(addr.addr.v4.ip.octets, sizeof addr.addr.v4.ip.octets)) + ":" + std::to_string(addr.addr.v4.port); +} - // Run jobs until none are left. - void drain() { - for (;;) { - std::function job; - { - std::lock_guard lock(mutex); - if (jobs.empty()) { - return; - } - job = std::move(jobs.front()); - jobs.pop_front(); - } - job(); - } - } -}; +std::string socket_hex(const api::socket_addr_v4 &v4) { + api::socket_addr addr{}; + addr.addr.v4 = v4; + return socket_hex(addr); +} -int script() { - std::printf("limit %llu\n", ull(api::LIMIT)); - - api::Point start{1, 2}; - api::Point p = start.offset(2, 3); - std::printf("offset %d %d\n", p.x, p.y); - print("debug ", p.debug(), "\n"); - std::printf("eq %s\n", yes(p == api::Point{3, 5})); - api::Point d = api::Point::default_(); - std::printf("default %d %d\n", d.x, d.y); - - api::Counter c = api::Counter::new_("c", 5); - std::printf("get %llu\n", ull(c.get())); - print("name ", c.name(), "\n"); - if (auto v = c.add(10)) { - std::printf("add ok %llu\n", ull(*v)); - } - if (auto v = c.add(2000); !v) { - print("add err ", api::Error_to_string(v.error()), " "); - print("", api::Error_debug(v.error()), "\n"); - } - if (auto v = c.sub(20); !v) { - std::printf("sub err underflow by %llu ", ull(std::get(v.error()).by)); - print("", api::Error_debug(v.error()), "\n"); - } - c.rename("d"); - print("name ", c.name(), "\n"); - std::printf("is d %s\n", yes(c.is("d"))); - { - api::Counter copy = c.clone(); - (void)copy.add(1); - std::printf("clone %llu original %llu\n", ull(copy.get()), ull(c.get())); - } - print("debug ", c.debug(), "\n"); - api::Label label = std::move(c).into_label(p); - print("label ", label.debug(), "\n"); - // An empty buffer C++ made is not none. - std::printf("note %s %s\n", yes(api::has_text(api::Note{api::buf()})), yes(api::has_text(api::Note{}))); - - // A tuple returns through one out pointer per element. - auto [below, above] = api::Counter::new_("s", 7).split(5); - print("split ", below.name(), " "); - std::printf("%llu ", ull(below.get())); - print("", above.name(), " "); - std::printf("%llu\n", ull(above.get())); - auto [only] = api::only(api::Counter::new_("o", 3)); - print("only ", only.name(), " "); - std::printf("%llu\n", ull(only.get())); - auto [w8, w16, w32, w64] = api::widths(98305); - std::printf("widths %u %d %u %llu\n", w8, w16, w32, ull(w64)); - for (std::uint64_t divisor : {2, 0}) { - if (auto r = api::divide(7, divisor)) { - std::printf("divide %llu %llu\n", ull(std::get<0>(*r)), ull(std::get<1>(*r))); - } else { - print("divide err ", api::Error_to_string(r.error()), "\n"); - } - } - // A tuple inside another type is a std::tuple. - for (std::uint64_t n : {98305, 0}) { - if (auto spread = api::spread(n)) { - auto [s8, s16, s32, s64] = *spread; - std::printf("spread %u %d %u %llu\n", s8, s16, s32, ull(s64)); - } else { - std::printf("spread none\n"); - } - } - for (const char *needle : {"lo", "x"}) { - if (auto found = api::find("hello", needle)) { - std::printf("find %zu %zu\n", std::get<0>(*found), std::get<1>(*found)); - } else { - std::printf("find none\n"); - } - } - std::printf("rows"); - auto stat_rows = api::rows({api::Point{1, 2}, api::Point{3, 3}}); - for (std::size_t i = 0; i < stat_rows.size(); i++) { - auto &[name, shape, at] = stat_rows[i]; - print(i == 0 ? " " : ", ", name, " "); - print("", api::Shape_debug(shape), " "); - std::printf("%d %d", at.x, at.y); +std::string socket_hex(const api::socket_addr_v6 &v6) { + api::socket_addr addr{}; + addr.v6 = true; + addr.addr.v6 = v6; + return socket_hex(addr); +} + +// Print a list as Rust's `{:?}` does, each item as `show` spells it. +template +void print_list(const std::vector &list, F show) { + std::printf("["); + for (size_t i = 0; i < list.size(); i++) { + std::printf(i ? ", %s" : "%s", show(list[i]).c_str()); } - std::printf("\n"); - { - // Each handle in a tuple moves in, as one taken by value does. - std::vector> meters; - meters.emplace_back("low", api::Counter::new_("l", 1)); - meters.emplace_back("high", api::Counter::new_("h", 9)); - auto board = api::Board::new_(std::move(meters)); - // The counters a board returns build another, each handle moved back in. - board = api::Board::new_(std::move(board).into_counters()); - std::printf("ranked"); - auto ranked = board.ranked(); - for (std::size_t i = 0; i < ranked.size(); i++) { - auto &[name, counter] = ranked[i]; - print(i == 0 ? " " : ", ", name, " "); - print("", counter.name(), " "); - std::printf("%llu", ull(counter.get())); - } + std::printf("]"); +} + +// Print each of `n`'s lists, its floats as their bits, as transcript.rs does. +void numbers(std::string_view what, const api::Numbers &n) { + auto line = [&](const char *name, const auto &list, auto show) { + std::printf("%.*s %s ", static_cast(what.size()), what.data(), name); + print_list(list, show); std::printf("\n"); - auto best = board.best(); - print("best ", best.name(), " "); - std::printf("%llu\n", ull(best.get())); + }; + auto num = [](auto v) { return std::to_string(v); }; + line("u16", n.u16s, num); + line("u32", n.u32s, num); + line("u64", n.u64s, num); + line("i8", n.i8s, [](int8_t v) { return std::to_string(int(v)); }); + line("i16", n.i16s, num); + line("i32", n.i32s, num); + line("i64", n.i64s, num); + line("f32", n.f32s, [](float v) { + std::uint32_t bits; + std::memcpy(&bits, &v, sizeof bits); + return std::to_string(bits); + }); + line("f64", n.f64s, [](double v) { + std::uint64_t bits; + std::memcpy(&bits, &v, sizeof bits); + return std::to_string(bits); + }); + if (n.some) { + std::printf("%.*s some Some(", static_cast(what.size()), what.data()); + print_list(*n.some, num); + std::printf(")\n"); + } else { + std::printf("%.*s some None\n", static_cast(what.size()), what.data()); } +} + +// A path no Rust string spells: on Unix, bytes that are not UTF-8; on Windows, a lone +// surrogate, which is WTF-8's `ed a0 80`. +api::buf unspelled() { +#ifdef _WIN32 + static const std::uint8_t stray[] = {0xed, 0xa0, 0x80}; + return api::buf(api::view(stray, sizeof stray)); +#else + return api::stray(); +#endif +} + +// A channel's futures, polled by hand. +void channel() { + static int wakes = 0; + api::Channel channel = api::Channel::new_(); + api::waker waker([]() { wakes++; }); { - // A map crosses as its pairs and a set as its items, which Rust collects in order, - // each key once, the last kept. - api::Atlas loose; - loose.points.emplace_back(api::buf("b"), api::Point{1, 1}); - loose.points.emplace_back(api::buf("ab"), api::Point{2, 3}); - loose.points.emplace_back(api::buf("b"), api::Point{4, 4}); - loose.ids = {3, 1, 3}; - auto atlas = loose.with("c", api::Point{5, 6}); - std::printf("atlas"); - for (std::size_t i = 0; i < atlas.points.size(); i++) { - auto &[name, at] = atlas.points[i]; - print(i == 0 ? " " : ", ", name, " "); - std::printf("%d %d", at.x, at.y); - } - std::printf("; ids"); - for (auto id : atlas.ids) { - std::printf(" %u", id); - } - std::printf("\n"); - } - // Another crate's error crosses as its message. - for (const char *text : {"80", "x"}) { - if (auto port = api::port(text)) { - std::printf("port %u\n", unsigned(port.value())); - } else { - print("port err ", port.error(), "\n"); + api::Channel_recv_future recv = channel.recv(); + std::printf("recv pending %s\n", yes(!recv.poll(waker).has_value())); + channel.send("hi"); + std::printf("woken %d\n", wakes); + if (auto payload = recv.poll(waker)) { + print("recv ", *payload, "\n"); } } - api::Span span{{2, 10}, std::make_tuple(api::buf("s"), api::Shape::square)}; - auto [lower_half, upper_half] = api::halves(span); - std::printf("halves %u %u %u %u ", std::get<0>(lower_half), std::get<1>(lower_half), std::get<0>(upper_half), - std::get<1>(upper_half)); - print("", span.debug(), "\n"); - auto [swapped_n, swapped_text] = api::swapped({"t", 4}); - std::printf("swapped %u ", swapped_n); - print("", swapped_text, "\n"); - using single = std::tuple>; - for (const auto &value : {std::optional(), std::optional(single()), std::optional(single(3))}) { - auto doubled = api::doubled(value); - if (!doubled) { - std::printf("doubled None\n"); - } else if (auto n = std::get<0>(*doubled)) { - std::printf("doubled Some((Some(%u),))\n", *n); + channel.send(""); + { + api::Channel_recv_nonempty_future nonempty = channel.recv_nonempty(); + if (auto r = nonempty.poll(waker)) { + if (*r) { + std::printf("nonempty %zu\n", r->value().size()); + } else { + print("nonempty err ", api::Error_to_string(r->error()), "\n"); + } } else { - std::printf("doubled Some((None,))\n"); + std::printf("nonempty pending\n"); } } - // A borrowed or boxed tuple of one is a tuple, not its element. { - std::uint8_t lent_bytes[] = {1, 2}; - std::uint8_t boxed_bytes[] = {3}; - auto [lent] = api::lent_back(std::make_tuple(api::view(lent_bytes, 2))); - auto [boxed] = api::boxed_tuple(api::view(boxed_bytes, 1)); - const api::buf *both[] = {&lent, &boxed}; - for (int i = 0; i < 2; i++) { - std::printf("%s[", i == 0 ? "lent back " : " boxed "); - for (std::size_t j = 0; j < both[i]->size(); j++) { - std::printf("%s%u", j == 0 ? "" : ", ", both[i]->data()[j]); + auto fill4 = api::Batch::new_(); + auto fill2 = api::pair(); + auto filled4 = api::fill_4(fill4, 9).poll(waker); + auto filled2 = api::fill_2(fill2, 1).poll(waker); + if (filled4 && filled2) { + std::printf("fill"); + for (auto v : *filled4) { + std::printf(" %u", unsigned(v)); + } + for (auto v : *filled2) { + std::printf(" %u", unsigned(v)); } - std::printf("]"); + std::printf("\n"); } - std::printf("\n"); } - // A borrowed string and an owned one share a tuple struct. - print("title Some((\"", std::get<0>(*api::title(true)), "\",)) "); - std::printf("%s ", api::title(false) ? "Some" : "None"); - print("named Some((\"", std::get<0>(*api::named("x")), "\",))\n"); - // Each lent counter is a new handle to a clone. - api::Registry registry = api::Registry::new_(api::Counter::new_("first", 1)); - std::printf("last %s\n", yes(registry.last().has_value())); - registry.push(api::Counter::new_("last", 2)); - { - api::Counter first = registry.first_get(); - (void)first.add(10); - std::printf("first %llu lent %llu\n", ull(registry.first_get().get()), ull(first.get())); - api::Counter last = *registry.last(); - (void)last.add(10); - std::printf("last %llu lent %llu\n", ull(registry.last()->get()), ull(last.get())); - } - // A closure lent for the call edits the first counter through its class. - std::uint64_t by = 5; - bool edited = registry.edit([&](api::borrow counter) { - (void)counter->add(by); - return counter->edited() && counter->get() == 6; - }); - std::printf("edit %s %llu\n", yes(edited), ull(registry.first_get().get())); - // A setter moves an object in, as assignment does. - registry.first_set(api::Counter::new_("second", 3)); - std::printf("set first %llu ", ull(registry.first_get().get())); - print("", registry.first_get().name(), "\n"); - std::printf("walk %llu\n", ull(api::walk(3, [](const api::Cursor &cursor) { return cursor.at() * 2; }))); - std::printf("each %u\n", api::each(2, [](std::uint32_t at) { std::printf("visit %u\n", at); })); - std::printf("offset %u\n", api::offset([] { return 7u; }, 3)); - std::printf("shift %u\n", api::shift([] { return 7u; }, 4)); - - // A type generic only over lifetimes is a handle to its 'static form. + // The send happens at the call: the future is dropped unpolled. + channel.send_later("eager"); { - api::Name name = api::Name::owned("a"); - api::Name joined = name.join(api::Name::owned("b")); - print("joined ", joined.as_str(), " "); - print("", joined.debug(), " "); - std::printf("%s\n", yes(joined == name)); - std::string text = "c"; - joined.rename(text); - // The name took a copy: the caller's buffer is its own again. - text[0] = 'x'; - print("renamed ", joined.as_str(), "\n"); - api::Name longest = api::longer(std::move(joined), api::Name::owned("dd")); - print("longer ", longest.as_str(), "\n"); - print("unnamed [", api::unnamed().as_str(), "]\n"); - api::Name lit = api::Name::borrowed("lit"); - print("borrowed ", lit.as_str(), " "); - std::printf("%s %s\n", lit.shares(api::Name::borrowed("lit")) ? "true" : "false", - lit.shares(api::Name::borrowed("other")) ? "true" : "false"); - } - - std::printf("total %llu\n", ull(api::total({2, 5}))); - std::printf("reach %u\n", unsigned(api::reach(2, 5))); - std::printf("scaled"); - for (auto v : {api::scaled({UINT64_MAX, UINT64_MAX}, 1), api::scaled({1, 1}, 1ULL << 63), api::scaled({0, 1ULL << 63}, 2)}) { - if (v) { - std::printf(" %016llx%016llx", ull(v->hi), ull(v->lo)); - } else { - std::printf(" none"); + api::Channel_recv_future recv = channel.recv(); + if (auto payload = recv.poll(waker)) { + print("recv ", *payload, "\n"); } } - std::printf("\n"); + // The send happens at the call, and the future borrows the channel and the tag. { - auto hex = [](const std::array &sum) { - std::printf(" %02x%02x%02x%02x", sum[0], sum[1], sum[2], sum[3]); - }; - auto digest = api::Digest::new_(); - digest.sum_set(api::fingerprint("deadbeef").value()); - std::printf("digest"); - hex(digest.sum_get()); - hex(digest.flipped({0xff, 0, 0xff, 0})); - print(" ", api::fingerprint("zz").error(), "\n"); + api::Channel_tagged_future tagged = channel.tagged("tag"); + if (auto text = tagged.poll(waker)) { + print("tagged ", *text, "\n"); + } } + // So does a future borrowing an optional slice, which the export owns while it is pending. { - auto batch = api::Batch::new_(); - unsigned accepted = 0; - for (std::uint32_t v = 1; v <= 5; v++) { - accepted += batch.push(v); - } - auto batch2 = api::pair(); - unsigned paired = 0; - for (std::uint32_t v = 1; v <= 3; v++) { - paired += batch2.push(v); - } - auto emptied = api::drain_4(batch); - std::printf("batch %zu %u %llu %llu %zu %u %llu\n", batch.capacity(), accepted, ull(emptied), ull(api::drain_4(batch)), - batch2.capacity(), paired, ull(api::drain_2(batch2))); - std::printf("capacities %zu %zu\n", api::capacities_4_2(batch, batch2), api::capacities_2_2(batch2, batch2)); - } - api::range_u64 wide = api::widen({2, 5}, 1); - std::printf("widen %llu %llu\n", ull(wide.start), ull(wide.end)); - api::bounds_u64 ranges[] = { - {{API_BOUND_INCLUDED, 2}, {API_BOUND_EXCLUDED, 5}}, {{API_BOUND_INCLUDED, 2}, {API_BOUND_INCLUDED, 5}}, - {{API_BOUND_INCLUDED, 3}, {API_BOUND_UNBOUNDED, 0}}, {{API_BOUND_UNBOUNDED, 0}, {API_BOUND_UNBOUNDED, 0}}, - {{API_BOUND_EXCLUDED, 2}, {API_BOUND_INCLUDED, 4}}, - }; - std::printf("count"); - for (const auto &range : ranges) { - std::printf(" %zu", api::count(range)); - } - std::printf("\n"); - std::printf("end "); - print_bound(api::end(3)); - std::printf(" "); - print_bound(api::end(0)); - std::printf("\n"); - auto [ends_start, ends_end] = api::ends(3); - std::printf("ends "); - print_bound(ends_start); - std::printf(" "); - print_bound(ends_end); - std::printf("\n"); - for (std::uint64_t n : {2, 5}) { - if (auto r = api::below(n, 3)) { - std::printf("below %llu\n", ull(*r)); - } else { - std::printf("below err "); - print_bound(r.error().start); - std::printf(" "); - print_bound(r.error().end); - std::printf("\n"); + api::Channel_itemized_future itemized = channel.itemized(std::vector{1, 2, 3}); + if (auto count = itemized.poll(waker)) { + std::printf("itemized %zu\n", *count); } } - api::Window window{{2, 8}, api::end(5)}; - std::printf("window %s %s ", yes(window.contains(4)), yes(window.contains(6))); - print("", window.debug(), "\n"); - - print("", api::greet("x", api::Shape::square), "\n"); - std::printf("len %zu\n", api::len("abc")); - const std::uint8_t binary[] = {0xff, 0x00, 'a'}; - print("hex ", api::hex(api::view(binary, sizeof binary)), "\n"); - print("timed hex ", api::timed_hex(api::view(binary, sizeof binary)), "\n"); - print("sample hex ", api::sample_hex(api::view(binary, sizeof binary)), "\n"); - print("queued hex ", api::queued_hex(api::view(binary, sizeof binary)), "\n"); - print("tick ", api::tick_name(api::Label{api::buf("tick"), std::nullopt, std::nullopt}), "\n"); - print("rooted ", api::rooted_name(api::Label{api::buf("rooted"), std::nullopt, std::nullopt}), "\n"); - print("stored ", api::stored_text("stored"), "\n"); - print("layer ", api::layer_name(api::Label{api::buf("layer"), std::nullopt, std::nullopt}), "\n"); - api::Event events[] = {api::Event_Moved{p}, api::Event_Named{api::buf("n")}, api::Event_Done{}}; - for (const auto &event : events) { - print("", api::describe(event), "\n"); - } - - // A `Copy` value passed by value is copied, so it stays usable. + // Another crate's future borrowing its bytes, which the export owns while it is pending. { - api::Stamp stamp = api::Stamp::from_millis(2500); - std::printf("secs %llu\n", ull(stamp.secs())); - std::printf("later %s\n", yes(api::Stamp::from_millis(3000).later(stamp))); - std::printf("secs %llu\n", ull(stamp.secs())); - print("whole ", stamp.whole().debug(), "\n"); - api::Message message = api::Message::new_(stamp, "body"); - print("payload ", message.payload_get(), "\n"); - print("stamp ", message.stamp_get()->debug(), "\n"); - std::printf("sent %s\n", yes(message.sent())); - // Setters assign in place: the bytes are copied in, and a `Copy` value copied. - api::Stamp reset = api::Stamp::from_millis(4000); - message.stamp_set(reset); - message.payload_set("edited"); - print("payload ", message.payload_get(), "\n"); - print("stamp ", message.stamp_get()->debug(), "\n"); - std::printf("secs %llu\n", ull(reset.secs())); - message.stamp_set(std::nullopt); - std::printf("stamp %s\n", yes(message.stamp_get().has_value())); - } - - // A value past a word, copied across: a closure takes and returns one by value. - { - api::Moment moment = *api::Moment::new_(1500, 1000); - std::printf("moment %llu %s\n", ull(moment.millis()), yes(!api::Moment::new_(1, 0).has_value())); - api::Moment shifted = api::shifted(moment, [](const api::Moment &m) { return m.after(500); }); - std::printf("shifted %llu %s\n", ull(shifted.millis()), yes(shifted == moment.after(500))); - std::printf("wrapped %llu %s\n", ull(moment.after(UINT64_MAX).millis()), yes(moment == shifted)); + api::byte_len_future measuring = api::byte_len("abc"); + if (auto len = measuring.poll(waker)) { + std::printf("byte_len %zu\n", *len); + } } - - // A value with padding, or bytes that vary, is a handle, as no table says where padding is. + channel.send("sized"); { - api::Gap gap = api::Gap::new_(7, 3); - std::printf("gap %llu %s\n", ull(gap.sum()), yes(gap == api::Gap::new_(7, 3))); - api::Berth berth = api::Berth::new_(4u); - std::printf("berth Some(%u) %s\n", *berth.at(), api::Berth::new_(std::nullopt).at() ? "Some" : "None"); + api::Channel_recv_sized_future sized = channel.recv_sized(); + if (auto r = sized.poll(waker)) { + print("sized ", std::get<0>(*r), " "); + std::printf("%zu\n", std::get<1>(*r)); + } } - - // A `Copy` type changed in place is a value, whose change reaches only the copy changed. + // The waker moves into Rust, which keeps it until the send wakes it. + channel.notify(waker); + channel.send("rung"); + std::printf("woken %d\n", wakes); + // A poll with no async twin is a future. { - api::Score score = api::Score::of(2); - api::Score step = api::Score::of(3); - score.add(step); - score.add(step); - std::printf("score %llu %llu %llu\n", ull(score.count()), ull(step.doubled().count()), ull(step.count())); - api::Score copy = score; - std::uint64_t taken = copy.take(); - std::printf("taken %llu %llu %llu\n", ull(taken), ull(copy.count()), ull(score.count())); - api::Score other = step; - auto [before0, before1] = copy.absorb(other); - std::printf("absorbed %llu %llu %llu %llu %llu\n", ull(before0), ull(before1), ull(copy.count()), - ull(other.count()), ull(step.count())); - api::Hits hits = api::Hits::of(1, 2); - api::Hits kept = hits; - hits.add(api::Hits::of(10, 20)); - hits.hits_set(7); - std::printf("hits %llu %llu %llu %llu %s\n", ull(hits.hits_get()), ull(hits.misses_get()), ull(kept.hits_get()), - ull(kept.misses_get()), yes(hits == kept)); - api::Hits counted = kept; - bool counted_same = counted.eq_(kept); - std::printf("counted %s %llu\n", yes(counted_same), ull(counted.hits_get())); - api::Extent extent = api::Extent::new_(5, 3); - api::Extent extent_start = extent; - std::uint64_t old = extent.slide(10); - extent.start_set(extent.start_get() + 1); - std::printf("extent %llu %llu %llu %llu %llu\n", ull(old), ull(extent.start_get()), ull(extent.end()), - ull(extent_start.start_get()), ull(extent_start.end())); - api::Weighted weighted{step, 4}; - std::printf("weighted %llu %llu\n", ull(weighted.total()), ull(weighted.score.count() + step.count())); - // A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. - api::Mark mark = api::Mark::of(1); - mark.add(2); - api::Parcel parcel{mark.clone(), api::buf("abc")}; - std::printf("heft %llu\n", ull(api::heft(std::make_tuple(mark.clone(), api::view("ab")), parcel, - std::make_tuple(api::Counter::new_("w", 1), api::view("abcd"))))); - // A value's `&mut self` beside a checked handle. - api::Score noted = api::Score::of(2); - std::uint64_t noted_before = noted.note(api::Mark::of(5)); - std::printf("noted %llu %llu\n", ull(noted_before), ull(noted.count())); - } - - std::uint8_t levels[] = {1, 2, 3, 4}; - std::printf("kept %u\n", api::emit(std::make_unique(), api::view(levels, sizeof levels))); + api::Channel_poll_take_future take = channel.poll_take(); + if (auto payload = take.poll(waker)) { + print("take ", *payload, "\n"); + } + } + channel.send("measured"); { - api::Logger logger = api::Logger::new_(std::make_unique()); - std::printf("write %s\n", yes(logger.write("hi"))); + api::Channel_poll_measure_future measure = channel.poll_measure(2); + if (auto r = measure.poll(waker)) { + std::printf("measure %zu\n", r->value()); + } + } + // A context is made of the waker, which Rust keeps until the send wakes it. + channel.listen(waker); + channel.send("heard"); + std::printf("woken %d\n", wakes); + // A returned waker wakes the waiter's task, through Rust, until its last copy drops. + api::Waiter waiter = api::Waiter::new_(waker); + waiter.waker().wake(); + waiter.context().wake(); + std::printf("woken %d\n", wakes); +} + +// A kept closure: called again at the instant it asks for, then once its waiter wakes. +void drive() { + api::Moment began = *api::Moment::new_(0, 1000); + int calls = 0; + auto drive = api::drive(began, [&](const api::Moment &now, const api::Waiter &waiter) { + using result = api::result, std::string>; + calls++; + if (calls == 1) { + return result::ok(now.after(5)); + } + if (calls == 2) { + std::printf("drive %llu\n", ull(now.millis() - began.millis())); + waiter.waker().wake(); + return result::ok(std::nullopt); + } + return result::err("stopped after " + std::to_string(calls)); + }); + api::waker waker([] {}); + std::optional stopped; + while (!(stopped = drive.poll(waker))) { } - std::printf("dropped\n"); - // Rust calls it on another thread, before the call returns. - std::uint8_t threshold = 2; - std::printf("filtered %u\n", api::filter(api::view(levels, sizeof levels), [threshold](std::uint8_t level, api::view line) { - std::printf("filter %u %.*s\n", level, static_cast(line.size()), reinterpret_cast(line.data())); - return level > threshold; - })); + print("drive ", *stopped, "\n"); +} - { - api::Channel channel = api::Channel::new_(); - api::waker waker([]() { wakes++; }); - { - api::Channel_recv_future recv = channel.recv(); - std::printf("recv pending %s\n", yes(!recv.poll(waker).has_value())); - channel.send("hi"); - std::printf("woken %d\n", wakes); - if (auto payload = recv.poll(waker)) { - print("recv ", *payload, "\n"); - } - } - channel.send(""); - { - api::Channel_recv_nonempty_future nonempty = channel.recv_nonempty(); - if (auto r = nonempty.poll(waker)) { - if (*r) { - std::printf("nonempty %zu\n", r->value().size()); - } else { - print("nonempty err ", api::Error_to_string(r->error()), "\n"); - } - } else { - std::printf("nonempty pending\n"); - } - } - { - auto fill4 = api::Batch::new_(); - auto fill2 = api::pair(); - auto filled4 = api::fill_4(fill4, 9).poll(waker); - auto filled2 = api::fill_2(fill2, 1).poll(waker); - if (filled4 && filled2) { - std::printf("fill"); - for (auto v : *filled4) { - std::printf(" %u", unsigned(v)); - } - for (auto v : *filled2) { - std::printf(" %u", unsigned(v)); - } - std::printf("\n"); - } - } +// A reader of bytes in memory, which Rust reads and seeks. +struct memory { + std::string bytes; + std::size_t at = 0; - // The send happens at the call: the future is dropped unpolled. - channel.send_later("eager"); - { - api::Channel_recv_future recv = channel.recv(); - if (auto payload = recv.poll(waker)) { - print("recv ", *payload, "\n"); - } - } - // The send happens at the call, and the future borrows the channel and the tag. - { - api::Channel_tagged_future tagged = channel.tagged("tag"); - if (auto text = tagged.poll(waker)) { - print("tagged ", *text, "\n"); - } - } - // So does a future borrowing an optional slice, which the export owns while it is pending. - { - api::Channel_itemized_future itemized = channel.itemized(std::vector{1, 2, 3}); - if (auto count = itemized.poll(waker)) { - std::printf("itemized %zu\n", *count); - } - } - // Another crate's future borrowing its bytes, which the export owns while it is pending. - { - api::byte_len_future measuring = api::byte_len("abc"); - if (auto len = measuring.poll(waker)) { - std::printf("byte_len %zu\n", *len); - } - } - channel.send("sized"); - { - api::Channel_recv_sized_future sized = channel.recv_sized(); - if (auto r = sized.poll(waker)) { - print("sized ", std::get<0>(*r), " "); - std::printf("%zu\n", std::get<1>(*r)); - } - } - // The waker moves into Rust, which keeps it until the send wakes it. - channel.notify(waker); - channel.send("rung"); - std::printf("woken %d\n", wakes); - // A poll with no async twin is a future. - { - api::Channel_poll_take_future take = channel.poll_take(); - if (auto payload = take.poll(waker)) { - print("take ", *payload, "\n"); - } - } - channel.send("measured"); - { - api::Channel_poll_measure_future measure = channel.poll_measure(2); - if (auto r = measure.poll(waker)) { - std::printf("measure %zu\n", r->value()); - } + api::result read(std::uint8_t *buf, std::size_t len) { + std::size_t n = std::min(len, bytes.size() - at); + std::memcpy(buf, bytes.data() + at, n); + at += n; + return api::result::ok(n); + } + api::result seek(std::int64_t offset, std::ios_base::seekdir dir) { + std::int64_t base = dir == std::ios_base::beg ? 0 : static_cast(dir == std::ios_base::cur ? at : bytes.size()); + if (base + offset < 0) { + return api::result::err("before the start"); } - // A context is made of the waker, which Rust keeps until the send wakes it. - channel.listen(waker); - channel.send("heard"); - std::printf("woken %d\n", wakes); - // A returned waker wakes the waiter's task, through Rust, until its last copy drops. - api::Waiter waiter = api::Waiter::new_(waker); - waiter.waker().wake(); - waiter.context().wake(); - std::printf("woken %d\n", wakes); + at = static_cast(base + offset); + return api::result::ok(at); } +}; - // A value that holds itself is an object. - { - api::Node list = api::Node::new_(1, std::nullopt); - list.push(2); - std::printf("node %llu\n", ull(list.sum())); +// A reader whose reads fail, as the transcript's: each seek lands at 0. +struct broken_reader { + api::result read(std::uint8_t *, std::size_t) { + return api::result::err("broken"); } - - { - api::Tally tally = api::Tally::new_(); - tally.bump(); - std::uint32_t count = tally.bump(); - std::printf("tally %u %s\n", count, yes(tally == tally)); - std::printf("both %u\n", api::bump_both(tally, tally)); - std::printf("peek %u\n", api::peek(tally, [](const api::Tally &lent) { return lent.bump(); })); + api::result seek(std::int64_t, std::ios_base::seekdir) { + return api::result::ok(0); } +}; - // Another export's types, which this export's function takes and returns. - { - api::Area area = api::grow(api::Area::new_({2, 3}), 1); - api::Size size = area.size(); - std::printf("area %u %u %llu\n", size.width, size.height, ull(area.pixels())); - } - - // Generic types, each at the instances it infers, named by their arguments. - api::Pair_u32 pair{2, 5}; - api::Pair_u32 swapped = pair.swap(); - std::printf("pair %u %u sum %u ", swapped.left, swapped.right, pair.sum()); - print("", pair.debug(), " "); - std::printf("%s\n", yes(pair == swapped)); - std::printf("even %s %s\n", yes(pair.even()), yes(api::Pair_u32{7, 7}.even())); - // An instance renamed alone, beside another of `Pair` that keeps its name. - api::Pair_Size_u8 sizes = api::tag({1, 2}, 3); - api::Pair_u8_Size flipped = sizes.swap(); - std::printf("sized %u %u ", flipped.left, flipped.right.width); - print("", flipped.debug(), "\n"); - api::Pair_u8_Size beside = api::Pair_u32{258, 9}.beside_Size(sizes.left); - std::printf("beside %u ", beside.left); - print("", beside.debug(), "\n"); - { - // At its default, named as the type itself. - api::Stack stack = api::Stack::new_(); - const char *names[] = {"a", "b"}; - for (int i = 0; i < 2; i++) { - stack.push(api::Counter::new_(names[i], static_cast(i) + 1)); - } - std::optional top = stack.pop(); - std::printf("stack %zu Some(%llu)", stack.depth(), ull(top->get())); - std::printf(" %s", yes(stack.pop().has_value())); - std::printf(" %s\n", yes(!stack.pop().has_value())); - // Generic functions and methods, at each implementation of the trait bounding them, - // by reference, which leaves C++ its handle. Two arguments sharing a last segment - // name their instances apart by the module of one. - api::Counter from_point = api::Counter::seeded_Point("p", {-3, 4}); - api::Counter seeded_Size = api::Counter::seeded_Size("s", {5, 6}); - api::Counter from_counter = api::Counter::seeded_Counter("c", from_point); - api::Counter from_polar = api::Counter::seeded_polar_Point("q", {1, 2}); - std::printf("seeded %llu %llu %llu %llu past %llu seeds %llu\n", ull(from_point.get()), ull(seeded_Size.get()), - ull(from_counter.get()), ull(from_polar.get()), ull(stack.depth_past_Point({1, 2})), - ull(api::seeds_Point_Size({2, 3}))); - } - - // A trait implemented for `Point` and `&Point` apart: one instance. - std::printf("weigh %u\n", api::weigh_Point({-1, 2})); - // A function named as the type it returns, and one named as a type it does not. - std::printf("polar %u %s area %llu\n", api::polar_point(2).value().distance, yes(!api::polar_point(0)), - ull(api::area({2, 3}))); - std::printf("wind %u\n", api::wind(api::PolarTurn{2}, api::polar_Turn{3})); - // Names that clash in some language, each kept apart there. - print("clash ", api::clash_Tone{440}.debug(), " "); - print("", api::clash_TONE{3}.debug(), " "); - print("", api::Cancelled{2}.debug(), ""); - api::clash_Span clash_span{4}; - std::printf(" span %u ", clash_span.width_()); - print("", clash_span.to_string_(), " "); - print("", clash_span.to_string(), ""); - api::clash_Store clash_store = api::clash_Store::new_(7); - std::printf(" store %u %u", clash_store.free_(), clash_store.close()); - std::printf(" audio %u %u nested %u\n", api::clash_audio_encoder_finish(), api::clash_audio_encoder_finish_(), - api::clash_nested(std::make_tuple(std::make_tuple(std::uint8_t{1}, std::uint16_t{2}), 3u), - std::make_tuple(std::make_tuple(std::uint8_t{1}, std::uint16_t{2}, 3u)))); - // Instances that name each other, and one made only by an impl of it. - std::printf("cross %u outer %u\n", api::cross(api::Left_Right_u8{api::Right_u8{1}}, api::Right_Left_u8{api::Left_u8{2}}), - api::Outer_Inner_u8::new_(4).get()); - // A bound that outlives the call takes a value, and an instance only a constant names. - std::printf("kept %llu boxed %u\n", ull(api::kept_Point({1, -2})), api::BOXED().value); - std::printf("keep %d\n", api::keep_Point({1, -2})); - std::printf("kept or %d %d keeper %d\n", api::kept_or_Point(api::Point{5, 2}), api::kept_or_Point(std::nullopt), - api::keeper_Point({5, 2})); - // Inferred instances taking a lent closure and a foreign implementation, and one only - // its impl of a trait names. - api::Pair_u32 sides{2, 5}; - std::printf("apply %u\n", api::apply_u32(sides, [](std::uint32_t side) { return side * 3; })); - std::printf("report %u\n", api::report_u32(sides, std::make_unique())); - std::printf("wrapped %llu\n", ull(api::kept_Wrap_u32({4}))); - std::printf("keeps %u\n", api::keeps(std::make_unique()).value); - - // Its Drop runs when C++ destroys the handle, not before. - { - api::Token token = api::Token::new_(7); - std::printf("token %u dropped %u\n", token.id_get(), api::dropped()); - } - std::printf("dropped %u\n", api::dropped()); - - // A field and the method of its name, each its own member. - api::Retry retry = api::Retry::new_(5u); - std::optional limit = retry.limit_get(); - std::printf("retry %d %u %u %u\n", limit.has_value(), limit.value_or(0), retry.limit(), retry.delay()); - // The renamed field's setter, named as its getter. - retry.limit_set(std::nullopt); - std::printf("retry %u\n", retry.limit()); - std::printf("slot %u\n", api::Slot_u8::new_(200).value()); - - // Foreign types: a URL parsed from text, socket addresses, OS paths, and `Vec`s. - api::Url base = api::Url::parse("https://example.com/a/b").value(); - print("url ", base.to_string(), " host "); - if (auto host = api::host(base)) { - print("Some(\"", *host, "\")\n"); - } else { - std::printf("None\n"); +// A reader whose reads fail, which seeks anywhere from its start, as Rust's `Cursor` does. +struct far_reader : broken_reader { + api::result seek_start(std::uint64_t offset) { + return api::result::ok(offset); } - if (auto resolved = api::resolve(base, "c?d")) { - print("resolve ", resolved->to_string(), " "); - std::printf("%s\n", *resolved == base ? "true" : "false"); +}; + +// Print what `tail` read of `file`. +template +void tail(R &file) { + auto read = api::tail(file, 5); + if (read) { + print("tail ", std::get<0>(*read), ""); + std::printf(" %llu\n", ull(std::get<1>(*read))); } else { - print("resolve err ", resolved.error(), "\n"); + print("tail error ", read.error(), "\n"); } - if (auto parsed = api::Url::parse("no scheme")) { - print("parse ", parsed->to_string(), "\n"); +} + +// Readers over bytes, whose reads fail, and that seek past `INT64_MAX`. +void readers() { + memory hello{"hello world"}; + tail(hello); + broken_reader broken; + tail(broken); + // A seek from the start reaches the reader whole, past `INT64_MAX`, as `Cursor` takes one. + far_reader far; + auto sought = api::seek_to(far, UINT64_MAX); + if (sought) { + std::printf("sought %llu\n", ull(*sought)); } else { - print("parse err ", parsed.error(), "\n"); - } - - api::socket_addr v4{}; - v4.addr.v4.ip.octets[0] = 127; - v4.addr.v4.ip.octets[3] = 1; - v4.addr.v4.port = 8080; - api::socket_addr v6{}; - v6.v6 = true; - v6.addr.v6.ip.octets[15] = 1; - v6.addr.v6.port = 443; - v6.addr.v6.scope_id = 3; - auto ports = api::ports({v4, v6}); - std::printf("ports [%u, %u]\n", ports[0], ports[1]); - std::vector names; - names.emplace_back(api::view("a")); - names.emplace_back(api::view("b")); - api::Peer peer = api::Peer{v6, names}.next("c"); - std::printf("peer Peer { addr: [::%u%%%u]:%u, names: ", peer.addr.addr.v6.ip.octets[15], peer.addr.addr.v6.scope_id, - peer.addr.addr.v6.port); - print_strings(peer.names); - std::printf(" } "); - print_strings(peer.aliases()); - std::printf("\n"); - - // A path's bytes as the OS holds them, which need not be UTF-8. - api::buf file = api::file("dir", "f\\'\"\t"); - auto parents = api::parents({file, "/"}); - print_escaped("file ", file, "\n"); - std::printf("parents"); - for (const auto &parent : parents) { - if (parent) { - print_escaped(" ", *parent, ""); - } else { - std::printf(" none"); - } - } - std::printf("\n"); - - auto words = api::words(" one two three "); - std::printf("words %zu ", words.size()); - print_strings(words); - std::printf("\n"); - print("sentence ", api::sentence(std::vector(words.begin(), words.end())), " "); - print("", api::sentence(std::nullopt), "\n"); - print("sentence ", api::sentence(std::vector()), "|\n"); - std::printf("either %zu %zu\n", api::either("abc"), api::either(std::nullopt)); - print("prefixed ", api::prefixed("cd", api::view("ab")), " "); - print("", api::prefixed("cd", std::nullopt), "\n"); - std::printf("coordinates %d %d\n", api::coordinates(api::Point{2, 3}), api::coordinates(std::nullopt)); - { - auto two = api::Counter::new_("two", 2); - auto three = api::Counter::new_("three", 3); - std::printf("plus %llu %llu\n", static_cast(two.plus(&three)), - static_cast(two.plus(nullptr))); - bool added = two.add_to(&three); - bool added_none = two.add_to(nullptr); - std::printf("add_to %s %s %llu\n", added ? "true" : "false", added_none ? "true" : "false", - static_cast(three.get())); + print("sought error ", sought.error(), "\n"); } +} - { - // A value passed for &mut, which takes what Rust wrote back. - api::buf encoded(api::view("0,")); - api::put_number(1, encoded); - api::put_number(23, encoded); - print("put_number ", encoded, "\n"); - ::std::tuple entry(api::buf(api::view("ab")), 1); - uint32_t stamps = api::push_counted(entry, 'c'); - std::printf("push_counted %u ", stamps); - print("", ::std::get<0>(entry), " "); - std::printf("%u\n", ::std::get<1>(entry)); - api::buf digits(api::view("7x9")); - auto first_digit = api::digit(digits); - auto skipped = api::digit(digits); - auto last_digit = api::digit(digits); - std::printf("digit %u %s %u %zu\n", unsigned(first_digit.value()), yes(!skipped.has_value()), - unsigned(last_digit.value()), digits.size()); - api::Point nudged{1, 2}; - api::nudge(nudged, 3); - std::printf("nudge %d %d\n", nudged.x, nudged.y); - } - { - auto config = api::secure("h3"); - print("secure ", api::alpn_lent(config), " "); - print("", api::alpn(config), "\n"); - auto cert = api::certify("der"); - std::printf("cert %llu ", ull(api::cert_len(cert))); - print("", api::cert_der(std::move(cert)), " "); - std::vector chain; - chain.push_back(api::certify("a")); - chain.push_back(api::certify("bc")); - std::printf("%llu\n", ull(api::chain_len(std::move(chain)))); - // Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. - print("resolver ", api::resolved(api::resolver("r1")), "\n"); - auto codecs = api::Codecs::new_(); - std::printf("codecs %u\n", unsigned(codecs.ids())); - auto listed = codecs.list_get(); - std::vector reversed; - reversed.push_back(std::move(listed[1])); - reversed.push_back(std::move(listed[0])); - codecs.list_set(std::move(reversed)); - std::printf("codecs reversed %u\n", unsigned(codecs.ids())); - // A standard library value no type maps, in a handle. - auto failure = api::failure("boom"); - print("failure ", api::failure_message(failure), " "); - print("", api::failure_kind(std::move(failure)), "\n"); - // Iterators, passed as the arrays of their items. - std::printf("sum_all %u\n", unsigned(api::sum_all({1, 2, 3}))); - std::vector weighed; - weighed.push_back(api::Counter::new_("w", 3)); - std::printf("weigh_all %llu\n", ull(api::weigh_all_Counter(std::move(weighed)))); - std::printf("offered_len %llu\n", ull(api::offered_len({"h3", "moq-00"}))); - print("join_words ", api::join_words({"a", "b", "c"}), "\n"); - // Bytes that must be `'static`, interned. - print("der ", api::Der::from_slice("der").bytes(), "\n"); - print("der again ", api::Der::from_slice("der").bytes(), "\n"); - auto session = api::resume("h3", 60); - print("resume ", session.value().alpn(), " "); - std::printf("%u\n", unsigned(session.value().lifetime().seconds)); - print("resume err ", api::resume("", 60).error(), "\n"); - auto meters = api::Meters::new_(); - auto first = meters.first(); - first.add(2); - unsigned long long added = first.add(3); - std::printf("lent %llu %llu\n", added, ull(meters.first().count())); - meters.clear(); - std::printf("cleared %llu\n", ull(meters.first().count())); - auto last = meters.last_get(); - last.add(4); - std::printf("field lent %llu\n", ull(last.add(1))); - // An optional field that is not Clone, lent as `Some` of a handle. - std::printf("spare %s\n", meters.spare_get() ? "true" : "false"); - meters.spare_set(api::Meter::default_()); - auto spare = meters.spare_get(); - spare->add(5); - std::printf("spare lent %llu\n", ull(spare->add(1))); - auto tallies = api::Tallies::new_(); - tallies.first().bump(); - std::printf("tallied %u\n", tallies.first().bump()); - } - { - // A draft borrowing its ledger exclusively until it is destroyed, through which its - // sheet's members are reached by Deref and DerefMut. - auto ledger = api::Ledger::new_(); - { - auto draft = ledger.edit().value(); - draft.title_set("minutes"); - draft.write("first"); - print("draft ", draft.title_get(), " "); - std::printf("%u ", draft.lines()); - print("", draft.describe(), " "); - std::printf("%s\n", yes(draft.edited())); - std::printf("committed %u\n", std::move(draft).commit()); - } - print("ledger ", ledger.title(), " "); - std::printf("%u\n", ledger.published()); - { - auto draft = ledger.edit().value(); - std::printf("read %u %s\n", draft.lines(), yes(draft.edited())); - } - { - auto draft = ledger.edit().value(); - draft.write("second"); - } - std::printf("dropped %u\n", ledger.published()); - std::printf("receipt %u\n", ledger.receipt().count()); - { - auto marker = api::Marker::new_(api::input("m"), 3, 5); - marker.y_set(7); - std::printf("forwarded %u %u %d %d", api::Pad_u16::wide().title(), api::Layered::new_().lines(), - marker.x_get(), marker.y_get()); - print(" [", api::Pad_u8::small().describe(), "]"); - print(" [", api::Pad_u16::wide().describe(), "]\n"); +// Futures of a value that is not `Send`, polled on this thread until each is ready. +void local_later(const api::Local &local) { + api::waker waker([]() {}); + const api::Local *froms[] = {&local, nullptr}; + for (const api::Local *from : froms) { + api::local_or_new_later_future later = api::local_or_new_later(from); + auto made = later.poll(waker); + while (!made) { + made = later.poll(waker); } - ledger.seal(); - print("sealed ", api::Error_to_string(ledger.edit().error()), "\n"); + std::printf("local later%s %u\n", from ? "" : " fresh", static_cast(made->bump())); } +} - std::printf("chunks ["); - auto chunks = api::chunks("abcde", 2); - for (std::size_t i = 0; i < chunks.size(); i++) { - std::printf("%s[", i == 0 ? "" : ", "); - for (std::size_t j = 0; j < chunks[i].size(); j++) { - std::printf("%s%u", j == 0 ? "" : ", ", chunks[i].data()[j]); - } - std::printf("]"); - } - std::printf("]\n"); - - auto counters = api::counters({"x", "y"}); - std::printf("counters"); - for (std::size_t i = 0; i < counters.size(); i++) { - print(i == 0 ? " " : ", ", counters[i].name(), " "); - std::printf("%llu", static_cast(counters[i].get())); - } - std::printf("\n"); - std::vector some, boxed; - some.push_back(std::move(counters[0])); - boxed.push_back(std::move(counters[1])); - auto worth = api::worth(std::move(some), std::move(boxed)); - std::printf("worth %llu %llu\n", ull(worth), ull(api::worth(std::nullopt, {}))); - std::optional counts[] = { - api::held_count(std::tuple{api::Counter::new_("h", 4)}), - api::held_count(std::nullopt), - }; - std::printf("held"); - for (auto count : counts) { - if (count) { - std::printf(" Some(%llu)", ull(*count)); - } else { - std::printf(" None"); - } +} // namespace hook + +} // namespace + +#include "transcript.hpp" + +namespace { + +// Each check that must hold, beyond the transcript. +int check(bool ok, const char *what) { + if (!ok) { + std::fprintf(stderr, "failed: %s\n", what); + std::exit(1); } - std::printf("\n"); - print("boxed Some(\"", *api::boxed_name(api::boxed_counter("b")), "\") "); - std::printf("%s %s\n", api::boxed_name(std::nullopt) ? "Some" : "None", api::boxed_counter(std::nullopt) ? "false" : "true"); - std::printf("less %u\n", api::less(5, 2)); + return 0; +} - auto sums = api::sums({{1, 2}, {}, {3}}); - std::printf("sums [%u, %u, %u]\n", sums[0], sums[1], sums[2]); +// What the transcript's script says only in Rust: C++'s own copies, hashes, ranges, and +// operators, each checked by an assertion. +int checks() { + // Fields named as an `operator==`'s argument might be. { - // Fields named as an `operator==`'s argument might be. api::Shadowed one{{1}, 2, 3}; api::Shadowed two{{1}, 2, 4}; - if (!(one == one) || one == two || !(one != two)) { - std::fprintf(stderr, "a record with fields named other, a, and b compares wrong\n"); - std::abort(); - } + check(one == one && !(one == two) && one != two, "a record with fields named other, a, and b compares"); } + // Types named as an `operator==`'s arguments might be. { - // Types named as an `operator==`'s arguments might be. api::a one{1}; api::a two{2}; api::b unit = api::b_One{}; api::b two_b = api::b_Two{2}; auto handle = api::c::new_(1); - if (!(one == one) || one == two || !(unit != two_b) || !(handle == api::c::new_(1)) || handle == api::c::new_(2)) { - std::fprintf(stderr, "types named a, b, and c compare wrong\n"); - std::abort(); - } - } - std::printf("least"); - for (const auto &set : api::least({{3, 1}, {}, {2}})) { - std::printf(" ["); - for (std::size_t j = 0; j < set.size(); j++) { - std::printf(j ? ", %u" : "%u", set[j]); - } - std::printf("]"); - } - std::printf("\n"); - numbers("edges", api::Numbers::edges()); - numbers("reversed", api::Numbers::edges().reversed()); - { - auto edges = api::Numbers::edges(); - auto nan = api::Measure::new_(std::nan(""), false); - auto same = [](bool b) { return b ? "true" : "false"; }; - std::printf("float equal %s %s %s %s %s\n", same(edges == edges), same(edges == api::Numbers::edges()), - same(api::Numbers::zero(true) == api::Numbers::zero(false)), same(nan == nan), - same(api::Measure::new_(-0.0, true) == api::Measure::new_(0.0, false))); - } - std::printf("sum u32 %llu %llu\n", static_cast(api::sum_u32({})), - static_cast(api::sum_u32({UINT32_MAX, UINT32_MAX, 2}))); - std::printf("doubled i64 "); - print_list(api::doubled_i64({INT64_MIN, -1, 0, INT64_MAX}), [](int64_t v) { return std::to_string(v); }); - std::printf("\n"); - std::printf("boxed floats "); - print_list(api::boxed_floats({-0.0, f64_from(0x7ff8000000000001)}), [](double v) { return std::to_string(f64_bits(v)); }); - std::printf("\n"); - auto summed = api::summed({{1, 2}, {-4, 6}}); - auto none_summed = api::summed({}); - std::printf("summed %d %d %d %d\n", summed.x, summed.y, none_summed.x, none_summed.y); - std::printf("longest %zu %zu\n", api::longest({"a", "abc"}), api::longest({})); - print("first of Some(\"", api::first_of({"a", "b"}).value(), "\") "); - std::printf("%s\n", api::first_of({}) ? "Some" : "None"); - auto limits = api::byte_limits("a", "bc"); - print("limits ", limits.low, " "); - print("", limits.high, " "); - auto breadth = api::breadth({{0, 5000000}, {2, 0}}); - std::printf("breadth %llu\n", static_cast(breadth.secs * 1000 + breadth.nanos / 1000000)); - print("joined ", api::joined({"ab", "", "c"}), " "); - std::printf("%zu read %llu\n", api::joined({}).size(), static_cast(api::read_len("hello"))); - - api::Json doc = api::Json::parse(R"({"b": [1, 2.5, null], "a": "\u00e9"})").value(); - print("json ", api::encode(doc), "\n"); - print("timed text ", api::timed_text(doc), "\n"); - api::Json tagged = api::tagged(std::move(doc), "t"); - print("tagged ", tagged.to_text(), "\n"); - { - // A JSON object's entries cross as pairs of a key and its document, each moved in. - std::vector> pairs; - pairs.emplace_back("b", api::Json::parse("[1]").value()); - pairs.emplace_back("a", api::Json::parse("2").value()); - auto entries = api::entries(std::move(pairs), "t"); - std::printf("entries"); - for (std::size_t i = 0; i < entries.size(); i++) { - auto &[key, value] = entries[i]; - print(i == 0 ? " " : ", ", key, " "); - print("", value.to_text(), ""); - } - std::printf("\n"); - } - if (auto parsed = api::Json::parse("{\"a\":")) { - print("json parse ", parsed->to_text(), "\n"); - } else { - print("json parse err ", parsed.error(), "\n"); - } - - api::Site site = api::Site::new_(base); - print("site ", site.home_get().to_string(), " "); - print("", site.home_get().to_string(), "\n"); - - // Slices, passed in and returned as clones, and the socket address of each family. - auto shapes = api::Shape_ALL(); - std::printf("shapes ["); - for (std::size_t i = 0; i < shapes.size(); i++) { - print(i == 0 ? "" : ", ", api::Shape_debug(shapes[i]), ""); - } - std::printf("] greetings "); - print_strings(api::GREETINGS()); - std::printf("\n"); - auto both = api::Shape_BOTH(); - std::printf("both ["); - for (std::size_t i = 0; i < both.size(); i++) { - print(i == 0 ? "" : ", ", api::Shape_debug(both[i]), ""); - } - std::printf("] primes ["); - auto primes = api::PRIMES(); - for (std::size_t i = 0; i < primes.size(); i++) { - std::printf("%s%u", i == 0 ? "" : ", ", unsigned(primes[i])); - } - std::printf("]\n"); - api::Trail trail = api::Trail::new_({api::Point{1, 2}, api::Point{3, 4}}, {"a", "b"}); - auto points = trail.points(); - std::printf("trail ["); - for (std::size_t i = 0; i < points.size(); i++) { - print(i == 0 ? "" : ", ", points[i].debug(), ""); - } - auto labels = trail.labels(); - std::printf("] ["); - for (std::size_t i = 0; i < labels.size(); i++) { - print(i == 0 ? "" : ", ", labels[i].debug(), ""); - } - std::printf("]\n"); - // Returned iterators, each collected at the call: drained labels are gone after. - auto iter_points = trail.iter(); - std::printf("iterated ["); - for (std::size_t i = 0; i < iter_points.size(); i++) { - print(i == 0 ? "" : ", ", iter_points[i].debug(), ""); - } - std::printf("] "); - print_strings(trail.names()); - auto iter_bytes = trail.bytes(); - std::printf(" ["); - for (std::size_t i = 0; i < iter_bytes.size(); i++) { - std::printf("%s%u", i == 0 ? "" : ", ", iter_bytes.data()[i]); - } - std::printf("]\n"); - auto drained = trail.drain(); - std::printf("drained ["); - for (std::size_t i = 0; i < drained.size(); i++) { - print(i == 0 ? "" : ", ", drained[i].debug(), ""); - } - auto left = trail.labels(); - std::printf("] then ["); - for (std::size_t i = 0; i < left.size(); i++) { - print(i == 0 ? "" : ", ", left[i].debug(), ""); - } - std::printf("]\n"); - // A filter, collected at the call. - auto beyond = trail.beyond(1); - std::printf("beyond"); - for (std::size_t i = 0; i < beyond.size(); i++) { - std::printf("%s%d %d", i == 0 ? " " : ", ", beyond[i].x, beyond[i].y); - } - std::printf("\n"); - auto numbered = api::numbered({"p", "q"}); - std::printf("numbered"); - for (std::size_t i = 0; i < numbered.size(); i++) { - print(i == 0 ? " " : ", ", numbered[i].name(), " "); - std::printf("%llu", static_cast(numbered[i].get())); - } - std::printf("\n"); - api::socket_addr_v4 at4{}; - at4.ip.octets[0] = 127; - at4.ip.octets[3] = 1; - at4.port = 8080; - api::socket_addr_v6 at6{}; - at6.ip.octets[15] = 1; - at6.port = 443; - at6.scope_id = 3; - auto [next4, next6] = api::nexts(at4, at6); - const auto &n4 = next4.ip.octets; - std::printf("nexts %u.%u.%u.%u %u %u %u\n", n4[0], n4[1], n4[2], n4[3], next4.port, next6.port, next6.scope_id); - auto print_hex = [](const std::uint8_t *bytes, std::size_t len) { - for (std::size_t b = 0; b < len; b++) { - std::printf("%02x", bytes[b]); - } - }; - auto print_ip = [&](const api::ip_addr &ip) { - if (ip.v6) { - print_hex(ip.ip.v6.octets, 16); - } else { - print_hex(ip.ip.v4.octets, 4); - } - }; - auto print_socket = [&](const api::socket_addr &addr) { - if (addr.v6) { - print_hex(addr.addr.v6.ip.octets, 16); - std::printf(":%u:%u:%u", addr.addr.v6.port, addr.addr.v6.flowinfo, addr.addr.v6.scope_id); - } else { - print_hex(addr.addr.v4.ip.octets, 4); - std::printf(":%u", addr.addr.v4.port); - } - }; - { - api::ipv4_addr ip4{}; - ip4.octets[0] = 10; - ip4.octets[3] = 255; - api::ipv6_addr ip6{}; - ip6.octets[14] = ip6.octets[15] = 0xff; - api::ip_addr local4{}, local6{}, nextip4_{}, nextip6_{}; - local4.ip.v4.octets[0] = 127; - local4.ip.v4.octets[3] = 1; - local6.v6 = true; - local6.ip.v6.octets[15] = 1; - auto [nextip4, nextip6] = api::next_ips(ip4, ip6); - nextip4_.ip.v4 = nextip4; - nextip6_.v6 = true; - nextip6_.ip.v6 = nextip6; - auto mapped = api::flip(local4); - std::printf("ips"); - for (auto ip : {nextip4_, nextip6_, mapped, api::flip(mapped), api::flip(local6)}) { - std::printf(" "); - print_ip(ip); - } - std::printf("\n"); - } - // Lossless round trips: each type's edge values, passed through Rust and back. - { - std::printf("lossless duration"); - for (api::duration ll_dur : {api::duration{0, 0}, api::duration{0, 1}, api::duration{9223372036u, 854775808u}, - api::duration{UINT64_MAX, 999999999u}}) { - ll_dur = api::same_duration(ll_dur); - std::printf(" %llu.%09u", static_cast(ll_dur.secs), ll_dur.nanos); - } - std::printf("\n"); - std::printf("lossless u64 %llu %llu %llu\n", static_cast(api::same_u64(0)), - static_cast(api::same_u64(1ull << 63)), - static_cast(api::same_u64(UINT64_MAX))); - std::printf("lossless usize %zu %zu\n", api::same_usize(0), api::same_usize(SIZE_MAX)); - std::printf("lossless isize %td %td\n", api::same_isize(PTRDIFF_MIN), api::same_isize(PTRDIFF_MAX)); - std::printf("lossless u128"); - for (api::u128 ll_wide : {api::u128{0, 0}, api::u128{0, 1}, api::u128{UINT64_MAX, UINT64_MAX}}) { - ll_wide = api::same_u128(ll_wide); - std::printf(" %016llx%016llx", static_cast(ll_wide.hi), static_cast(ll_wide.lo)); - } - std::printf("\n"); - std::printf("lossless char"); - for (char32_t ll_code : {U'\0', static_cast(0xd7ff), static_cast(0xe000), static_cast(0x10ffff)}) { - std::printf(" %x", static_cast(api::same_char(ll_code))); - } - std::printf("\n"); - // A path no Rust string spells: bytes that are not UTF-8, or on Windows, WTF-8's lone - // surrogate. -#ifdef _WIN32 - static const std::uint8_t ll_stray[] = {0xed, 0xa0, 0x80}; -#else - static const std::uint8_t ll_stray[] = {0xff}; -#endif - std::printf("lossless path"); - for (auto ll_same : {api::same_path("a/\xc3\xa9"), api::same_path(api::view(ll_stray, sizeof ll_stray))}) { - std::printf(" "); - print_hex(ll_same.data(), ll_same.size()); - } - std::printf("\n"); - api::socket_addr_v4 ll_sv4{}; - std::memset(ll_sv4.ip.octets, 0xff, 4); - ll_sv4.port = UINT16_MAX; - api::socket_addr_v6 ll_sv6{}; - ll_sv6.ip.octets[1] = 1; - ll_sv6.ip.octets[15] = 2; - ll_sv6.port = 3; - ll_sv6.flowinfo = ll_sv6.scope_id = UINT32_MAX; - api::socket_addr ll_sockets[2] = {}; - ll_sockets[0].addr.v4 = api::same_socket_addr_v4(ll_sv4); - ll_sockets[1].v6 = true; - ll_sockets[1].addr.v6 = api::same_socket_addr_v6(ll_sv6); - std::printf("lossless socket"); - for (const auto &ll_socket : ll_sockets) { - std::printf(" "); - print_socket(ll_socket); - } - for (const auto &ll_socket : ll_sockets) { - std::printf(" "); - print_socket(api::same_socket_addr(ll_socket)); - } - std::printf("\n"); - api::Key ll_key_a = api::Key::new_("a"), ll_key_b = api::Key::new_("b"); - if (ll_key_a.hash() != ll_key_a.hash_of()) { - std::fprintf(stderr, "Key::hash differs from Rust's own hash\n"); - std::exit(1); - } - std::hash ll_hasher; - std::printf("key %s %s\n", ll_hasher(ll_key_a) == ll_hasher(api::Key::new_("a")) ? "true" : "false", - ll_hasher(ll_key_a) == ll_hasher(ll_key_b) ? "true" : "false"); - api::ip_addr ll_edge4{}, ll_edge6{}; - std::memset(ll_edge4.ip.v4.octets, 0xff, 4); - ll_edge6.v6 = true; - ll_edge6.ip.v6.octets[0] = ll_edge6.ip.v6.octets[1] = 0xff; - ll_edge6.ip.v6.octets[15] = 1; - std::printf("lossless ip "); - print_ip(api::same_ip_addr(ll_edge4)); - std::printf(" "); - print_ip(api::same_ip_addr(ll_edge6)); - std::printf("\n"); + check(one == one && !(one == two) && unit != two_b && handle == api::c::new_(1) && !(handle == api::c::new_(2)), + "types named a, b, and c compare"); } - - // serde_json's map iterator, collected as pairs of a key and its document. + // A name takes a copy of the caller's buffer, which is its own again after. { - std::vector> pairs; - pairs.emplace_back("b", api::Json::parse("[1]").value()); - pairs.emplace_back("a", api::Json::parse("2").value()); - auto sections = api::sections(std::move(pairs)); - std::printf("sections"); - for (std::size_t i = 0; i < sections.size(); i++) { - auto &[key, value] = sections[i]; - print(i == 0 ? " " : ", ", key, " "); - print("", value.to_text(), ""); - } - std::printf("\n"); + api::Name name = api::Name::owned("a"); + std::string text = "c"; + name.rename(text); + text[0] = 'x'; + check(name.as_str().str() == "c", "a renamed name holds its own copy"); } - // An instant only Rust makes, which each call copies out of its handle, and compares. - { - auto millis = [](api::duration elapsed) { return static_cast(elapsed.secs * 1000 + elapsed.nanos / 1000000); }; - auto began = api::now(); - auto ended = api::later(began, {1, 500000000}); - std::printf("instants %llu %llu %s %s\n", millis(api::since(ended, began)), millis(api::since(began, ended)), - began == api::later(began, {0, 0}) ? "true" : "false", began == ended ? "true" : "false"); - // An instant lent inside an `Option`, which takes no handle. - std::printf("has_instant %s %s\n", api::has_instant(&began) ? "true" : "false", api::has_instant(nullptr) ? "true" : "false"); - } - // tracing's level, and its filter as an optional level whose empty is `OFF`. + // `std::hash` hashes a key as Rust's `Hash` does: equal keys alike, and these two apart. { - auto verbosity = api::Verbosity::new_(api::Level::warn); - print("verbosity ", api::spell(verbosity.filter()), " "); - print("", api::spell(api::louder(verbosity.filter())), "\n"); - verbosity.level_set(api::Level::trace); - std::printf("verbosity %s ", verbosity.level_get() == api::Level::trace ? "true" : "false"); - print("", api::spell(verbosity.filter()), " "); - print("", api::spell(api::louder(verbosity.filter())), " "); - print("", api::spell(api::louder(std::nullopt)), "\n"); - } - - // Closures C++ implements that return what Rust then owns, or that Rust keeps. - print("made ", api::made(3, [](std::uint32_t n) { return std::to_string(n) + " times"; }), "\n"); - // A closure taking and returning `Copy` values copies them, never running their `Clone`. + api::Key a = api::Key::new_("a"); + api::Key b = api::Key::new_("b"); + check(a.hash() == a.hash_of(), "Key::hash is Rust's own hash"); + std::hash hasher; + check(hasher(a) == hasher(api::Key::new_("a")) && hasher(a) != hasher(b), "std::hash hashes keys as Rust does"); + } + // `Copy` objects with no C++ copy, beside bytes: a returned vector moves back in, stored or + // not, each ticket moved and each name viewed in place. { - api::Ticket kept = api::Ticket::new_(9); - std::uint32_t given = - api::reissue(api::Ticket::new_(7), [](const api::Ticket &t) { return api::Ticket::new_(t.number() + 1); }) - .number(); - std::uint32_t held = api::reissue(api::Ticket::new_(7), [&kept](const api::Ticket &) { return kept; }).number(); - std::printf("reissued %u %u, cloned %u\n", static_cast(given), static_cast(held), - static_cast(api::Ticket::clones())); - // A record's traits borrow the checked handle it holds. - api::Mark nine = api::Mark::of(9); - api::Seat front = api::seat(nine, 1); - api::Seat back = api::seat(nine, 2); - print("seat ", front.debug(), ""); - std::printf(" %s %s\n", front == front ? "true" : "false", front == back ? "true" : "false"); - } - { - // `Copy` objects with no C++ copy, beside bytes: a returned vector moves back in, - // stored or not, each ticket moved and each name viewed in place. std::vector> lent; lent.emplace_back("a", api::Ticket::new_(1)); auto returned = api::tickets(lent); auto again = api::tickets(api::tickets(std::move(returned))); - if (again.size() != 1 || std::get<0>(again[0]).str() != "a" || std::get<1>(again[0]).number() != 1) { - std::fprintf(stderr, "returned tickets passed back wrong\n"); - std::abort(); - } + check(again.size() == 1 && std::get<0>(again[0]).str() == "a" && std::get<1>(again[0]).number() == 1, + "returned tickets pass back"); } #ifdef __cpp_lib_ranges + // A range whose end is a sentinel of another type than its begin. { - // A range whose end is a sentinel of another type than its begin. std::vector letters{"p", "q", "r"}; auto taken = api::counters(letters | std::views::take_while([](const std::string &n) { return n != "r"; })); - if (taken.size() != 2 || taken[1].name().str() != "q") { - std::fprintf(stderr, "a sentinel range passed wrong\n"); - std::abort(); - } + check(taken.size() == 2 && taken[1].name().str() == "q", "a sentinel range passes"); } #endif // A kept closure, called on another thread after the call that took it returned. - if (api::Spawned::new_([] { return 7; }).join() != 7) { - std::fprintf(stderr, "failed: a kept closure runs on another thread\n"); - return 1; - } - // A kept closure: called again at the instant it asks for, then once its waiter wakes. - { - api::Moment began = *api::Moment::new_(0, 1000); - int calls = 0; - auto drive = api::drive(began, [&](const api::Moment &now, const api::Waiter &waiter) { - using result = api::result, std::string>; - calls++; - if (calls == 1) { - return result::ok(now.after(5)); - } - if (calls == 2) { - std::printf("drive %llu\n", ull(now.millis() - began.millis())); - waiter.waker().wake(); - return result::ok(std::nullopt); - } - return result::err("stopped after " + std::to_string(calls)); - }); - api::waker waker([] {}); - std::optional stopped; - while (!(stopped = drive.poll(waker))) { - } - print("drive ", *stopped, "\n"); - } - { - memory hello{"hello world"}; - tail(hello); - broken_reader broken; - tail(broken); - // A seek from the start reaches the reader whole, past `INT64_MAX`, as `Cursor` takes one. - far_reader far; - auto sought = api::seek_to(far, UINT64_MAX); - if (sought) { - std::printf("sought %llu\n", static_cast(*sought)); - } else { - print("sought error ", sought.error(), "\n"); - } - } - print("non zeros ", api::describe_non_zeros(api::non_zeros()), "\n"); - for (auto hop : {std::optional{}, std::optional{1}, std::optional{UINT64_MAX}}) { - if (auto next = api::next_hop(hop)) { - std::printf("hop Some(%llu)\n", static_cast(*next)); - } else { - std::printf("hop None\n"); - } - } - std::printf("farther hop %u\n", static_cast(api::farther_hop(api::Pair_non_zero_u16{3, UINT16_MAX}))); - { - api::Local local = api::Local::new_(); - api::Local shared = api::local_or_new(&local); - std::uint32_t bumped = local.bump(); - std::printf("local %u %u\n", static_cast(bumped), static_cast(shared.bump())); - std::printf("local fresh %u\n", static_cast(api::local_or_new(nullptr).bump())); - std::printf("local either %u\n", static_cast(api::bump_either(nullptr, shared))); - api::waker waker([]() {}); - const api::Local *froms[] = {&local, nullptr}; - for (const api::Local *from : froms) { - api::local_or_new_later_future later = api::local_or_new_later(from); - auto made = later.poll(waker); - while (!made) { - made = later.poll(waker); - } - std::printf("local later%s %u\n", from ? "" : " fresh", static_cast(made->bump())); - } - } - + check(api::Spawned::new_([] { return 7; }).join() == 7, "a kept closure runs on another thread"); // A returned `Vec<&Token>` holds clones, which the vector drops. - api::Token twice = api::Token::new_(9); - std::uint32_t before = api::dropped(); { - auto tokens = twice.twice(); - if (tokens.size() != 2 || tokens[1].id_get() != 9) { - return 1; + api::Token twice = api::Token::new_(9); + std::uint32_t before = api::dropped(); + { + auto tokens = twice.twice(); + check(tokens.size() == 2 && tokens[1].id_get() == 9, "a vector of lent tokens holds clones"); } + check(api::dropped() == before + 2, "the vector drops its clones"); } - if (api::dropped() != before + 2) { - return 1; - } + std::printf("checks ok\n"); return 0; } -// The futures' semantics beyond the transcript, each checked by an assertion. -int check(bool ok, const char *what) { - if (!ok) { - std::fprintf(stderr, "failed: %s\n", what); - std::exit(1); +// A queue of jobs that a test runs when it chooses: the executor futures run on. +struct queue { + std::mutex mutex; + std::deque> jobs; + + auto executor() { + return [this](std::function job) { + std::lock_guard lock(mutex); + jobs.push_back(std::move(job)); + }; } - return 0; -} + + // Run jobs until none are left. + void drain() { + for (;;) { + std::function job; + { + std::lock_guard lock(mutex); + if (jobs.empty()) { + return; + } + job = std::move(jobs.front()); + jobs.pop_front(); + } + job(); + } + } +}; // A future C++ implements, which Rust polls: ready on its `ready`th poll, keeping the // waker of the last in what it shares with the test. @@ -1700,7 +696,7 @@ int foreign_futures() { return api::result, const char *>::err("failed"); }); check(std::move(drive).get().str() == "failed", "a closure's error reaches Rust as its message"); - memory empty{""}; + hook::memory empty{""}; empty.at = 0; auto read = api::tail(empty, 5); check(read && std::get<0>(*read).empty() && std::get<1>(*read) == 0, "a reader of nothing reads nothing"); @@ -2196,8 +1192,12 @@ int main(int argc, char **argv) { if (argc > 1 && std::strcmp(argv[1], "rehomed") == 0) { return rehomed(); } + if (argc > 1 && std::strcmp(argv[1], "checks") == 0) { + return checks(); + } if (argc > 1) { return broken(argv[1]); } - return script(); + transcript::script(); + return 0; } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 9b5eadc00..ac78a5dea 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -165,11 +165,17 @@ fn transcript() -> &'static transcript::Transcript { /// language's test puts on its path. fn generated(language: &str, file: &str, contents: &str) -> PathBuf { let dir = scratch().join("api").join(format!("{language}-transcript")); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join(file), contents).unwrap(); + // Written only when it changes, so what builds from it stays fresh. + step::write(&dir.join(file), contents); dir } +/// The directory of `transcript.hpp`, which `tests/api.cpp` includes: the transcript as +/// C++. +fn cpp_transcript() -> PathBuf { + generated("cpp", "transcript.hpp", &transcript::cpp::emit(transcript())) +} + fn api() -> &'static Api { static API: OnceLock = OnceLock::new(); API.get_or_init(|| { @@ -400,14 +406,22 @@ fn sanitized(sanitizer: &str) { ("ASAN_OPTIONS", "detect_leaks=1:abort_on_error=1"), ("TSAN_OPTIONS", "halt_on_error=1"), ]; + let scripts = cpp_transcript(); for (compiler, std, src, args) in [ ("clang", "-std=c11", "api.c", &["threads"][..]), - ("clang++", "-std=c++17", "api.cpp", &["futures", "lifetimes"][..]), + ( + "clang++", + "-std=c++17", + "api.cpp", + &["futures", "lifetimes", "checks"][..], + ), ] { let exe = dir.join(src.replace('.', "-")); run(Command::new(compiler) .args([std, "-g", "-Wall", "-Wextra", "-Werror", &sanitize, "-I"]) .arg(api.out.join("include")) + .arg("-I") + .arg(&scripts) .arg(tests.join(src)) .arg(&lib) .args(&native) @@ -458,10 +472,14 @@ fn api_miri() { #[test] fn api_cpp() { let api = api(); + let link = Link { + generated: Some(cpp_transcript()), + ..api.link() + }; for (standard, plain) in [(17, true), (20, false), (23, true)] { let exe = scratch().join("api").join(format!("api-c++{standard}{EXE_SUFFIX}")); cxx( - &api.link(), + &link, standard, plain, &manifest_dir().join("tests").join("api.cpp"), @@ -475,6 +493,7 @@ fn api_cpp() { ); run(Command::new(&exe).arg("futures")); run(Command::new(&exe).arg("lifetimes")); + run(Command::new(&exe).arg("checks")); let rehomed = run(Command::new(&exe).arg("rehomed")); assert_eq!(String::from_utf8_lossy(&rehomed.stdout), "scaled by 7\n"); for (case, message) in [ @@ -509,7 +528,7 @@ fn api_cpp() { } if !cfg!(target_env = "msvc") { - cpp_strict(api); + cpp_strict(&link); } // Each crate's header builds alone, needing only the headers it includes. @@ -562,13 +581,19 @@ int main() {} /// Clang's ownership checks: the whole script builds clean under them, and each case of /// `tests/api_strict.cpp` fails with its diagnostic. -fn cpp_strict(api: &Api) { - let include = api.out.join("include"); +fn cpp_strict(link: &Link) { + let include = &link.include; + let generated = link + .generated + .as_deref() + .expect("tests/api.cpp includes its transcript"); // What each case printed, kept apart from the others'; its object is not. let clang = |src: &Path, case: u8| { let mut cmd = Command::new("clang++"); cmd.args(["-std=c++17", "-Wconsumed", "-Wdangling", "-Werror", "-c", "-I"]) - .arg(&include) + .arg(include) + .arg("-I") + .arg(generated) .arg(format!("-DCASE={case}")) .arg(src) .arg("-o") @@ -579,7 +604,7 @@ fn cpp_strict(api: &Api) { .join(format!("{}-{case}.stamp", src.file_stem().unwrap().to_string_lossy())); let step = Step { stamp: &stamp, - reads: &[src, &include], + reads: &[src, include, generated], writes: &[], }; // Case 0 must build, so only the failing cases keep a failure. @@ -631,6 +656,8 @@ struct Link<'a> { include: PathBuf, staticlib: PathBuf, native: &'a [String], + /// A directory of headers written for the program, such as its transcript. + generated: Option, } impl Api { @@ -639,6 +666,7 @@ impl Api { include: self.out.join("include"), staticlib: self.staticlib(), native: &self.native, + generated: None, } } } @@ -647,9 +675,11 @@ impl Api { /// exceptions and RTTI off if `plain`, and warnings as errors: by `CXX` or the platform's /// compiler, given MSVC's flags where the target is MSVC's. fn cxx(link: &Link, standard: u8, plain: bool, src: &Path, exe: &Path) { + let mut reads = vec![src, &link.include, &link.staticlib]; + reads.extend(link.generated.as_deref()); let step = Step { stamp: &step::stamp(exe), - reads: &[src, &link.include, &link.staticlib], + reads: &reads, writes: &[exe], }; step.run(&mut cxx_command(link, standard, plain, src, exe)); @@ -680,7 +710,11 @@ fn cxx_command(link: &Link, standard: u8, plain: bool, src: &Path, exe: &Path) - obj.push(exe.with_extension("obj")); let mut out = OsString::from("-Fe"); out.push(exe); - cmd.arg("-I").arg(include).arg(src).arg(obj).arg(out); + cmd.arg("-I").arg(include); + if let Some(generated) = &link.generated { + cmd.arg("-I").arg(generated); + } + cmd.arg(src).arg(obj).arg(out); cmd.arg("-link").arg(&link.staticlib).args(link.native); return cmd; } @@ -700,12 +734,11 @@ fn cxx_command(link: &Link, standard: u8, plain: bool, src: &Path, exe: &Path) - "-Werror", "-I", ]) - .arg(include) - .arg(src) - .arg(&link.staticlib) - .args(link.native) - .arg("-o") - .arg(exe); + .arg(include); + if let Some(generated) = &link.generated { + cmd.arg("-I").arg(generated); + } + cmd.arg(src).arg(&link.staticlib).args(link.native).arg("-o").arg(exe); cmd } diff --git a/ffi/tests/fixtures/shapes.rs b/ffi/tests/fixtures/shapes.rs index 20be278ef..6db4a888b 100644 --- a/ffi/tests/fixtures/shapes.rs +++ b/ffi/tests/fixtures/shapes.rs @@ -1455,6 +1455,7 @@ fn round_trip(built: &Built, language: &str) { include: built.out.join("include"), staticlib: built.staticlib(), native: &built.native, + generated: None, }; super::cxx(&link, 17, false, &main, &exe); run(&mut Command::new(&exe)) diff --git a/ffi/tests/fixtures/transcript/cpp.rs b/ffi/tests/fixtures/transcript/cpp.rs new file mode 100644 index 000000000..6f7345e63 --- /dev/null +++ b/ffi/tests/fixtures/transcript/cpp.rs @@ -0,0 +1,1595 @@ +//! The transcript as C++: a header `tests/api.cpp` includes after its namespace `hook`, which +//! holds its own functions `transcript.rs` defines, whose `transcript::script()` runs the +//! script through the generated header. +//! +//! C++ evaluates a call's arguments in no set order, but a braced list's in order, so each +//! line's values are a list, as Rust's are in order. A local moves at its last use, where +//! Rust moves it, and is copied, or cloned where C++ has no copy, at each use before. + +use std::collections::BTreeSet; +use std::fmt::Write; + +use super::ir::{Access, Family, Int, Mutability, Receiver, Type}; +use super::{BoundKind, Expr, FnId, Kind, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; + +const LANGUAGE: &str = "C++"; + +/// Helpers the script calls, each for a value C++ shapes apart from Rust. +const PRELUDE: &str = r#"// Generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript. Do not edit. +// tests/api.cpp includes it after its namespace `hook`, which holds the functions transcript.rs +// defines. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "api.hpp" + +namespace rs { + +[[noreturn]] inline void fail(const char *what) { + std::fprintf(stderr, "%s\n", what); + std::abort(); +} + +// A line of the transcript, its pieces evaluated in order, as a braced list's are. +inline void line(std::initializer_list pieces) { + std::string out; + for (const auto &piece : pieces) { + out += piece; + } + out += '\n'; + std::fwrite(out.data(), 1, out.size(), stdout); +} + +inline std::string cat(std::initializer_list pieces) { + std::string out; + for (const auto &piece : pieces) { + out += piece; + } + return out; +} + +// Bytes, or a string, as text. +template +std::string text(const B &bytes) { + return std::string(reinterpret_cast(std::data(bytes)), std::size(bytes)); +} + +inline std::string flag(bool value) { + return value ? "true" : "false"; +} + +// Zeros before `digits` up to `width`. +inline std::string pad(std::string digits, int width) { + if (static_cast(digits.size()) < width) { + digits.insert(0, static_cast(width) - digits.size(), '0'); + } + return digits; +} + +template +std::string hex(T value, int width) { + auto bits = static_cast(static_cast>(value)); + std::string digits; + do { + digits.insert(digits.begin(), "0123456789abcdef"[bits % 16]); + bits /= 16; + } while (bits != 0); + return pad(digits, width); +} + +inline std::string hex(api::u128 value, int width) { + return pad(value.hi != 0 ? hex(value.hi, 0) + hex(value.lo, 16) : hex(value.lo, 0), width); +} + +template +std::string padded(T value, int width) { + std::string digits = std::to_string(value); + if (digits[0] == '-') { + return "-" + pad(digits.substr(1), width - 1); + } + return pad(digits, width); +} + +// A string as Rust's `Debug` prints it. +template +std::string quoted(const B &bytes) { + std::string out = "\""; + for (char c : text(bytes)) { + switch (c) { + case '"': + case '\\': + out += '\\'; + out += c; + break; + case '\n': + out += "\\n"; + break; + case '\t': + out += "\\t"; + break; + case '\r': + out += "\\r"; + break; + case '\0': + out += "\\0"; + break; + default: + if (static_cast(c) < 0x20 || c == 0x7f) { + char escaped[16]; + std::snprintf(escaped, sizeof escaped, "\\u{%x}", static_cast(static_cast(c))); + out += escaped; + } else { + out += c; + } + } + } + return out + "\""; +} + +template +std::string option(const std::optional &value, F show) { + return value ? "Some(" + show(*value) + ")" : "None"; +} + +template +std::string list(const L &items, F show) { + std::string out = "["; + bool first = true; + for (const auto &item : items) { + out += first ? "" : ", "; + out += show(item); + first = false; + } + return out + "]"; +} + +// Bytes as Rust's `Debug` prints a slice of them. +template +std::string bytes(const B &bytes) { + return list(bytes, [](std::uint8_t b) { return std::to_string(b); }); +} + +template +std::string bound(const B &bound) { + switch (bound.kind) { + case API_BOUND_INCLUDED: + return "Included(" + std::to_string(bound.value) + ")"; + case API_BOUND_EXCLUDED: + return "Excluded(" + std::to_string(bound.value) + ")"; + default: + return "Unbounded"; + } +} + +// `items.map(show).collect::>().join(sep)`. +template +std::string join(R &&items, const char *sep, F show) { + std::string out; + bool first = true; + for (auto &&item : items) { + out += first ? "" : sep; + out += show(item); + first = false; + } + return out; +} + +// A vector of `items`, each moved in, which a braced list cannot. +template +std::vector vec(A &&...items) { + std::vector out; + out.reserve(sizeof...(items)); + (out.emplace_back(std::forward(items)), ...); + return out; +} + +template +T some(std::optional &&value) { + if (!value) { + fail("called `Option::unwrap()` on a `None` value"); + } + return std::move(*value); +} + +template +const T &some(const std::optional &value) { + if (!value) { + fail("called `Option::unwrap()` on a `None` value"); + } + return *value; +} + +// An object a closure is lent: itself, or what a borrow lends. +template +T &lent(T &object) { + return object; +} + +template +T &lent(api::borrow &object) { + return *object.operator->(); +} + +template +T &lent(const api::borrow &object) { + return *object.operator->(); +} + +template +const T *ptr(const T &value) { + return &value; +} + +inline api::socket_addr socket(api::socket_addr_v4 v4) { + api::socket_addr out{}; + out.addr.v4 = v4; + return out; +} + +inline api::socket_addr socket(api::socket_addr_v6 v6) { + api::socket_addr out{}; + out.v6 = true; + out.addr.v6 = v6; + return out; +} + +inline api::ip_addr ip(api::ipv4_addr v4) { + api::ip_addr out{}; + out.ip.v4 = v4; + return out; +} + +inline api::ip_addr ip(api::ipv6_addr v6) { + api::ip_addr out{}; + out.v6 = true; + out.ip.v6 = v6; + return out; +} + +inline double f64(std::uint64_t bits) { + double out; + std::memcpy(&out, &bits, sizeof out); + return out; +} + +inline float f32(std::uint32_t bits) { + float out; + std::memcpy(&out, &bits, sizeof out); + return out; +} + +} // namespace rs +"#; + +/// The C++ header of `t`'s script. +pub(crate) fn emit(t: &Transcript) -> String { + let mut used = BTreeSet::new(); + for step in &t.steps { + each_expr(step, &mut |e| { + walk(e, &mut |e| { + if let Kind::Var(name) = &e.kind { + used.insert(name.clone()); + } + }) + }); + } + let mut e = Emitter { + t, + depth: 1, + fresh: 0, + level: 0, + owned: Vec::new(), + used, + }; + let body = e.steps(&t.steps); + let body = resolve(&body); + format!("{PRELUDE}\nnamespace transcript {{\n\ninline void script() {{\n{body}}}\n\n}} // namespace transcript\n") +} + +/// Each expression a step holds, its arms' and closures' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +/// How a local is used where it appears, marked in the output until the last use of each +/// is known. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Use { + /// Read in place. + Read, + /// Moved at its last use, and copied before it. + Move, + /// Moved at its last use, and cloned before it, as C++ has no copy. + Clone, + /// Cloned: a local a closure takes by value from outside it, which may run again. + Cloned, + /// Moved, as `drop` does. + Drop, +} + +impl Use { + fn code(self) -> char { + match self { + Use::Read => 'R', + Use::Move => 'M', + Use::Clone => 'C', + Use::Cloned => 'K', + Use::Drop => 'D', + } + } +} + +/// A local marked as used: resolved once the whole script is written. +fn marker(name: &str, how: Use) -> String { + format!("\u{1}{}{}\u{2}", how.code(), ident(name)) +} + +/// `body` with each marked local resolved: moved at its last use, which C++ reads in text +/// order, as no closure the script defines runs after a later statement. +fn resolve(body: &str) -> String { + let markers = || { + let mut at = 0; + std::iter::from_fn(move || { + let start = at + body[at..].find('\u{1}')?; + let end = start + body[start..].find('\u{2}').unwrap(); + at = end + 1; + Some((start, end)) + }) + }; + let mut last = std::collections::BTreeMap::new(); + for (start, end) in markers() { + last.insert(&body[start + 2..end], start); + } + let mut out = String::new(); + let mut at = 0; + for (start, end) in markers() { + out.push_str(&body[at..start]); + let name = &body[start + 2..end]; + let is_last = last[name] == start; + let resolved = match (&body[start + 1..start + 2], is_last) { + ("R", _) | ("M", false) => name.to_string(), + ("M", true) | ("C", true) | ("D", _) => format!("std::move({name})"), + ("C", false) | ("K", _) => format!("{name}.clone()"), + (code, _) => unreachable!("a marker {code}"), + }; + out.push_str(&resolved); + at = end + 1; + } + out.push_str(&body[at..]); + out +} + +/// Where a value goes: what it may be written as, and whether a local there is moved. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Place { + /// An argument of a call, of the type its parameter takes, which C++ converts to. + Arg, + /// A value of its own: a local, or what a closure returns. + Own, + /// A value of its own inside another, of the type its field or element takes, which C++ + /// converts to. + Element, + /// Read in place, such as an operand or what a line prints. + Read, +} + +struct Emitter<'t> { + t: &'t Transcript, + depth: usize, + fresh: usize, + /// How many closures deep the script is. + level: usize, + /// Each local the script owns, and how many closures deep it is: a closure deeper + /// never moves it, as it may run again. + owned: Vec<(String, usize)>, + /// Each local some expression reads; any other is declared `[[maybe_unused]]`. + used: BTreeSet, +} + +/// C++'s keywords, which no name may be. +const KEYWORDS: &[&str] = &[ + "alignas", + "alignof", + "and", + "and_eq", + "asm", + "auto", + "bitand", + "bitor", + "bool", + "break", + "case", + "catch", + "char", + "char8_t", + "char16_t", + "char32_t", + "class", + "compl", + "concept", + "const", + "consteval", + "constexpr", + "constinit", + "const_cast", + "continue", + "co_await", + "co_return", + "co_yield", + "decltype", + "default", + "delete", + "do", + "double", + "dynamic_cast", + "else", + "enum", + "explicit", + "export", + "extern", + "false", + "float", + "for", + "friend", + "goto", + "if", + "inline", + "int", + "long", + "mutable", + "namespace", + "new", + "noexcept", + "not", + "not_eq", + "nullptr", + "operator", + "or", + "or_eq", + "private", + "protected", + "public", + "register", + "reinterpret_cast", + "requires", + "return", + "short", + "signed", + "sizeof", + "static", + "static_assert", + "static_cast", + "struct", + "switch", + "template", + "this", + "thread_local", + "throw", + "true", + "try", + "typedef", + "typeid", + "typename", + "union", + "unsigned", + "using", + "virtual", + "void", + "volatile", + "wchar_t", + "while", + "xor", + "xor_eq", + // What the script names unqualified, and the standard library's macros. + "api", + "std", + "rs", + "hook", + "transcript", + "assert", + "errno", + "stdin", + "stdout", + "stderr", + "major", + "minor", + "unix", + "linux", + "NULL", + "EOF", +]; + +/// A Rust name in C++, as the generated header escapes one. +fn ident(name: &str) -> String { + match name.chars().next() { + Some(c) if c.is_ascii_digit() => format!("_{name}"), + _ if KEYWORDS.contains(&name) => format!("{name}_"), + _ => name.to_string(), + } +} + +/// A method named after a trait's, `_` apart from its class of the same name. +fn apart(bare: &str, class: &str) -> String { + match bare == class { + true => format!("{bare}_"), + false => bare.to_string(), + } +} + +/// A Rust identifier in snake case, as the generated header names a variant. +fn snake(name: &str) -> String { + let chars: Vec = name.chars().collect(); + let mut out = String::new(); + for (i, &c) in chars.iter().enumerate() { + if c.is_uppercase() { + let prev = i.checked_sub(1).map(|j| chars[j]); + let next = chars.get(i + 1); + let boundary = match prev { + Some(p) if p.is_lowercase() || p.is_ascii_digit() => true, + Some(p) if p.is_uppercase() => next.is_some_and(|n| n.is_lowercase()), + _ => false, + }; + if boundary && !out.ends_with('_') { + out.push('_'); + } + out.extend(c.to_lowercase()); + } else { + out.push(c); + } + } + out +} + +fn cpp_int(int: Int) -> &'static str { + match int { + Int::U8 => "std::uint8_t", + Int::U16 => "std::uint16_t", + Int::U32 => "std::uint32_t", + Int::U64 => "std::uint64_t", + Int::Usize => "std::size_t", + Int::I8 => "std::int8_t", + Int::I16 => "std::int16_t", + Int::I32 => "std::int32_t", + Int::I64 => "std::int64_t", + Int::Isize => "std::ptrdiff_t", + } +} + +/// An integer literal any C++ integer converts from exactly. +fn int_literal(n: super::Num) -> String { + let m = n.magnitude; + match (n.negative, m) { + (false, m) if m <= i32::MAX as u128 => m.to_string(), + (false, m) if m <= i64::MAX as u128 => format!("{m}LL"), + (false, m) => format!("{m}ULL"), + (true, m) if m <= i32::MAX as u128 => format!("-{m}"), + (true, m) if m == 1 << 63 => "(-9223372036854775807LL - 1)".to_string(), + (true, m) => format!("-{m}LL"), + } +} + +impl Emitter<'_> { + fn indent(&self) -> String { + "\t".repeat(self.depth) + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("{what}{}_", self.fresh) + } + + fn line(&self, out: &mut String, line: &str) { + let _ = writeln!(out, "{}{line}", self.indent()); + } + + fn steps(&mut self, steps: &[Step]) -> String { + let mut out = String::new(); + for step in steps { + self.step(step, &mut out); + } + out + } + + fn step(&mut self, step: &Step, out: &mut String) { + match step { + Step::Let(Pat::Tuple(pats), value) if matches!(&value.kind, Kind::Tuple(_)) && is_tuple(&value.ty) => { + // A tuple built to be taken apart: each element bound in order. + let Kind::Tuple(elements) = &value.kind else { + unreachable!() + }; + for (pat, element) in pats.iter().zip(elements) { + self.step(&Step::Let(pat.clone(), element.clone()), out); + } + } + Step::Let(pat, value) => { + let v = self.value(value, &value.ty, Place::Own); + self.bind(pat, &v, &value.ty, out); + } + Step::Print(pieces) => { + let pieces = self.pieces(pieces); + self.line(out, &format!("rs::line({{{pieces}}});")); + } + Step::Do(value) => { + let v = self.value(value, &value.ty, Place::Read); + match unref(&value.ty) { + Type::Unit => self.line(out, &format!("{v};")), + _ => self.line(out, &format!("(void){v};")), + } + } + Step::Drop(name) => { + let gone = self.fresh("dropped"); + self.line( + out, + &format!("{{ [[maybe_unused]] auto {gone} = {}; }}", marker(name, Use::Drop)), + ); + } + Step::Match { value, ok, err } => { + let v = self.value(value, &value.ty, Place::Own); + let tmp = self.fresh("matched"); + self.line(out, "{"); + self.depth += 1; + self.line(out, &format!("auto {tmp} = {v};")); + let (ok_value, ok_ty, err_value, err_ty) = match &value.ty { + Type::Option(inner) => ( + format!("std::move(*{tmp})"), + (**inner).clone(), + String::new(), + Type::Unit, + ), + Type::Result(ok, err) => ( + format!("std::move(*{tmp})"), + (**ok).clone(), + format!("std::move({tmp}.error())"), + (**err).clone(), + ), + ty => panic!("a match on {ty:?}"), + }; + self.line(out, &format!("if ({tmp}) {{")); + self.depth += 1; + if let Some(pat) = &ok.pat { + self.bind(pat, &ok_value, &ok_ty, out); + } + let body = self.steps(&ok.steps); + out.push_str(&body); + self.depth -= 1; + self.line(out, "} else {"); + self.depth += 1; + if let Some(pat) = &err.pat { + self.bind(pat, &err_value, &err_ty, out); + } + let body = self.steps(&err.steps); + out.push_str(&body); + self.depth -= 1; + self.line(out, "}"); + self.depth -= 1; + self.line(out, "}"); + } + } + } + + /// `[[maybe_unused]] ` if nothing reads `name`. + fn unused(&self, name: &str) -> &'static str { + match self.used.contains(name) { + true => "", + false => "[[maybe_unused]] ", + } + } + + /// `pat` bound to the value `v` of type `ty`, each name a local the script owns. + fn bind(&mut self, pat: &Pat, v: &str, ty: &Type, out: &mut String) { + match pat { + Pat::Name(name, _) => { + self.owned.push((name.clone(), self.level)); + self.line(out, &format!("{}auto {} = {v};", self.unused(name), ident(name))); + } + Pat::Ignore(_) => self.line(out, &format!("(void){v};")), + Pat::Tuple(pats) => { + let tmp = self.fresh("tuple"); + self.line(out, &format!("auto {tmp} = {v};")); + let base = unref(ty).base(); + for (i, (pat, ty)) in pats.iter().zip(elements(base)).enumerate() { + let element = match is_tuple(base) { + true => format!("std::get<{i}>(std::move({tmp}))"), + false => member(&tmp, i), + }; + self.bind(pat, &element, &ty, out); + } + } + } + } + + /// `pat` bound to the value `v` of type `ty` by reference, each name a closure's. + fn bind_ref(&mut self, pat: &Pat, v: &str, ty: &Type, out: &mut String) { + match pat { + Pat::Name(name, _) => { + self.line(out, &format!("{}auto &&{} = {v};", self.unused(name), ident(name))); + } + Pat::Ignore(_) => {} + Pat::Tuple(pats) => { + let tmp = self.fresh("tuple"); + self.line(out, &format!("auto &&{tmp} = {v};")); + let tys = elements(ty); + for (i, pat) in pats.iter().enumerate() { + let element = match is_tuple(unref(ty).base()) { + true => format!("std::get<{i}>({tmp})"), + false => member(&tmp, i), + }; + self.bind_ref(pat, &element, &tys[i], out); + } + } + } + } + + /// The C++ of a format's pieces: the items of a braced list of strings. + fn pieces(&mut self, pieces: &[Piece]) -> String { + let mut parts = Vec::new(); + for piece in pieces { + match piece { + Piece::Text(text) => parts.push(string(text)), + Piece::Value(e, spec) => { + let v = self.value(e, &e.ty, Place::Read); + parts.push(self.show(&v, &e.ty, *spec)); + } + } + } + parts.join(", ") + } + + /// `v`, a value of `ty`, as a `std::string` the way Rust formats it with `spec`. + fn show(&mut self, v: &str, ty: &Type, spec: Spec) -> String { + let ty = unref(ty).base(); + match spec { + Spec::Hex(width) => return format!("rs::hex({v}, {width})"), + Spec::Padded(width) => return format!("rs::padded({v}, {width})"), + Spec::Debug => return self.debug(v, ty), + Spec::Display => {} + } + match ty { + Type::Bool => format!("rs::flag({v})"), + Type::String | Type::Str => format!("rs::text({v})"), + Type::Int(_) | Type::NonZero(_) => format!("std::to_string({v})"), + Type::Object(i) => { + let o = &self.t.api.objects[*i]; + let name = self.t.type_name(LANGUAGE, ty); + match o.methods.iter().position(|m| m.access == Access::Text) { + Some(index) => format!( + "rs::text({v}.{}())", + self.t.name( + LANGUAGE, + FnId { + owner: Owner::Object(*i), + index + } + ) + ), + None if o.traits.display => format!("rs::text({v}.{}())", apart("to_string", name)), + None => panic!("Display of {name}, which has none"), + } + } + Type::Record(i) if self.t.api.records[*i].traits.display => { + format!("rs::text({v}.{}())", apart("to_string", self.t.type_name(LANGUAGE, ty))) + } + Type::Enum(i) if self.t.api.enums[*i].traits.display => { + format!("rs::text(api::{}_to_string({v}))", self.t.type_name(LANGUAGE, ty)) + } + ty => panic!("Display of {ty:?}"), + } + } + + /// `v` as Rust's `Debug` prints a value of `ty`. + fn debug(&mut self, v: &str, ty: &Type) -> String { + match unref(ty).base() { + Type::Bool => format!("rs::flag({v})"), + Type::Int(_) | Type::NonZero(_) => format!("std::to_string({v})"), + Type::String | Type::Str => format!("rs::quoted({v})"), + Type::Option(inner) => { + let x = self.fresh("x"); + let show = self.debug(&x, inner); + format!("rs::option({v}, [&](const auto &{x}) {{ return {show}; }})") + } + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => format!("rs::bytes({v})"), + Type::List(_, item) => { + let x = self.fresh("x"); + let show = self.debug(&x, item); + format!("rs::list({v}, [&](const auto &{x}) {{ return {show}; }})") + } + Type::Tuple(elements) => { + let x = self.fresh("x"); + let parts: Vec = (0..elements.len()) + .map(|i| self.debug(&format!("std::get<{i}>({x})"), &elements[i])) + .collect(); + let tail = if parts.len() == 1 { ",)" } else { ")" }; + format!( + "[&](const auto &{x}) {{ return rs::cat({{\"(\", {}, \"{tail}\"}}); }}({v})", + parts.join(", \", \", ") + ) + } + Type::Bound(_) => format!("rs::bound({v})"), + ty @ (Type::Record(_) | Type::Object(_)) => { + format!("rs::text({v}.{}())", apart("debug", self.t.type_name(LANGUAGE, ty))) + } + ty @ Type::Enum(_) => format!("rs::text(api::{}_debug({v}))", self.t.type_name(LANGUAGE, ty)), + ty => panic!("Debug of {ty:?}"), + } + } + + /// The C++ type of a value of `ty`, owning what it holds, as the header returns one. + fn ctype(&self, ty: &Type) -> String { + match ty { + Type::Unit => "void".to_string(), + Type::Bool => "bool".to_string(), + Type::Int(int) | Type::NonZero(int) => cpp_int(*int).to_string(), + Type::F32 => "float".to_string(), + Type::F64 => "double".to_string(), + Type::Char => "char32_t".to_string(), + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => { + "api::buf".to_string() + } + Type::Array(n) => format!("std::array"), + Type::U128 => "api::u128".to_string(), + Type::Duration => "api::duration".to_string(), + Type::SocketAddr(family) => format!("api::{}", addr(true, *family)), + Type::IpAddr(family) => format!("api::{}", addr(false, *family)), + Type::List(_, inner) => format!("std::vector<{}>", self.ctype(inner)), + Type::Option(inner) => format!("std::optional<{}>", self.ctype(inner)), + Type::Box(inner) | Type::Ref(_, inner) => self.ctype(inner), + ty @ (Type::Record(_) | Type::Enum(_) | Type::Object(_)) => { + format!("api::{}", self.t.type_name(LANGUAGE, ty)) + } + Type::Range(int) => format!("api::range_{}", int.rust()), + Type::Bound(int) => format!("api::bound_{}", int.rust()), + Type::Bounds(int) => format!("api::bounds_{}", int.rust()), + Type::Tuple(elements) => { + let elements: Vec = elements.iter().map(|e| self.ctype(e)).collect(); + format!("std::tuple<{}>", elements.join(", ")) + } + ty => panic!("no C++ type of {ty:?}"), + } + } + + /// Whether C++ copies a value of `ty`, as it does every value but a handle's. + fn copyable(&self, ty: &Type) -> bool { + self.copyable_in(ty, &mut Vec::new()) + } + + fn copyable_in(&self, ty: &Type, seen: &mut Vec) -> bool { + if seen.contains(ty) { + return true; + } + seen.push(ty.clone()); + let api = &self.t.api; + match ty { + Type::Object(i) => api.objects[*i].shared, + Type::Record(i) => { + api.records[*i].opaque.is_some() || api.records[*i].fields.iter().all(|f| self.copyable_in(&f.ty, seen)) + } + Type::Enum(i) => api.enums[*i] + .variants + .iter() + .flat_map(|v| &v.fields) + .all(|f| self.copyable_in(&f.ty, seen)), + Type::Callback(..) | Type::Closure(_) | Type::Reader | Type::Future => false, + Type::Option(inner) | Type::Box(inner) | Type::List(_, inner) => self.copyable_in(inner, seen), + Type::Ref(_, inner) => self.copyable_in(inner, seen), + Type::Tuple(elements) => elements.iter().all(|e| self.copyable_in(e, seen)), + _ => true, + } + } + + /// Whether the parameter type `ty` is a pointer in C++, null for `None`. + fn pointer(&self, ty: &Type) -> bool { + match ty { + Type::Option(inner) => match &**inner { + Type::Ref(_, object) => matches!(**object, Type::Object(_)), + Type::Object(i) => self.t.api.objects[*i].copy, + _ => false, + }, + Type::Ref(_, inner) | Type::Box(inner) => self.pointer(inner), + _ => false, + } + } + + /// Whether a call reads a local passed for the parameter type `ty` in place, rather than + /// taking it. + fn reads(&self, ty: &Type) -> bool { + match ty { + Type::Ref(..) => true, + // A `Copy` handle, which C++ takes by reference and copies out of. + Type::Object(i) => self.t.api.objects[*i].copy, + _ => false, + } + } + + /// A local `name` of type `ty`, used as `place` takes it. + fn var(&self, name: &str, ty: &Type, place: Place, want: &Type) -> String { + let read = match place { + Place::Read => true, + Place::Arg => self.reads(want), + Place::Own | Place::Element => false, + }; + if read { + return marker(name, Use::Read); + } + let owned = self + .owned + .iter() + .rev() + .find(|(n, _)| n == name) + .is_some_and(|(_, level)| *level == self.level); + let copyable = self.copyable(unref(ty)); + let handle = matches!(unref(ty).base(), Type::Object(_)); + let how = match (owned, copyable, handle) { + (true, true, _) => Use::Move, + (true, false, true) => Use::Clone, + (true, false, false) => Use::Move, + (false, true, _) => Use::Read, + (false, false, true) => Use::Cloned, + (false, false, false) => panic!("a copy of {name}, whose {ty:?} C++ cannot copy"), + }; + marker(name, how) + } + + /// The C++ of `e` as `place` takes it, where a value of type `want` goes. + fn value(&mut self, e: &Expr, want: &Type, place: Place) -> String { + // An address of one family where either is taken, as `.into()` makes one. + match (unref(&e.ty).base(), unref(want).base()) { + (Type::SocketAddr(Family::V4 | Family::V6), Type::SocketAddr(Family::Any)) + if !matches!(e.kind, Kind::Socket(_)) => + { + return format!("rs::socket({})", self.kind(e, &e.ty, place)); + } + (Type::IpAddr(Family::V4 | Family::V6), Type::IpAddr(Family::Any)) if !matches!(e.kind, Kind::Ip(_)) => { + return format!("rs::ip({})", self.kind(e, &e.ty, place)); + } + _ => {} + } + self.kind(e, want, place) + } + + fn kind(&mut self, e: &Expr, want: &Type, place: Place) -> String { + match &e.kind { + Kind::Unit => panic!("a unit value"), + Kind::Bool(b) => b.to_string(), + Kind::Int(n) => match unref(want).base() { + Type::U128 => { + let bits = match n.negative { + true => panic!("a negative u128"), + false => n.magnitude, + }; + format!("api::u128{{{}ULL, {}ULL}}", bits as u64, (bits >> 64) as u64) + } + Type::Int(int) | Type::NonZero(int) if place == Place::Own => { + format!("{}{{{}}}", cpp_int(*int), int_literal(*n)) + } + _ => int_literal(*n), + }, + Kind::Float(f) => match unref(want).base() { + Type::F32 => format!("rs::f32({:#x})", (*f as f32).to_bits()), + _ if !f.is_finite() || (*f == 0.0 && f.is_sign_negative()) => format!("rs::f64({:#x}ULL)", f.to_bits()), + _ => format!("{f:?}"), + }, + Kind::Char(c) => format!("char32_t{{{:#x}}}", *c as u32), + Kind::Str(s) => match place { + Place::Arg if !s.contains('\0') => string(s), + _ => format!("api::buf(api::view({}, {}))", string(s), s.len()), + }, + Kind::Bytes(b) => match unref(want).base() { + Type::Array(n) => { + let items: Vec = b.iter().map(|b| b.to_string()).collect(); + format!("std::array{{{{{}}}}}", items.join(", ")) + } + _ if place == Place::Arg => format!("api::view({}, {})", bytes(b), b.len()), + _ => format!("api::buf(api::view({}, {}))", bytes(b), b.len()), + }, + Kind::Duration(secs, nanos) => format!( + "api::duration{{{}, {nanos}}}", + int_literal(super::Num::new(*secs as i128)) + ), + Kind::Socket(addr) => { + let family = match unref(want).base() { + Type::SocketAddr(family) => *family, + ty => panic!("a socket address as {ty:?}"), + }; + let inner = match addr { + std::net::SocketAddr::V4(a) => { + format!("api::socket_addr_v4{{{}, {}}}", ipv4(a.ip()), a.port()) + } + std::net::SocketAddr::V6(a) => format!( + "api::socket_addr_v6{{{}, {}, {}, {}}}", + ipv6(a.ip()), + a.port(), + int_literal(super::Num::new(a.flowinfo() as i128)), + int_literal(super::Num::new(a.scope_id() as i128)) + ), + }; + match (family, addr) { + (Family::Any, _) => format!("rs::socket({inner})"), + (Family::V4, std::net::SocketAddr::V4(_)) | (Family::V6, std::net::SocketAddr::V6(_)) => inner, + _ => panic!("a socket address of another family than {family:?}"), + } + } + Kind::Ip(ip) => { + let family = match unref(want).base() { + Type::IpAddr(family) => *family, + ty => panic!("an IP address as {ty:?}"), + }; + let inner = match ip { + std::net::IpAddr::V4(ip) => ipv4(ip), + std::net::IpAddr::V6(ip) => ipv6(ip), + }; + match (family, ip) { + (Family::Any, _) => format!("rs::ip({inner})"), + (Family::V4, std::net::IpAddr::V4(_)) | (Family::V6, std::net::IpAddr::V6(_)) => inner, + _ => panic!("an IP address of another family than {family:?}"), + } + } + Kind::None => match place { + Place::Arg if self.pointer(want) => "nullptr".to_string(), + Place::Arg => "std::nullopt".to_string(), + _ => format!("{}{{}}", self.ctype(&option_of(want, &e.ty))), + }, + Kind::Some(inner) => { + let option = option_of(want, &e.ty); + let Type::Option(inner_want) = &option else { + unreachable!() + }; + if place == Place::Arg && self.pointer(want) { + return match &inner.kind { + Kind::Var(name) => format!("&{}", marker(name, Use::Read)), + _ => format!("rs::ptr({})", self.value(inner, inner_want, Place::Read)), + }; + } + // An argument converts to the optional its parameter takes, unless what it holds + // is optional too. + match (place, unref(inner_want).base()) { + (Place::Arg, Type::Option(_)) | (Place::Own | Place::Element | Place::Read, _) => { + let v = self.value(inner, inner_want, Place::Element); + format!("{}({v})", self.ctype(&option)) + } + (Place::Arg, _) => self.value(inner, inner_want, Place::Arg), + } + } + Kind::Tuple(elements) => match unref(&e.ty).base() { + Type::Range(int) => { + let (a, b) = ( + self.value(&elements[0], &Type::Int(*int), Place::Arg), + self.value(&elements[1], &Type::Int(*int), Place::Arg), + ); + format!("api::range_{}{{{a}, {b}}}", int.rust()) + } + Type::Bounds(int) => { + let (a, b) = ( + self.value(&elements[0], &Type::Bound(*int), Place::Arg), + self.value(&elements[1], &Type::Bound(*int), Place::Arg), + ); + format!("api::bounds_{}{{{a}, {b}}}", int.rust()) + } + _ => { + let tuple = match unref(want).base() { + ty @ Type::Tuple(_) => ty.clone(), + _ => unref(&e.ty).base().clone(), + }; + let wants = elements_of(&tuple); + let parts: Vec = elements + .iter() + .zip(&wants) + .map(|(e, t)| self.value(e, t, Place::Element)) + .collect(); + format!("{}({})", self.ctype(&tuple), parts.join(", ")) + } + }, + Kind::List(items) => { + let item = match unref(want).base() { + Type::List(_, item) => (**item).clone(), + _ => match unref(&e.ty).base() { + Type::List(_, item) => (**item).clone(), + ty => panic!("a list as {ty:?}"), + }, + }; + let ty = self.ctype(&item); + match items.is_empty() { + true => format!("std::vector<{ty}>{{}}"), + false => { + let parts: Vec = items.iter().map(|e| self.value(e, &item, Place::Element)).collect(); + format!("rs::vec<{ty}>({})", parts.join(", ")) + } + } + } + Kind::Record(r, fields) => { + let ty = Type::Record(*r); + if self.t.api.records[*r].opaque.is_some() { + panic!( + "a literal of {}, which C++ makes only by its functions", + self.t.type_name(LANGUAGE, &ty) + ); + } + let name = self.t.type_name(LANGUAGE, &ty).to_string(); + let field_types: Vec = self.t.api.records[*r].fields.iter().map(|f| f.ty.clone()).collect(); + let args: Vec = fields + .iter() + .zip(&field_types) + .map(|(f, ty)| self.value(f, ty, Place::Element)) + .collect(); + format!("api::{name}{{{}}}", args.join(", ")) + } + Kind::Variant(en, v, fields) => { + let name = self.t.type_name(LANGUAGE, &Type::Enum(*en)).to_string(); + let enumeration = &self.t.api.enums[*en]; + let variant = &enumeration.variants[*v]; + if enumeration.variants.iter().all(|v| v.fields.is_empty()) { + return format!("api::{name}::{}", ident(&snake(&variant.name))); + } + let field_types: Vec = variant.fields.iter().map(|f| f.ty.clone()).collect(); + let variant_name = variant.name.clone(); + let args: Vec = fields + .iter() + .zip(&field_types) + .map(|(f, ty)| self.value(f, ty, Place::Element)) + .collect(); + format!("api::{name}_{variant_name}{{{}}}", args.join(", ")) + } + Kind::Bound(kind, value) => { + let Type::Bound(int) = unref(&e.ty) else { + panic!("a bound of {:?}", e.ty) + }; + let (kind, v) = match (kind, value) { + (BoundKind::Unbounded, _) => ("UNBOUNDED", "0".to_string()), + (BoundKind::Included, Some(v)) => ("INCLUDED", self.value(v, &Type::Int(*int), Place::Arg)), + (BoundKind::Excluded, Some(v)) => ("EXCLUDED", self.value(v, &Type::Int(*int), Place::Arg)), + _ => unreachable!(), + }; + format!("api::bound_{}{{API_BOUND_{kind}, {v}}}", int.rust()) + } + Kind::Default => { + let ty = unref(&e.ty).base(); + let name = self.t.type_name(LANGUAGE, ty).to_string(); + match ty { + Type::Enum(_) => format!("api::{name}_default()"), + _ => format!("api::{name}::{}()", apart("default_", &name)), + } + } + Kind::Var(name) => self.var(name, &e.ty, place, want), + Kind::Const(c) => format!( + "api::{}", + self.t + .named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::"))) + ), + Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args), + Kind::Field(base, i) => { + let b = self.base(base, place); + let Type::Record(r) = unref(&base.ty).base() else { + panic!("a field of {:?}", base.ty) + }; + format!("{b}.{}", ident(&self.t.api.records[*r].fields[*i].name)) + } + Kind::Element(base, i) => { + let b = self.base(base, place); + match is_tuple(unref(&base.ty).base()) { + true => format!("std::get<{i}>({b})"), + false => member(&b, *i), + } + } + Kind::Clone(inner) => { + let v = self.value(inner, &inner.ty, Place::Read); + match unref(&inner.ty).base() { + // What a call returned is a value of its own already. + ty if !self.copyable(ty) && matches!(inner.kind, Kind::Call(..) | Kind::Local(..)) => v, + ty => { + let ty = ty.clone(); + self.cloned(&v, &ty) + } + } + } + Kind::Unwrap(inner) => { + let v = self.unwrapped(inner, place); + match &inner.ty { + Type::Result(..) => format!("{v}.value()"), + _ => format!("rs::some({v})"), + } + } + Kind::UnwrapErr(inner) => { + let v = self.unwrapped(inner, place); + format!("{v}.error()") + } + Kind::IsErr(inner) | Kind::IsNone(inner) => { + format!("!{}.has_value()", self.value(inner, &inner.ty, Place::Read)) + } + Kind::IsSome(inner) => format!("{}.has_value()", self.value(inner, &inner.ty, Place::Read)), + Kind::Binary(op, a, b) => { + let (a, b) = (self.value(a, &a.ty, Place::Read), self.value(b, &b.ty, Place::Read)); + let (op, arithmetic) = match op { + Op::Eq => ("==", false), + Op::Ne => ("!=", false), + Op::Lt => ("<", false), + Op::Gt => (">", false), + Op::And => ("&&", false), + Op::Add => ("+", true), + Op::Sub => ("-", true), + Op::Mul => ("*", true), + Op::Rem => ("%", true), + }; + match arithmetic { + true => format!("static_cast<{}>({a} {op} {b})", self.ctype(unref(&e.ty))), + false => format!("({a} {op} {b})"), + } + } + Kind::Closure(params, steps, value) => self.closure(params, steps, value), + Kind::Local(name, args) => match unref(&e.ty).base() { + // A unit struct implementing a callback, owned by Rust once passed. + Type::Callback(..) if args.is_empty() => format!("std::make_unique()"), + _ => { + let args: Vec = args.iter().map(|a| self.value(a, &a.ty, Place::Arg)).collect(); + format!("hook::{name}({})", args.join(", ")) + } + }, + Kind::Format(pieces) => format!("rs::cat({{{}}})", self.pieces(pieces)), + Kind::Join { items, pat, body, sep } => { + let items_v = self.value(items, &items.ty, Place::Read); + let item_ty = match unref(&items.ty).base() { + Type::List(_, item) => (**item).clone(), + ty => panic!("a join over {ty:?}"), + }; + let lambda = self.lambda(&[(pat.clone(), item_ty)], &[], body, true); + format!("rs::join({items_v}, {}, {lambda})", string(sep)) + } + Kind::MapOr { + option, + none, + pat, + some, + } => { + let o = self.value(option, &option.ty, Place::Read); + let Type::Option(inner) = unref(&option.ty).base() else { + panic!("map_or of {:?}", option.ty) + }; + let inner = (**inner).clone(); + let text = matches!(unref(&e.ty).base(), Type::String | Type::Str); + let normal = |v: String| match text { + true => format!("rs::text({v})"), + false => v, + }; + let none_v = normal(self.value(none, &e.ty, Place::Own)); + let tmp = self.fresh("option"); + self.depth += 1; + self.level += 1; + let mut body = String::new(); + self.line(&mut body, &format!("auto &&{tmp} = {o};")); + self.line(&mut body, &format!("if (!{tmp}) {{")); + self.depth += 1; + self.line(&mut body, &format!("return {none_v};")); + self.depth -= 1; + self.line(&mut body, "}"); + self.bind_ref(pat, &format!("*{tmp}"), &inner, &mut body); + let some_v = normal(self.value(some, &e.ty, Place::Own)); + self.line(&mut body, &format!("return {some_v};")); + self.level -= 1; + self.depth -= 1; + format!("[&]() {{\n{body}{}}}()", self.indent()) + } + Kind::Utf8(inner) => format!("rs::text({})", self.value(inner, &inner.ty, Place::Read)), + Kind::Len(inner) => format!("{}.size()", self.value(inner, &inner.ty, Place::Read)), + } + } + + /// Rust's `Clone` of `v`, a value of `ty`: a C++ copy, a handle's `clone()`, or a + /// record's fields each cloned. + fn cloned(&mut self, v: &str, ty: &Type) -> String { + match ty { + Type::Object(i) if !self.t.api.objects[*i].shared => { + format!("{v}.{}()", apart("clone", self.t.type_name(LANGUAGE, ty))) + } + ty if self.copyable(ty) => v.to_string(), + Type::Record(r) => { + let x = self.fresh("x"); + let fields: Vec<(String, Type)> = self.t.api.records[*r] + .fields + .iter() + .map(|f| (ident(&f.name), f.ty.clone())) + .collect(); + let fields: Vec = fields + .iter() + .map(|(name, ty)| self.cloned(&format!("{x}.{name}"), ty)) + .collect(); + format!( + "[&](const auto &{x}) {{ return {}{{{}}}; }}({v})", + self.ctype(ty), + fields.join(", ") + ) + } + ty => panic!("a clone of {ty:?}, which C++ cannot copy"), + } + } + + /// The base of a field or an element: a local moves only where its field moves out. + fn base(&mut self, base: &Expr, place: Place) -> String { + match (&base.kind, place) { + (Kind::Var(name), Place::Own | Place::Element) => { + let owned = self + .owned + .iter() + .rev() + .find(|(n, _)| n == name) + .is_some_and(|(_, level)| *level == self.level); + marker(name, if owned { Use::Move } else { Use::Read }) + } + _ => self.value(base, &base.ty, Place::Read), + } + } + + /// What an `unwrap` takes apart: a local moves out where it is the value's own. + fn unwrapped(&mut self, inner: &Expr, place: Place) -> String { + match place { + Place::Read => self.value(inner, &inner.ty, Place::Read), + _ => self.base(inner, Place::Own), + } + } + + /// A closure: a lambda taking each parameter by reference, which runs `steps`, then + /// returns `value`. + fn closure(&mut self, params: &[Pat], steps: &[super::Step], value: &Expr) -> String { + let params: Vec<(Pat, Type)> = params.iter().map(|p| (p.clone(), pat_type(p))).collect(); + self.lambda(¶ms, steps, value, false) + } + + /// A lambda of `params`, running `steps`, then returning `value`, as a string if `text`. + fn lambda(&mut self, params: &[(Pat, Type)], steps: &[Step], value: &Expr, text: bool) -> String { + self.level += 1; + self.depth += 1; + let mut body = String::new(); + let mut names = Vec::new(); + for (pat, ty) in params { + match pat { + // An object lent `&mut`, which C++ lends as a borrow. + Pat::Name(name, Type::Ref(Mutability::Mut, inner)) if matches!(**inner, Type::Object(_)) => { + let lent = self.fresh("lent"); + names.push(format!("auto &&{lent}")); + self.line( + &mut body, + &format!("{}auto &{} = rs::lent({lent});", self.unused(name), ident(name)), + ); + } + Pat::Name(name, _) => names.push(format!("{}auto &&{}", self.unused(name), ident(name))), + Pat::Ignore(_) => names.push("auto &&".to_string()), + Pat::Tuple(_) => { + let tuple = self.fresh("item"); + names.push(format!("auto &&{tuple}")); + self.bind_ref(pat, &tuple, ty, &mut body); + } + } + } + let steps = self.steps(steps); + body.push_str(&steps); + let returned = match (&value.kind, text) { + (Kind::Unit, _) => None, + (_, true) => Some(format!("rs::text({})", self.value(value, &value.ty, Place::Own))), + (_, false) => Some(self.value(value, &value.ty, Place::Own)), + }; + self.depth -= 1; + self.level -= 1; + let params = names.join(", "); + match (body.is_empty(), returned) { + (true, Some(v)) if !v.contains('\n') => format!("[&]({params}) {{ return {v}; }}"), + (_, returned) => { + if let Some(v) = returned { + self.depth += 1; + self.line(&mut body, &format!("return {v};")); + self.depth -= 1; + } + format!("[&]({params}) {{\n{body}{}}}", self.indent()) + } + } + } + + /// A call of `id`: a function of the namespace, an associated function of a type, a + /// method, or a field's getter or setter. + fn call(&mut self, id: FnId, receiver: Option<&Expr>, args: &[Expr]) -> String { + let f = self.t.function(id); + if f.future { + panic!("a call of {}, a future, which only a hook awaits", self.t.key(id)); + } + let name = self.t.name(LANGUAGE, id).to_string(); + let params: Vec = f.params.iter().map(|p| p.ty.clone()).collect(); + let receives = f.receiver; + // C++ takes no unit. + let args: Vec = args + .iter() + .zip(¶ms) + .filter(|(_, ty)| **ty != Type::Unit) + .map(|(a, ty)| self.value(a, ty, Place::Arg)) + .collect(); + let args = args.join(", "); + let owner = self.t.owner(id); + match (id.owner, receiver) { + (Owner::Free, _) => format!("api::{name}({args})"), + // An enum's methods are functions of the namespace, taking it first. + (Owner::Enum(_), Some(r)) => { + let r = self.value(r, &r.ty, Place::Read); + match args.is_empty() { + true => format!("api::{name}({r})"), + false => format!("api::{name}({r}, {args})"), + } + } + (Owner::Enum(_), None) => format!("api::{name}({args})"), + (_, Some(r)) => { + // A handle's method taking `self` moves it out, unless it is `Copy`. + let moves = match (receives, unref(&r.ty).base()) { + (Some(Receiver::Owned), Type::Object(i)) => !self.t.api.objects[*i].copy, + _ => false, + }; + let r = match (&r.kind, moves) { + (Kind::Var(name), true) => marker(name, Use::Move), + _ => self.value(r, &r.ty, Place::Read), + }; + format!("{r}.{name}({args})") + } + (_, None) => { + let owner = owner.unwrap(); + format!("api::{}::{name}({args})", self.t.type_name(LANGUAGE, &owner)) + } + } + } +} + +/// Whether `ty` is a tuple in C++, whose elements `std::get` reads, rather than a range's or +/// bounds' members. +fn is_tuple(ty: &Type) -> bool { + matches!(ty, Type::Tuple(_)) +} + +/// The type a pattern binds. +fn pat_type(pat: &Pat) -> Type { + match pat { + Pat::Name(_, ty) | Pat::Ignore(ty) => ty.clone(), + Pat::Tuple(pats) => Type::Tuple(pats.iter().map(pat_type).collect()), + } +} + +/// The `i`th member of a range or bounds. +fn member(v: &str, i: usize) -> String { + match i { + 0 => format!("{v}.start"), + 1 => format!("{v}.end"), + _ => panic!("a range's element {i}"), + } +} + +/// The types of the elements of a tuple, a range, or bounds. +fn elements(ty: &Type) -> Vec { + elements_of(unref(ty).base()) +} + +fn elements_of(ty: &Type) -> Vec { + match ty { + Type::Tuple(elements) => elements.clone(), + Type::Range(int) => vec![Type::Int(*int); 2], + Type::Bounds(int) => vec![Type::Bound(*int); 2], + ty => panic!("the elements of {ty:?}"), + } +} + +/// The option type of a `Some` or a `None` going where `want` is taken. +fn option_of(want: &Type, own: &Type) -> Type { + match unref(want).base() { + ty @ Type::Option(_) => ty.clone(), + _ => match unref(own).base() { + ty @ Type::Option(_) => ty.clone(), + ty => panic!("an option as {ty:?}"), + }, + } +} + +fn addr(socket: bool, family: Family) -> &'static str { + match (socket, family) { + (true, Family::Any) => "socket_addr", + (true, Family::V4) => "socket_addr_v4", + (true, Family::V6) => "socket_addr_v6", + (false, Family::Any) => "ip_addr", + (false, Family::V4) => "ipv4_addr", + (false, Family::V6) => "ipv6_addr", + } +} + +fn ipv4(ip: &std::net::Ipv4Addr) -> String { + let octets: Vec = ip.octets().iter().map(|o| o.to_string()).collect(); + format!("api::ipv4_addr{{{{{}}}}}", octets.join(", ")) +} + +fn ipv6(ip: &std::net::Ipv6Addr) -> String { + let octets: Vec = ip.octets().iter().map(|o| o.to_string()).collect(); + format!("api::ipv6_addr{{{{{}}}}}", octets.join(", ")) +} + +/// A C++ string literal of `s`'s UTF-8, each byte past ASCII's printable ones escaped. +fn string(s: &str) -> String { + bytes(s.as_bytes()) +} + +/// A C++ string literal of `b`, each byte past ASCII's printable ones in octal, which takes +/// no more than three digits. +fn bytes(b: &[u8]) -> String { + let mut out = String::from("\""); + for &byte in b { + match byte { + b'"' | b'\\' => { + out.push('\\'); + out.push(byte as char); + } + b'\n' => out.push_str("\\n"), + b'\t' => out.push_str("\\t"), + b'\r' => out.push_str("\\r"), + // `??` begins a trigraph before C++17. + b'?' if out.ends_with('?') => out.push_str("\\?"), + 0x20..0x7f => out.push(byte as char), + _ => { + let _ = write!(out, "\\{byte:03o}"); + } + } + } + out.push('"'); + out +} diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 79879ef50..b41a99d18 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -11,6 +11,7 @@ //! as its futures, or prints a value no binding shapes alike, such as `hex`. Anything else //! fails, naming its line. +pub(crate) mod cpp; pub(crate) mod ir; mod parse; pub(crate) mod python; From 89610279f8e0c12ec4364beef376842a49e9eb49 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:12:48 -0800 Subject: [PATCH 12/28] wip: generate the C transcript tests/fixtures/transcript/c.rs emits transcript.c from the typed transcript, which tests/api.c includes after the transcript's own functions; api.c keeps only those and the checks its output does not show. Co-Authored-By: Claude Opus 5.5 --- ffi/src/c.rs | 63 +- ffi/src/glue.rs | 3 +- ffi/tests/api.c | 1956 ++++---------------- ffi/tests/fixtures.rs | 15 +- ffi/tests/fixtures/transcript/c.rs | 2271 ++++++++++++++++++++++++ ffi/tests/fixtures/transcript/mod.rs | 14 +- ffi/tests/fixtures/transcript/parse.rs | 35 +- 7 files changed, 2699 insertions(+), 1658 deletions(-) create mode 100644 ffi/tests/fixtures/transcript/c.rs diff --git a/ffi/src/c.rs b/ffi/src/c.rs index 38d2f2218..fb612bfef 100644 --- a/ffi/src/c.rs +++ b/ffi/src/c.rs @@ -1,6 +1,6 @@ //! The C header: the declarations of everything [`crate::glue`] defines. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::hash::Hasher; use rustc_data_structures::stable_hash::StableHasher; @@ -8,15 +8,17 @@ use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, Sig, Ty}; use crate::ir::{Function, Int, Literal, Receiver, Traits, Type}; -/// The header for `abi`, as `.h`, and its contract: a hash of what it declares, -/// which the library returns from `_contract`. -pub(crate) fn header(abi: &Abi<'_>, packages: &str) -> (String, u64) { +/// The header for `abi`, as `.h`, its contract: a hash of what it declares, which +/// the library returns from `_contract`, and the C names it gives each item. +pub(crate) fn header(abi: &Abi<'_>, packages: &str) -> (String, u64, BTreeMap) { let mut h = Header { abi, out: String::new(), defined: BTreeSet::new(), + names: BTreeMap::new(), }; h.write(); + h.name_items(); // Platform independent, so a header names the same contract wherever it is generated. let mut hasher = StableHasher::new(); hasher.write(h.out.as_bytes()); @@ -37,7 +39,7 @@ pub(crate) fn header(abi: &Abi<'_>, packages: &str) -> (String, u64) { #endif /* {guard} */\n", body = h.out, ); - (header, contract) + (header, contract, h.names) } struct Header<'a> { @@ -45,9 +47,59 @@ struct Header<'a> { out: String, /// The value structs written so far, so each is written after what it holds. defined: BTreeSet, + /// The C name of each item, by its key, as every binding's names are kept. + names: BTreeMap, } impl Header<'_> { + /// Record the C name of each type, its fields and variants, constant, and tuple; each + /// function's is recorded as it is declared. `prefix` keys the prefix itself, which the + /// structs of options, lists, and ranges are named after. + fn name_items(&mut self) { + let abi = self.abi; + let api = abi.api; + let identity: HashMap = (0..api.records.len()) + .map(|i| abi.record(i)) + .chain((0..api.enums.len()).map(|i| abi.enumeration(i))) + .chain((0..api.objects.len()).map(|i| abi.object(i))) + .chain((0..api.callbacks.len()).map(|i| abi.callback(i))) + .map(|name| (name.clone(), name)) + .collect(); + self.names.extend(crate::lock::types(abi, &identity)); + self.names.insert("prefix".to_string(), abi.prefix.clone()); + for record in &api.records { + for field in &record.fields { + let key = format!("{} / field {}", crate::lock::type_key(&record.shown), field.name); + self.names.insert(key, abi::escape(&field.name)); + } + } + for (i, e) in api.enums.iter().enumerate() { + let upper = abi.enumeration(i).to_uppercase(); + for v in &e.variants { + let owner = crate::lock::type_key(&e.shown); + let snake = abi::snake(&v.name); + let constant = format!("{upper}_{}", snake.to_uppercase()); + self.names.insert(format!("{owner} / variant {}", v.name), constant); + if !v.fields.is_empty() { + self.names + .insert(format!("{owner} / member {}", v.name), abi::escape(&snake)); + } + for field in &v.fields { + let key = format!("{owner} / variant {} / field {}", v.name, field.name); + self.names.insert(key, abi::escape(&field.name)); + } + } + } + for constant in &api.constants { + let key = format!("const {}", constant.path.join("::")); + self.names.insert(key, abi.constant(&constant.path)); + } + for (name, elements) in &abi.tuples { + let key = format!("tuple {}", abi.spell(&Type::Tuple(elements.clone()))); + self.names.insert(key, name.clone()); + } + } + fn line(&mut self, line: impl AsRef) { self.out.push_str(line.as_ref()); self.out.push('\n'); @@ -464,6 +516,7 @@ impl Header<'_> { fn function(&mut self, function: &Function, owner: Option<&Ty>) { let export = self.abi.export(function, owner); + crate::lock::function(&mut self.names, function, &export.call.name); let mut docs = function.docs.clone(); // What the call moves out of the caller's handles, which are then only freed. // A handle taken by value: one taken `&mut` is not `const` either, but stays. diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 11896a261..99cdd7fc5 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -362,7 +362,7 @@ impl Crate<'_> { // Only Kotlin passes a JNI value, so every other language exports the rest. let rest = self.abi.api.without_jni(); let rest = self.abi.without_jni(&rest); - let (header, contract) = crate::c::header(&rest, &self.packages()); + let (header, contract, c) = crate::c::header(&rest, &self.packages()); let cpp = crate::cpp::headers(&rest, &self.packages())?; let kotlin = crate::kotlin::generate(self.abi, &self.packages(), contract)?; let python = crate::python::generate(&rest, &self.packages(), contract)?; @@ -372,6 +372,7 @@ impl Crate<'_> { let dart = crate::dart::generate(&rest, &self.packages(), contract)?; let web = crate::web::generate(&rest, &self.packages(), contract)?; let mut names: std::collections::BTreeMap> = [ + ("C", c), ("C++", cpp.names), ("Kotlin", kotlin.names), ("Python", python.names), diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 283cf1114..3113d1263 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1,6 +1,10 @@ /* The api fixture's C test: the script fixtures/api/examples/transcript.rs runs * natively, through the exported C ABI. tests/fixtures.rs compares the transcripts. * + * The script is transcript.c, which tests/fixtures/transcript generates from the + * transcript's; this file holds the functions it calls by the transcript's names, and + * the checks its output does not show. + * * With an argument, it instead breaks one contract of the ABI, which must abort. */ #include @@ -27,64 +31,6 @@ static void print(const char *before, api_buf buf, const char *after) { api_buf_free(buf); } -/* Print each of `numbers`' lists, its floats as their bits, as transcript.rs does. */ -#define PRINT_LIST(list, fmt, cast) \ - do { \ - printf("["); \ - for (size_t i_ = 0; i_ < (list).len; i_++) { \ - printf(i_ ? ", " fmt : fmt, cast((list).ptr[i_])); \ - } \ - printf("]"); \ - } while (0) - -static unsigned long long f32_bits(float f) { - uint32_t bits; - memcpy(&bits, &f, sizeof bits); - return bits; -} - -static unsigned long long f64_bits(double f) { - uint64_t bits; - memcpy(&bits, &f, sizeof bits); - return bits; -} - -static void numbers(const char *what, const api_Numbers *n) { - printf("%s u16 ", what); - PRINT_LIST(n->u16s, "%u", (unsigned)); - printf("\n"); - printf("%s u32 ", what); - PRINT_LIST(n->u32s, "%u", (unsigned)); - printf("\n"); - printf("%s u64 ", what); - PRINT_LIST(n->u64s, "%llu", (unsigned long long)); - printf("\n"); - printf("%s i8 ", what); - PRINT_LIST(n->i8s, "%d", (int)); - printf("\n"); - printf("%s i16 ", what); - PRINT_LIST(n->i16s, "%d", (int)); - printf("\n"); - printf("%s i32 ", what); - PRINT_LIST(n->i32s, "%d", (int)); - printf("\n"); - printf("%s i64 ", what); - PRINT_LIST(n->i64s, "%lld", (long long)); - printf("\n"); - printf("%s f32 ", what); - PRINT_LIST(n->f32s, "%llu", f32_bits); - printf("\n"); - printf("%s f64 ", what); - PRINT_LIST(n->f64s, "%llu", f64_bits); - printf("\n"); - if (n->some.ptr) { - printf("%s some Some(", what); - PRINT_LIST(n->some, "%d", (int)); - printf(")\n"); - } else { - printf("%s some None\n", what); - } -} static int wakes = 0; static int drops = 0; @@ -236,30 +182,6 @@ static bool started_futures(void) { return ok; } -/* made's closure: a string it hands Rust, as api_buf_copy made it. */ -static api_buf made_times(void *data, uint32_t n) { - (void)data; - char text[32]; - snprintf(text, sizeof text, "%u times", (unsigned)n); - return api_buf_copy(str(text)); -} - -/* reissue's closures: a new ticket, and a copy of one C keeps. */ -static api_Ticket reissue_next(void *data, api_Ticket ticket) { - (void)data; - return api_Ticket_new(api_Ticket_number(&ticket) + 1); -} - -static api_Ticket reissue_kept(void *data, api_Ticket ticket) { - (void)ticket; - return *(const api_Ticket *)data; -} - -/* shifted's closure: the moment 500 ticks later. */ -static api_Moment moment_after(void *data, api_Moment moment) { - (void)data; - return api_Moment_after(&moment, 500); -} static uint32_t spawned_task(void *data) { (void)data; @@ -423,111 +345,6 @@ static void tail(api_foreign_reader reader) { } } -/* Closures C implements that Rust keeps or that return what Rust then owns, and readers - * C implements: whether each behaved. */ -static bool closures(void) { - print("made ", api_made(3, made_times, NULL), "\n"); - - /* A closure taking and returning `Copy` values copies them, never running their `Clone`. */ - api_Ticket kept = api_Ticket_new(9); - api_Ticket seven = api_Ticket_new(7); - api_Ticket given = api_reissue(seven, reissue_next, NULL); - api_Ticket held = api_reissue(seven, reissue_kept, &kept); - printf("reissued %u %u, cloned %u\n", (unsigned)api_Ticket_number(&given), (unsigned)api_Ticket_number(&held), - (unsigned)api_Ticket_clones()); - /* A record's traits borrow the checked handle it holds. */ - api_Mark *nine = api_Mark_of(9); - api_Seat front = api_seat(nine, 1, NULL); - api_Seat back = api_seat(nine, 2, NULL); - print("seat ", api_Seat_debug(&front, NULL), ""); - printf(" %s %s\n", api_Seat_eq(&front, &front, NULL) ? "true" : "false", - api_Seat_eq(&front, &back, NULL) ? "true" : "false"); - api_Seat_free(&back); - api_Seat_free(&front); - api_Mark_free(nine); - - /* A kept closure, called on another thread after the call that took it returned. */ - bool spawned_freed = false; - api_Spawned *spawned = api_Spawned_new(spawned_task, &spawned_freed, spawned_free); - uint32_t joined = api_Spawned_join(spawned, NULL); - api_Spawned_free(spawned); - if (joined != 7 || !spawned_freed) { - return false; - } - - api_waker waker = {.wake = wake, .drop = drop, .data = NULL}; - api_Moment start = api_Moment_new(0, 1000).value; - driver d = {.start = start}; - api_drive_future *drive = api_drive(start, drive_poll, &d, drive_free); - api_buf stopped; - int woken = wakes; - while (api_drive_poll(drive, waker, &stopped) == API_POLL_PENDING) { - } - print("drive ", stopped, "\n"); - bool ok = d.freed && wakes == woken + 1; - api_drive_future_free(drive); - - /* Dropped before it finishes, it frees the closure it kept. */ - driver idle = {.start = start}; - drive = api_drive(start, drive_idle, &idle, drive_free); - ok = ok && api_drive_poll(drive, waker, &stopped) == API_POLL_PENDING && !idle.freed; - api_drive_future_free(drive); - ok = ok && idle.freed; - - memory hello = {.bytes = "hello world", .len = 11}; - tail((api_foreign_reader){.read = memory_read, .seek = memory_seek, .data = &hello}); - tail((api_foreign_reader){.read = broken_read, .seek = broken_seek, .data = NULL}); - - /* A seek from the start reaches the reader whole, past INT64_MAX, as `Cursor` takes one. */ - uint64_t landed = 0; - api_buf landed_err; - if (api_seek_to((api_foreign_reader){.read = memory_read, .seek = memory_seek, .data = &hello}, UINT64_MAX, &landed, - &landed_err)) { - printf("sought %llu\n", (unsigned long long)landed); - } else { - print("sought error ", landed_err, "\n"); - } - print("non zeros ", api_describe_non_zeros(api_non_zeros()), "\n"); - api_option_non_zero_u64 hops[] = {{0}, {.some = true, .value = 1}, {.some = true, .value = UINT64_MAX}}; - for (size_t i = 0; i < sizeof hops / sizeof hops[0]; i++) { - api_option_non_zero_u64 hop = api_next_hop(hops[i]); - if (hop.some) { - printf("hop Some(%llu)\n", (unsigned long long)hop.value); - } else { - printf("hop None\n"); - } - } - printf("farther hop %u\n", (unsigned)api_farther_hop((api_Pair_non_zero_u16){.left = 3, .right = UINT16_MAX})); - { - api_status local_status = 0; - api_Local *local = api_Local_new(); - api_Local *shared = api_local_or_new(local, &local_status); - uint32_t once = api_Local_bump(local, &local_status); - printf("local %u %u\n", once, api_Local_bump(shared, &local_status)); - api_Local *fresh = api_local_or_new(NULL, &local_status); - printf("local fresh %u\n", api_Local_bump(fresh, &local_status)); - printf("local either %u\n", api_bump_either(NULL, shared, &local_status)); - const api_Local *froms[2] = {local, NULL}; - const char *labels[2] = {"local later", "local later fresh"}; - for (int i = 0; i < 2; i++) { - api_local_or_new_later_future *later = api_local_or_new_later(froms[i], &local_status); - api_Local *made = NULL; - while (local_status == 0 && - api_local_or_new_later_poll(later, (api_waker){0}, &made, &local_status) == API_POLL_PENDING) { - } - printf("%s %u\n", labels[i], made ? api_Local_bump(made, &local_status) : 0); - api_Local_free(made); - api_local_or_new_later_future_free(later); - } - if (local_status != 0) { - ok = false; - } - api_Local_free(fresh); - api_Local_free(shared); - api_Local_free(local); - } - return ok; -} /* The Log callback: keeps even levels. */ static bool log_line(void *data, uint8_t level, api_buf line) { @@ -541,44 +358,6 @@ static void log_free(void *data) { printf("freed\n"); } -/* A lent closure: adds data's amount to the counter lent for the call. */ -static bool edit(void *data, api_Counter *counter) { - api_Counter_add(counter, *(const uint64_t *)data, NULL, NULL, NULL); - return api_Counter_edited(counter, NULL) && api_Counter_get(counter, NULL) == 6; -} - -/* Lent closures borrowing their object shared: one `Sync`, one not. */ -static uint32_t seven(void *data) { - (void)data; - return 7; -} - -/* A lent closure of an inferred instance's type. */ -static uint32_t triple(void *data, uint32_t side) { - (void)data; - return side * 3; -} - -static uint64_t visit(void *data, const api_Cursor *cursor) { - (void)data; - return api_Cursor_at(cursor, NULL) * 2; -} - -static void print_visit(void *data, uint32_t at) { - (void)data; - printf("visit %u\n", at); -} - -static uint32_t peek_tally(void *data, const api_Tally *tally) { - (void)data; - return api_Tally_bump(tally, NULL); -} - -/* A lent closure, which Rust calls on another thread: keeps levels above data's. */ -static bool keep_line(void *data, uint8_t level, api_buf line) { - printf("filter %u %.*s\n", level, (int)line.len, (const char *)line.ptr); - return level > *(const uint8_t *)data; -} /* Breaks a lent handle's contract: frees it, or moves its value out. */ static bool free_lent(void *data, api_Counter *counter) { @@ -594,617 +373,46 @@ static bool move_lent(void *data, api_Counter *counter) { return false; } -/* Bytes as Rust's `escape_ascii` prints those of a path. */ -static void print_escaped(const char *before, api_buf buf, const char *after) { - printf("%s", before); - for (size_t i = 0; i < buf.len; i++) { - uint8_t b = buf.ptr[i]; - switch (b) { - case '\t': - printf("\\t"); - break; - case '\r': - printf("\\r"); - break; - case '\n': - printf("\\n"); - break; - case '\\': - case '\'': - case '"': - printf("\\%c", b); - break; - default: - if (b >= 0x20 && b < 0x7f) { - putchar(b); - } else { - printf("\\x%02x", b); - } - } - } - printf("%s", after); - api_buf_free(buf); -} - -/* A socket address, as Rust's Display prints the ones the script makes. */ -static void print_addr(api_socket_addr addr) { - if (!addr.v6) { - const uint8_t *ip = addr.addr.v4.ip.octets; - printf("%u.%u.%u.%u:%u", ip[0], ip[1], ip[2], ip[3], addr.addr.v4.port); - return; - } - /* Only the loopback, `::1`. */ - printf("[::%u%%%u]:%u", addr.addr.v6.ip.octets[15], addr.addr.v6.scope_id, addr.addr.v6.port); -} -/* Bytes in hex. */ -static void print_hex(const uint8_t *bytes, size_t len) { - for (size_t i = 0; i < len; i++) { - printf("%02x", bytes[i]); - } +/* The transcript's own functions, which the generated script calls by the names + * transcript.rs gives them, defined after it, beside the helpers it defines. */ +static api_Log Print(void); +static void channel(void); +static void drive(void); +static void readers(void); +static void local_later(const api_Local *local); +static api_buf hex(api_buf bytes); +static api_buf escaped(api_buf path); +static api_buf path_hex(api_buf path); +static api_buf seconds(api_duration d); +static uint64_t millis(api_duration d); +static uint32_t code(uint32_t c); +static api_vec_tls_Codec reversed(api_vec_tls_Codec list); +static api_vec_u64 f64_bits(api_vec_f64 floats); +static api_buf socket_hex(api_socket_addr addr); +static api_buf ip_hex(api_ip_addr ip); +static void numbers(api_buf what, api_Numbers n); +static api_buf unspelled(void); + +#include "transcript.c" + +/* Each string a function of the transcript's returns is the script's to free. */ + +static api_buf copied(const char *text, size_t len) { + return api_buf_copy((api_buf){.ptr = (const uint8_t *)text, .len = len}); } -/* A socket address as the script's socket_hex prints it. */ -static void print_socket_hex(api_socket_addr addr) { - if (!addr.v6) { - print_hex(addr.addr.v4.ip.octets, 4); - printf(":%u", addr.addr.v4.port); - return; - } - print_hex(addr.addr.v6.ip.octets, 16); - printf(":%u:%u:%u", addr.addr.v6.port, addr.addr.v6.flowinfo, addr.addr.v6.scope_id); -} - -/* An IP address's bytes in hex, so its length shows its family. */ -static void print_ip_hex(api_ip_addr ip) { - if (ip.v6) { - print_hex(ip.ip.v6.octets, 16); - } else { - print_hex(ip.ip.v4.octets, 4); - } +/* Print's Log: keeps even levels, and says when Rust frees it. */ +static api_Log Print(void) { + static const api_Log_vtable vtable = {.free = log_free, .log = log_line}; + return (api_Log){.vtable = &vtable}; } -/* A bound, as Rust's Debug prints it. */ -static void print_bound(api_bound_u64 bound) { - switch (bound.kind) { - case API_BOUND_INCLUDED: - printf("Included(%llu)", (unsigned long long)bound.value); - break; - case API_BOUND_EXCLUDED: - printf("Excluded(%llu)", (unsigned long long)bound.value); - break; - case API_BOUND_UNBOUNDED: - printf("Unbounded"); - break; - } -} - -static int script(void) { - printf("limit %llu\n", (unsigned long long)API_LIMIT); - - api_Point start = {.x = 1, .y = 2}; - api_Point p = api_Point_offset(&start, 2, 3); - printf("offset %d %d\n", p.x, p.y); - print("debug ", api_Point_debug(&p), "\n"); - api_Point expected = {.x = 3, .y = 5}; - printf("eq %s\n", api_Point_eq(&p, &expected) ? "true" : "false"); - api_Point d = api_Point_default(); - printf("default %d %d\n", d.x, d.y); - - api_Counter *c = api_Counter_new(str("c"), 5); - printf("get %llu\n", (unsigned long long)api_Counter_get(c, NULL)); - print("name ", api_Counter_name(c, NULL), "\n"); - uint64_t v; - api_Error err; - if (api_Counter_add(c, 10, &v, &err, NULL)) { - printf("add ok %llu\n", (unsigned long long)v); - } - if (!api_Counter_add(c, 2000, &v, &err, NULL)) { - print("add err ", api_Error_to_string(&err), " "); - print("", api_Error_debug(&err), "\n"); - api_Error_free(&err); - } - if (!api_Counter_sub(c, 20, &v, &err, NULL)) { - printf("sub err underflow by %llu ", (unsigned long long)err.underflow.by); - print("", api_Error_debug(&err), "\n"); - api_Error_free(&err); - } - api_Counter_rename(c, str("d"), NULL); - print("name ", api_Counter_name(c, NULL), "\n"); - printf("is d %s\n", api_Counter_is(c, str("d"), NULL) ? "true" : "false"); - api_Counter *copy = api_Counter_clone(c, NULL); - api_Counter_add(copy, 1, NULL, NULL, NULL); - printf("clone %llu original %llu\n", (unsigned long long)api_Counter_get(copy, NULL), - (unsigned long long)api_Counter_get(c, NULL)); - api_Counter_free(copy); - print("debug ", api_Counter_debug(c, NULL), "\n"); - api_Label label = api_Counter_into_label(c, (api_option_Point){.some = true, .value = p}, NULL); - api_Counter_free(c); - print("label ", api_Label_debug(&label), "\n"); - api_Label_free(&label); - /* Empty text is not none: only a null pointer is. */ - api_Note empty = {.text = {.ptr = (const uint8_t *)"", .len = 0}}; - printf("note %s %s\n", api_has_text(empty) ? "true" : "false", api_has_text((api_Note){0}) ? "true" : "false"); - - /* A tuple returns through one out pointer per element. */ - api_Counter *whole = api_Counter_new(str("s"), 7); - api_Counter *below, *above; - api_Counter_split(whole, 5, &below, &above, NULL); - api_Counter_free(whole); - print("split ", api_Counter_name(below, NULL), " "); - printf("%llu ", (unsigned long long)api_Counter_get(below, NULL)); - print("", api_Counter_name(above, NULL), " "); - printf("%llu\n", (unsigned long long)api_Counter_get(above, NULL)); - api_Counter_free(below); - api_Counter_free(above); - api_Counter *one = api_Counter_new(str("o"), 3); - api_Counter *only; - api_only(one, &only, NULL); - api_Counter_free(one); - print("only ", api_Counter_name(only, NULL), " "); - printf("%llu\n", (unsigned long long)api_Counter_get(only, NULL)); - api_Counter_free(only); - uint8_t w8; - int16_t w16; - uint32_t w32; - uint64_t w64; - api_widths(98305, &w8, &w16, &w32, &w64); - printf("widths %u %d %u %llu\n", w8, w16, w32, (unsigned long long)w64); - uint64_t divisors[] = {2, 0}; - for (int i = 0; i < 2; i++) { - uint64_t q, r; - if (api_divide(7, divisors[i], &q, &r, &err)) { - printf("divide %llu %llu\n", (unsigned long long)q, (unsigned long long)r); - } else { - print("divide err ", api_Error_to_string(&err), "\n"); - api_Error_free(&err); - } - } - /* A tuple inside another type is a struct, its fields _0, _1, and so on. */ - uint64_t spreads[] = {98305, 0}; - for (int i = 0; i < 2; i++) { - api_option_tuple_u8_i16_u32_u64 spread = api_spread(spreads[i]); - if (spread.some) { - printf("spread %u %d %u %llu\n", spread.value._0, spread.value._1, spread.value._2, - (unsigned long long)spread.value._3); - } else { - printf("spread none\n"); - } - } - const char *needles[] = {"lo", "x"}; - for (int i = 0; i < 2; i++) { - api_option_tuple_usize_usize found = api_find(str("hello"), str(needles[i])); - if (found.some) { - printf("find %zu %zu\n", found.value._0, found.value._1); - } else { - printf("find none\n"); - } - } - api_Point row_points[] = {{.x = 1, .y = 2}, {.x = 3, .y = 3}}; - api_vec_tuple_string_Shape_Point stat_rows = api_rows((api_vec_Point){.ptr = row_points, .len = 2}); - printf("rows"); - for (size_t i = 0; i < stat_rows.len; i++) { - /* The array's free frees each element's buffer. */ - printf("%s%.*s ", i == 0 ? " " : ", ", (int)stat_rows.ptr[i]._0.len, (const char *)stat_rows.ptr[i]._0.ptr); - print("", api_Shape_debug(&stat_rows.ptr[i]._1), " "); - printf("%d %d", stat_rows.ptr[i]._2.x, stat_rows.ptr[i]._2.y); - } - printf("\n"); - api_vec_tuple_string_Shape_Point_free(stat_rows); - /* Each handle in a tuple moves in, as one taken by value does. */ - api_tuple_string_Counter meters[] = { - {._0 = str("low"), ._1 = api_Counter_new(str("l"), 1)}, - {._0 = str("high"), ._1 = api_Counter_new(str("h"), 9)}, - }; - api_Board *board = api_Board_new((api_vec_tuple_string_Counter){.ptr = meters, .len = 2}, NULL); - api_Counter_free(meters[0]._1); - api_Counter_free(meters[1]._1); - api_vec_tuple_string_Counter ranked = api_Board_ranked(board, NULL); - printf("ranked"); - for (size_t i = 0; i < ranked.len; i++) { - printf("%s%.*s ", i == 0 ? " " : ", ", (int)ranked.ptr[i]._0.len, (const char *)ranked.ptr[i]._0.ptr); - print("", api_Counter_name(ranked.ptr[i]._1, NULL), " "); - printf("%llu", (unsigned long long)api_Counter_get(ranked.ptr[i]._1, NULL)); - } - printf("\n"); - api_vec_tuple_string_Counter_free(ranked); - api_Counter *best = api_Board_best(board, NULL); - print("best ", api_Counter_name(best, NULL), " "); - printf("%llu\n", (unsigned long long)api_Counter_get(best, NULL)); - api_Counter_free(best); - api_Board_free(board); - /* A map crosses as its pairs and a set as its items, which Rust collects in order, each - * key once, the last kept. */ - api_tuple_string_Point atlas_points[] = { - {._0 = str("b"), ._1 = {.x = 1, .y = 1}}, - {._0 = str("ab"), ._1 = {.x = 2, .y = 3}}, - {._0 = str("b"), ._1 = {.x = 4, .y = 4}}, - }; - uint32_t atlas_ids[] = {3, 1, 3}; - api_Atlas loose = { - .points = {.ptr = atlas_points, .len = 3}, - .ids = {.ptr = atlas_ids, .len = 3}, - }; - api_Atlas atlas = api_Atlas_with(&loose, str("c"), (api_Point){.x = 5, .y = 6}); - printf("atlas"); - for (size_t i = 0; i < atlas.points.len; i++) { - printf("%s%.*s ", i == 0 ? " " : ", ", (int)atlas.points.ptr[i]._0.len, (const char *)atlas.points.ptr[i]._0.ptr); - printf("%d %d", atlas.points.ptr[i]._1.x, atlas.points.ptr[i]._1.y); - } - printf("; ids"); - for (size_t i = 0; i < atlas.ids.len; i++) { - printf(" %u", atlas.ids.ptr[i]); - } - printf("\n"); - api_Atlas_free(&atlas); - /* Another crate's error crosses as its message. */ - const char *port_texts[] = {"80", "x"}; - for (size_t i = 0; i < 2; i++) { - uint16_t port; - api_buf port_err; - if (api_port(str(port_texts[i]), &port, &port_err)) { - printf("port %u\n", port); - } else { - print("port err ", port_err, "\n"); - } - } - api_Span span = { - .bounds = {._0 = 2, ._1 = 10}, - .named = {.some = true, .value = {._0 = str("s"), ._1 = API_SHAPE_SQUARE}}, - }; - api_tuple_u32_u32 lower_half, upper_half; - api_halves(span, &lower_half, &upper_half); - printf("halves %u %u %u %u ", lower_half._0, lower_half._1, upper_half._0, upper_half._1); - print("", api_Span_debug(&span), "\n"); - uint32_t swapped_n; - api_buf swapped_text; - api_swapped((api_tuple_string_u32){._0 = str("t"), ._1 = 4}, &swapped_n, &swapped_text); - printf("swapped %u ", swapped_n); - print("", swapped_text, "\n"); - api_option_tuple_option_u32 doubles[] = { - {.some = false}, - {.some = true, .value = {._0 = {.some = false}}}, - {.some = true, .value = {._0 = {.some = true, .value = 3}}}, - }; - for (int i = 0; i < 3; i++) { - api_option_tuple_option_u32 doubled = api_doubled(doubles[i]); - if (!doubled.some) { - printf("doubled None\n"); - } else if (!doubled.value._0.some) { - printf("doubled Some((None,))\n"); - } else { - printf("doubled Some((Some(%u),))\n", doubled.value._0.value); - } - } - /* A borrowed or boxed tuple of one is a tuple struct, not its element. */ - uint8_t lent_bytes[] = {1, 2}; - uint8_t boxed_bytes[] = {3}; - api_tuple_bytes lent_one = api_lent_back((api_tuple_bytes){._0 = {.ptr = lent_bytes, .len = 2}}); - api_tuple_bytes boxed_one = api_boxed_tuple((api_buf){.ptr = boxed_bytes, .len = 1}); - api_buf both[] = {lent_one._0, boxed_one._0}; - for (int i = 0; i < 2; i++) { - printf("%s[", i == 0 ? "lent back " : " boxed "); - for (size_t j = 0; j < both[i].len; j++) { - printf("%s%u", j == 0 ? "" : ", ", both[i].ptr[j]); - } - printf("]"); - api_buf_free(both[i]); - } - printf("\n"); - /* A borrowed string and an owned one share a tuple struct. */ - api_option_tuple_string formal = api_title(true); - api_option_tuple_string informal = api_title(false); - api_option_tuple_string named = api_named(str("x")); - print("title Some((\"", formal.value._0, "\",)) "); - printf("%s ", informal.some ? "Some" : "None"); - print("named Some((\"", named.value._0, "\",))\n"); - - /* Each lent counter is a new handle to a clone. */ - /* A handle whose value moved in is still the caller's to free. */ - api_Counter *moved = api_Counter_new(str("first"), 1); - api_Registry *registry = api_Registry_new(moved, NULL); - api_Counter_free(moved); - printf("last %s\n", api_Registry_last(registry, NULL) != NULL ? "true" : "false"); - moved = api_Counter_new(str("last"), 2); - api_Registry_push(registry, moved, NULL); - api_Counter_free(moved); - api_Counter *first = api_Registry_first_get(registry, NULL); - api_Counter_add(first, 10, NULL, NULL, NULL); - api_Counter *lent = api_Registry_first_get(registry, NULL); - printf("first %llu lent %llu\n", (unsigned long long)api_Counter_get(lent, NULL), - (unsigned long long)api_Counter_get(first, NULL)); - api_Counter_free(lent); - api_Counter_free(first); - api_Counter *last = api_Registry_last(registry, NULL); - api_Counter_add(last, 10, NULL, NULL, NULL); - lent = api_Registry_last(registry, NULL); - printf("last %llu lent %llu\n", (unsigned long long)api_Counter_get(lent, NULL), - (unsigned long long)api_Counter_get(last, NULL)); - api_Counter_free(lent); - api_Counter_free(last); - uint64_t by = 5; - bool edited = api_Registry_edit(registry, edit, &by, NULL); - first = api_Registry_first_get(registry, NULL); - printf("edit %s %llu\n", edited ? "true" : "false", (unsigned long long)api_Counter_get(first, NULL)); - api_Counter_free(first); - /* A setter moves an object in, as assignment does, leaving the handle to be freed. */ - api_Counter *second = api_Counter_new(str("second"), 3); - api_Registry_first_set(registry, second, NULL); - api_Counter_free(second); - first = api_Registry_first_get(registry, NULL); - printf("set first %llu ", (unsigned long long)api_Counter_get(first, NULL)); - print("", api_Counter_name(first, NULL), "\n"); - api_Counter_free(first); - printf("walk %llu\n", (unsigned long long)api_walk(3, visit, NULL)); - printf("each %u\n", api_each(2, print_visit, NULL)); - printf("offset %u\n", api_offset(seven, NULL, 3)); - printf("shift %u\n", api_shift(seven, NULL, 4)); - api_Registry_free(registry); - - /* A type generic only over lifetimes is a handle to its 'static form. */ - api_Name *name = api_Name_owned(str("a")); - api_Name *b = api_Name_owned(str("b")); - api_Name *joined = api_Name_join(name, b, NULL); - api_Name_free(b); - print("joined ", api_Name_as_str(joined, NULL), " "); - print("", api_Name_debug(joined, NULL), " "); - printf("%s\n", api_Name_eq(joined, name, NULL) ? "true" : "false"); - api_Name_free(name); - char text[] = "c"; - api_Name_rename(joined, str(text), NULL); - /* The name took a copy: the caller's buffer is its own again. */ - text[0] = 'x'; - print("renamed ", api_Name_as_str(joined, NULL), "\n"); - api_Name *dd = api_Name_owned(str("dd")); - api_Name *longest = api_longer(joined, dd, NULL); - print("longer ", api_Name_as_str(longest, NULL), "\n"); - api_Name_free(longest); - api_Name_free(dd); - api_Name_free(joined); - api_Name *unnamed = api_unnamed(); - print("unnamed [", api_Name_as_str(unnamed, NULL), "]\n"); - api_Name_free(unnamed); - /* Two buffers of equal text, interned into one string. */ - char lit_text[] = "lit", again_text[] = "lit"; - api_Name *lit = api_Name_borrowed(str(lit_text)); - api_Name *again = api_Name_borrowed(str(again_text)); - api_Name *other = api_Name_borrowed(str("other")); - print("borrowed ", api_Name_as_str(lit, NULL), " "); - printf("%s %s\n", api_Name_shares(lit, again, NULL) ? "true" : "false", api_Name_shares(lit, other, NULL) ? "true" : "false"); - api_Name_free(lit); - api_Name_free(again); - api_Name_free(other); - - printf("total %llu\n", (unsigned long long)api_total((api_range_u64){.start = 2, .end = 5})); - printf("reach %u\n", (unsigned)api_reach(2, 5)); - api_option_u128 scaled[] = { - api_scaled((api_u128){.lo = UINT64_MAX, .hi = UINT64_MAX}, 1), - api_scaled((api_u128){.lo = 1, .hi = 1}, 1ULL << 63), - api_scaled((api_u128){.hi = 1ULL << 63}, 2), - }; - printf("scaled"); - for (size_t i = 0; i < 3; i++) { - if (scaled[i].some) { - printf(" %016llx%016llx", (unsigned long long)scaled[i].value.hi, (unsigned long long)scaled[i].value.lo); - } else { - printf(" none"); - } - } - printf("\n"); - api_array_u8_4 sum, unparsed; - api_buf unparsed_err; - if (!api_fingerprint(str("deadbeef"), &sum, &unparsed_err) || api_fingerprint(str("zz"), &unparsed, &unparsed_err)) { - return 1; - } - api_Digest *digest = api_Digest_new(); - api_Digest_sum_set(digest, sum, NULL); - api_array_u8_4 got = api_Digest_sum_get(digest, NULL); - api_array_u8_4 masked = api_Digest_flipped(digest, (api_array_u8_4){{0xff, 0, 0xff, 0}}, NULL); - printf("digest %02x%02x%02x%02x %02x%02x%02x%02x", got.items[0], got.items[1], got.items[2], got.items[3], - masked.items[0], masked.items[1], masked.items[2], masked.items[3]); - print(" ", unparsed_err, "\n"); - api_Digest_free(digest); - api_Batch *batch = api_Batch_new(); - unsigned accepted = 0; - for (uint32_t v = 1; v <= 5; v++) { - accepted += api_Batch_push(batch, v, NULL); - } - api_Batch_2 *batch2 = api_pair(); - unsigned paired = 0; - for (uint32_t v = 1; v <= 3; v++) { - paired += api_Batch_2_push(batch2, v, NULL); - } - unsigned long long emptied = api_drain_4(batch, NULL); - printf("batch %zu %u %llu %llu %zu %u %llu\n", api_Batch_capacity(batch, NULL), accepted, emptied, - (unsigned long long)api_drain_4(batch, NULL), api_Batch_2_capacity(batch2, NULL), paired, (unsigned long long)api_drain_2(batch2, NULL)); - printf("capacities %zu %zu\n", api_capacities_4_2(batch, batch2, NULL), api_capacities_2_2(batch2, batch2, NULL)); - api_Batch_2_free(batch2); - api_Batch_free(batch); - api_range_u64 wide = api_widen((api_range_u64){.start = 2, .end = 5}, 1); - printf("widen %llu %llu\n", (unsigned long long)wide.start, (unsigned long long)wide.end); - api_bounds_u64 ranges[] = { - {.start = {API_BOUND_INCLUDED, 2}, .end = {API_BOUND_EXCLUDED, 5}}, - {.start = {API_BOUND_INCLUDED, 2}, .end = {API_BOUND_INCLUDED, 5}}, - {.start = {API_BOUND_INCLUDED, 3}}, - {.start = {API_BOUND_UNBOUNDED, 0}}, - {.start = {API_BOUND_EXCLUDED, 2}, .end = {API_BOUND_INCLUDED, 4}}, - }; - printf("count"); - for (int i = 0; i < 5; i++) { - printf(" %zu", api_count(ranges[i])); - } - printf("\n"); - printf("end "); - print_bound(api_end(3)); - printf(" "); - print_bound(api_end(0)); - printf("\n"); - api_bound_u64 ends_start, ends_end; - api_ends(3, &ends_start, &ends_end); - printf("ends "); - print_bound(ends_start); - printf(" "); - print_bound(ends_end); - printf("\n"); - uint64_t belows[] = {2, 5}; - for (int i = 0; i < 2; i++) { - uint64_t n; - api_bounds_u64 outside; - if (api_below(belows[i], 3, &n, &outside)) { - printf("below %llu\n", (unsigned long long)n); - } else { - printf("below err "); - print_bound(outside.start); - printf(" "); - print_bound(outside.end); - printf("\n"); - } - } - api_Window window = {.range = {.start = 2, .end = 8}, .end = api_end(5)}; - printf("window %s %s ", api_Window_contains(&window, 4) ? "true" : "false", - api_Window_contains(&window, 6) ? "true" : "false"); - print("", api_Window_debug(&window), "\n"); - - print("", api_greet(str("x"), API_SHAPE_SQUARE), "\n"); - printf("len %zu\n", api_len(str("abc"))); - api_buf binary = {.ptr = (const uint8_t *)"\xff\0a", .len = 3}; - print("hex ", api_hex(binary), "\n"); - print("timed hex ", api_timed_hex(binary), "\n"); - print("sample hex ", api_sample_hex(binary), "\n"); - print("queued hex ", api_queued_hex(binary), "\n"); - print("tick ", api_tick_name((api_Label){.name = str("tick")}), "\n"); - print("rooted ", api_rooted_name((api_Label){.name = str("rooted")}), "\n"); - print("stored ", api_stored_text(str("stored")), "\n"); - print("layer ", api_layer_name((api_Label){.name = str("layer")}), "\n"); - api_Event events[3] = { - {.tag = API_EVENT_MOVED, .moved = {._0 = p}}, - {.tag = API_EVENT_NAMED, .named = {.name = str("n")}}, - {.tag = API_EVENT_DONE}, - }; - for (int i = 0; i < 3; i++) { - print("", api_describe(events[i]), "\n"); - } - - /* A `Copy` value passed by value is copied, so it stays usable, and frees nothing. */ - api_Stamp stamp = api_Stamp_from_millis(2500); - printf("secs %llu\n", (unsigned long long)api_Stamp_secs(&stamp)); - api_Stamp later = api_Stamp_from_millis(3000); - printf("later %s\n", api_Stamp_later(&later, stamp) ? "true" : "false"); - printf("secs %llu\n", (unsigned long long)api_Stamp_secs(&stamp)); - api_Stamp rounded = api_Stamp_whole(&stamp); - print("whole ", api_Stamp_debug(&rounded), "\n"); - api_Message *message = api_Message_new((api_option_Stamp){.some = true, .value = stamp}, str("body")); - print("payload ", api_Message_payload_get(message, NULL), "\n"); - api_option_Stamp read = api_Message_stamp_get(message, NULL); - print("stamp ", api_Stamp_debug(&read.value), "\n"); - printf("sent %s\n", api_Message_sent(message, NULL) ? "true" : "false"); - /* Setters assign in place: the bytes are copied in, and a `Copy` value copied. */ - api_Stamp reset = api_Stamp_from_millis(4000); - api_Message_stamp_set(message, (api_option_Stamp){.some = true, .value = reset}, NULL); - api_Message_payload_set(message, str("edited"), NULL); - print("payload ", api_Message_payload_get(message, NULL), "\n"); - read = api_Message_stamp_get(message, NULL); - print("stamp ", api_Stamp_debug(&read.value), "\n"); - printf("secs %llu\n", (unsigned long long)api_Stamp_secs(&reset)); - api_Message_stamp_set(message, (api_option_Stamp){0}, NULL); - printf("stamp %s\n", api_Message_stamp_get(message, NULL).some ? "true" : "false"); - api_Message_free(message); - - /* A value past a word, copied across: a closure takes and returns one by value. */ - api_option_Moment made = api_Moment_new(1500, 1000); - api_Moment moment = made.value; - printf("moment %llu %s\n", (unsigned long long)api_Moment_millis(&moment), - api_Moment_new(1, 0).some ? "false" : "true"); - api_Moment shifted = api_shifted(moment, moment_after, NULL); - api_Moment later_moment = api_Moment_after(&moment, 500); - printf("shifted %llu %s\n", (unsigned long long)api_Moment_millis(&shifted), - api_Moment_eq(&shifted, &later_moment) ? "true" : "false"); - api_Moment wrapped = api_Moment_after(&moment, UINT64_MAX); - printf("wrapped %llu %s\n", (unsigned long long)api_Moment_millis(&wrapped), - api_Moment_eq(&moment, &shifted) ? "true" : "false"); - - /* A value with padding, or bytes that vary, is a handle, as no table says where padding is. */ - api_Gap *gap = api_Gap_new(7, 3); - api_Gap *same_gap = api_Gap_new(7, 3); - printf("gap %llu %s\n", (unsigned long long)api_Gap_sum(gap), api_Gap_eq(gap, same_gap) ? "true" : "false"); - api_Gap_free(same_gap); - api_Gap_free(gap); - api_Berth *berth = api_Berth_new((api_option_u32){.some = true, .value = 4}); - api_Berth *empty_berth = api_Berth_new((api_option_u32){0}); - api_option_u32 berth_at = api_Berth_at(berth); - printf("berth Some(%u) %s\n", berth_at.value, api_Berth_at(empty_berth).some ? "Some" : "None"); - api_Berth_free(empty_berth); - api_Berth_free(berth); - - /* A `Copy` type changed in place is a value, whose change reaches only the copy changed. */ - api_Score score = api_Score_of(2); - api_Score step = api_Score_of(3); - api_Score_add(&score, step); - api_Score_add(&score, step); - api_Score doubled_score = api_Score_doubled(&step); - printf("score %llu %llu %llu\n", (unsigned long long)api_Score_count(&score), - (unsigned long long)api_Score_count(&doubled_score), (unsigned long long)api_Score_count(&step)); - api_Score score_copy = score; - uint64_t taken = api_Score_take(&score_copy); - printf("taken %llu %llu %llu\n", (unsigned long long)taken, (unsigned long long)api_Score_count(&score_copy), - (unsigned long long)api_Score_count(&score)); - api_Score other_score = step; - uint64_t before0, before1; - api_Score_absorb(&score_copy, other_score, &other_score, &before0, &before1); - printf("absorbed %llu %llu %llu %llu %llu\n", (unsigned long long)before0, (unsigned long long)before1, - (unsigned long long)api_Score_count(&score_copy), (unsigned long long)api_Score_count(&other_score), - (unsigned long long)api_Score_count(&step)); - api_Hits hits = api_Hits_of(1, 2); - api_Hits kept = hits; - api_Hits_add(&hits, api_Hits_of(10, 20)); - api_Hits_hits_set(&hits, 7); - printf("hits %llu %llu %llu %llu %s\n", (unsigned long long)api_Hits_hits_get(&hits), - (unsigned long long)api_Hits_misses_get(&hits), (unsigned long long)api_Hits_hits_get(&kept), - (unsigned long long)api_Hits_misses_get(&kept), - api_Hits_eq(&hits, &kept) ? "true" : "false"); - api_Hits counted = kept; - bool counted_same = api_Hits_eq_(&counted, kept); - printf("counted %s %llu\n", counted_same ? "true" : "false", (unsigned long long)api_Hits_hits_get(&counted)); - api_Extent extent = api_Extent_new(5, 3); - api_Extent extent_start = extent; - uint64_t old = api_Extent_slide(&extent, 10); - api_Extent_start_set(&extent, api_Extent_start_get(&extent) + 1); - printf("extent %llu %llu %llu %llu %llu\n", (unsigned long long)old, - (unsigned long long)api_Extent_start_get(&extent), (unsigned long long)api_Extent_end(&extent), - (unsigned long long)api_Extent_start_get(&extent_start), (unsigned long long)api_Extent_end(&extent_start)); - api_Weighted weighted = {.score = step, .weight = 4}; - printf("weighted %llu %llu\n", (unsigned long long)api_Weighted_total(&weighted), - (unsigned long long)(api_Score_count(&weighted.score) + api_Score_count(&step))); - api_Weighted_free(&weighted); - /* A checked mark beside bytes in a tuple and in a record lent, and bytes beside a move. */ - api_Mark *mark = api_Mark_of(1); - api_Mark_add(mark, 2, NULL); - api_Counter *hefted = api_Counter_new(str("w"), 1); - printf("heft %llu\n", (unsigned long long)api_heft((api_tuple_Mark_bytes){mark, str("ab")}, - (api_Parcel){.mark = mark, .payload = str("abc")}, - (api_tuple_Counter_bytes){hefted, str("abcd")}, NULL)); - api_Counter_free(hefted); - /* A value's `&mut self` beside a checked handle. */ - api_Score noted = api_Score_of(2); - api_Mark *noted_by = api_Mark_of(5); - uint64_t noted_before = api_Score_note(¬ed, noted_by, NULL); - printf("noted %llu %llu\n", (unsigned long long)noted_before, (unsigned long long)api_Score_count(¬ed)); - api_Mark_free(noted_by); - api_Mark_free(mark); - - static const api_Log_vtable print_log = {.free = log_free, .log = log_line}; - uint8_t levels[] = {1, 2, 3, 4}; - api_buf lines = {.ptr = levels, .len = sizeof levels}; - printf("kept %u\n", api_emit((api_Log){.vtable = &print_log}, lines)); - api_Logger *logger = api_Logger_new((api_Log){.vtable = &print_log}); - printf("write %s\n", api_Logger_write(logger, str("hi")) ? "true" : "false"); - api_Logger_free(logger); - printf("dropped\n"); - uint8_t threshold = 2; - printf("filtered %u\n", api_filter(lines, keep_line, &threshold)); - +/* A channel's futures, polled by hand. */ +static void channel(void) { api_Channel *channel = api_Channel_new(); api_waker waker = {.wake = wake, .drop = drop, .data = NULL}; + api_Error err; api_Channel_recv_future *recv = api_Channel_recv(channel, NULL); api_buf payload; printf("recv pending %s\n", api_Channel_recv_poll(recv, waker, &payload) == API_POLL_PENDING ? "true" : "false"); @@ -1316,881 +524,341 @@ static int script(void) { returned = api_Waiter_context(waiter, NULL); returned.wake(returned.data); printf("woken %d\n", wakes); + /* Passed back, it moves into Rust as any waker does. */ int woken = wakes; api_Channel_notify(channel, returned, NULL); api_Waiter_free(waiter); api_Channel_send(channel, str("again"), NULL); if (wakes != woken + 1) { - return 1; + tr_fail("a waker passed back did not wake"); } api_Channel_clear(channel, NULL); /* The waiter a pending poll registers lives until the next poll, so the send wakes it. */ take = api_Channel_poll_take(channel, NULL); if (api_Channel_poll_take_poll(take, waker, &payload) != API_POLL_PENDING) { - return 1; + tr_fail("a poll_take of an empty channel was ready"); } woken = wakes; api_Channel_send(channel, str("later"), NULL); if (wakes != woken + 1 || api_Channel_poll_take_poll(take, waker, &payload) != API_POLL_READY) { - return 1; + tr_fail("a pending poll_take's waiter did not wake"); } api_buf_free(payload); api_Channel_poll_take_future_free(take); api_Channel_free(channel); + /* Each future dropped its waker once it finished, and Rust the one it was given. */ + if (drops != 15) { + tr_fail("a waker was not dropped"); + } +} - /* A value that holds itself is an object. */ - api_Node *list = api_Node_new(1, NULL, NULL); - api_Node_push(list, 2, NULL); - printf("node %llu\n", (unsigned long long)api_Node_sum(list, NULL)); - api_Node_free(list); - - api_Tally *tally = api_Tally_new(); - api_Tally_bump(tally, NULL); - uint32_t count = api_Tally_bump(tally, NULL); - printf("tally %u %s\n", count, api_Tally_eq(tally, tally, NULL) ? "true" : "false"); - printf("both %u\n", api_bump_both(tally, tally, NULL)); - printf("peek %u\n", api_peek(tally, peek_tally, NULL, NULL)); - api_Tally_free(tally); - - /* Another export's types, which this export's function takes and returns. */ - api_Area *small = api_Area_new((api_Size){.width = 2, .height = 3}); - api_Area *area = api_grow(small, 1); - api_Area_free(small); - api_Size size = api_Area_size(area); - printf("area %u %u %llu\n", size.width, size.height, (unsigned long long)api_Area_pixels(area)); - api_Area_free(area); - - /* Generic types, each at the instances it infers, named by their arguments. */ - api_Pair_u32 pair = {.left = 2, .right = 5}; - api_Pair_u32 swapped = api_Pair_u32_swap(&pair); - printf("pair %u %u sum %u ", swapped.left, swapped.right, api_Pair_u32_sum(&pair)); - print("", api_Pair_u32_debug(&pair), " "); - printf("%s\n", api_Pair_u32_eq(&pair, &swapped) ? "true" : "false"); - api_Pair_u32 twins = {.left = 7, .right = 7}; - printf("even %s %s\n", api_Pair_u32_even(&pair) ? "true" : "false", - api_Pair_u32_even(&twins) ? "true" : "false"); - /* An instance renamed alone, beside another of `Pair` that keeps its name. */ - api_Pair_Size_u8 sizes = api_tag((api_Size){.width = 1, .height = 2}, 3); - api_Pair_u8_Size flipped = api_Pair_Size_u8_swap(&sizes); - printf("sized %u %u ", flipped.left, flipped.right.width); - print("", api_Pair_u8_Size_debug(&flipped), "\n"); - api_Pair_u32 byte = {.left = 258, .right = 9}; - api_Pair_u8_Size beside = api_Pair_u32_beside_Size(&byte, sizes.left); - printf("beside %u ", beside.left); - print("", api_Pair_u8_Size_debug(&beside), "\n"); - /* At its default, named as the type itself. */ - api_Stack *stack = api_Stack_new(); - const char *names[] = {"a", "b"}; - for (int i = 0; i < 2; i++) { - api_Counter *pushed = api_Counter_new(str(names[i]), (uint64_t)i + 1); - api_Stack_push(stack, pushed, NULL); - api_Counter_free(pushed); - } - api_Counter *top = api_Stack_pop(stack, NULL); - printf("stack %zu Some(%llu)", api_Stack_depth(stack, NULL), (unsigned long long)api_Counter_get(top, NULL)); - api_Counter_free(top); - api_Counter *next = api_Stack_pop(stack, NULL); - printf(" %s", next != NULL ? "true" : "false"); - api_Counter_free(next); - printf(" %s\n", api_Stack_pop(stack, NULL) == NULL ? "true" : "false"); - /* Generic functions and methods, at each implementation of the trait bounding them, by - reference, which leaves C its handle. */ - api_Counter *from_point = api_Counter_seeded_Point(str("p"), (api_Point){.x = -3, .y = 4}); - api_Counter *from_size = api_Counter_seeded_Size(str("s"), (api_Size){.width = 5, .height = 6}); - api_Counter *from_counter = api_Counter_seeded_Counter(str("c"), from_point, NULL); - /* Two instances whose arguments share a last segment: one takes its module too. */ - api_Counter *from_polar = api_Counter_seeded_polar_Point(str("q"), (api_polar_Point){.turns = 1, .distance = 2}); - printf("seeded %llu %llu %llu %llu past %llu seeds %llu\n", (unsigned long long)api_Counter_get(from_point, NULL), - (unsigned long long)api_Counter_get(from_size, NULL), (unsigned long long)api_Counter_get(from_counter, NULL), - (unsigned long long)api_Counter_get(from_polar, NULL), - (unsigned long long)api_Stack_depth_past_Point(stack, (api_Point){.x = 1, .y = 2}, NULL), - (unsigned long long)api_seeds_Point_Size((api_Size){.width = 2, .height = 3})); - api_Counter_free(from_point); - api_Counter_free(from_size); - api_Counter_free(from_counter); - api_Counter_free(from_polar); - api_Stack_free(stack); - - /* A trait implemented for `Point` and `&Point` apart: one instance. */ - printf("weigh %u\n", api_weigh_Point((api_Point){.x = -1, .y = 2})); - /* A function named as the type it returns, and one named as a type it does not. */ - printf("polar %u %s area %llu\n", api_polar_point(2).value.distance, api_polar_point(0).some ? "false" : "true", - (unsigned long long)api_area((api_Size){.width = 2, .height = 3})); - printf("wind %u\n", api_wind((api_PolarTurn){.whole = 2}, (api_polar_Turn){.part = 3})); - /* Names that clash in some language, each kept apart there. */ - api_clash_Tone tone = {.hz = 440}; - api_clash_TONE loud = {.db = 3}; - api_Cancelled cancelled = {.step = 2}; - print("clash ", api_clash_Tone_debug(&tone), " "); - print("", api_clash_TONE_debug(&loud), " "); - print("", api_Cancelled_debug(&cancelled), ""); - api_clash_Span clash_span = {.width = 4}; - printf(" span %u ", api_clash_Span_width(&clash_span)); - print("", api_clash_Span_to_string_(&clash_span), " "); - print("", api_clash_Span_to_string(&clash_span), ""); - api_clash_Store *clash_store = api_clash_Store_new(7); - printf(" store %u %u", api_clash_Store_free_(clash_store), api_clash_Store_close(clash_store)); - api_clash_Store_free(clash_store); - api_option_tuple_tuple_u8_u16_u32 clash_pair = {.some = true, .value = {._0 = {._0 = 1, ._1 = 2}, ._1 = 3}}; - api_option_tuple_tuple_u8_u16_u32_ clash_triple = {.some = true, .value = {._0 = {._0 = 1, ._1 = 2, ._2 = 3}}}; - printf(" audio %u %u nested %u\n", api_clash_audio_encoder_finish(), api_clash_audio_encoder_finish_(), - api_clash_nested(clash_pair, clash_triple)); - /* Instances that name each other, and one made only by an impl of it. */ - api_Outer_Inner_u8 *outer = api_Outer_Inner_u8_new(4); - printf("cross %u outer %u\n", - api_cross((api_Left_Right_u8){.value = {.value = 1}}, (api_Right_Left_u8){.value = {.value = 2}}), - api_Outer_Inner_u8_get(outer)); - api_Outer_Inner_u8_free(outer); - /* A bound that outlives the call takes a value, and an instance only a constant names. */ - printf("kept %llu boxed %u\n", (unsigned long long)api_kept_Point((api_Point){.x = 1, .y = -2}), api_BOXED().value); - printf("keep %d\n", api_keep_Point((api_Point){.x = 1, .y = -2})); - api_Point five = {.x = 5, .y = 2}; - printf("kept or %d %d keeper %d\n", api_kept_or_Point((api_option_Point){.some = true, .value = five}), - api_kept_or_Point((api_option_Point){0}), api_keeper_Point(five)); - /* Inferred instances taking a lent closure and a foreign implementation, and one only - * its impl of a trait names. */ - api_Pair_u32 sides = {.left = 2, .right = 5}; - printf("apply %u\n", api_apply_u32(sides, triple, NULL)); - printf("report %u\n", api_report_u32(sides, (api_Log){.vtable = &print_log})); - printf("wrapped %llu\n", (unsigned long long)api_kept_Wrap_u32((api_Wrap_u32){.value = 4})); - printf("keeps %u\n", api_keeps((api_Log){.vtable = &print_log}).value); - - /* Its Drop runs when C frees the handle, not before. */ - api_Token *token = api_Token_new(7); - printf("token %u dropped %u\n", api_Token_id_get(token, NULL), api_dropped()); - api_Token_free(token); - printf("dropped %u\n", api_dropped()); - - /* A field and the method of its name, each its own function. */ - api_Retry *retry = api_Retry_new((api_option_u32){.some = true, .value = 5}); - api_option_u32 limit = api_Retry_limit_get(retry, NULL); - printf("retry %d %u %u %u\n", limit.some, limit.value, api_Retry_limit(retry, NULL), api_Retry_delay(retry, NULL)); - /* The renamed field's setter, named as its getter. */ - api_Retry_limit_set(retry, (api_option_u32){0}, NULL); - printf("retry %u\n", api_Retry_limit(retry, NULL)); - api_Retry_free(retry); - api_Slot_u8 *slot = api_Slot_u8_new(200); - printf("slot %u\n", api_Slot_u8_value(slot)); - api_Slot_u8_free(slot); - /* Foreign types: a URL parsed from text, socket addresses, OS paths, and `Vec`s. */ - api_Url *base; - api_buf parse_err; - if (!api_Url_parse(str("https://example.com/a/b"), &base, &parse_err)) { - return 1; +/* A kept closure: called again at the instant it asks for, then once its waiter wakes. */ +static void drive(void) { + api_waker waker = {.wake = wake, .drop = drop, .data = NULL}; + api_Moment start = api_Moment_new(0, 1000).value; + driver d = {.start = start}; + api_drive_future *drive = api_drive(start, drive_poll, &d, drive_free); + api_buf stopped; + int woken = wakes; + while (api_drive_poll(drive, waker, &stopped) == API_POLL_PENDING) { } - print("url ", api_Url_to_string(base, NULL), " host "); - api_buf host = api_host(base, NULL); - if (host.ptr != NULL) { - print("Some(\"", host, "\")\n"); - } else { - printf("None\n"); - } - api_Url *resolved; - api_buf resolve_err; - api_Url *base_clone = api_Url_clone(base, NULL); - if (api_resolve(base_clone, str("c?d"), &resolved, &resolve_err, NULL)) { - print("resolve ", api_Url_to_string(resolved, NULL), " "); - printf("%s\n", api_Url_eq(resolved, base, NULL) ? "true" : "false"); - api_Url_free(resolved); - } else { - print("resolve err ", resolve_err, "\n"); - } - api_Url_free(base_clone); - api_Url_free(base); - api_Url *bad; - if (api_Url_parse(str("no scheme"), &bad, &parse_err)) { - print("parse ", api_Url_to_string(bad, NULL), "\n"); - api_Url_free(bad); - } else { - print("parse err ", parse_err, "\n"); + print("drive ", stopped, "\n"); + if (!d.freed || wakes != woken + 1) { + tr_fail("drive kept its closure, or its waiter did not wake"); } + api_drive_future_free(drive); +} - api_socket_addr addrs[2] = { - {.addr.v4 = {.ip = {{127, 0, 0, 1}}, .port = 8080}}, - {.v6 = true, .addr.v6 = {.ip = {{[15] = 1}}, .port = 443, .scope_id = 3}}, - }; - api_vec_u16 ports = api_ports((api_vec_socket_addr){.ptr = addrs, .len = 2}); - printf("ports [%u, %u]\n", ports.ptr[0], ports.ptr[1]); - api_vec_u16_free(ports); - api_buf peer_names[] = {str("a"), str("b")}; - api_Peer peer_start = {.addr = addrs[1], .names = {.ptr = peer_names, .len = 2}}; - api_Peer peer = api_Peer_next(&peer_start, str("c")); - printf("peer Peer { addr: "); - print_addr(peer.addr); - printf(", names: ["); - for (size_t i = 0; i < peer.names.len; i++) { - printf("%s\"%.*s\"", i == 0 ? "" : ", ", (int)peer.names.ptr[i].len, (const char *)peer.names.ptr[i].ptr); - } - printf("] } ["); - api_vec_string aliases = api_Peer_aliases(&peer); - for (size_t i = 0; i < aliases.len; i++) { - printf("%s\"%.*s\"", i == 0 ? "" : ", ", (int)aliases.ptr[i].len, (const char *)aliases.ptr[i].ptr); - } - printf("]\n"); - api_vec_string_free(aliases); - api_buf debug = api_Peer_debug(&peer); - api_Peer_free(&peer); - api_buf_free(debug); - - /* A path's bytes as the OS holds them, which need not be UTF-8. */ - api_buf stray = api_stray(); - /* A second owner of the buffer goes to Rust, which takes it, so stray stays ours. */ - api_buf in_stray = api_file(api_buf_clone(stray), str("f")); - if (in_stray.len != 3 || memcmp(in_stray.ptr, "\xff/f", 3) != 0) { - return 1; - } - api_buf_free(stray); - api_buf_free(in_stray); - api_buf file = api_file(str("dir"), str("f\\'\"\t")); - api_buf paths[] = {file, str("/")}; - api_vec_option_path parents = api_parents((api_vec_path){.ptr = paths, .len = 2}); - print_escaped("file ", file, "\n"); - printf("parents"); - for (size_t i = 0; i < parents.len; i++) { - if (parents.ptr[i].ptr != NULL) { - print_escaped(" ", parents.ptr[i], ""); - } else { - printf(" none"); - } +/* Readers C implements: one over bytes, one whose reads fail, and a seek from the start + * past INT64_MAX, which reaches the reader whole, as `Cursor` takes one. */ +static void readers(void) { + memory hello = {.bytes = "hello world", .len = 11}; + tail((api_foreign_reader){.read = memory_read, .seek = memory_seek, .data = &hello}); + tail((api_foreign_reader){.read = broken_read, .seek = broken_seek, .data = NULL}); + memory empty = {.bytes = "", .len = 0}; + uint64_t landed = 0; + api_buf landed_err; + if (api_seek_to((api_foreign_reader){.read = memory_read, .seek = memory_seek, .data = &empty}, UINT64_MAX, &landed, + &landed_err)) { + printf("sought %llu\n", (unsigned long long)landed); + } else { + print("sought error ", landed_err, "\n"); } - printf("\n"); - /* Each element taken: the array alone is freed. */ - parents.len = 0; - api_vec_option_path_free(parents); - - api_vec_string words = api_words(str(" one two three ")); - printf("words %zu [", words.len); - for (size_t i = 0; i < words.len; i++) { - printf("%s\"%.*s\"", i == 0 ? "" : ", ", (int)words.ptr[i].len, (const char *)words.ptr[i].ptr); - } - printf("]\n"); - print("sentence ", api_sentence(words), " "); - print("", api_sentence((api_vec_string){0}), "\n"); - api_vec_string_free(words); - /* An empty array that is not None: its pointer is not null. */ - api_buf no_words[1]; - print("sentence ", api_sentence((api_vec_string){.ptr = no_words, .len = 0}), "|\n"); - /* An optional borrow: a null buffer or handle is None. */ - printf("either %zu %zu\n", api_either(str("abc")), api_either((api_buf){0})); - print("prefixed ", api_prefixed(str("cd"), str("ab")), " "); - print("", api_prefixed(str("cd"), (api_buf){0}), "\n"); - api_Point corner = {.x = 2, .y = 3}; - printf("coordinates %d %d\n", api_coordinates((api_option_Point){.some = true, .value = corner}), - api_coordinates((api_option_Point){0})); - api_Counter *two = api_Counter_new(str("two"), 2); - api_Counter *three = api_Counter_new(str("three"), 3); - printf("plus %llu %llu\n", (unsigned long long)api_Counter_plus(two, three, NULL), - (unsigned long long)api_Counter_plus(two, NULL, NULL)); - bool added = api_Counter_add_to(two, three, NULL); - bool added_none = api_Counter_add_to(two, NULL, NULL); - printf("add_to %s %s %llu\n", added ? "true" : "false", added_none ? "true" : "false", - (unsigned long long)api_Counter_get(three, NULL)); - api_Counter_free(two); - api_Counter_free(three); - - /* A value passed for &mut: Rust writes back what the call left, which the caller frees. - * A view passed stays the caller's, and a buffer Rust returned Rust takes back. */ - api_buf encoded, appended; - api_put_number(1, str("0,"), &encoded); - api_put_number(23, encoded, &appended); - print("put_number ", appended, "\n"); - api_tuple_bytes_u32 stamped; - uint32_t stamps = api_push_counted((api_tuple_bytes_u32){._0 = str("ab"), ._1 = 1}, 'c', &stamped); - printf("push_counted %u ", stamps); - print("", stamped._0, " "); - printf("%u\n", stamped._1); - api_buf digits_left, digits_rest; - uint8_t first_digit, last_digit; - api_Error digit_error; - api_digit(str("7x9"), &digits_left, &first_digit, &digit_error); - /* The failed call took a byte too. Each buffer Rust returned it takes back. */ - bool skipped = !api_digit(digits_left, &digits_rest, &last_digit, &digit_error); - api_digit(digits_rest, &digits_left, &last_digit, &digit_error); - printf("digit %u %s %u %zu\n", first_digit, skipped ? "true" : "false", last_digit, digits_left.len); - api_buf_free(digits_left); - api_Point nudged = {.x = 1, .y = 2}; - api_nudge(nudged, 3, &nudged); - printf("nudge %d %d\n", nudged.x, nudged.y); - - /* An Arc of another crate's type: an opaque handle, taken back by value or lent. */ - api_tls_Config *config = api_secure(str("h3")); - print("secure ", api_alpn_lent(config, NULL), " "); - api_tls_Config *config_copy = api_tls_Config_clone(config, NULL); - print("", api_alpn(config_copy, NULL), "\n"); - api_tls_Config_free(config_copy); - api_tls_Config_free(config); - /* Another crate's value by value: an opaque handle, lent or taken back. */ - api_tls_Cert *cert = api_certify(str("der")); - printf("cert %llu ", (unsigned long long)api_cert_len(cert, NULL)); - print("", api_cert_der(cert, NULL), " "); - api_tls_Cert_free(cert); - api_tls_Cert *chain[2] = {api_certify(str("a")), api_certify(str("bc"))}; - printf("%llu\n", (unsigned long long)api_chain_len((api_vec_tls_Cert){.ptr = chain, .len = 2}, NULL)); - api_tls_Cert_free(chain[0]); - api_tls_Cert_free(chain[1]); - /* Another crate's trait objects: an `Arc`, taken back, and `&'static` ones, held by value. */ - api_tls_Resolver *resolver = api_resolver(str("r1")); - print("resolver ", api_resolved(resolver, NULL), "\n"); - api_tls_Resolver_free(resolver); - api_Codecs *codecs = api_Codecs_new(); - printf("codecs %u\n", api_Codecs_ids(codecs, NULL)); - api_vec_tls_Codec listed = api_Codecs_list_get(codecs, NULL); - api_tls_Codec *codecs_reversed[2] = {listed.ptr[1], listed.ptr[0]}; - api_Codecs_list_set(codecs, (api_vec_tls_Codec){.ptr = codecs_reversed, .len = 2}, NULL); - /* The setter took each handle's value: the array, and the handles, are still ours to free. */ - api_vec_tls_Codec_free(listed); - printf("codecs reversed %u\n", api_Codecs_ids(codecs, NULL)); - api_Codecs_free(codecs); - /* A standard library value no type maps, in a handle. */ - api_std_io_Error *failure = api_failure(str("boom")); - print("failure ", api_failure_message(failure, NULL), " "); - print("", api_failure_kind(failure, NULL), "\n"); - api_std_io_Error_free(failure); - /* Iterators, passed as the arrays of their items. */ - const uint32_t summed_items[] = {1, 2, 3}; - printf("sum_all %u\n", api_sum_all((api_vec_u32){.ptr = summed_items, .len = 3})); - /* Each counter moves in, leaving its handle only to free. */ - api_Counter *weighed = api_Counter_new(str("w"), 3); - printf("weigh_all %llu\n", (unsigned long long)api_weigh_all_Counter((api_vec_Counter){.ptr = &weighed, .len = 1}, NULL)); - api_Counter_free(weighed); - const api_buf alpns[] = {str("h3"), str("moq-00")}; - printf("offered_len %zu\n", api_offered_len((api_vec_bytes){.ptr = alpns, .len = 2})); - const api_buf joined_words[] = {str("a"), str("b"), str("c")}; - print("join_words ", api_join_words((api_vec_string){.ptr = joined_words, .len = 3}), "\n"); - /* Bytes that must be `'static`, interned. */ +} + +/* Futures of a value that is not Send, polled on this thread until each is ready. */ +static void local_later(const api_Local *local) { + api_status status = 0; + const api_Local *froms[2] = {local, NULL}; + const char *labels[2] = {"local later", "local later fresh"}; for (int i = 0; i < 2; i++) { - api_Der *der = api_Der_from_slice(str("der")); - print(i == 0 ? "der " : "der again ", api_Der_bytes(der), "\n"); - api_Der_free(der); - } - /* Another crate's type only signatures name, exported by its path there, and its error, - * which crosses as its message. */ - api_tls_Session *session; - api_buf session_err; - if (!api_resume(str("h3"), 60, &session, &session_err)) { - return 1; - } - print("resume ", api_tls_Session_alpn(session), " "); - printf("%u\n", api_tls_Session_lifetime(session).seconds); - api_tls_Session_free(session); - if (api_resume(str(""), 60, &session, &session_err)) { - return 1; - } - print("resume err ", session_err, "\n"); - /* A borrow of a meter that is not Clone, lent from its owner's handle. */ - { - api_Meters *lender = api_Meters_new(); - api_Meter *first = api_Meters_first(lender, NULL); - api_Meter_add(first, 2, NULL); - unsigned long long added = api_Meter_add(first, 3, NULL); - api_Meter *again = api_Meters_first(lender, NULL); - printf("lent %llu %llu\n", added, (unsigned long long)api_Meter_count(again, NULL)); - api_Meter_free(again); - api_Meter_free(first); - api_Meters_clear(lender, NULL); - again = api_Meters_first(lender, NULL); - printf("cleared %llu\n", (unsigned long long)api_Meter_count(again, NULL)); - api_Meter_free(again); - /* A field that is not Clone, lent as a method's borrowed return is. */ - api_Meter *last = api_Meters_last_get(lender, NULL); - api_Meter_add(last, 4, NULL); - printf("field lent %llu\n", (unsigned long long)api_Meter_add(last, 1, NULL)); - api_Meter_free(last); - /* An optional field that is not Clone, lent as `Some` of a handle. */ - api_Meter *spare = api_Meters_spare_get(lender, NULL); - printf("spare %s\n", spare != NULL ? "true" : "false"); - api_Meter *fresh = api_Meter_default(); - api_Meters_spare_set(lender, fresh, NULL); - api_Meter_free(fresh); - spare = api_Meters_spare_get(lender, NULL); - api_Meter_add(spare, 5, NULL); - printf("spare lent %llu\n", (unsigned long long)api_Meter_add(spare, 1, NULL)); - api_Meter_free(spare); - api_Meters_free(lender); - /* One lent from a handle that is not Sync, on one thread at a time. */ - api_Tallies *tallies = api_Tallies_new(); - api_Tally *tallied = api_Tallies_first(tallies, NULL); - api_Tally_bump(tallied, NULL); - api_Tally_free(tallied); - tallied = api_Tallies_first(tallies, NULL); - printf("tallied %u\n", api_Tally_bump(tallied, NULL)); - api_Tally_free(tallied); - api_Tallies_free(tallies); - } - /* A draft borrowing its ledger exclusively until it drops, through which its sheet's - * members are reached by Deref and DerefMut. */ - { - api_Ledger *ledger = api_Ledger_new(); - api_Draft *draft; - api_Error err; - api_Ledger_edit(ledger, &draft, &err, NULL); - api_Draft_title_set(draft, str("minutes"), NULL); - api_Draft_write(draft, str("first"), NULL); - print("draft ", api_Draft_title_get(draft, NULL), " "); - printf("%u ", api_Draft_lines(draft, NULL)); - print("", api_Draft_describe(draft, NULL), " "); - printf("%s\n", api_Draft_edited(draft, NULL) ? "true" : "false"); - printf("committed %u\n", api_Draft_commit(draft, NULL)); - api_Draft_free(draft); - print("ledger ", api_Ledger_title(ledger, NULL), " "); - printf("%u\n", api_Ledger_published(ledger, NULL)); - api_Ledger_edit(ledger, &draft, &err, NULL); - printf("read %u %s\n", api_Draft_lines(draft, NULL), api_Draft_edited(draft, NULL) ? "true" : "false"); - api_Draft_free(draft); - api_Ledger_edit(ledger, &draft, &err, NULL); - api_Draft_write(draft, str("second"), NULL); - api_Draft_free(draft); - printf("dropped %u\n", api_Ledger_published(ledger, NULL)); - api_Receipt *receipt = api_Ledger_receipt(ledger, NULL); - printf("receipt %u\n", api_Receipt_count(receipt, NULL)); - api_Receipt_free(receipt); - { - api_Pad_u8 *small = api_Pad_u8_small(); - api_Pad_u16 *wide = api_Pad_u16_wide(); - api_Layered *layered = api_Layered_new(); - api_Marker *marker = api_Marker_new(str("m"), 3, 5); - api_Marker_y_set(marker, 7, NULL); - printf("forwarded %u %u %d %d", api_Pad_u16_title(wide), api_Layered_lines(layered), - api_Marker_x_get(marker, NULL), api_Marker_y_get(marker, NULL)); - print(" [", api_Pad_u8_describe(small), "]"); - print(" [", api_Pad_u16_describe(wide), "]\n"); - api_Marker_free(marker); - api_Layered_free(layered); - api_Pad_u16_free(wide); - api_Pad_u8_free(small); + api_local_or_new_later_future *later = api_local_or_new_later(froms[i], &status); + api_Local *made = NULL; + while (status == 0 && api_local_or_new_later_poll(later, (api_waker){0}, &made, &status) == API_POLL_PENDING) { } - api_Ledger_seal(ledger, NULL); - if (!api_Ledger_edit(ledger, &draft, &err, NULL)) { - print("sealed ", api_Error_to_string(&err), "\n"); - api_Error_free(&err); - } - api_Ledger_free(ledger); + printf("%s %u\n", labels[i], made ? api_Local_bump(made, &status) : 0); + api_Local_free(made); + api_local_or_new_later_future_free(later); } - - api_vec_bytes chunks = api_chunks(str("abcde"), 2); - printf("chunks ["); - for (size_t i = 0; i < chunks.len; i++) { - printf("%s[", i == 0 ? "" : ", "); - for (size_t j = 0; j < chunks.ptr[i].len; j++) { - printf("%s%u", j == 0 ? "" : ", ", chunks.ptr[i].ptr[j]); - } - printf("]"); + if (status != 0) { + tr_fail("a local's future failed"); } - printf("]\n"); - api_vec_bytes_free(chunks); +} - api_buf counter_names[] = {str("x"), str("y")}; - api_vec_Counter counters = api_counters((api_vec_string){.ptr = counter_names, .len = 2}); - printf("counters"); - for (size_t i = 0; i < counters.len; i++) { - print(i == 0 ? " " : ", ", api_Counter_name(counters.ptr[i], NULL), " "); - printf("%llu", (unsigned long long)api_Counter_get(counters.ptr[i], NULL)); +/* Bytes in hex, two digits each. */ +static api_buf hex(api_buf bytes) { + char text[256]; + size_t n = 0; + for (size_t i = 0; i < bytes.len && n + 3 <= sizeof text; i++) { + n += (size_t)snprintf(text + n, sizeof text - n, "%02x", bytes.ptr[i]); } - printf("\n"); - /* Each counter moves in, leaving its handle only to free. */ - uint64_t worth = api_worth((api_vec_Counter){.ptr = counters.ptr, .len = 1}, (api_vec_Counter){.ptr = counters.ptr + 1, .len = 1}, NULL); - uint64_t none = api_worth((api_vec_Counter){0}, (api_vec_Counter){.ptr = counters.ptr, .len = 0}, NULL); - printf("worth %llu %llu\n", (unsigned long long)worth, (unsigned long long)none); - api_vec_Counter_free(counters); - api_Counter *held = api_Counter_new(str("h"), 4); - api_option_u64 counts[] = { - api_held_count((api_option_tuple_Counter){.some = true, .value = {._0 = held}}, NULL), - api_held_count((api_option_tuple_Counter){0}, NULL), - }; - api_Counter_free(held); - printf("held"); - for (size_t i = 0; i < 2; i++) { - if (counts[i].some) { - printf(" Some(%llu)", (unsigned long long)counts[i].value); - } else { - printf(" None"); + return copied(text, n); +} + +/* A path's bytes as `escape_ascii` prints them. */ +static api_buf escaped(api_buf path) { + tr_text t = {0}; + for (size_t i = 0; i < path.len; i++) { + uint8_t b = path.ptr[i]; + switch (b) { + case '\t': + tr_str(&t, "\\t"); + break; + case '\r': + tr_str(&t, "\\r"); + break; + case '\n': + tr_str(&t, "\\n"); + break; + case '\\': + case '\'': + case '"': + tr_fmt(&t, "\\%c", b); + break; + default: + if (b >= 0x20 && b < 0x7f) { + tr_put(&t, (const char *)&b, 1); + } else { + tr_fmt(&t, "\\x%02x", b); + } } } - printf("\n"); - api_Counter *boxed = api_boxed_counter(str("b")); - print("boxed Some(\"", api_boxed_name(boxed, NULL), "\") "); - api_Counter_free(boxed); - printf("%s %s\n", api_boxed_name(NULL, NULL).ptr ? "Some" : "None", api_boxed_counter((api_buf){0}) ? "false" : "true"); - printf("less %u\n", api_less(5, 2)); - - uint32_t row0[] = {1, 2}; - uint32_t row2[] = {3}; - api_vec_u32 rows[] = {{.ptr = row0, .len = 2}, {.ptr = row0, .len = 0}, {.ptr = row2, .len = 1}}; - api_vec_u32 sums = api_sums((api_vec_vec_u32){.ptr = rows, .len = 3}); - printf("sums [%u, %u, %u]\n", sums.ptr[0], sums.ptr[1], sums.ptr[2]); - api_vec_u32_free(sums); - uint32_t set0[] = {3, 1}; - uint32_t set2[] = {2}; - api_vec_u32 sets[] = {{.ptr = set0, .len = 2}, {.ptr = set0, .len = 0}, {.ptr = set2, .len = 1}}; - api_vec_vec_u32 least = api_least((api_vec_vec_u32){.ptr = sets, .len = 3}); - printf("least"); - for (size_t i = 0; i < least.len; i++) { - printf(" ["); - for (size_t j = 0; j < least.ptr[i].len; j++) { - printf(j ? ", %u" : "%u", least.ptr[i].ptr[j]); - } - printf("]"); + return tr_done(&t); +} + +static api_buf path_hex(api_buf path) { + return hex(path); +} + +/* A duration as its seconds and nine digits of nanoseconds. */ +static api_buf seconds(api_duration d) { + char text[64]; + int n = snprintf(text, sizeof text, "%llu.%09u", (unsigned long long)d.secs, (unsigned)d.nanos); + return copied(text, (size_t)n); +} + +/* A duration in whole milliseconds. */ +static uint64_t millis(api_duration d) { + return d.secs * 1000 + d.nanos / 1000000; +} + +/* A char's code point. */ +static uint32_t code(uint32_t c) { + return c; +} + +/* The list reversed in place, a view of it: the script frees the list it passed. */ +static api_vec_tls_Codec reversed(api_vec_tls_Codec list) { + api_tls_Codec **items = (api_tls_Codec **)list.ptr; + for (size_t i = 0; i < list.len / 2; i++) { + api_tls_Codec *swap = items[i]; + items[i] = items[list.len - 1 - i]; + items[list.len - 1 - i] = swap; } - printf("\n"); - api_vec_vec_u32_free(least); - api_Numbers edges = api_Numbers_edges(); - numbers("edges", &edges); - api_Numbers reversed = api_Numbers_reversed(&edges); - numbers("reversed", &reversed); - api_Numbers others = api_Numbers_edges(); - api_Numbers negative = api_Numbers_zero(true); - api_Numbers positive = api_Numbers_zero(false); - api_Measure nan = api_Measure_new(NAN, false); - api_Measure under = api_Measure_new(-0.0, true); - api_Measure over = api_Measure_new(0.0, false); - printf("float equal %s %s %s %s %s\n", api_Numbers_eq(&edges, &edges) ? "true" : "false", - api_Numbers_eq(&edges, &others) ? "true" : "false", api_Numbers_eq(&negative, &positive) ? "true" : "false", - api_Measure_eq(&nan, &nan) ? "true" : "false", api_Measure_eq(&under, &over) ? "true" : "false"); - api_Numbers_free(&edges); - api_Numbers_free(&reversed); - api_Numbers_free(&others); - api_Numbers_free(&negative); - api_Numbers_free(&positive); - api_Measure_free(&nan); - api_Measure_free(&under); - api_Measure_free(&over); - uint32_t totals[] = {UINT32_MAX, UINT32_MAX, 2}; - printf("sum u32 %llu %llu\n", (unsigned long long)api_sum_u32((api_vec_u32){0}), - (unsigned long long)api_sum_u32((api_vec_u32){.ptr = totals, .len = 3})); - int64_t doubling[] = {INT64_MIN, -1, 0, INT64_MAX}; - api_vec_i64 doubled = api_doubled_i64((api_vec_i64){.ptr = doubling, .len = 4}); - printf("doubled i64 "); - PRINT_LIST(doubled, "%lld", (long long)); - printf("\n"); - api_vec_i64_free(doubled); - uint64_t nan_bits = 0x7ff8000000000001; - double floats[2] = {-0.0, 0}; - memcpy(&floats[1], &nan_bits, sizeof nan_bits); - api_vec_f64 boxed_floats = api_boxed_floats((api_vec_f64){.ptr = floats, .len = 2}); - printf("boxed floats "); - PRINT_LIST(boxed_floats, "%llu", f64_bits); - printf("\n"); - api_vec_f64_free(boxed_floats); - api_Point summands[] = {{.x = 1, .y = 2}, {.x = -4, .y = 6}}; - api_Point summed = api_summed((api_vec_Point){.ptr = summands, .len = 2}); - api_Point none_summed = api_summed((api_vec_Point){.ptr = summands, .len = 0}); - printf("summed %d %d %d %d\n", summed.x, summed.y, none_summed.x, none_summed.y); - api_buf longest_words[] = {str("a"), str("abc")}; - size_t most = api_longest((api_vec_string){.ptr = longest_words, .len = 2}); - size_t no_longest = api_longest((api_vec_string){.ptr = longest_words, .len = 0}); - printf("longest %zu %zu\n", most, no_longest); - api_buf no_first = api_first_of((api_vec_string){.ptr = longest_words, .len = 0}); - print("first of Some(\"", api_first_of((api_vec_string){.ptr = longest_words, .len = 2}), "\") "); - printf("%s\n", no_first.ptr == NULL ? "None" : "Some"); - api_Limits_bytes limits = api_byte_limits(str("a"), str("bc")); - api_duration breadth = api_breadth((api_Limits_duration){.low = {.secs = 0, .nanos = 5000000}, .high = {.secs = 2, .nanos = 0}}); - printf("limits %.*s %.*s breadth %llu\n", (int)limits.low.len, (const char *)limits.low.ptr, (int)limits.high.len, - (const char *)limits.high.ptr, (unsigned long long)(breadth.secs * 1000 + breadth.nanos / 1000000)); - api_Limits_bytes_free(&limits); - api_buf parts[] = {str("ab"), str(""), str("c")}; - print("joined ", api_joined((api_vec_bytes){.ptr = parts, .len = 3}), " "); - api_buf no_parts = api_joined((api_vec_bytes){.ptr = parts, .len = 0}); - printf("%zu read %llu\n", no_parts.len, (unsigned long long)api_read_len(str("hello"))); - api_buf_free(no_parts); - - /* JSON crosses as a document, made from text and read back as text. */ - api_Json *doc; - if (!api_Json_parse(str("{\"b\": [1, 2.5, null], \"a\": \"\\u00e9\"}"), &doc, &parse_err)) { - return 1; + return (api_vec_tls_Codec){.ptr = list.ptr, .len = list.len}; +} + +/* Each float's bits, a view of storage of its own. */ +static api_vec_u64 f64_bits(api_vec_f64 floats) { + static uint64_t bits[64]; + if (floats.len > sizeof bits / sizeof bits[0]) { + tr_fail("f64_bits of too many floats"); } - print("json ", api_encode(doc, NULL), "\n"); - print("timed text ", api_timed_text(doc, NULL), "\n"); - api_Json *tagged = api_tagged(doc, str("t"), NULL); - api_Json_free(doc); - print("tagged ", api_Json_to_text(tagged, NULL), "\n"); - api_Json_free(tagged); - /* A JSON object's entries cross as pairs of a key and its document, each moved in. */ - api_tuple_string_Json json_pairs[2] = {{._0 = str("b")}, {._0 = str("a")}}; - if (!api_Json_parse(str("[1]"), &json_pairs[0]._1, &parse_err) || - !api_Json_parse(str("2"), &json_pairs[1]._1, &parse_err)) { - return 1; + for (size_t i = 0; i < floats.len; i++) { + memcpy(&bits[i], &floats.ptr[i], sizeof bits[i]); } - api_vec_tuple_string_Json json_entries = api_entries((api_vec_tuple_string_Json){.ptr = json_pairs, .len = 2}, str("t"), NULL); - api_Json_free(json_pairs[0]._1); - api_Json_free(json_pairs[1]._1); - printf("entries"); - for (size_t i = 0; i < json_entries.len; i++) { - printf("%s%.*s ", i == 0 ? " " : ", ", (int)json_entries.ptr[i]._0.len, (const char *)json_entries.ptr[i]._0.ptr); - print("", api_Json_to_text(json_entries.ptr[i]._1, NULL), ""); + return (api_vec_u64){.ptr = bits, .len = floats.len}; +} + +static void put_hex(tr_text *t, const uint8_t *bytes, size_t len) { + for (size_t i = 0; i < len; i++) { + tr_fmt(t, "%02x", bytes[i]); } - printf("\n"); - api_vec_tuple_string_Json_free(json_entries); - api_Json *broken; - if (api_Json_parse(str("{\"a\":"), &broken, &parse_err)) { - print("json parse ", api_Json_to_text(broken, NULL), "\n"); - api_Json_free(broken); +} + +/* A socket address as its IP's bytes in hex, its port, flow label, and scope, each + * IPv6's alone, apart by colons. */ +static api_buf socket_hex(api_socket_addr addr) { + tr_text t = {0}; + if (!addr.v6) { + put_hex(&t, addr.addr.v4.ip.octets, 4); + tr_fmt(&t, ":%u", addr.addr.v4.port); } else { - print("json parse err ", parse_err, "\n"); + put_hex(&t, addr.addr.v6.ip.octets, 16); + tr_fmt(&t, ":%u:%u:%u", addr.addr.v6.port, addr.addr.v6.flowinfo, addr.addr.v6.scope_id); } + return tr_done(&t); +} - api_Url *home; - if (!api_Url_parse(str("https://example.com/a/b"), &home, &parse_err)) { - return 1; - } - api_Site *site = api_Site_new(home, NULL); - api_Url *home0 = api_Site_home_get(site, NULL); - api_Url *home1 = api_Site_home_get(site, NULL); - print("site ", api_Url_to_string(home0, NULL), " "); - print("", api_Url_to_string(home1, NULL), "\n"); - api_Url_free(home0); - api_Url_free(home1); - api_Site_free(site); - api_Url_free(home); - - /* Slices, passed in and returned as clones, and the socket address of each family. */ - api_vec_Shape shapes = api_Shape_ALL(); - printf("shapes ["); - for (size_t i = 0; i < shapes.len; i++) { - print(i == 0 ? "" : ", ", api_Shape_debug(&shapes.ptr[i]), ""); - } - api_vec_Shape_free(shapes); - api_vec_string greetings = api_GREETINGS(); - printf("] greetings ["); - for (size_t i = 0; i < greetings.len; i++) { - printf("%s\"%.*s\"", i == 0 ? "" : ", ", (int)greetings.ptr[i].len, (const char *)greetings.ptr[i].ptr); - } - printf("]\n"); - api_vec_string_free(greetings); - api_vec_Shape shapes_both = api_Shape_BOTH(); - printf("both ["); - for (size_t i = 0; i < shapes_both.len; i++) { - print(i == 0 ? "" : ", ", api_Shape_debug(&shapes_both.ptr[i]), ""); - } - api_vec_Shape_free(shapes_both); - api_vec_u32 primes = api_PRIMES(); - printf("] primes ["); - for (size_t i = 0; i < primes.len; i++) { - printf("%s%u", i == 0 ? "" : ", ", primes.ptr[i]); - } - printf("]\n"); - api_vec_u32_free(primes); - api_Point trail_points[] = {{.x = 1, .y = 2}, {.x = 3, .y = 4}}; - api_buf trail_names[] = {str("a"), str("b")}; - api_Trail *trail = - api_Trail_new((api_vec_Point){.ptr = trail_points, .len = 2}, (api_vec_string){.ptr = trail_names, .len = 2}); - api_vec_Point points = api_Trail_points(trail, NULL); - printf("trail ["); - for (size_t i = 0; i < points.len; i++) { - print(i == 0 ? "" : ", ", api_Point_debug(&points.ptr[i]), ""); - } - api_vec_Point_free(points); - api_vec_Label labels = api_Trail_labels(trail, NULL); - printf("] ["); - for (size_t i = 0; i < labels.len; i++) { - print(i == 0 ? "" : ", ", api_Label_debug(&labels.ptr[i]), ""); - } - printf("]\n"); - api_vec_Label_free(labels); - /* Returned iterators, each collected at the call: drained labels are gone after. */ - api_vec_Point iter_points = api_Trail_iter(trail, NULL); - printf("iterated ["); - for (size_t i = 0; i < iter_points.len; i++) { - print(i == 0 ? "" : ", ", api_Point_debug(&iter_points.ptr[i]), ""); - } - api_vec_Point_free(iter_points); - api_vec_string iter_names = api_Trail_names(trail, NULL); - printf("] ["); - for (size_t i = 0; i < iter_names.len; i++) { - printf("%s\"%.*s\"", i == 0 ? "" : ", ", (int)iter_names.ptr[i].len, (const char *)iter_names.ptr[i].ptr); - } - api_vec_string_free(iter_names); - api_buf iter_bytes = api_Trail_bytes(trail, NULL); - printf("] ["); - for (size_t i = 0; i < iter_bytes.len; i++) { - printf("%s%u", i == 0 ? "" : ", ", iter_bytes.ptr[i]); - } - printf("]\n"); - api_buf_free(iter_bytes); - api_vec_Label drained = api_Trail_drain(trail, NULL); - printf("drained ["); - for (size_t i = 0; i < drained.len; i++) { - print(i == 0 ? "" : ", ", api_Label_debug(&drained.ptr[i]), ""); - } - api_vec_Label_free(drained); - api_vec_Label left = api_Trail_labels(trail, NULL); - printf("] then ["); - for (size_t i = 0; i < left.len; i++) { - print(i == 0 ? "" : ", ", api_Label_debug(&left.ptr[i]), ""); - } - printf("]\n"); - api_vec_Label_free(left); - /* A filter, collected at the call. */ - api_vec_Point beyond = api_Trail_beyond(trail, 1, NULL); - printf("beyond"); - for (size_t i = 0; i < beyond.len; i++) { - printf("%s%d %d", i == 0 ? " " : ", ", beyond.ptr[i].x, beyond.ptr[i].y); - } - printf("\n"); - api_vec_Point_free(beyond); - api_Trail_free(trail); - api_buf numbered_names[] = {str("p"), str("q")}; - api_vec_Counter numbered = api_numbered((api_vec_string){.ptr = numbered_names, .len = 2}); - printf("numbered"); - for (size_t i = 0; i < numbered.len; i++) { - print(i == 0 ? " " : ", ", api_Counter_name(numbered.ptr[i], NULL), " "); - printf("%llu", (unsigned long long)api_Counter_get(numbered.ptr[i], NULL)); - } - printf("\n"); - api_vec_Counter_free(numbered); - api_socket_addr_v4 at4 = {.ip = {{127, 0, 0, 1}}, .port = 8080}; - api_socket_addr_v6 at6 = {.ip = {{[15] = 1}}, .port = 443, .scope_id = 3}; - api_socket_addr_v4 next4; - api_socket_addr_v6 next6; - api_nexts(at4, at6, &next4, &next6); - const uint8_t *n4 = next4.ip.octets; - printf("nexts %u.%u.%u.%u %u %u %u\n", n4[0], n4[1], n4[2], n4[3], next4.port, next6.port, next6.scope_id); - api_ipv4_addr ip4 = {{10, 0, 0, 255}}, nextip4; - api_ipv6_addr ip6 = {{[14] = 0xff, [15] = 0xff}}, nextip6; - api_next_ips(ip4, ip6, &nextip4, &nextip6); - api_ip_addr mapped = api_flip((api_ip_addr){.ip.v4 = {{127, 0, 0, 1}}}); - api_ip_addr ips[] = { - {.ip.v4 = nextip4}, - {.v6 = true, .ip.v6 = nextip6}, - mapped, - api_flip(mapped), - api_flip((api_ip_addr){.v6 = true, .ip.v6 = {{[15] = 1}}}), - }; - printf("ips"); - for (size_t i = 0; i < sizeof ips / sizeof ips[0]; i++) { - printf(" "); - print_ip_hex(ips[i]); +/* An address's bytes in hex, so the length shows its family. */ +static api_buf ip_hex(api_ip_addr ip) { + tr_text t = {0}; + if (ip.v6) { + put_hex(&t, ip.ip.v6.octets, 16); + } else { + put_hex(&t, ip.ip.v4.octets, 4); } - printf("\n"); + return tr_done(&t); +} - /* Lossless round trips: each type's edge values, passed through Rust and back. */ - api_duration durations[] = {{0, 0}, {0, 1}, {9223372036u, 854775808u}, {UINT64_MAX, 999999999u}}; - printf("lossless duration"); - for (size_t i = 0; i < sizeof durations / sizeof durations[0]; i++) { - api_duration d = api_same_duration(durations[i]); - printf(" %llu.%09u", (unsigned long long)d.secs, d.nanos); - } - printf("\n"); - printf("lossless u64 %llu %llu %llu\n", (unsigned long long)api_same_u64(0), - (unsigned long long)api_same_u64(1ull << 63), (unsigned long long)api_same_u64(UINT64_MAX)); - printf("lossless usize %zu %zu\n", api_same_usize(0), api_same_usize(SIZE_MAX)); - printf("lossless isize %td %td\n", api_same_isize(PTRDIFF_MIN), api_same_isize(PTRDIFF_MAX)); - api_u128 u128s[] = {{0, 0}, {0, 1}, {UINT64_MAX, UINT64_MAX}}; - printf("lossless u128"); - for (size_t i = 0; i < sizeof u128s / sizeof u128s[0]; i++) { - api_u128 v = api_same_u128(u128s[i]); - printf(" %016llx%016llx", (unsigned long long)v.hi, (unsigned long long)v.lo); - } - printf("\n"); - uint32_t chars[] = {0, 0xd7ff, 0xe000, 0x10ffff}; - printf("lossless char"); - for (size_t i = 0; i < sizeof chars / sizeof chars[0]; i++) { - printf(" %x", api_same_char(chars[i])); - } +static unsigned long long bits32(float f) { + uint32_t bits; + memcpy(&bits, &f, sizeof bits); + return bits; +} + +static unsigned long long bits64(double f) { + uint64_t bits; + memcpy(&bits, &f, sizeof bits); + return bits; +} + +/* Print each of `numbers`' lists, its floats as their bits. */ +#define PRINT_LIST(list, fmt, cast) \ + do { \ + printf("["); \ + for (size_t i_ = 0; i_ < (list).len; i_++) { \ + printf(i_ ? ", " fmt : fmt, cast((list).ptr[i_])); \ + } \ + printf("]"); \ + } while (0) + +static void numbers(api_buf what_buf, api_Numbers n) { + int w = (int)what_buf.len; + const char *what = (const char *)what_buf.ptr; + printf("%.*s u16 ", w, what); + PRINT_LIST(n.u16s, "%u", (unsigned)); + printf("\n%.*s u32 ", w, what); + PRINT_LIST(n.u32s, "%u", (unsigned)); + printf("\n%.*s u64 ", w, what); + PRINT_LIST(n.u64s, "%llu", (unsigned long long)); + printf("\n%.*s i8 ", w, what); + PRINT_LIST(n.i8s, "%d", (int)); + printf("\n%.*s i16 ", w, what); + PRINT_LIST(n.i16s, "%d", (int)); + printf("\n%.*s i32 ", w, what); + PRINT_LIST(n.i32s, "%d", (int)); + printf("\n%.*s i64 ", w, what); + PRINT_LIST(n.i64s, "%lld", (long long)); + printf("\n%.*s f32 ", w, what); + PRINT_LIST(n.f32s, "%llu", bits32); + printf("\n%.*s f64 ", w, what); + PRINT_LIST(n.f64s, "%llu", bits64); printf("\n"); - api_buf same_paths[] = {str("a/\xc3\xa9"), {.ptr = (const uint8_t *)"\xff", .len = 1}}; - printf("lossless path"); - for (size_t i = 0; i < sizeof same_paths / sizeof same_paths[0]; i++) { - api_buf path = api_same_path(same_paths[i]); - printf(" "); - print_hex(path.ptr, path.len); - api_buf_free(path); + if (n.some.ptr) { + printf("%.*s some Some(", w, what); + PRINT_LIST(n.some, "%d", (int)); + printf(")\n"); + } else { + printf("%.*s some None\n", w, what); } - printf("\n"); - api_socket_addr_v4 sv4 = api_same_socket_addr_v4((api_socket_addr_v4){.ip = {{255, 255, 255, 255}}, .port = UINT16_MAX}); - api_socket_addr_v6 sv6 = api_same_socket_addr_v6( - (api_socket_addr_v6){.ip = {{0, 1, [15] = 2}}, .port = 3, .flowinfo = UINT32_MAX, .scope_id = UINT32_MAX}); - api_socket_addr sockets[] = {{.addr.v4 = sv4}, {.v6 = true, .addr.v6 = sv6}}; - printf("lossless socket"); - for (size_t i = 0; i < 2; i++) { - printf(" "); - print_socket_hex(sockets[i]); - } - for (size_t i = 0; i < 2; i++) { - printf(" "); - print_socket_hex(api_same_socket_addr(sockets[i])); +} + +/* A path no Rust string spells: bytes that are not UTF-8. */ +static api_buf unspelled(void) { + return api_stray(); +} + + +/* What the transcript's output does not show: each check of the ABI's contract beyond it. */ +static void checks(void) { + /* A name takes a copy: the caller's buffer is its own again. */ + api_Name *name = api_Name_owned(str("a")); + char text[] = "c"; + api_Name_rename(name, str(text), NULL); + text[0] = 'x'; + api_buf renamed = api_Name_as_str(name, NULL); + if (renamed.len != 1 || renamed.ptr[0] != 'c') { + tr_fail("a rename kept the caller's buffer"); } - printf("\n"); - api_Key *key_a = api_Key_new(str("a")), *key_a2 = api_Key_new(str("a")), *key_b = api_Key_new(str("b")); - if (api_Key_hash(key_a) != api_Key_hash_of(key_a)) { - fprintf(stderr, "api_Key_hash differs from Rust's own hash\n"); - abort(); - } - printf("key %s %s\n", api_Key_hash(key_a) == api_Key_hash(key_a2) ? "true" : "false", - api_Key_hash(key_a) == api_Key_hash(key_b) ? "true" : "false"); - api_Key_free(key_a); - api_Key_free(key_a2); - api_Key_free(key_b); - printf("lossless ip "); - print_ip_hex(api_same_ip_addr((api_ip_addr){.ip.v4 = {{255, 255, 255, 255}}})); - printf(" "); - print_ip_hex(api_same_ip_addr((api_ip_addr){.v6 = true, .ip.v6 = {{0xff, 0xff, [15] = 1}}})); - printf("\n"); + api_buf_free(renamed); + api_Name_free(name); - /* serde_json's map iterator, collected as pairs of a key and its document. */ - api_tuple_string_Json section_pairs[2] = {{._0 = str("b")}, {._0 = str("a")}}; - if (!api_Json_parse(str("[1]"), §ion_pairs[0]._1, &parse_err) || - !api_Json_parse(str("2"), §ion_pairs[1]._1, &parse_err)) { - return 1; + /* A path's bytes as the OS holds them, which need not be UTF-8. A second owner of the + * buffer goes to Rust, which takes it, so stray stays ours. */ + api_buf stray = api_stray(); + api_buf in_stray = api_file(api_buf_clone(stray), str("f")); + if (in_stray.len != 3 || memcmp(in_stray.ptr, "\xff/f", 3) != 0) { + tr_fail("a cloned buffer passed to Rust was not its own"); } - api_vec_tuple_string_Json sections = api_sections((api_vec_tuple_string_Json){.ptr = section_pairs, .len = 2}, NULL); - api_Json_free(section_pairs[0]._1); - api_Json_free(section_pairs[1]._1); - printf("sections"); - for (size_t i = 0; i < sections.len; i++) { - printf("%s%.*s ", i == 0 ? " " : ", ", (int)sections.ptr[i]._0.len, (const char *)sections.ptr[i]._0.ptr); - print("", api_Json_to_text(sections.ptr[i]._1, NULL), ""); + api_buf_free(stray); + api_buf_free(in_stray); + + api_Key *key = api_Key_new(str("a")); + if (api_Key_hash(key) != api_Key_hash_of(key)) { + tr_fail("api_Key_hash differs from Rust's own hash"); } - printf("\n"); - api_vec_tuple_string_Json_free(sections); - - /* An instant only Rust makes, a handle, as its padding is wherever rustc puts it, which - * each call copies out of, and compares. */ - api_Instant *began = api_now(); - api_Instant *ended = api_later(began, (api_duration){.secs = 1, .nanos = 500000000}); - api_Instant *same = api_later(began, (api_duration){.secs = 0, .nanos = 0}); - api_duration forward = api_since(ended, began); - api_duration backward = api_since(began, ended); - printf("instants %llu %llu %s %s\n", (unsigned long long)(forward.secs * 1000 + forward.nanos / 1000000), - (unsigned long long)(backward.secs * 1000 + backward.nanos / 1000000), api_Instant_eq(began, same) ? "true" : "false", - api_Instant_eq(began, ended) ? "true" : "false"); - /* An instant lent inside an `Option`, which takes no handle. */ - printf("has_instant %s %s\n", api_has_instant(began) ? "true" : "false", api_has_instant(NULL) ? "true" : "false"); - api_Instant_free(same); - api_Instant_free(ended); - api_Instant_free(began); - - /* tracing's level, and its filter as an optional level whose none is `OFF`. */ - api_Verbosity *verbosity = api_Verbosity_new(API_LEVEL_WARN); - print("verbosity ", api_spell(api_Verbosity_filter(verbosity, NULL)), " "); - print("", api_spell(api_louder(api_Verbosity_filter(verbosity, NULL))), "\n"); - api_Verbosity_level_set(verbosity, API_LEVEL_TRACE, NULL); - printf("verbosity %s ", api_Verbosity_level_get(verbosity, NULL) == API_LEVEL_TRACE ? "true" : "false"); - print("", api_spell(api_Verbosity_filter(verbosity, NULL)), " "); - print("", api_spell(api_louder(api_Verbosity_filter(verbosity, NULL))), " "); - print("", api_spell(api_louder((api_option_Level){.some = false})), "\n"); - api_Verbosity_free(verbosity); + api_Key_free(key); /* A returned `Vec<&Token>` holds clones, which its free drops. */ api_Token *twice = api_Token_new(9); uint32_t before = api_dropped(); api_vec_Token tokens = api_Token_twice(twice, NULL); if (tokens.len != 2 || api_Token_id_get(tokens.ptr[1], NULL) != 9) { - return 1; + tr_fail("api_Token_twice"); } api_vec_Token_free(tokens); if (api_dropped() != before + 2) { - return 1; + tr_fail("a returned vec's free did not drop its clones"); } api_Token_free(twice); - /* Each future dropped its waker once it finished, and Rust the one it was given. */ - if (drops != 15) { - return 1; + /* A kept closure, called on another thread after the call that took it returned. */ + bool spawned_freed = false; + api_Spawned *spawned = api_Spawned_new(spawned_task, &spawned_freed, spawned_free); + uint32_t joined = api_Spawned_join(spawned, NULL); + api_Spawned_free(spawned); + if (joined != 7 || !spawned_freed) { + tr_fail("a spawned closure"); + } + + /* Dropped before it finishes, a drive frees the closure it kept. */ + api_waker waker = {.wake = wake, .drop = drop, .data = NULL}; + api_Moment start = api_Moment_new(0, 1000).value; + driver idle = {.start = start}; + api_drive_future *drive = api_drive(start, drive_idle, &idle, drive_free); + api_buf stopped; + if (api_drive_poll(drive, waker, &stopped) != API_POLL_PENDING || idle.freed) { + tr_fail("an idle drive"); + } + api_drive_future_free(drive); + if (!idle.freed) { + tr_fail("a dropped drive kept its closure"); + } + + if (!foreign_futures()) { + tr_fail("foreign futures"); + } + if (!forwarding()) { + tr_fail("forwarding"); + } + if (!started_futures()) { + tr_fail("started futures"); } - return closures() && foreign_futures() && forwarding() && started_futures() ? 0 : 1; } + /* Each breaks a contract, which must abort with a message naming the function. */ /* A counter a closure was lent, which it fails to move out, then reads as it was. */ static bool move_lent_status(void *data, api_Counter *counter) { @@ -3000,5 +1668,7 @@ int main(int argc, char **argv) { if (argc > 1) { return broken(argv[1]); } - return script(); + script(); + checks(); + return 0; } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 9b5eadc00..20b82edcd 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -242,6 +242,13 @@ fn api() -> &'static Api { /// exclusively. const OUTLIVED: &str = "api_Meter_count: a handle lent from another outlived it"; +/// The directory of the C script generated from the transcript, which `tests/api.c` +/// includes. +fn c_script() -> PathBuf { + let header = std::fs::read_to_string(api().out.join("include").join("api.h")).unwrap(); + generated("c", "transcript.c", &transcript::c::emit(transcript(), &header)) +} + #[test] fn api_c() { let api = api(); @@ -249,15 +256,18 @@ fn api_c() { let cc = std::env::var_os("CC").unwrap_or_else(|| "cc".into()); let src = manifest_dir().join("tests").join("api.c"); let include = api.out.join("include"); + let script = c_script(); Step { stamp: &step::stamp(&exe), - reads: &[&src, &include, &api.staticlib()], + reads: &[&src, &include, &script, &api.staticlib()], writes: &[&exe], } .run( Command::new(cc) .args(["-std=c11", "-pedantic", "-Wall", "-Wextra", "-Werror", "-I"]) .arg(&include) + .arg("-I") + .arg(&script) .arg(&src) .arg(api.staticlib()) .args(&api.native) @@ -400,6 +410,7 @@ fn sanitized(sanitizer: &str) { ("ASAN_OPTIONS", "detect_leaks=1:abort_on_error=1"), ("TSAN_OPTIONS", "halt_on_error=1"), ]; + let script = c_script(); for (compiler, std, src, args) in [ ("clang", "-std=c11", "api.c", &["threads"][..]), ("clang++", "-std=c++17", "api.cpp", &["futures", "lifetimes"][..]), @@ -408,6 +419,8 @@ fn sanitized(sanitizer: &str) { run(Command::new(compiler) .args([std, "-g", "-Wall", "-Wextra", "-Werror", &sanitize, "-I"]) .arg(api.out.join("include")) + .arg("-I") + .arg(&script) .arg(tests.join(src)) .arg(&lib) .args(&native) diff --git a/ffi/tests/fixtures/transcript/c.rs b/ffi/tests/fixtures/transcript/c.rs new file mode 100644 index 000000000..69da8b158 --- /dev/null +++ b/ffi/tests/fixtures/transcript/c.rs @@ -0,0 +1,2271 @@ +//! The transcript as C: a file `tests/api.c` includes after its own functions, whose +//! `script()` runs the transcript through the C ABI, calling the functions `api.c` defines +//! under the names `transcript.rs` gives them. +//! +//! C frees what Rust drops, when Rust drops it: a temporary at the end of its statement, a +//! local at the end of its scope or at its `drop`, and a local moved into a call once that +//! call returns. A value C builds from literals is a view, which Rust copies and never frees, +//! so only what Rust returned is ever freed; one passed back by value is passed as a view +//! of itself, which leaves it the script's to free. + +use std::collections::HashMap; +use std::fmt::Write; + +use super::ir::{Access, Closure, Family, Int, Mutability, Receiver, Type}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Pat, Piece, Spec, Step, Transcript, unref}; + +const LANGUAGE: &str = "C"; + +/// Helpers the script calls, each for what C has no expression of: text built as Rust +/// formats it, bytes spelled by their length, and floats by their bits. +const PRELUDE: &str = r#"/* Generated from fixtures/api/examples/transcript.rs by tests/fixtures/transcript. */ + +#include + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wunused-function" + +/* Text a line or a format! builds. */ +typedef struct { + char *ptr; + size_t len; + size_t cap; +} tr_text; + +static void tr_put(tr_text *t, const char *s, size_t n) { + if (t->len + n + 1 > t->cap) { + t->cap = (t->len + n + 1) * 2; + t->ptr = realloc(t->ptr, t->cap); + if (!t->ptr) { + abort(); + } + } + if (n) { + memcpy(t->ptr + t->len, s, n); + } + t->len += n; +} + +static void tr_str(tr_text *t, const char *s) { + tr_put(t, s, strlen(s)); +} + +static void tr_fmt(tr_text *t, const char *fmt, ...) { + char small[64]; + va_list args; + va_start(args, fmt); + int n = vsnprintf(small, sizeof small, fmt, args); + va_end(args); + if (n < (int)sizeof small) { + tr_put(t, small, (size_t)n); + return; + } + char *big = malloc((size_t)n + 1); + va_start(args, fmt); + vsnprintf(big, (size_t)n + 1, fmt, args); + va_end(args); + tr_put(t, big, (size_t)n); + free(big); +} + +static void tr_buf(tr_text *t, PREFIX_buf b) { + tr_put(t, (const char *)b.ptr, b.len); +} + +/* A string as Rust's Debug prints it. */ +static void tr_quoted(tr_text *t, PREFIX_buf b) { + tr_str(t, "\""); + for (size_t i = 0; i < b.len; i++) { + unsigned char c = b.ptr[i]; + switch (c) { + case '"': + tr_str(t, "\\\""); + break; + case '\\': + tr_str(t, "\\\\"); + break; + case '\n': + tr_str(t, "\\n"); + break; + case '\r': + tr_str(t, "\\r"); + break; + case '\t': + tr_str(t, "\\t"); + break; + case 0: + tr_str(t, "\\0"); + break; + default: + if (c < 0x20 || c == 0x7f) { + tr_fmt(t, "\\u{%x}", c); + } else { + tr_put(t, (const char *)&c, 1); + } + } + } + tr_str(t, "\""); +} + +/* A char's UTF-8. */ +static void tr_char(tr_text *t, uint32_t c) { + char out[4]; + size_t n; + if (c < 0x80) { + out[0] = (char)c; + n = 1; + } else if (c < 0x800) { + out[0] = (char)(0xc0 | (c >> 6)); + out[1] = (char)(0x80 | (c & 0x3f)); + n = 2; + } else if (c < 0x10000) { + out[0] = (char)(0xe0 | (c >> 12)); + out[1] = (char)(0x80 | ((c >> 6) & 0x3f)); + out[2] = (char)(0x80 | (c & 0x3f)); + n = 3; + } else { + out[0] = (char)(0xf0 | (c >> 18)); + out[1] = (char)(0x80 | ((c >> 12) & 0x3f)); + out[2] = (char)(0x80 | ((c >> 6) & 0x3f)); + out[3] = (char)(0x80 | (c & 0x3f)); + n = 4; + } + tr_put(t, out, n); +} + +/* A u128 in hex, zero-padded to width digits. */ +static void tr_hex128(tr_text *t, PREFIX_u128 v, int width) { + char digits[33]; + if (v.hi) { + snprintf(digits, sizeof digits, "%llx%016llx", (unsigned long long)v.hi, (unsigned long long)v.lo); + } else { + snprintf(digits, sizeof digits, "%llx", (unsigned long long)v.lo); + } + for (int pad = width - (int)strlen(digits); pad > 0; pad--) { + tr_str(t, "0"); + } + tr_str(t, digits); +} + +/* The line, written whole, then freed. */ +static void tr_line(tr_text *t) { + tr_put(t, "\n", 1); + fwrite(t->ptr, 1, t->len, stdout); + free(t->ptr); +} + +/* The text as a buffer Rust owns, the text freed. */ +static PREFIX_buf tr_done(tr_text *t) { + PREFIX_buf b = PREFIX_buf_copy((PREFIX_buf){(const uint8_t *)(t->ptr ? t->ptr : ""), t->len, NULL}); + free(t->ptr); + return b; +} + +/* A buffer as a view, which Rust copies rather than takes. */ +static PREFIX_buf tr_view(PREFIX_buf b) { + b.owner = NULL; + return b; +} + +static double tr_f64(uint64_t bits) { + double f; + memcpy(&f, &bits, sizeof f); + return f; +} + +static float tr_f32(uint32_t bits) { + float f; + memcpy(&f, &bits, sizeof f); + return f; +} + +/* What an unwrap of None or of an error does in Rust. */ +static void tr_fail(const char *what) { + fprintf(stderr, "%s\n", what); + abort(); +} + +/* The items of an empty array, which is no None. */ +static _Alignas(max_align_t) const unsigned char tr_empty[64]; +"#; + +/// The C file of `t`'s script, `header` the export's C header it calls. +pub(crate) fn emit(t: &Transcript, header: &str) -> String { + let prefix = t.named(LANGUAGE, "prefix").to_string(); + let mut e = Emitter { + t, + upper: prefix.to_uppercase(), + declared: declared(header, &prefix), + p: prefix, + defs: String::new(), + out: String::new(), + depth: 1, + fresh: 0, + frames: Vec::new(), + scopes: vec![Scope::default()], + }; + for step in &t.steps { + e.step(step); + } + e.drop_scope(); + let mut out = PRELUDE.replace("PREFIX", &e.p); + out.push('\n'); + out.push_str(&e.defs); + out.push_str("static void script(void) {\n"); + out.push_str(&e.out); + out.push_str("}\n\n#pragma GCC diagnostic pop\n"); + out +} + +/// Each function `header` declares, by its name: how many parameters it takes, and +/// whether its last is a status. +fn declared(header: &str, prefix: &str) -> HashMap { + let status = format!("{prefix}_status *"); + let mut out = HashMap::new(); + for line in header.lines() { + let skip = line.starts_with(|c: char| c.is_whitespace() || c == '#' || c == '/' || c == '*') + || line.starts_with("typedef") + || !line.ends_with(");"); + if skip { + continue; + } + let Some(open) = line.find('(') else { continue }; + let name: String = { + let before: Vec = line[..open].chars().collect(); + let start = before + .iter() + .rposition(|c| !(c.is_alphanumeric() || *c == '_')) + .map_or(0, |i| i + 1); + before[start..].iter().collect() + }; + let params = &line[open + 1..line.len() - 2]; + let mut parts = Vec::new(); + let (mut depth, mut start) = (0, 0); + for (i, c) in params.char_indices() { + match c { + '(' => depth += 1, + ')' => depth -= 1, + ',' if depth == 0 => { + parts.push(params[start..i].trim()); + start = i + 1; + } + _ => {} + } + } + parts.push(params[start..].trim()); + let count = if parts == ["void"] { 0 } else { parts.len() }; + let statused = parts.last().is_some_and(|p| p.starts_with(&status)); + out.insert(name, (count, statused)); + } + out +} + +/// What the script frees once its owner goes: `key` names it, so a move out finds it. +#[derive(Clone)] +struct Owned { + key: String, + code: Vec, +} + +#[derive(Default)] +struct Scope { + locals: Vec<(String, Val)>, + owned: Vec, +} + +/// A C value: its expression, its Rust type, and its C type. +#[derive(Clone)] +struct Val { + c: String, + ty: Type, + cty: String, + form: Form, + /// Whether `c` names a place, so it may be read again without running anything. + named: bool, + /// Whether `c` has an address. + lv: bool, +} + +#[derive(Clone)] +enum Form { + Plain, + /// A tuple as its elements, each its own value, as a call returns one through its outs. + Tuple(Vec), + /// A call's `Result`: whether it succeeded, its value, and its error. + Result { + flag: String, + ok: Box, + err: Box, + }, +} + +impl Val { + fn new(c: impl Into, ty: Type, cty: impl Into) -> Val { + Val { + c: c.into(), + ty, + cty: cty.into(), + form: Form::Plain, + named: false, + lv: false, + } + } + + /// A value a variable or another place holds. + fn place(c: impl Into, ty: Type, cty: impl Into) -> Val { + Val { + named: true, + lv: true, + ..Val::new(c, ty, cty) + } + } + + fn unit() -> Val { + Val::new("", Type::Unit, "void") + } +} + +struct Emitter<'t> { + t: &'t Transcript, + p: String, + upper: String, + declared: HashMap, + /// The closures' functions, before the script that passes them. + defs: String, + out: String, + depth: usize, + fresh: usize, + /// The temporaries of each statement being written, freed at its end. + frames: Vec>, + scopes: Vec, +} + +impl Emitter<'_> { + fn line(&mut self, line: &str) { + let _ = writeln!(self.out, "{}{line}", "\t".repeat(self.depth)); + } + + fn fresh(&mut self, what: &str) -> String { + self.fresh += 1; + format!("tr_{what}{}", self.fresh) + } + + // Ownership. + + /// Start a statement: what it makes is freed at its end. + fn begin(&mut self) { + self.frames.push(Vec::new()); + } + + fn end(&mut self) { + let frame = self.frames.pop().expect("a statement"); + for owned in frame.iter().rev() { + for code in &owned.code { + self.line(code); + } + } + } + + /// A block of its own scope, opened by `head`. + fn open(&mut self, head: &str) { + self.line(&format!("{head} {{")); + self.depth += 1; + self.scopes.push(Scope::default()); + self.frames.push(Vec::new()); + } + + fn close(&mut self) { + self.end(); + self.drop_scope(); + self.depth -= 1; + self.line("}"); + } + + /// Free what the innermost scope owns, the last first, as Rust drops its locals. + fn drop_scope(&mut self) { + let scope = self.scopes.pop().expect("a scope"); + for owned in scope.owned.iter().rev() { + for code in &owned.code { + self.line(code); + } + } + } + + /// `c`, of type `ty`, freed at the end of this statement. + fn temp(&mut self, c: &str, ty: &Type) { + if self.owns(ty) { + let code = self.free(c, ty); + self.frames.last_mut().expect("a statement").push(Owned { + key: c.to_string(), + code, + }); + } + } + + /// Take `key` out of this statement's temporaries: whether it was one. + fn take(&mut self, key: &str) -> bool { + let Some(frame) = self.frames.last_mut() else { + return false; + }; + match frame.iter().position(|o| o.key == key) { + Some(i) => { + frame.remove(i); + true + } + None => false, + } + } + + /// The local `name`. + fn lookup(&self, name: &str) -> Option<&Val> { + self.scopes + .iter() + .rev() + .find_map(|s| s.locals.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v)) + } + + fn local(&self, name: &str) -> Val { + self.lookup(name).unwrap_or_else(|| panic!("no local {name}")).clone() + } + + /// What a scope owns under `key`, taken out. + fn take_owned(&mut self, key: &str) -> Option { + for scope in self.scopes.iter_mut().rev() { + if let Some(i) = scope.owned.iter().position(|o| o.key == key) { + return Some(scope.owned.remove(i)); + } + } + None + } + + /// The local `name` moved into a call: freed once the call's statement ends. + fn consume(&mut self, name: &str) { + let val = self.local(name); + let keys: Vec = match &val.form { + Form::Tuple(parts) => parts.iter().map(|p| p.c.clone()).collect(), + _ => vec![val.c.clone()], + }; + for key in keys { + if let Some(owned) = self.take_owned(&key) { + self.frames.last_mut().expect("a statement").push(owned); + } + } + } + + /// The local `name`, which a call wrote back through its `&mut`, owns what Rust wrote. + fn rewritten(&mut self, name: &str) { + let val = self.local(name); + if !self.owns(&val.ty) || self.scopes.iter().any(|s| s.owned.iter().any(|o| o.key == val.c)) { + return; + } + assert!(!self.holds_handle(&val.ty), "a &mut of a local holding a handle"); + let code = self.free(&val.c, &val.ty); + let scope = (self.scopes.iter_mut().rev()) + .find(|s| s.locals.iter().any(|(n, _)| n == name)) + .expect("the local's scope"); + scope.owned.push(Owned { key: val.c, code }); + } + + // Types. + + fn owns(&self, ty: &Type) -> bool { + self.owns_in(ty, &mut Vec::new()) + } + + fn owns_in(&self, ty: &Type, seen: &mut Vec) -> bool { + let api = &self.t.api; + match ty { + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => true, + Type::List(..) | Type::Object(_) => true, + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) => self.owns_in(inner, seen), + Type::Tuple(elements) => elements.iter().any(|e| self.owns_in(e, seen)), + Type::Record(i) if !seen.contains(ty) => { + seen.push(ty.clone()); + api.records[*i].opaque.is_none() && api.records[*i].fields.iter().any(|f| self.owns_in(&f.ty, seen)) + } + Type::Enum(i) if !seen.contains(ty) => { + seen.push(ty.clone()); + (api.enums[*i].variants.iter().flat_map(|v| &v.fields)).any(|f| self.owns_in(&f.ty, seen)) + } + _ => false, + } + } + + /// Whether a value of `ty` holds bytes Rust would take if passed by value. + fn viewed(&self, ty: &Type) -> bool { + let api = &self.t.api; + match ty { + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => true, + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) => self.viewed(inner), + Type::Tuple(elements) => elements.iter().any(|e| self.viewed(e)), + Type::Record(i) => { + api.records[*i].opaque.is_none() && api.records[*i].fields.iter().any(|f| self.viewed(&f.ty)) + } + Type::Enum(i) => (api.enums[*i].variants.iter().flat_map(|v| &v.fields)).any(|f| self.viewed(&f.ty)), + _ => false, + } + } + + fn holds_handle(&self, ty: &Type) -> bool { + let mut handles = Vec::new(); + self.handles(ty, &mut handles, &mut Vec::new()); + !handles.is_empty() + } + + fn handles(&self, ty: &Type, out: &mut Vec, seen: &mut Vec) { + let api = &self.t.api; + match ty { + Type::Object(i) => out.push(*i), + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => { + self.handles(inner, out, seen) + } + Type::Tuple(elements) => elements.iter().for_each(|e| self.handles(e, out, seen)), + Type::Record(i) if !seen.contains(ty) => { + seen.push(ty.clone()); + api.records[*i] + .fields + .iter() + .for_each(|f| self.handles(&f.ty, out, seen)); + } + Type::Enum(i) if !seen.contains(ty) => { + seen.push(ty.clone()); + (api.enums[*i].variants.iter().flat_map(|v| &v.fields)).for_each(|f| self.handles(&f.ty, out, seen)); + } + _ => {} + } + } + + /// Whether a local of `ty` stays usable after Rust passes it by value. + fn copy(&self, ty: &Type) -> bool { + let api = &self.t.api; + match ty { + Type::Object(i) => api.objects[*i].copy, + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => false, + Type::List(..) | Type::Callback(..) | Type::Closure(_) => false, + Type::Option(inner) | Type::Box(inner) => self.copy(inner), + Type::Ref(..) => true, + Type::Tuple(elements) => elements.iter().all(|e| self.copy(e)), + Type::Record(i) => api.records[*i].fields.iter().all(|f| self.copy(&f.ty)), + Type::Enum(i) => (api.enums[*i].variants.iter().flat_map(|v| &v.fields)).all(|f| self.copy(&f.ty)), + _ => true, + } + } + + /// The C name of a record, enum, object, or callback. + fn type_name(&self, ty: &Type) -> String { + match ty { + Type::Callback(i, _) => { + let path = self.t.api.callbacks[*i].path.join("::"); + self.t.named(LANGUAGE, &format!("type {path}")).to_string() + } + ty => self.t.type_name(LANGUAGE, ty).to_string(), + } + } + + /// A type's name after the prefix, as the structs built from it are named. + fn key(&self, ty: &Type) -> String { + let strip = |name: String| name[self.p.len() + 1..].to_string(); + match ty { + Type::Unit => "unit".to_string(), + Type::Bool => "bool".to_string(), + Type::Str | Type::String => "string".to_string(), + Type::Slice | Type::Vec | Type::Bytes => "bytes".to_string(), + Type::Path | Type::PathBuf => "path".to_string(), + Type::Int(int) => int.rust().to_string(), + Type::NonZero(int) => format!("non_zero_{}", int.rust()), + Type::F32 => "f32".to_string(), + Type::F64 => "f64".to_string(), + Type::Char => "char".to_string(), + Type::U128 => "u128".to_string(), + Type::Duration => "duration".to_string(), + Type::Array(n) => format!("array_u8_{n}"), + Type::SocketAddr(family) => addr(true, *family).to_string(), + Type::IpAddr(family) => addr(false, *family).to_string(), + Type::Option(inner) => format!("option_{}", self.key(inner)), + Type::List(_, inner) => format!("vec_{}", self.key(inner)), + Type::Tuple(_) => strip( + self.tuple_struct(ty) + .unwrap_or_else(|| panic!("C has no struct of {ty:?}")), + ), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => strip(self.type_name(ty)), + Type::Range(int) => format!("range_{}", int.rust()), + Type::Bound(int) => format!("bound_{}", int.rust()), + Type::Bounds(int) => format!("bounds_{}", int.rust()), + Type::Ref(_, inner) | Type::Box(inner) => self.key(inner), + other => panic!("no C struct holds {other:?}"), + } + } + + /// A tuple type as its struct's name is keyed: its elements' keys, a tuple's spelled. + fn spell(&self, ty: &Type) -> String { + match ty { + Type::Tuple(elements) => { + let elements: Vec = elements.iter().map(|e| self.spell(e)).collect(); + match elements.len() { + 1 => format!("({},)", elements[0]), + _ => format!("({})", elements.join(", ")), + } + } + ty => self.key(ty), + } + } + + /// The C struct of tuple type `ty`, if the header has one. + fn tuple_struct(&self, ty: &Type) -> Option { + let ty = owned(unref(ty)); + let Type::Tuple(_) = ty.base() else { return None }; + self.t + .find(LANGUAGE, &format!("tuple {}", self.spell(ty.base()))) + .map(str::to_string) + } + + /// The C type of a value of `ty`. + fn cty(&self, ty: &Type) -> String { + let p = &self.p; + match ty { + Type::Unit => "void".to_string(), + Type::Bool => "bool".to_string(), + Type::Int(int) | Type::NonZero(int) => c_int(*int).to_string(), + Type::F32 => "float".to_string(), + Type::F64 => "double".to_string(), + Type::Char => "uint32_t".to_string(), + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => { + format!("{p}_buf") + } + Type::U128 => format!("{p}_u128"), + Type::Duration => format!("{p}_duration"), + Type::Array(n) => format!("{p}_array_u8_{n}"), + Type::SocketAddr(family) => format!("{p}_{}", addr(true, *family)), + Type::IpAddr(family) => format!("{p}_{}", addr(false, *family)), + Type::List(_, inner) => format!("{p}_vec_{}", self.key(inner)), + Type::Option(inner) if nullable(inner) => self.cty(inner), + Type::Option(inner) => format!("{p}_option_{}", self.key(inner)), + Type::Box(inner) => self.cty(inner), + Type::Ref(m, inner) => match &**inner { + Type::Object(_) if *m == Mutability::Not => format!("const {} *", self.type_name(inner)), + inner => self.cty(inner), + }, + Type::Record(_) | Type::Enum(_) | Type::Callback(..) => self.type_name(ty), + Type::Object(_) => format!("{} *", self.type_name(ty)), + Type::Range(_) | Type::Bound(_) | Type::Bounds(_) => format!("{p}_{}", self.key(ty)), + Type::Tuple(_) => self + .tuple_struct(ty) + .unwrap_or_else(|| panic!("C has no struct of {ty:?}")), + other => panic!("no C value is a {other:?}"), + } + } + + /// Whether a C value of `ty` is a struct, which `{0}` zeroes, rather than a scalar. + fn is_struct(&self, ty: &Type) -> bool { + match ty { + Type::Unit | Type::Bool | Type::Int(_) | Type::NonZero(_) | Type::F32 | Type::F64 | Type::Char => false, + Type::Object(_) => false, + Type::Enum(i) => !self.t.api.enums[*i].variants.iter().all(|v| v.fields.is_empty()), + Type::Option(inner) if nullable(inner) => self.is_struct(inner), + Type::Ref(_, inner) | Type::Box(inner) => self.is_struct(inner), + _ => true, + } + } + + fn zero(&self, ty: &Type) -> &'static str { + if self.is_struct(ty) { "{0}" } else { "0" } + } + + /// What frees `c`, an owned value of `ty`. + fn free(&self, c: &str, ty: &Type) -> Vec { + let p = &self.p; + match ty { + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => { + vec![format!("{p}_buf_free({c});")] + } + Type::List(_, inner) => vec![format!("{p}_vec_{}_free({c});", self.key(inner))], + Type::Object(_) => vec![format!("{}_free({c});", self.type_name(ty))], + Type::Ref(_, inner) | Type::Box(inner) => self.free(c, inner), + Type::Option(inner) if nullable(inner) => self.free(c, inner), + Type::Option(inner) if self.owns(inner) => { + let inner = self.free(&format!("{c}.value"), inner).join(" "); + vec![format!("if ({c}.some) {{ {inner} }}")] + } + Type::Record(_) | Type::Enum(_) if self.owns(ty) => vec![format!("{}_free(&{c});", self.type_name(ty))], + Type::Tuple(elements) => (elements.iter().enumerate()) + .flat_map(|(i, e)| self.free(&format!("{c}._{i}"), e)) + .collect(), + _ => Vec::new(), + } + } + + /// `c`, a place holding a value of `ty`, as a view that leaves Rust nothing to take. + fn view(&self, c: &str, ty: &Type) -> String { + if !self.viewed(ty) { + return c.to_string(); + } + let api = &self.t.api; + match ty { + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf => { + format!("tr_view({c})") + } + Type::Ref(_, inner) | Type::Box(inner) => self.view(c, inner), + Type::Option(inner) if nullable(inner) => self.view(c, inner), + Type::Option(inner) => format!( + "({}){{.some = {c}.some, .value = {}}}", + self.cty(ty), + self.view(&format!("{c}.value"), inner) + ), + Type::Record(i) => { + let key = format!("type {}", self.t.rust(ty)); + let fields: Vec = (api.records[*i].fields.iter()) + .map(|f| { + let name = self.t.named(LANGUAGE, &format!("{key} / field {}", f.name)); + format!(".{name} = {}", self.view(&format!("{c}.{name}"), &f.ty)) + }) + .collect(); + format!("({}){{{}}}", self.cty(ty), fields.join(", ")) + } + Type::Tuple(elements) => { + let fields: Vec = (elements.iter().enumerate()) + .map(|(i, e)| format!("._{i} = {}", self.view(&format!("{c}._{i}"), e))) + .collect(); + format!("({}){{{}}}", self.cty(ty), fields.join(", ")) + } + ty => panic!("a {ty:?} holding bytes passed by value"), + } + } + + /// Whether the header declares `name` taking a status last, checking it declares it. + fn statused(&self, name: &str) -> bool { + self.declared + .get(name) + .unwrap_or_else(|| panic!("the C header declares no {name}")) + .1 + } + + /// The call of `name` with `args`, a status appended if it takes one. + fn invoke(&self, name: &str, mut args: Vec) -> String { + if self.statused(name) { + args.push("NULL".to_string()); + } + let (count, _) = self.declared[name]; + assert_eq!( + count, + args.len(), + "{name} takes {count} parameters, not ({})", + args.join(", ") + ); + format!("{name}({})", args.join(", ")) + } + + // Values. + + /// `v` where its address is taken: bound to a variable unless it is a place. + fn place(&mut self, v: Val) -> Val { + if v.lv && v.named { + return v; + } + let name = self.fresh("p"); + self.line(&format!("{} {name} = {};", v.cty, v.c)); + Val { + c: name, + named: true, + lv: true, + ..v + } + } + + /// A call's result, bound to a fresh variable, freed at the statement's end if owned. + fn bound(&mut self, call: String, ty: &Type) -> Val { + if *ty == Type::Unit { + self.line(&format!("{call};")); + return Val::unit(); + } + let name = self.fresh("t"); + let cty = self.cty(ty); + self.line(&format!("{cty} {name} = {call};")); + self.temp(&name, ty); + Val::place(name, ty.clone(), cty) + } + + fn expr(&mut self, e: &Expr) -> Val { + self.value(e, &e.ty) + } + + /// The C argument of `e`, passed where `want` is taken. + fn arg(&mut self, e: &Expr, want: &Type) -> String { + let v = self.value(e, want); + self.pass(v, want) + } + + /// `v` as an argument where `want` is taken: a tuple of elements in its struct, an + /// address of one family as any, an array as bytes, and what Rust would take as a view. + fn pass(&mut self, v: Val, want: &Type) -> String { + let w = unref(want).base().clone(); + let p = self.p.clone(); + match v.form { + Form::Tuple(parts) => { + let elements = match &w { + Type::Tuple(elements) => elements.clone(), + Type::Bounds(int) => vec![Type::Bound(*int), Type::Bound(*int)], + w => panic!("a tuple passed as {w:?}"), + }; + let fields: Vec = match &w { + Type::Bounds(_) => vec!["start".to_string(), "end".to_string()], + _ => (0..parts.len()).map(|i| format!("_{i}")).collect(), + }; + let values: Vec = (parts.into_iter().zip(&elements).zip(fields)) + .map(|((part, ty), field)| format!(".{field} = {}", self.pass(part, ty))) + .collect(); + return format!("({}){{{}}}", self.cty(&w), values.join(", ")); + } + Form::Result { .. } => panic!("a Result passed as {w:?}"), + Form::Plain => {} + } + let have = unref(&v.ty).base().clone(); + match (&have, &w) { + (Type::SocketAddr(f), Type::SocketAddr(Family::Any)) if *f != Family::Any => { + let six = *f == Family::V6; + let member = if six { "v6" } else { "v4" }; + return format!("({p}_socket_addr){{.v6 = {six}, .addr.{member} = {}}}", v.c); + } + (Type::IpAddr(f), Type::IpAddr(Family::Any)) if *f != Family::Any => { + let six = *f == Family::V6; + let member = if six { "v6" } else { "v4" }; + return format!("({p}_ip_addr){{.v6 = {six}, .ip.{member} = {}}}", v.c); + } + (Type::Array(n), w) if is_buf(w) => { + let v = self.place(v); + return format!("({p}_buf){{{}.items, {n}, NULL}}", v.c); + } + _ => {} + } + let mut c = match v.named && self.viewed(&v.ty) { + true => self.view(&v.c, &v.ty), + false => v.c.clone(), + }; + let wc = self.cty(want); + if v.cty.starts_with("const ") && !wc.starts_with("const ") && wc.ends_with('*') { + c = format!("({wc}){c}"); + } + c + } + + /// The C of `e`, built as `want` where it is a literal. + fn value(&mut self, e: &Expr, want: &Type) -> Val { + let t = self.t; + let p = self.p.clone(); + let base = unref(want).base().clone(); + match &e.kind { + Kind::Unit => Val::unit(), + Kind::Bool(b) => Val::new(b.to_string(), Type::Bool, "bool"), + Kind::Int(n) => self.int(*n, &base), + Kind::Float(f) => match base { + Type::F32 => Val::new(format!("tr_f32(0x{:x}u)", (*f as f32).to_bits()), Type::F32, "float"), + Type::F64 => Val::new(format!("tr_f64(0x{:x}ULL)", f.to_bits()), Type::F64, "double"), + ty => panic!("a float as {ty:?}"), + }, + Kind::Char(c) => Val::new(format!("0x{:x}u", *c as u32), Type::Char, "uint32_t"), + Kind::Str(s) => self.bytes(s.as_bytes(), want), + Kind::Bytes(b) => match base { + Type::Array(n) => { + assert_eq!(n, b.len(), "an array literal of another length"); + let items: Vec = b.iter().map(|b| b.to_string()).collect(); + let cty = format!("{p}_array_u8_{n}"); + Val { + lv: true, + ..Val::new( + format!("({cty}){{.items = {{{}}}}}", items.join(", ")), + base.clone(), + cty, + ) + } + } + _ => self.bytes(b, want), + }, + Kind::Duration(secs, nanos) => { + let cty = format!("{p}_duration"); + Val::new( + format!("({cty}){{.secs = {secs}ULL, .nanos = {nanos}u}}"), + Type::Duration, + cty, + ) + } + Kind::Socket(addr) => self.socket(addr, &base), + Kind::Ip(ip) => self.ip(ip, &base), + Kind::None => { + let Type::Option(inner) = &base else { + panic!("None as {base:?}") + }; + let cty = self.cty(&base); + match nullable(inner) && !self.is_struct(inner) { + true => Val::new("NULL", base.clone(), cty), + false => Val::new(format!("({cty}){{0}}"), base.clone(), cty), + } + } + Kind::Some(inner) => { + let Type::Option(iw) = &base else { + panic!("Some as {base:?}") + }; + let iw = (**iw).clone(); + if nullable(&iw) { + let v = self.value(inner, &iw); + let c = self.pass(v, &iw); + return Val::new(c, base.clone(), self.cty(&base)); + } + let v = self.value(inner, &iw); + let c = self.pass(v, &iw); + let cty = self.cty(&base); + Val { + lv: true, + ..Val::new(format!("({cty}){{.some = true, .value = {c}}}"), base.clone(), cty) + } + } + Kind::Tuple(elements) => match &base { + Type::Range(int) => { + let int = Type::Int(*int); + let (a, b) = (self.arg(&elements[0], &int), self.arg(&elements[1], &int)); + let cty = self.cty(&base); + Val::new(format!("({cty}){{.start = {a}, .end = {b}}}"), base.clone(), cty) + } + Type::Bounds(int) => { + let bound = Type::Bound(*int); + let (a, b) = (self.arg(&elements[0], &bound), self.arg(&elements[1], &bound)); + let cty = self.cty(&base); + Val::new(format!("({cty}){{.start = {a}, .end = {b}}}"), base.clone(), cty) + } + _ => { + let wants: Vec = match &base { + Type::Tuple(ws) => ws.clone(), + _ => elements.iter().map(|e| e.ty.clone()).collect(), + }; + let parts: Vec = elements.iter().zip(&wants).map(|(e, w)| self.value(e, w)).collect(); + let ty = Type::Tuple(wants); + let cty = self.tuple_struct(&ty).unwrap_or_default(); + Val { + form: Form::Tuple(parts), + ..Val::new("", ty, cty) + } + } + }, + Kind::List(items) => { + let Type::List(_, item) = &base else { + panic!("a list as {base:?}") + }; + let item = (**item).clone(); + let cty = self.cty(&base); + let elem = self.cty(&owned(&item)); + let len = items.len(); + let ptr = match items.is_empty() { + true => match &item.base() { + Type::Object(_) => format!("({elem}const *)(const void *)tr_empty"), + _ => format!("(const {elem} *)(const void *)tr_empty"), + }, + false => { + let values: Vec = items.iter().map(|e| self.arg(e, &item)).collect(); + format!("({elem}[]){{{}}}", values.join(", ")) + } + }; + Val { + lv: true, + ..Val::new(format!("({cty}){{{ptr}, {len}, NULL}}"), base.clone(), cty) + } + } + Kind::Record(r, fields) => { + let record = &t.api.records[*r]; + assert!( + record.opaque.is_none(), + "a literal of {}, which only Rust makes", + t.rust(&Type::Record(*r)) + ); + let ty = Type::Record(*r); + let key = format!("type {}", t.rust(&ty)); + let values: Vec = (fields.iter().zip(&record.fields)) + .map(|(v, f)| { + let name = t.named(LANGUAGE, &format!("{key} / field {}", f.name)).to_string(); + format!(".{name} = {}", self.arg(v, &f.ty)) + }) + .collect(); + let cty = self.cty(&ty); + Val { + lv: true, + ..Val::new(format!("({cty}){{{}}}", values.join(", ")), ty, cty) + } + } + Kind::Variant(en, v, fields) => { + let ty = Type::Enum(*en); + let enumeration = &t.api.enums[*en]; + let variant = &enumeration.variants[*v]; + let key = format!("type {}", t.rust(&ty)); + let constant = t + .named(LANGUAGE, &format!("{key} / variant {}", variant.name)) + .to_string(); + let cty = self.cty(&ty); + if enumeration.variants.iter().all(|v| v.fields.is_empty()) { + return Val::new(constant, ty, cty); + } + if fields.is_empty() { + return Val { + lv: true, + ..Val::new(format!("({cty}){{.tag = {constant}}}"), ty, cty) + }; + } + let member = t + .named(LANGUAGE, &format!("{key} / member {}", variant.name)) + .to_string(); + let values: Vec = (fields.iter().zip(&variant.fields)) + .map(|(v, f)| { + let name = t.named( + LANGUAGE, + &format!("{key} / variant {} / field {}", variant.name, f.name), + ); + let name = name.to_string(); + format!(".{name} = {}", self.arg(v, &f.ty)) + }) + .collect(); + Val { + lv: true, + ..Val::new( + format!("({cty}){{.tag = {constant}, .{member} = {{{}}}}}", values.join(", ")), + ty, + cty, + ) + } + } + Kind::Bound(kind, value) => { + let Type::Bound(int) = base else { + panic!("a bound as {base:?}") + }; + let cty = self.cty(&base); + let (kind, v) = match (kind, value) { + (BoundKind::Unbounded, _) => ("UNBOUNDED", "0".to_string()), + (BoundKind::Included, Some(v)) => ("INCLUDED", self.arg(v, &Type::Int(int))), + (BoundKind::Excluded, Some(v)) => ("EXCLUDED", self.arg(v, &Type::Int(int))), + _ => unreachable!(), + }; + let upper = self.upper.clone(); + Val::new( + format!("({cty}){{.kind = {upper}_BOUND_{kind}, .value = {v}}}"), + base.clone(), + cty, + ) + } + Kind::Default => { + let ty = base.clone(); + let name = format!("{}_default", self.type_name(&ty)); + let call = self.invoke(&name, Vec::new()); + self.bound(call, &ty) + } + Kind::Var(name) => self.local(name), + Kind::Const(c) => { + let constant = &t.api.constants[*c]; + let name = t.named(LANGUAGE, &format!("const {}", constant.path.join("::"))); + let ty = match constant.value { + super::ir::Literal::Bool(_) => Type::Bool, + super::ir::Literal::Int(int, _) => Type::Int(int), + }; + let cty = self.cty(&ty); + Val::new(name, ty, cty) + } + Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args), + Kind::Field(record, i) => { + let b = self.expr(record); + let b = match b.named { + true => b, + false => self.place(b), + }; + let Type::Record(r) = unref(&b.ty).base() else { + panic!("a field of {:?}", b.ty) + }; + let field = &t.api.records[*r].fields[*i]; + let key = format!("type {} / field {}", t.rust(&Type::Record(*r)), field.name); + let name = t.named(LANGUAGE, &key); + Val::place(format!("{}.{name}", b.c), field.ty.clone(), self.cty(&field.ty)) + } + Kind::Element(tuple, i) => { + let b = self.expr(tuple); + match (&b.form, unref(&b.ty).base()) { + (Form::Tuple(parts), _) => parts[*i].clone(), + (_, Type::Range(int)) => { + let field = if *i == 0 { "start" } else { "end" }; + Val::new(format!("{}.{field}", b.c), Type::Int(*int), c_int(*int)) + } + (_, Type::Tuple(elements)) => { + let ty = elements[*i].clone(); + let b = self.place(b); + Val::place(format!("{}._{i}", b.c), ty.clone(), self.cty(&ty)) + } + (_, ty) => panic!("an element of {ty:?}"), + } + } + Kind::Clone(inner) => { + let v = self.expr(inner); + match unref(&v.ty).base() { + Type::Object(_) => { + let ty = owned(unref(&v.ty)); + let name = format!("{}_clone", self.type_name(&ty)); + let call = self.invoke(&name, vec![v.c.clone()]); + self.bound(call, &ty) + } + // A value C holds is read where it is: its clone is the same view. + _ => v, + } + } + Kind::Unwrap(inner) => { + let v = self.expr(inner); + self.unwrap(v) + } + Kind::UnwrapErr(inner) => { + let v = self.expr(inner); + let Form::Result { flag, err, .. } = &v.form else { + panic!("unwrap_err of {:?}", v.ty) + }; + self.line(&format!("if ({flag}) tr_fail(\"unwrap_err of an Ok\");")); + let err = (**err).clone(); + if self.take(flag) { + self.temp(&err.c, &err.ty); + } + err + } + Kind::IsErr(inner) => { + let v = self.expr(inner); + let Form::Result { flag, .. } = &v.form else { + panic!("is_err of {:?}", v.ty) + }; + Val::new(format!("(!{flag})"), Type::Bool, "bool") + } + Kind::IsSome(inner) => { + let v = self.expr(inner); + let v = self.named(v); + Val::new(format!("({})", self.is_some(&v)), Type::Bool, "bool") + } + Kind::IsNone(inner) => { + let v = self.expr(inner); + let v = self.named(v); + Val::new(format!("(!({}))", self.is_some(&v)), Type::Bool, "bool") + } + Kind::Binary(op, a, b) => self.binary(*op, a, b, &e.ty), + Kind::Closure(..) => panic!("a closure anywhere but an argument"), + Kind::Local(name, args) => { + let params = t.locals.get(name).cloned().unwrap_or_default(); + assert_eq!(params.len(), args.len(), "{name} takes {} arguments", params.len()); + let args: Vec = args.iter().zip(¶ms).map(|(a, p)| self.arg(a, p)).collect(); + let call = format!("{name}({})", args.join(", ")); + self.bound(call, &e.ty) + } + Kind::Format(pieces) => { + let text = self.text(pieces); + let name = self.fresh("t"); + self.line(&format!("{p}_buf {name} = tr_done(&{text});")); + self.temp(&name, &Type::String); + Val::place(name, Type::String, format!("{p}_buf")) + } + Kind::Join { items, pat, body, sep } => self.join(items, pat, body, sep), + Kind::MapOr { + option, + none, + pat, + some, + } => self.map_or(option, none, pat, some, &e.ty), + Kind::Utf8(inner) => { + let v = self.expr(inner); + Val { ty: Type::String, ..v } + } + Kind::Len(inner) => { + let v = self.expr(inner); + let v = self.named(v); + Val::new(format!("{}.len", v.c), Type::Int(Int::Usize), "size_t") + } + } + } + + /// `v`, bound to a variable unless it names one, so it may be read again. + fn named(&mut self, v: Val) -> Val { + match v.named || !matches!(v.form, Form::Plain) { + true => v, + false => self.place(v), + } + } + + fn int(&self, n: Num, ty: &Type) -> Val { + let p = &self.p; + match ty { + Type::Int(int) | Type::NonZero(int) => { + let cty = c_int(*int); + let m = n.magnitude; + let c = match (n.negative, int.signed()) { + (true, _) if m == 1u128 << (int.bits() - 1) => format!("(({cty})(-{}LL - 1))", m - 1), + (true, _) => format!("(({cty})-{m}LL)"), + (false, true) => format!("(({cty}){m}LL)"), + (false, false) => format!("(({cty}){m}ULL)"), + }; + Val::new(c, ty.clone(), cty) + } + Type::U128 => { + let m = n.magnitude; + let cty = format!("{p}_u128"); + let c = format!("({cty}){{.lo = {}ULL, .hi = {}ULL}}", m as u64, (m >> 64) as u64); + Val { + lv: true, + ..Val::new(c, Type::U128, cty) + } + } + Type::F32 => Val::new( + format!("tr_f32(0x{:x}u)", (n.magnitude as f32).to_bits()), + Type::F32, + "float", + ), + Type::F64 => Val::new( + format!("tr_f64(0x{:x}ULL)", (n.magnitude as f64).to_bits()), + Type::F64, + "double", + ), + ty => panic!("an integer as {ty:?}"), + } + } + + /// Bytes, or a string's, as a view of a literal. + fn bytes(&self, b: &[u8], want: &Type) -> Val { + let p = &self.p; + let cty = format!("{p}_buf"); + let ty = match unref(want).base() { + ty if is_buf(ty) => ty.clone(), + ty => panic!("bytes as {ty:?}"), + }; + Val { + lv: true, + ..Val::new( + format!("({cty}){{(const uint8_t *){}, {}, NULL}}", literal(b), b.len()), + ty, + cty, + ) + } + } + + fn octets(octets: &[u8]) -> String { + let o: Vec = octets.iter().map(|o| o.to_string()).collect(); + format!("{{{{{}}}}}", o.join(", ")) + } + + fn socket(&self, addr: &std::net::SocketAddr, want: &Type) -> Val { + let Type::SocketAddr(family) = want else { + panic!("a socket address as {want:?}") + }; + let v4 = + |a: &std::net::SocketAddrV4| format!("{{.ip = {}, .port = {}}}", Self::octets(&a.ip().octets()), a.port()); + let v6 = |a: &std::net::SocketAddrV6| { + format!( + "{{.ip = {}, .port = {}, .flowinfo = {}u, .scope_id = {}u}}", + Self::octets(&a.ip().octets()), + a.port(), + a.flowinfo(), + a.scope_id() + ) + }; + let cty = self.cty(want); + let c = match (family, addr) { + (Family::Any, std::net::SocketAddr::V4(a)) => format!("({cty}){{.v6 = false, .addr.v4 = {}}}", v4(a)), + (Family::Any, std::net::SocketAddr::V6(a)) => format!("({cty}){{.v6 = true, .addr.v6 = {}}}", v6(a)), + (Family::V4, std::net::SocketAddr::V4(a)) => format!("({cty}){}", v4(a)), + (Family::V6, std::net::SocketAddr::V6(a)) => format!("({cty}){}", v6(a)), + (family, addr) => panic!("{addr} as a socket address of {family:?}"), + }; + Val { + lv: true, + ..Val::new(c, want.clone(), cty) + } + } + + fn ip(&self, ip: &std::net::IpAddr, want: &Type) -> Val { + let Type::IpAddr(family) = want else { + panic!("an IP address as {want:?}") + }; + let cty = self.cty(want); + let c = match (family, ip) { + (Family::Any, std::net::IpAddr::V4(a)) => { + format!("({cty}){{.v6 = false, .ip.v4 = {}}}", Self::octets(&a.octets())) + } + (Family::Any, std::net::IpAddr::V6(a)) => { + format!("({cty}){{.v6 = true, .ip.v6 = {}}}", Self::octets(&a.octets())) + } + (Family::V4, std::net::IpAddr::V4(a)) => format!("({cty}){}", Self::octets(&a.octets())), + (Family::V6, std::net::IpAddr::V6(a)) => format!("({cty}){}", Self::octets(&a.octets())), + (family, ip) => panic!("{ip} as an IP address of {family:?}"), + }; + Val { + lv: true, + ..Val::new(c, want.clone(), cty) + } + } + + /// Whether `v`, an option, is `Some`. + fn is_some(&self, v: &Val) -> String { + let Type::Option(inner) = unref(&v.ty).base() else { + panic!("an option of {:?}", v.ty) + }; + match (nullable(inner), inner.base()) { + (true, Type::Object(_)) => format!("{} != NULL", v.c), + (true, _) => format!("{}.ptr != NULL", v.c), + (false, _) => format!("{}.some", v.c), + } + } + + /// The value `v`, an option known to be `Some`, holds. + fn inner(&self, v: &Val) -> Val { + let Type::Option(inner) = unref(&v.ty).base() else { + panic!("an option of {:?}", v.ty) + }; + let inner = (**inner).clone(); + let cty = self.cty(&inner); + match nullable(&inner) { + true => Val { + ty: inner, + cty, + ..v.clone() + }, + false => Val::place(format!("{}.value", v.c), inner, cty), + } + } + + fn unwrap(&mut self, v: Val) -> Val { + match &v.form { + Form::Result { flag, ok, .. } => { + self.line(&format!("if (!{flag}) tr_fail(\"unwrap of an Err\");")); + let ok = (**ok).clone(); + if self.take(flag) { + match &ok.form { + Form::Tuple(parts) => { + for part in parts { + self.temp(&part.c, &part.ty); + } + } + _ => self.temp(&ok.c, &ok.ty), + } + } + ok + } + _ => { + let v = self.named(v); + let some = self.is_some(&v); + self.line(&format!("if (!({some})) tr_fail(\"unwrap of None\");")); + let inner = self.inner(&v); + if self.take(&v.c) { + self.temp(&inner.c, &inner.ty); + } + inner + } + } + } + + fn binary(&mut self, op: Op, a: &Expr, b: &Expr, ty: &Type) -> Val { + if op == Op::And { + let a = self.expr(a); + let r = self.fresh("b"); + self.line(&format!("bool {r} = {};", a.c)); + self.open(&format!("if ({r})")); + let b = self.expr(b); + self.line(&format!("{r} = {};", b.c)); + self.close(); + return Val::new(r, Type::Bool, "bool"); + } + let (a, b) = (self.expr(a), self.expr(b)); + let operand = unref(&a.ty).base().clone(); + let c = match op { + Op::Eq | Op::Ne => { + let equal = match &operand { + Type::Record(_) => Some(true), + Type::Enum(_) => Some(true), + Type::Object(_) => Some(false), + _ => None, + }; + let eq = match equal { + Some(by_address) => { + let name = format!("{}_eq", self.type_name(&operand)); + let (a, b) = match by_address { + true => (self.place(a), self.place(b)), + false => (a, b), + }; + let amp = if by_address { "&" } else { "" }; + let call = self.invoke(&name, vec![format!("{amp}{}", a.c), format!("{amp}{}", b.c)]); + self.bound(call, &Type::Bool).c + } + None => format!("({} == {})", a.c, b.c), + }; + match op { + Op::Eq => eq, + _ => format!("(!{eq})"), + } + } + Op::Lt => format!("({} < {})", a.c, b.c), + Op::Gt => format!("({} > {})", a.c, b.c), + Op::Add | Op::Sub | Op::Mul | Op::Rem => { + let symbol = match op { + Op::Add => "+", + Op::Sub => "-", + Op::Mul => "*", + _ => "%", + }; + format!("(({})({} {symbol} {}))", self.cty(ty), a.c, b.c) + } + Op::And => unreachable!(), + }; + let cty = self.cty(ty); + Val::new(c, ty.clone(), cty) + } + + /// A call of `id`: a function, an associated function, a method, or a field's getter or + /// setter, its result bound to a variable, and each local it moves freed after it. + fn call(&mut self, id: FnId, receiver: Option<&Expr>, args: &[Expr]) -> Val { + let t = self.t; + let f = t.function(id); + assert!( + !f.future, + "{} makes a future, which only a function of api.c polls", + t.key(id) + ); + let name = t.name(LANGUAGE, id).to_string(); + let mut cargs = Vec::new(); + let mut moved = Vec::new(); + if let Some(r) = receiver { + let owner = t.owner(id).expect("a method's type"); + let v = self.expr(r); + let by_value = f.receiver == Some(Receiver::Owned); + if by_value + && !self.copy(&owner) + && let Kind::Var(local) = &r.kind + { + moved.push(local.clone()); + } + match owner { + Type::Object(i) => { + let constant = f.receiver == Some(Receiver::Ref) || (by_value && t.api.objects[i].copy); + let c = match !constant && v.cty.starts_with("const ") { + true => format!("({} *){}", self.type_name(&owner), v.c), + false => v.c, + }; + cargs.push(c); + } + _ => { + if f.receiver == Some(Receiver::Mut) { + assert!( + v.named && v.lv, + "{}: a value's &mut self on anything but a place", + t.key(id) + ); + } + let v = self.place(v); + cargs.push(format!("&{}", v.c)); + } + } + } + let mut written = Vec::new(); + let mut rewritten = Vec::new(); + for (a, param) in args.iter().zip(&f.params) { + match ¶m.ty { + Type::Closure(closure) => { + let (function, data) = self.closure(a, closure); + cargs.push(function); + cargs.push(data); + if closure.kept { + cargs.push("NULL".to_string()); + } + } + ty if written_back(ty) => { + let Kind::Var(local) = &a.kind else { + panic!("{}: a &mut of anything but a local", t.key(id)) + }; + let v = self.expr(a); + assert!(matches!(v.form, Form::Plain), "a &mut of a tuple's elements"); + cargs.push(v.c.clone()); + written.push(format!("&{}", v.c)); + rewritten.push(local.clone()); + } + ty => { + cargs.push(self.arg(a, ty)); + if let Kind::Var(local) = &a.kind + && !matches!(ty, Type::Ref(..)) + && !matches!(ty, Type::Option(inner) if matches!(**inner, Type::Ref(..))) + && !self.copy(&self.local(local).ty) + { + moved.push(local.clone()); + } + } + } + } + cargs.extend(written); + let result = self.returned(&name, f.ok.clone(), f.err.clone(), cargs); + for local in rewritten { + self.rewritten(&local); + } + for local in moved { + self.consume(&local); + } + result + } + + /// The call of `name` with `args`, returning `ok`, or failing with `err`, as the C + /// function does: a value returned, or written through outs. + fn returned(&mut self, name: &str, ok: Type, err: Option, mut args: Vec) -> Val { + if err.is_none() && !matches!(ok, Type::Tuple(_)) { + let ty = owned(&ok); + let call = self.invoke(name, args); + return self.bound(call, &ty); + } + let parts: Vec = match &ok { + Type::Unit => Vec::new(), + Type::Tuple(elements) => elements.iter().map(owned).collect(), + ok => vec![owned(ok)], + }; + let mut outs = Vec::new(); + for ty in &parts { + let out = self.out(ty); + args.push(format!("&{}", out.c)); + outs.push(out); + } + let ok_ty = owned(&ok); + let ok_val = match &ok { + Type::Unit => Val::unit(), + Type::Tuple(_) => { + let cty = self.tuple_struct(&ok_ty).unwrap_or_default(); + Val { + form: Form::Tuple(outs.clone()), + ..Val::new("", ok_ty.clone(), cty) + } + } + _ => outs[0].clone(), + }; + let Some(err) = err else { + let call = self.invoke(name, args); + self.line(&format!("{call};")); + for out in &outs { + self.temp(&out.c, &out.ty); + } + return ok_val; + }; + let err_ty = owned(&err); + let err_val = self.out(&err_ty); + args.push(format!("&{}", err_val.c)); + let flag = self.fresh("ok"); + let call = self.invoke(name, args); + self.line(&format!("bool {flag} = {call};")); + let ok_free: Vec = outs.iter().flat_map(|o| self.free(&o.c, &o.ty)).collect(); + let err_free = self.free(&err_val.c, &err_ty); + if !ok_free.is_empty() || !err_free.is_empty() { + let code = format!( + "if ({flag}) {{ {} }} else {{ {} }}", + ok_free.join(" "), + err_free.join(" ") + ); + self.frames.last_mut().expect("a statement").push(Owned { + key: flag.clone(), + code: vec![code], + }); + } + Val { + form: Form::Result { + flag, + ok: Box::new(ok_val), + err: Box::new(err_val), + }, + ..Val::new("", Type::Result(Box::new(ok_ty), Box::new(err_ty)), "") + } + } + + /// A zeroed variable a call writes a value of `ty` through. + fn out(&mut self, ty: &Type) -> Val { + let name = self.fresh("o"); + let cty = self.cty(ty); + let zero = self.zero(ty); + self.line(&format!("{cty} {name} = {zero};")); + Val::place(name, ty.clone(), cty) + } + + /// The function a closure is, and the data passed with it: each local it captures is + /// read through a static of its own, so a closure Rust keeps past the call reads it too. + fn closure(&mut self, e: &Expr, closure: &Closure) -> (String, String) { + let Kind::Closure(params, steps, value) = &e.kind else { + panic!("a closure's parameter passed anything but a closure") + }; + assert!( + closure.err.is_none(), + "a closure returning a Result, which only api.c writes" + ); + let n = self.fresh("closure"); + let mut used = Vec::new(); + for step in steps { + each_expr(step, &mut |e| walk(e, &mut |e| vars(e, &mut used))); + } + walk(value, &mut |e| vars(e, &mut used)); + let captured: Vec<(String, Val)> = (used.iter()) + .filter_map(|name| self.lookup(name).map(|v| (name.clone(), v.clone()))) + .collect(); + let env = format!("{n}_env"); + if !captured.is_empty() { + let fields: Vec = (captured.iter()) + .map(|(name, v)| { + assert!( + matches!(v.form, Form::Plain) && v.lv, + "a closure capturing {name}, which is no place" + ); + format!("\t{} *v_{name};\n", v.cty) + }) + .collect(); + let _ = writeln!(self.defs, "static struct {{\n{}}} {env};\n", fields.concat()); + for (name, v) in &captured { + self.line(&format!("{env}.v_{name} = &{};", v.c)); + } + } + let ret = self.cty(&closure.ok); + // The closure's body, written apart. + let out = std::mem::take(&mut self.out); + let depth = std::mem::replace(&mut self.depth, 1); + let frames = std::mem::take(&mut self.frames); + let mut scope = Scope::default(); + for (name, v) in &captured { + scope.locals.push(( + name.clone(), + Val::place(format!("(*{env}.v_{name})"), v.ty.clone(), v.cty.clone()), + )); + } + let scopes = std::mem::replace(&mut self.scopes, vec![scope]); + let mut decls = vec!["void *data".to_string()]; + let mut tuples = Vec::new(); + for (pat, ty) in params.iter().zip(&closure.params) { + let cty = self.cty(ty); + let name = match pat { + Pat::Name(name, _) => { + let c = format!("v_{name}"); + self.scopes[0] + .locals + .push((name.clone(), Val::place(c.clone(), ty.clone(), cty.clone()))); + c + } + Pat::Ignore(_) => self.fresh("unused"), + Pat::Tuple(_) => { + let c = self.fresh("arg"); + tuples.push((pat.clone(), Val::place(c.clone(), ty.clone(), cty.clone()))); + c + } + }; + decls.push(format!("{cty} {name}")); + } + for (pat, v) in tuples { + self.begin(); + self.bind(&pat, v); + self.end(); + } + self.steps(steps); + if !matches!(value.kind, Kind::Unit) { + self.begin(); + let v = self.value(value, &closure.ok); + let c = match is_buf(unref(&closure.ok).base()) { + // A buffer it returns is Rust's, one buf_copy made. + true if self.take(&v.c) => v.c.clone(), + true => format!("{}_buf_copy(tr_view({}))", self.p, v.c), + false => { + assert!(!self.owns(&closure.ok), "a closure returning a {:?}", closure.ok); + self.pass(v, &closure.ok) + } + }; + self.line(&format!("{ret} tr_ret = {c};")); + self.end(); + self.drop_scope(); + self.line("return tr_ret;"); + } else { + self.drop_scope(); + } + let body = std::mem::replace(&mut self.out, out); + self.depth = depth; + self.frames = frames; + self.scopes = scopes; + let _ = writeln!(self.defs, "static {ret} {n}({}) {{\n{body}}}\n", decls.join(", ")); + (n, "NULL".to_string()) + } + + /// The text a format's pieces make: each value is read first, as Rust's macros do, then + /// each is written. + fn text(&mut self, pieces: &[Piece]) -> String { + let values: Vec> = (pieces.iter()) + .map(|piece| match piece { + Piece::Text(_) => None, + Piece::Value(e, spec) => Some((self.expr(e), *spec)), + }) + .collect(); + let text = self.fresh("text"); + self.line(&format!("tr_text {text} = {{0}};")); + for (piece, value) in pieces.iter().zip(values) { + match (piece, value) { + (Piece::Text(s), _) => self.line(&format!("tr_put(&{text}, {}, {});", literal(s.as_bytes()), s.len())), + (_, Some((v, spec))) => self.show(&text, v, spec), + _ => unreachable!(), + } + } + text + } + + /// Append `v` to `text` as Rust formats it with `spec`. + fn show(&mut self, text: &str, v: Val, spec: Spec) { + let ty = unref(&v.ty).base().clone(); + match (spec, &ty) { + (Spec::Hex(width), Type::Int(_) | Type::NonZero(_)) => self.line(&format!( + "tr_fmt(&{text}, \"%0*llx\", {width}, (unsigned long long){});", + v.c + )), + (Spec::Hex(width), Type::U128) => self.line(&format!("tr_hex128(&{text}, {}, {width});", v.c)), + (Spec::Padded(width), Type::Int(int) | Type::NonZero(int)) => { + let (format, cast) = number(*int); + let format = format.replace('%', &format!("%0{width}")); + self.line(&format!("tr_fmt(&{text}, \"{format}\", ({cast}){});", v.c)) + } + (Spec::Display, _) => self.display(text, v), + (Spec::Debug, _) => self.debug(text, v), + (spec, ty) => panic!("{spec:?} of {ty:?}"), + } + } + + fn display(&mut self, text: &str, v: Val) { + let ty = unref(&v.ty).base().clone(); + match &ty { + Type::Bool => self.line(&format!("tr_str(&{text}, {} ? \"true\" : \"false\");", v.c)), + Type::Int(int) | Type::NonZero(int) => { + let (format, cast) = number(*int); + self.line(&format!("tr_fmt(&{text}, \"{format}\", ({cast}){});", v.c)) + } + Type::Char => self.line(&format!("tr_char(&{text}, {});", v.c)), + ty if is_buf(ty) => self.line(&format!("tr_buf(&{text}, {});", v.c)), + Type::Record(_) | Type::Enum(_) | Type::Object(_) => { + let s = match self.text_of(&ty) { + Some(id) => { + let f = self.t.function(id); + let name = self.t.name(LANGUAGE, id).to_string(); + let (ok, err) = (f.ok.clone(), f.err.clone()); + self.returned(&name, ok, err, vec![v.c.clone()]) + } + None => self.traited(&v, "to_string", &Type::String), + }; + self.line(&format!("tr_buf(&{text}, {});", s.c)) + } + ty => panic!("Display of {ty:?}"), + } + } + + /// The method an object's text is, which a binding names its Display. + fn text_of(&self, ty: &Type) -> Option { + let Type::Object(i) = ty else { return None }; + let index = self.t.api.objects[*i] + .methods + .iter() + .position(|m| m.access == Access::Text)?; + Some(FnId { + owner: super::Owner::Object(*i), + index, + }) + } + + /// The call of a std trait's function the header declares for `v`'s type, by `suffix`. + fn traited(&mut self, v: &Val, suffix: &str, ret: &Type) -> Val { + let ty = unref(&v.ty).base().clone(); + let name = format!("{}_{suffix}", self.type_name(&ty)); + let arg = match ty { + Type::Object(_) => v.c.clone(), + _ => { + let v = self.place(v.clone()); + format!("&{}", v.c) + } + }; + let call = self.invoke(&name, vec![arg]); + self.bound(call, ret) + } + + fn debug(&mut self, text: &str, v: Val) { + if let Form::Tuple(parts) = &v.form { + return self.debug_tuple(text, parts.clone()); + } + let ty = unref(&v.ty).base().clone(); + match &ty { + Type::Bool | Type::Int(_) | Type::NonZero(_) => self.display(text, v), + Type::String | Type::Str | Type::Path | Type::PathBuf => { + self.line(&format!("tr_quoted(&{text}, {});", v.c)) + } + Type::Option(_) => { + let v = self.named(v); + let some = self.is_some(&v); + let inner = self.inner(&v); + self.open(&format!("if ({some})")); + self.line(&format!("tr_str(&{text}, \"Some(\");")); + self.debug(text, inner); + self.line(&format!("tr_str(&{text}, \")\");")); + self.close(); + self.open("else"); + self.line(&format!("tr_str(&{text}, \"None\");")); + self.close(); + } + Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => { + let v = self.named(v); + let (items, len) = match ty { + Type::Array(n) => (format!("{}.items", v.c), n.to_string()), + _ => (format!("{}.ptr", v.c), format!("{}.len", v.c)), + }; + let i = self.fresh("i"); + self.line(&format!("tr_str(&{text}, \"[\");")); + self.open(&format!("for (size_t {i} = 0; {i} < {len}; {i}++)")); + self.line(&format!( + "tr_fmt(&{text}, {i} ? \", %u\" : \"%u\", (unsigned){items}[{i}]);" + )); + self.close(); + self.line(&format!("tr_str(&{text}, \"]\");")); + } + Type::List(_, item) => { + let v = self.named(v); + let i = self.fresh("i"); + self.line(&format!("tr_str(&{text}, \"[\");")); + self.open(&format!("for (size_t {i} = 0; {i} < {}.len; {i}++)", v.c)); + self.line(&format!("if ({i}) tr_str(&{text}, \", \");")); + let item = owned(item); + let cty = self.cty(&item); + self.debug(text, Val::place(format!("{}.ptr[{i}]", v.c), item, cty)); + self.close(); + self.line(&format!("tr_str(&{text}, \"]\");")); + } + Type::Tuple(elements) => { + let v = self.place(v); + let parts: Vec = (elements.iter().enumerate()) + .map(|(i, e)| Val::place(format!("{}._{i}", v.c), e.clone(), self.cty(e))) + .collect(); + self.debug_tuple(text, parts); + } + Type::Bound(_) => { + let v = self.named(v); + let upper = self.upper.clone(); + for (kind, name) in [("INCLUDED", "Included"), ("EXCLUDED", "Excluded")] { + self.line(&format!( + "if ({}.kind == {upper}_BOUND_{kind}) tr_fmt(&{text}, \"{name}(%llu)\", (unsigned long long){}.value);", + v.c, v.c + )); + } + self.line(&format!( + "if ({}.kind == {upper}_BOUND_UNBOUNDED) tr_str(&{text}, \"Unbounded\");", + v.c + )); + } + Type::Record(_) | Type::Enum(_) | Type::Object(_) => { + let s = self.traited(&v, "debug", &Type::String); + self.line(&format!("tr_buf(&{text}, {});", s.c)); + } + ty => panic!("Debug of {ty:?}"), + } + } + + fn debug_tuple(&mut self, text: &str, parts: Vec) { + self.line(&format!("tr_str(&{text}, \"(\");")); + let n = parts.len(); + for (i, part) in parts.into_iter().enumerate() { + if i > 0 { + self.line(&format!("tr_str(&{text}, \", \");")); + } + self.debug(text, part); + } + let tail = if n == 1 { ",)" } else { ")" }; + self.line(&format!("tr_str(&{text}, \"{tail}\");")); + } + + fn join(&mut self, items: &Expr, pat: &Pat, body: &Expr, sep: &str) -> Val { + let list = self.expr(items); + let list = self.named(list); + let Type::List(_, item) = unref(&list.ty).base() else { + panic!("a join over {:?}", list.ty) + }; + let item = owned(item); + let text = self.fresh("text"); + self.line(&format!("tr_text {text} = {{0}};")); + let i = self.fresh("i"); + self.open(&format!("for (size_t {i} = 0; {i} < {}.len; {i}++)", list.c)); + self.line(&format!( + "if ({i}) tr_put(&{text}, {}, {});", + literal(sep.as_bytes()), + sep.len() + )); + let cty = self.cty(&item); + self.bind(pat, Val::place(format!("{}.ptr[{i}]", list.c), item, cty)); + let b = self.expr(body); + self.line(&format!("tr_buf(&{text}, {});", b.c)); + self.close(); + let name = self.fresh("t"); + let p = &self.p; + let cty = format!("{p}_buf"); + self.line(&format!("{cty} {name} = tr_done(&{text});")); + self.temp(&name, &Type::String); + Val::place(name, Type::String, cty) + } + + fn map_or(&mut self, option: &Expr, none: &Expr, pat: &Pat, some: &Expr, ty: &Type) -> Val { + let opt = self.expr(option); + let opt = self.named(opt); + let name = self.fresh("t"); + let cty = self.cty(ty); + let zero = self.zero(ty); + self.line(&format!("{cty} {name} = {zero};")); + let is_some = self.is_some(&opt); + let inner = self.inner(&opt); + self.open(&format!("if ({is_some})")); + self.bind(pat, inner); + let v = self.expr(some); + let c = self.keep(v); + self.line(&format!("{name} = {c};")); + self.close(); + self.open("else"); + let v = self.expr(none); + let c = self.keep(v); + self.line(&format!("{name} = {c};")); + self.close(); + self.temp(&name, ty); + Val::place(name, ty.clone(), cty) + } + + /// `v` as a value that outlives this statement: a temporary taken from it, or a copy. + fn keep(&mut self, v: Val) -> String { + if self.take(&v.c) { + return v.c; + } + match unref(&v.ty).base() { + ty if is_buf(ty) => format!("{}_buf_copy(tr_view({}))", self.p, v.c), + ty if !self.owns(ty) => v.c, + ty => panic!("a {ty:?} kept past its statement"), + } + } + + // Patterns and steps. + + fn bind(&mut self, pat: &Pat, v: Val) { + match pat { + Pat::Ignore(_) => {} + Pat::Name(name, _) => self.bind_name(name, v), + Pat::Tuple(pats) => { + let parts = self.parts(v); + assert_eq!(parts.len(), pats.len(), "a tuple pattern of another length"); + for (pat, part) in pats.iter().zip(parts) { + self.bind(pat, part); + } + } + } + } + + /// The elements of `v`, a tuple or a pair of bounds, each owned if `v` was. + fn parts(&mut self, v: Val) -> Vec { + if let Form::Tuple(parts) = v.form { + return parts; + } + let v = self.named(v); + let owned = self.take(&v.c); + let parts: Vec = match unref(&v.ty).base() { + Type::Bounds(int) => ["start", "end"] + .iter() + .map(|f| Val::place(format!("{}.{f}", v.c), Type::Bound(*int), self.cty(&Type::Bound(*int)))) + .collect(), + Type::Tuple(elements) => (elements.iter().enumerate()) + .map(|(i, e)| Val::place(format!("{}._{i}", v.c), e.clone(), self.cty(e))) + .collect(), + ty => panic!("the elements of {ty:?}"), + }; + if owned { + for part in &parts { + self.temp(&part.c, &part.ty); + } + } + parts + } + + fn bind_name(&mut self, name: &str, v: Val) { + let c = format!("v_{name}"); + let local = match &v.form { + Form::Result { .. } => panic!("{name} bound to a Result"), + Form::Tuple(parts) => match self.tuple_struct(&v.ty) { + Some(tn) => { + let mut owned = false; + for part in parts { + owned |= self.take(&part.c); + } + let fields: Vec = (parts.iter().enumerate()) + .map(|(i, p)| format!("._{i} = {}", p.c)) + .collect(); + self.line(&format!("{tn} {c} = ({tn}){{{}}};", fields.join(", "))); + let local = Val::place(c.clone(), v.ty.clone(), tn); + if owned { + self.own(&c, &v.ty); + } + local + } + None => { + let mut locals = Vec::new(); + for (i, part) in parts.iter().enumerate() { + let pc = format!("{c}_{i}"); + self.line(&format!("{} {pc} = {};", part.cty, part.c)); + if self.take(&part.c) { + self.own(&pc, &part.ty); + } + locals.push(Val::place(pc, part.ty.clone(), part.cty.clone())); + } + Val { + form: Form::Tuple(locals), + ..Val::new("", v.ty.clone(), "") + } + } + }, + Form::Plain => { + self.line(&format!("{} {c} = {};", v.cty, v.c)); + if self.take(&v.c) { + self.own(&c, &v.ty); + } else if self.take_owned(&v.c).is_some() { + // A local moved to another: the new one owns it. + let code = self.free(&c, &v.ty); + self.scopes + .last_mut() + .unwrap() + .owned + .push(Owned { key: c.clone(), code }); + } else if self.owns(&v.ty) { + // A value C built of temporaries, which live as long as it does. + let frame = std::mem::take(self.frames.last_mut().expect("a statement")); + self.scopes.last_mut().unwrap().owned.extend(frame); + } + Val::place(c, v.ty.clone(), v.cty.clone()) + } + }; + self.scopes.last_mut().unwrap().locals.push((name.to_string(), local)); + } + + /// The local `c` of `ty` owned by the innermost scope. + fn own(&mut self, c: &str, ty: &Type) { + let code = self.free(c, ty); + if !code.is_empty() { + self.scopes.last_mut().unwrap().owned.push(Owned { + key: c.to_string(), + code, + }); + } + } + + fn steps(&mut self, steps: &[Step]) { + for step in steps { + self.step(step); + } + } + + fn step(&mut self, step: &Step) { + match step { + Step::Let(pat, value) => { + self.begin(); + let v = self.expr(value); + self.bind(pat, v); + self.end(); + } + Step::Print(pieces) => { + self.begin(); + let text = self.text(pieces); + self.line(&format!("tr_line(&{text});")); + self.end(); + } + Step::Do(value) => { + self.begin(); + let v = self.expr(value); + if matches!(v.form, Form::Plain) && !v.c.is_empty() && !v.named { + self.line(&format!("(void)({});", v.c)); + } + self.end(); + } + Step::Drop(name) => { + let v = self.local(name); + let keys: Vec = match &v.form { + Form::Tuple(parts) => parts.iter().map(|p| p.c.clone()).collect(), + _ => vec![v.c.clone()], + }; + for key in keys { + if let Some(owned) = self.take_owned(&key) { + for code in owned.code { + self.line(&code); + } + } + } + } + Step::Match { value, ok, err } => { + self.begin(); + let v = self.expr(value); + let (cond, ok_val, err_val) = match &v.form { + Form::Result { flag, ok, err } => (flag.clone(), Some((**ok).clone()), Some((**err).clone())), + _ => { + let v = self.named(v); + (self.is_some(&v), Some(self.inner(&v)), None) + } + }; + self.arm(&format!("if ({cond})"), ok, ok_val); + self.arm("else", err, err_val); + self.end(); + } + } + } + + fn arm(&mut self, head: &str, arm: &Arm, value: Option) { + self.open(head); + if let (Some(pat), Some(v)) = (&arm.pat, value) { + self.begin(); + self.bind(pat, v); + self.end(); + } + self.steps(&arm.steps); + self.close(); + } +} + +/// Each local `e` reads. +fn vars(e: &Expr, out: &mut Vec) { + if let Kind::Var(name) = &e.kind + && !out.contains(name) + { + out.push(name.clone()); + } +} + +/// Each expression a step holds, its arms' and closures' steps included. +fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} + +/// `ty` as Rust returns it to C: each borrow a clone, as the C ABI returns one. +fn owned(ty: &Type) -> Type { + match ty { + Type::Ref(_, inner) => owned(inner), + Type::Option(inner) => Type::Option(Box::new(owned(inner))), + Type::Box(inner) => Type::Box(Box::new(owned(inner))), + Type::List(c, inner) => Type::List(*c, Box::new(owned(inner))), + Type::Tuple(elements) => Type::Tuple(elements.iter().map(owned).collect()), + ty => ty.clone(), + } +} + +/// Whether `ty` crosses as a buffer. +fn is_buf(ty: &Type) -> bool { + matches!( + ty.base(), + Type::Str | Type::String | Type::Slice | Type::Vec | Type::Bytes | Type::Path | Type::PathBuf + ) +} + +/// Whether `Option` crosses as `ty`, a null pointer its `None`. +fn nullable(ty: &Type) -> bool { + matches!(ty.base(), Type::Object(_) | Type::List(..)) || is_buf(ty) +} + +/// Whether Rust writes a parameter of `ty` back through an out, as a `&mut` of a value. +fn written_back(ty: &Type) -> bool { + matches!(ty, Type::Ref(Mutability::Mut, inner) if !matches!(**inner, Type::Object(_) | Type::Reader)) +} + +fn addr(socket: bool, family: Family) -> &'static str { + match (socket, family) { + (true, Family::Any) => "socket_addr", + (true, Family::V4) => "socket_addr_v4", + (true, Family::V6) => "socket_addr_v6", + (false, Family::Any) => "ip_addr", + (false, Family::V4) => "ipv4_addr", + (false, Family::V6) => "ipv6_addr", + } +} + +fn c_int(int: Int) -> &'static str { + match int { + Int::U8 => "uint8_t", + Int::U16 => "uint16_t", + Int::U32 => "uint32_t", + Int::U64 => "uint64_t", + Int::Usize => "size_t", + Int::I8 => "int8_t", + Int::I16 => "int16_t", + Int::I32 => "int32_t", + Int::I64 => "int64_t", + Int::Isize => "ptrdiff_t", + } +} + +/// The `printf` format of an integer, and the type it is cast to for it. +fn number(int: Int) -> (&'static str, &'static str) { + match int.signed() { + true => ("%lld", "long long"), + false => ("%llu", "unsigned long long"), + } +} + +/// A C string literal of `bytes`, each byte past printable ASCII in octal, which takes at +/// most three digits, so no digit after one joins it. +fn literal(bytes: &[u8]) -> String { + let mut out = String::from("\""); + for &b in bytes { + match b { + b'"' | b'\\' => { + out.push('\\'); + out.push(b as char); + } + // `??` begins a trigraph. + b'?' => out.push_str("\\?"), + 0x20..0x7f => out.push(b as char), + _ => { + let _ = write!(out, "\\{b:03o}"); + } + } + } + out.push('"'); + out +} diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 79879ef50..70e35a8d7 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -11,6 +11,7 @@ //! as its futures, or prints a value no binding shapes alike, such as `hex`. Anything else //! fails, naming its line. +pub(crate) mod c; pub(crate) mod ir; mod parse; pub(crate) mod python; @@ -25,6 +26,9 @@ pub(crate) struct Transcript { pub(crate) api: ir::Api, names: BTreeMap>, pub(crate) steps: Vec, + /// The parameters' types of each function `transcript.rs` defines that the script calls, + /// by its name. + pub(crate) locals: BTreeMap>, } /// A statement of the script. @@ -239,8 +243,11 @@ impl Transcript { api: lock.api, names: lock.names, steps: Vec::new(), + locals: BTreeMap::new(), }; - transcript.steps = parse::main(&transcript, &std::fs::read_to_string(source).unwrap()); + let (steps, locals) = parse::main(&transcript, &std::fs::read_to_string(source).unwrap()); + transcript.steps = steps; + transcript.locals = locals; transcript } @@ -343,6 +350,11 @@ impl Transcript { self.named(language, &format!("type {}", self.rust(ty))) } + /// `language`'s name for the item `key` names, if it names one. + pub(crate) fn find(&self, language: &str, key: &str) -> Option<&str> { + self.names[language].get(key).map(String::as_str) + } + /// `language`'s name for the item `key` names, such as `const api::LIMIT`. pub(crate) fn named(&self, language: &str, key: &str) -> &str { let names = &self.names[language]; diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 3b34f067d..4e8163c3a 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -8,14 +8,16 @@ use syn::spanned::Spanned; use super::ir::{Access, Collection, Family, Function, Int, Literal, Mutability, Type}; use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; -/// The steps of `source`'s `main`. -pub(super) fn main(t: &Transcript, source: &str) -> Vec { +/// The steps of `source`'s `main`, and the parameters' types of each function it defines +/// that `main` calls. +pub(super) fn main(t: &Transcript, source: &str) -> (Vec, BTreeMap>) { let file = syn::parse_file(source).unwrap_or_else(|e| panic!("{}: {e}", at(e.span()))); let mut scope = Scope { t, vars: Vec::new(), units: Vec::new(), locals: BTreeMap::new(), + params: BTreeMap::new(), uses: BTreeMap::new(), taken: BTreeMap::new(), }; @@ -35,11 +37,12 @@ pub(super) fn main(t: &Transcript, source: &str) -> Vec { main = Some(f); continue; } - scope.locals.insert(f.sig.ident.to_string(), f.sig.output.clone()); + scope.locals.insert(f.sig.ident.to_string(), f.sig.clone()); } } let main = main.expect("transcript.rs has a main"); - scope.block(&main.block.stmts) + let steps = scope.block(&main.block.stmts); + (steps, scope.params) } /// `transcript.rs:line:column` of a span. @@ -66,7 +69,10 @@ struct Scope<'t> { units: Vec, /// The functions `transcript.rs` defines, each a language's own: what each returns, /// typed where it is called. - locals: BTreeMap, + locals: BTreeMap, + /// The parameters' types of each function `transcript.rs` defines that `main` calls, + /// which a language whose own functions are typed declares them by. + params: BTreeMap>, /// What each name a `use` brings in stands for. uses: BTreeMap>, /// How many locals took each name, so each binding gets its own. @@ -598,6 +604,7 @@ impl Scope<'_> { && let Some(name) = p.path.get_ident() && self.locals.contains_key(&name.to_string()) { + self.local_params(&name.to_string()); let args = call.args.iter().map(|a| self.infer(a)).collect(); return Expr::new(Kind::Local(name.to_string(), args), ty.clone()); } @@ -646,6 +653,18 @@ impl Scope<'_> { value } + /// Record the parameters' types of the function `name` that `transcript.rs` defines. + fn local_params(&mut self, name: &str) { + let inputs = self.locals[name].inputs.clone(); + let params = (inputs.iter()) + .map(|input| match input { + syn::FnArg::Typed(typed) => self.ty(&typed.ty), + input => fail(input, "a function of transcript.rs taking self"), + }) + .collect(); + self.params.insert(name.to_string(), params); + } + /// Whether `m` calls a method of the API's, not a conversion of the same name. fn api_method(&self, m: &syn::ExprMethodCall) -> bool { let Some(ty) = self.peek(&m.receiver) else { return false }; @@ -1184,9 +1203,11 @@ impl Scope<'_> { }; let args: Vec = call.args.iter().cloned().collect(); if let Some(name) = p.path.get_ident().map(|i| i.to_string()) - && let Some(output) = self.locals.get(&name) + && let Some(signature) = self.locals.get(&name) { - let ty = match output.clone() { + let output = signature.output.clone(); + self.local_params(&name); + let ty = match output { syn::ReturnType::Default => Type::Unit, syn::ReturnType::Type(_, ty) => self.ty(&ty), }; From 93c012c18ce127ea757d63c6844fe64b8f44f04b Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:15:21 -0800 Subject: [PATCH 13/28] style: rustfmt the transcript Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 18 +- ffi/src/collect.rs | 34 ++- ffi/src/dart.rs | 6 +- ffi/src/go.rs | 3 +- ffi/src/web.rs | 6 +- ffi/tests/fixtures.rs | 4 +- ffi/tests/fixtures/transcript/go.rs | 269 ++++++++++++++++++++---- ffi/tests/fixtures/transcript/ir.rs | 4 +- ffi/tests/fixtures/transcript/mod.rs | 12 +- ffi/tests/fixtures/transcript/parse.rs | 242 ++++++++++++++++----- ffi/tests/fixtures/transcript/python.rs | 163 +++++++++++--- ffi/tests/fixtures/transcript/swift.rs | 142 +++++++++++-- 12 files changed, 717 insertions(+), 186 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 0939016b7..9368cddd7 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -560,12 +560,7 @@ fn main() { // A field and the method of its name, each its own member. let mut retry = api::Retry::new(Some(5)); - println!( - "retry {:?} {} {}", - retry.limit, - retry.limit(), - retry.delay() - ); + println!("retry {:?} {} {}", retry.limit, retry.limit(), retry.delay()); // The renamed field's setter, named as its getter. retry.limit = None; println!("retry {}", retry.limit()); @@ -794,7 +789,10 @@ fn main() { println!("doubled i64 {:?}", api::doubled_i64(&[i64::MIN, -1, 0, i64::MAX])); println!( "boxed floats {:?}", - f64_bits(&api::boxed_floats(Box::new([-0.0, f64::from_bits(0x7ff8_0000_0000_0001)]))) + f64_bits(&api::boxed_floats(Box::new([ + -0.0, + f64::from_bits(0x7ff8_0000_0000_0001) + ]))) ); let summed = api::summed([Point { x: 1, y: 2 }, Point { x: -4, y: 6 }]); let none = api::summed([]); @@ -873,7 +871,11 @@ fn main() { // A filter, collected at the call. println!( "beyond {}", - trail.beyond(1).map(|p| format!("{} {}", p.x, p.y)).collect::>().join(", ") + trail + .beyond(1) + .map(|p| format!("{} {}", p.x, p.y)) + .collect::>() + .join(", ") ); println!( "numbered {}", diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index b6713dc75..6b025440d 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2628,8 +2628,7 @@ impl<'tcx> Collector<'tcx> { || (api.records.iter()).any(|r| args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) || (api.enums.iter()).any(|e| { args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) - || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) + }) || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if !used { self.api.enums.pop(); @@ -2656,12 +2655,10 @@ impl<'tcx> Collector<'tcx> { let used = api.functions.iter().any(signature) || (api.records.iter().enumerate()).any(|(i, r)| { (!value || i != gone) && (args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) - }) - || (api.enums.iter()).any(|e| { - args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) - || (api.objects.iter().enumerate()) - .any(|(i, o)| (value || i != gone) && (args(&o.args) || o.methods.iter().any(signature))) + }) || (api.enums.iter()).any(|e| { + args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) + }) || (api.objects.iter().enumerate()) + .any(|(i, o)| (value || i != gone) && (args(&o.args) || o.methods.iter().any(signature))) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if used { continue; @@ -3357,8 +3354,7 @@ impl<'tcx> Collector<'tcx> { // is, takes it from the future, as it would a parameter. ty::Ref(_, inner, _) if Some(*inner) == self_ty - && polled.is_some() - && let Some(kind) = self.task(ty, true) => + && polled.is_some() && let Some(kind) = self.task(ty, true) => { made = Some(*inner); tasks.push(Task { at: 0, kind }); @@ -4521,8 +4517,7 @@ impl<'tcx> Collector<'tcx> { .inputs() .iter() .filter(|&&input| input == param) - .count() - > 1 + .count() > 1 { return Some(Err(why("closure type taken twice", param.to_string()))); } @@ -4876,16 +4871,11 @@ impl<'tcx> Collector<'tcx> { let plain = matches!( ty.kind(), ty::Adt(..) - | ty::Bool - | ty::Char - | ty::Int(_) - | ty::Uint(_) - | ty::Float(_) - | ty::Str - | ty::Array(..) - | ty::Slice(_) - | ty::Ref(..) - | ty::Tuple(_) + | ty::Bool | ty::Char + | ty::Int(_) | ty::Uint(_) + | ty::Float(_) | ty::Str + | ty::Array(..) | ty::Slice(_) + | ty::Ref(..) | ty::Tuple(_) ); let (method, driven) = match (implements(iterator, ty), implements(into_iterator, ty)) { (true, _) => (next, item), diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index bfd73610f..8ec320841 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -621,13 +621,11 @@ impl<'a> Gen<'a> { !matches!( ty, Ty::Buf - | Ty::U128 - | Ty::Duration + | Ty::U128 | Ty::Duration | Ty::SocketAddr(_) | Ty::IpAddr(_) | Ty::Struct(_) - | Ty::Waker - | Ty::ForeignFuture + | Ty::Waker | Ty::ForeignFuture | Ty::ForeignReader ) } diff --git a/ffi/src/go.rs b/ffi/src/go.rs index 7e3f68951..e967a9595 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -2611,8 +2611,7 @@ impl<'a> Gen<'a> { let everywhere = abi.api.everywhere(function.on); let closable = receiver.is_some() && owner_ty.is_some_and(|ty| self.fails(ty)) || function.params.iter().any(|p| self.fails(&p.ty)) - || status - || !everywhere; + || status || !everywhere; if function.err.is_some() || function.future || closable { results.push("error".to_string()); } diff --git a/ffi/src/web.rs b/ffi/src/web.rs index e3233fc72..4a8cdc91c 100644 --- a/ffi/src/web.rs +++ b/ffi/src/web.rs @@ -674,13 +674,11 @@ impl<'a> Gen<'a> { !matches!( ty, Ty::Buf - | Ty::U128 - | Ty::Duration + | Ty::U128 | Ty::Duration | Ty::SocketAddr(_) | Ty::IpAddr(_) | Ty::Struct(_) - | Ty::Waker - | Ty::ForeignFuture + | Ty::Waker | Ty::ForeignFuture | Ty::ForeignReader ) } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 7cf85a3b3..4380ef028 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -1231,7 +1231,8 @@ fn api_swift() { // The test's executor preference is macOS 15's. let exe = dir.join("api-test"); let test = manifest_dir().join("tests").join("api.swift"); - let script = generated("swift", "transcript.swift", &transcript::swift::emit(transcript())).join("transcript.swift"); + let script = + generated("swift", "transcript.swift", &transcript::swift::emit(transcript())).join("transcript.swift"); // The Clang module the test and the contract program import on Linux. let nodump = manifest_dir().join("tests").join("nodump"); let step = Step { @@ -3952,4 +3953,3 @@ fn profiled() { "{stderr}" ); } - diff --git a/ffi/tests/fixtures/transcript/go.rs b/ffi/tests/fixtures/transcript/go.rs index 9ad69a84d..67ed3630d 100644 --- a/ffi/tests/fixtures/transcript/go.rs +++ b/ffi/tests/fixtures/transcript/go.rs @@ -264,10 +264,16 @@ pub(crate) fn emit(t: &Transcript) -> String { e.used = used; e.reserved = RESERVED.iter().map(|s| s.to_string()).collect(); e.reserved.extend(locals.iter().map(|name| local(name))); - for name in t.names(LANGUAGE).iter().filter_map(|(key, name)| key.strip_prefix("crate ").map(|_| name)) { + for name in t + .names(LANGUAGE) + .iter() + .filter_map(|(key, name)| key.strip_prefix("crate ").map(|_| name)) + { e.reserved.insert(name.to_string()); } - for package in ["fmt", "strings", "errors", "unicode", "utf8", "math", "context", "slices", "rt", "io"] { + for package in [ + "fmt", "strings", "errors", "unicode", "utf8", "math", "context", "slices", "rt", "io", + ] { e.reserved.insert(package.to_string()); } for package in ["errors", "fmt", "strings", "unicode", "unicode/utf8"] { @@ -328,9 +334,16 @@ fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { f(expr); let mut inner = |e: &Expr| walk(e, f); match &expr.kind { - Kind::Some(e) | Kind::Field(e, _) | Kind::Element(e, _) | Kind::Clone(e) | Kind::Unwrap(e) | Kind::UnwrapErr(e) => inner(e), + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => es.iter().for_each(inner), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), Kind::Binary(_, a, b) => { inner(a); @@ -361,7 +374,61 @@ fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { /// Go's keywords and the predeclared names the script calls, which no local may take. const RESERVED: &[&str] = &[ - "break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough", "for", "func", "go", "goto", "if", "import", "interface", "map", "package", "range", "return", "select", "struct", "switch", "type", "var", "any", "bool", "byte", "error", "false", "float32", "float64", "int", "int8", "int16", "int32", "int64", "len", "nil", "rune", "string", "true", "uint", "uint8", "uint16", "uint32", "uint64", "append", "make", "max", "min", "new", "panic", "script", "main", + "break", + "case", + "chan", + "const", + "continue", + "default", + "defer", + "else", + "fallthrough", + "for", + "func", + "go", + "goto", + "if", + "import", + "interface", + "map", + "package", + "range", + "return", + "select", + "struct", + "switch", + "type", + "var", + "any", + "bool", + "byte", + "error", + "false", + "float32", + "float64", + "int", + "int8", + "int16", + "int32", + "int64", + "len", + "nil", + "rune", + "string", + "true", + "uint", + "uint8", + "uint16", + "uint32", + "uint64", + "append", + "make", + "max", + "min", + "new", + "panic", + "script", + "main", ]; /// The Go name of a function `transcript.rs` defines: in camel case, unexported. A unit @@ -475,7 +542,9 @@ impl Emitter<'_> { Step::Let(pat, value) => { if let Type::Result(_, err) = &value.ty { // `let _ =` of a `Result`, which drops its error. - let Pat::Ignore(_) = pat else { panic!("a let binding a Result whole") }; + let Pat::Ignore(_) = pat else { + panic!("a let binding a Result whole") + }; let made = self.made(value, Failure::Bind, false, out); let error = self.error_type(err); self.line(out, &format!("ignore_[{error}]({})", made.error.unwrap())); @@ -628,9 +697,14 @@ impl Emitter<'_> { /// The elements of `v`, a tuple or bounds of `ty`. fn parts(&mut self, v: &str, ty: &Type) -> Vec<(String, Type)> { match unref(ty).base() { - Type::Bounds(int) => vec![(format!("{v}.Start"), Type::Bound(*int)), (format!("{v}.End"), Type::Bound(*int))], + Type::Bounds(int) => vec![ + (format!("{v}.Start"), Type::Bound(*int)), + (format!("{v}.End"), Type::Bound(*int)), + ], Type::Tuple(elements) if elements.len() == 1 => vec![(v.to_string(), elements[0].clone())], - Type::Tuple(elements) => (elements.iter().enumerate()).map(|(i, ty)| (format!("{v}.V{i}"), ty.clone())).collect(), + Type::Tuple(elements) => (elements.iter().enumerate()) + .map(|(i, ty)| (format!("{v}.V{i}"), ty.clone())) + .collect(), ty => panic!("the elements of {ty:?}"), } } @@ -833,7 +907,9 @@ impl Emitter<'_> { let elements = elements.clone(); let parts: Vec = match elements.len() { 1 => vec![self.debug(v, &elements[0])], - _ => (elements.iter().enumerate()).map(|(i, ty)| self.debug(&format!("{v}.V{i}"), ty)).collect(), + _ => (elements.iter().enumerate()) + .map(|(i, ty)| self.debug(&format!("{v}.V{i}"), ty)) + .collect(), }; let tail = if parts.len() == 1 { ",)" } else { ")" }; format!("\"(\" + {} + \"{tail}\"", parts.join(" + \", \" + ")) @@ -937,7 +1013,14 @@ impl Emitter<'_> { let rust = self.t.rust(&ty); let record = &self.t.api.records[*r]; let named: Vec<(String, Type)> = (record.fields.iter()) - .map(|f| (self.t.named(LANGUAGE, &format!("type {rust} / field {}", f.name)).to_string(), f.ty.clone())) + .map(|f| { + ( + self.t + .named(LANGUAGE, &format!("type {rust} / field {}", f.name)) + .to_string(), + f.ty.clone(), + ) + }) .collect(); let values: Vec = (fields.iter().zip(&named)) .map(|(f, (name, ty))| { @@ -953,12 +1036,19 @@ impl Emitter<'_> { let rust = self.t.rust(&ty); let enumeration = &self.t.api.enums[*en]; let variant = &enumeration.variants[*v]; - let name = self.t.named(LANGUAGE, &format!("type {rust} / variant {}", variant.name)).to_string(); + let name = self + .t + .named(LANGUAGE, &format!("type {rust} / variant {}", variant.name)) + .to_string(); let package = self.package(&enumeration.home.krate.clone()); if enumeration.variants.iter().all(|v| v.fields.is_empty()) { return format!("{package}.{name}"); } - let named: Vec<(String, Type)> = variant.fields.iter().map(|f| (field_name(&f.name), f.ty.clone())).collect(); + let named: Vec<(String, Type)> = variant + .fields + .iter() + .map(|f| (field_name(&f.name), f.ty.clone())) + .collect(); let values: Vec = (fields.iter().zip(&named)) .map(|(f, (name, ty))| { let v = self.value(f, ty, out); @@ -969,7 +1059,9 @@ impl Emitter<'_> { format!("{package}.{name}{{{}}}", values.join(", ")) } Kind::Bound(kind, value) => { - let Type::Bound(_) = &base else { panic!("a bound as {base:?}") }; + let Type::Bound(_) = &base else { + panic!("a bound as {base:?}") + }; let rt = self.rt(); let ty = self.go(&base); match (kind, value) { @@ -1002,7 +1094,10 @@ impl Emitter<'_> { } Kind::Const(c) => { let constant = &self.t.api.constants[*c]; - let name = self.t.named(LANGUAGE, &format!("const {}", constant.path.join("::"))).to_string(); + let name = self + .t + .named(LANGUAGE, &format!("const {}", constant.path.join("::"))) + .to_string(); let package = self.package(&constant.home.krate.clone()); format!("{package}.{name}") } @@ -1033,10 +1128,15 @@ impl Emitter<'_> { } Kind::Field(base, i) => { let b = self.expr(base, out); - let Type::Record(r) = unref(&base.ty).base() else { panic!("a field of {:?}", base.ty) }; + let Type::Record(r) = unref(&base.ty).base() else { + panic!("a field of {:?}", base.ty) + }; let rust = self.t.rust(&Type::Record(*r)); let field = &self.t.api.records[*r].fields[*i].name; - let name = self.t.named(LANGUAGE, &format!("type {rust} / field {field}")).to_string(); + let name = self + .t + .named(LANGUAGE, &format!("type {rust} / field {field}")) + .to_string(); format!("{b}.{name}") } Kind::Element(base, i) => { @@ -1051,7 +1151,14 @@ impl Emitter<'_> { match unref(&inner.ty).base() { Type::Object(_) => { self.lent(&v); - let made = self.hoist(&format!("{v}.Clone()"), &[inner.ty.clone()], true, Failure::Panic, true, out); + let made = self.hoist( + &format!("{v}.Clone()"), + &[inner.ty.clone()], + true, + Failure::Panic, + true, + out, + ); made.values[0].clone() } Type::List(..) => format!("{}.Clone({v})", self.std("slices")), @@ -1068,7 +1175,14 @@ impl Emitter<'_> { match item.base() { Type::Object(_) => { self.moved(&v); - let made = self.hoist(&format!("present_({v})"), &[(**item).clone()], false, Failure::Panic, true, out); + let made = self.hoist( + &format!("present_({v})"), + &[(**item).clone()], + false, + Failure::Panic, + true, + out, + ); made.values[0].clone() } _ => format!("some_({v})"), @@ -1077,19 +1191,26 @@ impl Emitter<'_> { ty => panic!("unwrap of {ty:?}"), }, Kind::UnwrapErr(inner) => { - let Type::Result(_, err) = &inner.ty else { panic!("unwrap_err of {:?}", inner.ty) }; + let Type::Result(_, err) = &inner.ty else { + panic!("unwrap_err of {:?}", inner.ty) + }; let made = self.made(inner, Failure::Bind, false, out); self.payload(&made.error.unwrap(), err) } Kind::IsErr(inner) => { - let Type::Result(_, err) = &inner.ty else { panic!("is_err of {:?}", inner.ty) }; + let Type::Result(_, err) = &inner.ty else { + panic!("is_err of {:?}", inner.ty) + }; let made = self.made(inner, Failure::Bind, false, out); let error = self.error_type(err); format!("isErr_[{error}]({})", made.error.unwrap()) } Kind::IsSome(inner) | Kind::IsNone(inner) => { let v = self.expr(inner, out); - let test = format!("({v} {} nil)", if matches!(e.kind, Kind::IsSome(_)) { "!=" } else { "==" }); + let test = format!( + "({v} {} nil)", + if matches!(e.kind, Kind::IsSome(_)) { "!=" } else { "==" } + ); self.lent(&v); test } @@ -1097,7 +1218,9 @@ impl Emitter<'_> { Kind::Join { items, pat, body, sep } => { let items_v = self.expr(items, out); self.lent(&items_v); - let Type::List(_, item) = unref(&items.ty).base() else { panic!("a join over {:?}", items.ty) }; + let Type::List(_, item) = unref(&items.ty).base() else { + panic!("a join over {:?}", items.ty) + }; let item = (**item).clone(); let parts = self.fresh("j"); let x = self.fresh("x"); @@ -1116,9 +1239,16 @@ impl Emitter<'_> { self.line(out, "}"); format!("{}.Join({parts}, {})", self.std("strings"), string(sep)) } - Kind::MapOr { option, none, pat, some } => { + Kind::MapOr { + option, + none, + pat, + some, + } => { let option_v = self.expr(option, out); - let Type::Option(inner) = unref(&option.ty).base() else { panic!("map_or of {:?}", option.ty) }; + let Type::Option(inner) = unref(&option.ty).base() else { + panic!("map_or of {:?}", option.ty) + }; let inner = (**inner).clone(); let none_v = self.value(none, &e.ty, out); let result = self.fresh("m"); @@ -1163,8 +1293,12 @@ impl Emitter<'_> { /// taken, or an array of bytes where bytes are. fn coerce(&mut self, v: &str, have: &Type, want: &Type) -> String { match (unref(have).base(), want) { - (Type::SocketAddr(Family::V4), Type::SocketAddr(Family::Any)) => format!("{}.SocketAddrFromV4({v})", self.rt()), - (Type::SocketAddr(Family::V6), Type::SocketAddr(Family::Any)) => format!("{}.SocketAddrFromV6({v})", self.rt()), + (Type::SocketAddr(Family::V4), Type::SocketAddr(Family::Any)) => { + format!("{}.SocketAddrFromV4({v})", self.rt()) + } + (Type::SocketAddr(Family::V6), Type::SocketAddr(Family::Any)) => { + format!("{}.SocketAddrFromV6({v})", self.rt()) + } (Type::IpAddr(Family::V4), Type::IpAddr(Family::Any)) => format!("{}.IpAddrFromV4({v})", self.rt()), (Type::IpAddr(Family::V6), Type::IpAddr(Family::Any)) => format!("{}.IpAddrFromV6({v})", self.rt()), (Type::Array(_), Type::Slice | Type::Vec | Type::Bytes) => format!("{}.NewBytes({v}[:])", self.rt()), @@ -1177,7 +1311,14 @@ impl Emitter<'_> { let (value, family) = match addr { std::net::SocketAddr::V4(a) => { let ip: Vec = a.ip().octets().iter().map(|o| o.to_string()).collect(); - (format!("{rt}.SocketAddrV4{{IP: {rt}.Ipv4Addr{{{}}}, Port: {}}}", ip.join(", "), a.port()), "V4") + ( + format!( + "{rt}.SocketAddrV4{{IP: {rt}.Ipv4Addr{{{}}}, Port: {}}}", + ip.join(", "), + a.port() + ), + "V4", + ) } std::net::SocketAddr::V6(a) => { let ip: Vec = a.ip().octets().iter().map(|o| o.to_string()).collect(); @@ -1229,11 +1370,16 @@ impl Emitter<'_> { _ => Type::Bound(*int), }; let go = self.go(&ty); - let (a, b) = (self.value(&elements[0], &element, out), self.value(&elements[1], &element, out)); + let (a, b) = ( + self.value(&elements[0], &element, out), + self.value(&elements[1], &element, out), + ); format!("{go}{{Start: {a}, End: {b}}}") } Type::Tuple(types) => { - let values: Vec = (elements.iter().zip(types)).map(|(e, t)| self.value(e, t, out)).collect(); + let values: Vec = (elements.iter().zip(types)) + .map(|(e, t)| self.value(e, t, out)) + .collect(); for v in &values { self.moved(v); } @@ -1272,10 +1418,24 @@ impl Emitter<'_> { self.lent(&x); self.lent(&y); let fails = matches!(ty, Type::Object(_)) || fails(self.t, &ty); - let made = self.hoist(&format!("{x}.Equal({y})"), &[Type::Bool], fails, Failure::Panic, true, out); + let made = self.hoist( + &format!("{x}.Equal({y})"), + &[Type::Bool], + fails, + Failure::Panic, + true, + out, + ); format!("{not}{}", made.values[0]) } - Type::Bool | Type::Int(_) | Type::NonZero(_) | Type::Char | Type::F32 | Type::F64 | Type::String | Type::Str => { + Type::Bool + | Type::Int(_) + | Type::NonZero(_) + | Type::Char + | Type::F32 + | Type::F64 + | Type::String + | Type::Str => { format!("({x} {} {y})", if op == Op::Eq { "==" } else { "!=" }) } ty => panic!("== of {ty:?}"), @@ -1284,7 +1444,9 @@ impl Emitter<'_> { Op::Lt => format!("({x} < {y})"), Op::Gt => format!("({x} > {y})"), Op::Add | Op::Sub | Op::Mul | Op::Rem => { - let Type::Int(_) = ty else { panic!("arithmetic on {ty:?}") }; + let Type::Int(_) = ty else { + panic!("arithmetic on {ty:?}") + }; let f = match op { Op::Add => "add_", Op::Sub => "sub_", @@ -1299,7 +1461,9 @@ impl Emitter<'_> { /// A closure, as a function literal bound before the statement that passes it. fn closure(&mut self, params: &[Pat], steps: &[Step], value: &Expr, want: &Type, out: &mut String) -> String { - let Type::Closure(closure) = want else { panic!("a closure as {want:?}") }; + let Type::Closure(closure) = want else { + panic!("a closure as {want:?}") + }; if closure.err.is_some() { panic!("a closure returning a Result, which Go returns beside an error"); } @@ -1345,7 +1509,9 @@ impl Emitter<'_> { /// A call of a function `transcript.rs` defines, each argument as its own type. fn local_call(&mut self, e: &Expr, out: &mut String) -> String { - let Kind::Local(name, args) = &e.kind else { unreachable!() }; + let Kind::Local(name, args) = &e.kind else { + unreachable!() + }; let args: Vec = args.iter().map(|a| self.expr(a, out)).collect(); for a in &args { self.lent(a); @@ -1368,7 +1534,9 @@ impl Emitter<'_> { /// A call expression `e`, made: bound before the statement, its error handled as /// `failure` says, its values `kept` or else left `_`. fn made(&mut self, e: &Expr, failure: Failure, kept: bool, out: &mut String) -> Made { - let Kind::Call(id, receiver, args) = &e.kind else { panic!("{} is no call", describe(&e.kind)) }; + let Kind::Call(id, receiver, args) = &e.kind else { + panic!("{} is no call", describe(&e.kind)) + }; let f = self.t.function(*id); let receiver = receiver.as_ref().map(|r| { let v = self.expr(r, out); @@ -1382,7 +1550,9 @@ impl Emitter<'_> { for (arg, param) in args.iter().zip(&f.params) { if written(¶m.ty) { // A value passed for `&mut`, which the call writes back through its pointer. - let Kind::Var(name) = &arg.kind else { panic!("a value passed for &mut that is no local") }; + let Kind::Var(name) = &arg.kind else { + panic!("a value passed for &mut that is no local") + }; values.push(format!("&{}", self.ident(name))); continue; } @@ -1397,7 +1567,15 @@ impl Emitter<'_> { } /// The call of `id` on `receiver` with `args`, each already Go, made. - fn call_with(&mut self, id: FnId, receiver: Option, mut args: Vec, failure: Failure, kept: bool, out: &mut String) -> Made { + fn call_with( + &mut self, + id: FnId, + receiver: Option, + mut args: Vec, + failure: Failure, + kept: bool, + out: &mut String, + ) -> Made { let f = self.t.function(id); let name = self.t.name(LANGUAGE, id).to_string(); if f.future { @@ -1434,7 +1612,15 @@ impl Emitter<'_> { } /// `call`, of values of `types` and an error if `errs`, bound before the statement. - fn hoist(&mut self, call: &str, types: &[Type], errs: bool, failure: Failure, kept: bool, out: &mut String) -> Made { + fn hoist( + &mut self, + call: &str, + types: &[Type], + errs: bool, + failure: Failure, + kept: bool, + out: &mut String, + ) -> Made { let values: Vec = types .iter() .map(|_| match kept { @@ -1467,7 +1653,8 @@ impl Emitter<'_> { } for (v, ty) in made.values.iter().zip(types) { if v != "_" && holds_handle(ty) { - self.handles.insert(v.clone(), !matches!(unref(ty).base(), Type::Object(_))); + self.handles + .insert(v.clone(), !matches!(unref(ty).base(), Type::Object(_))); } } made @@ -1547,7 +1734,9 @@ impl Emitter<'_> { fn go_param(&mut self, ty: &Type) -> String { match ty.base() { Type::Slice | Type::Vec | Type::Bytes => "[]byte".to_string(), - Type::Option(inner) if matches!(inner.base(), Type::Slice | Type::Vec | Type::Bytes) => "*[]byte".to_string(), + Type::Option(inner) if matches!(inner.base(), Type::Slice | Type::Vec | Type::Bytes) => { + "*[]byte".to_string() + } _ => self.go(ty), } } diff --git a/ffi/tests/fixtures/transcript/ir.rs b/ffi/tests/fixtures/transcript/ir.rs index aeae91583..cb76f481e 100644 --- a/ffi/tests/fixtures/transcript/ir.rs +++ b/ffi/tests/fixtures/transcript/ir.rs @@ -35,7 +35,9 @@ impl Api { pub(crate) fn handles(&self, ty: &Type, out: &mut Vec, seen: &mut Vec<(bool, usize)>) { match ty { Type::Object(i) => out.push(*i), - Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => self.handles(inner, out, seen), + Type::Option(inner) | Type::Box(inner) | Type::Ref(_, inner) | Type::List(_, inner) => { + self.handles(inner, out, seen) + } Type::Tuple(elements) => elements.iter().for_each(|ty| self.handles(ty, out, seen)), Type::Record(i) if !seen.contains(&(false, *i)) => { seen.push((false, *i)); diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index 0282d7da5..454a321de 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -11,12 +11,12 @@ //! as its futures, or prints a value no binding shapes alike, such as `hex`. Anything else //! fails, naming its line. -pub(crate) mod dart; pub(crate) mod cpp; -pub(crate) mod ir; -mod parse; +pub(crate) mod dart; pub(crate) mod go; +pub(crate) mod ir; pub(crate) mod kotlin; +mod parse; pub(crate) mod python; pub(crate) mod swift; pub(crate) mod typescript; @@ -44,7 +44,11 @@ pub(crate) enum Step { /// `drop(name)`: the local's value drops here, not at the end of its scope. Drop(String), /// A `match` on a `Result` or an `Option`, `ok` on `Ok` or `Some`. - Match { value: Expr, ok: Arm, err: Arm }, + Match { + value: Expr, + ok: Arm, + err: Arm, + }, } /// A `match` arm: the pattern binding the payload, if any, and the steps it runs. diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 3b34f067d..c92c93058 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -74,7 +74,16 @@ struct Scope<'t> { } /// Conversions that leave a value as the binding has it. -const CONVERSIONS: &[&str] = &["to_string", "to_vec", "to_owned", "into", "as_ref", "into_iter", "iter", "as_deref"]; +const CONVERSIONS: &[&str] = &[ + "to_string", + "to_vec", + "to_owned", + "into", + "as_ref", + "into_iter", + "iter", + "as_deref", +]; impl Scope<'_> { fn import(&mut self, tree: &syn::UseTree, prefix: &mut Vec) { @@ -187,7 +196,9 @@ impl Scope<'_> { fail(field, "an assignment to an element") }; let receiver = self.infer(&field.base); - let Some(id) = self.method_of(&receiver.ty, &name.to_string(), |f| matches!(f.access, Access::Field { set: true, .. })) else { + let Some(id) = self.method_of(&receiver.ty, &name.to_string(), |f| { + matches!(f.access, Access::Field { set: true, .. }) + }) else { fail(field, format!("no setter of {name} on {}", self.describe(&receiver.ty))) }; let ty = self.t.function(id).params[0].ty.clone(); @@ -230,7 +241,14 @@ impl Scope<'_> { fail(pat, "a tuple pattern of another length"); } let elements = elements.clone(); - Pat::Tuple(tuple.elems.iter().zip(&elements).map(|(p, ty)| self.bind(p, ty)).collect()) + Pat::Tuple( + tuple + .elems + .iter() + .zip(&elements) + .map(|(p, ty)| self.bind(p, ty)) + .collect(), + ) } pat => fail(pat, "a pattern other than a name, `_`, or a tuple"), } @@ -240,7 +258,11 @@ impl Scope<'_> { fn ty(&self, ty: &syn::Type) -> Type { match ty { syn::Type::Reference(r) => { - let mutability = if r.mutability.is_some() { Mutability::Mut } else { Mutability::Not }; + let mutability = if r.mutability.is_some() { + Mutability::Mut + } else { + Mutability::Not + }; Type::Ref(mutability, Box::new(self.ty(&r.elem))) } syn::Type::Paren(p) => self.ty(&p.elem), @@ -248,7 +270,8 @@ impl Scope<'_> { let Some(syn::TypeParamBound::Trait(bound)) = t.bounds.first() else { fail(t, "a trait object of no trait") }; - self.type_of_path(&bound.path).unwrap_or_else(|| fail(t, "a trait object the API lacks")) + self.type_of_path(&bound.path) + .unwrap_or_else(|| fail(t, "a trait object the API lacks")) } syn::Type::Tuple(t) if t.elems.is_empty() => Type::Unit, syn::Type::Tuple(t) => Type::Tuple(t.elems.iter().map(|e| self.ty(e)).collect()), @@ -305,7 +328,9 @@ impl Scope<'_> { Type::Int(Int::U8) => Type::Vec, item => Type::List(Collection::Vec, Box::new(item)), }, - _ => self.type_of_path(&p.path).unwrap_or_else(|| fail(ty, "a type the API lacks")), + _ => self + .type_of_path(&p.path) + .unwrap_or_else(|| fail(ty, "a type the API lacks")), } } ty => fail(ty, "this type"), @@ -319,8 +344,18 @@ impl Scope<'_> { let api = &self.t.api; let types: Vec<(Type, &Vec, bool)> = (api.records.iter().enumerate()) .map(|(i, r)| (Type::Record(i), &r.path, r.args.is_empty())) - .chain(api.enums.iter().enumerate().map(|(i, e)| (Type::Enum(i), &e.path, e.args.is_empty()))) - .chain(api.objects.iter().enumerate().map(|(i, o)| (Type::Object(i), &o.path, o.args.is_empty()))) + .chain( + api.enums + .iter() + .enumerate() + .map(|(i, e)| (Type::Enum(i), &e.path, e.args.is_empty())), + ) + .chain( + api.objects + .iter() + .enumerate() + .map(|(i, o)| (Type::Object(i), &o.path, o.args.is_empty())), + ) .collect(); let pick = |found: Vec<&(Type, &Vec, bool)>| -> Option { match found.as_slice() { @@ -352,7 +387,8 @@ impl Scope<'_> { .unwrap_or_else(|e| fail(mac, e)); let mut args = args.into_iter(); let Some(syn::Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(lit), .. + lit: syn::Lit::Str(lit), + .. })) = args.next() else { fail(mac, "a format without its string") @@ -504,7 +540,10 @@ impl Scope<'_> { syn::Expr::Lit(lit) => match &lit.lit { syn::Lit::Str(s) => Expr::new(Kind::Str(s.value()), Type::Ref(Mutability::Not, Box::new(Type::Str))), syn::Lit::Bool(b) => Expr::new(Kind::Bool(b.value), Type::Bool), - syn::Lit::ByteStr(b) => Expr::new(Kind::Bytes(b.value()), Type::Ref(Mutability::Not, Box::new(Type::Slice))), + syn::Lit::ByteStr(b) => Expr::new( + Kind::Bytes(b.value()), + Type::Ref(Mutability::Not, Box::new(Type::Slice)), + ), syn::Lit::Int(i) if !i.suffix().is_empty() => { let int = int_named(i.suffix()).unwrap_or_else(|| fail(i, "this integer suffix")); self.check(expr, &Type::Int(int)) @@ -568,10 +607,16 @@ impl Scope<'_> { return Expr::new(e.kind, ty.clone()); } } - syn::Expr::MethodCall(m) if m.method == "parse" || (m.method == "unwrap" && matches!(&*m.receiver, syn::Expr::MethodCall(r) if r.method == "parse")) => { + syn::Expr::MethodCall(m) + if m.method == "parse" + || (m.method == "unwrap" + && matches!(&*m.receiver, syn::Expr::MethodCall(r) if r.method == "parse")) => + { return self.parsed(m, ty); } - syn::Expr::MethodCall(m) if CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() && !self.api_method(m) => { + syn::Expr::MethodCall(m) + if CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() && !self.api_method(m) => + { return self.check(&m.receiver, ty); } // `[..].into_iter().map(..).collect()`, as a map's or a set's items are built. @@ -579,7 +624,14 @@ impl Scope<'_> { syn::Expr::Call(call) => { let func = &*call.func; let one = call.args.len() == 1; - let passed = ["String::from", "Bytes::from_static", "Box::new", "PathBuf::from", "Path::new", "Bytes::from"]; + let passed = [ + "String::from", + "Bytes::from_static", + "Box::new", + "PathBuf::from", + "Path::new", + "Bytes::from", + ]; if one && passed.iter().any(|p| path_is(func, p)) { return self.check(&call.args[0], ty); } @@ -590,7 +642,13 @@ impl Scope<'_> { let value = self.check(&call.args[0], inner); return Expr::new(Kind::Some(Box::new(value)), ty.clone()); } - let empties = ["Default::default", "Box::default", "Vec::new", "String::new", "Bytes::new"]; + let empties = [ + "Default::default", + "Box::default", + "Vec::new", + "String::new", + "Bytes::new", + ]; if call.args.is_empty() && empties.iter().any(|p| path_is(func, p)) { return self.empty(expr, ty); } @@ -641,7 +699,10 @@ impl Scope<'_> { } let value = self.infer(expr); if !fits(&value.ty, ty) { - fail(expr, format!("{} where {} is taken", self.describe(&value.ty), self.describe(ty))); + fail( + expr, + format!("{} where {} is taken", self.describe(&value.ty), self.describe(ty)), + ); } value } @@ -853,7 +914,15 @@ impl Scope<'_> { } }; let start = end(self, r.start.as_deref(), BoundKind::Included); - let last = end(self, r.end.as_deref(), if closed { BoundKind::Included } else { BoundKind::Excluded }); + let last = end( + self, + r.end.as_deref(), + if closed { + BoundKind::Included + } else { + BoundKind::Excluded + }, + ); Expr::new(Kind::Tuple(vec![start, last]), ty.clone()) } other => fail(r, format!("a range as {}", self.describe(other))), @@ -869,7 +938,12 @@ impl Scope<'_> { fail(c, "a closure of another arity"); } let depth = self.vars.len(); - let params = c.inputs.iter().zip(&closure.params).map(|(p, ty)| self.bind(p, ty)).collect(); + let params = c + .inputs + .iter() + .zip(&closure.params) + .map(|(p, ty)| self.bind(p, ty)) + .collect(); let (steps, value) = self.body(&c.body, &closure.ok); self.vars.truncate(depth); Expr::new(Kind::Closure(params, steps, Box::new(value)), ty.clone()) @@ -880,7 +954,11 @@ impl Scope<'_> { let mut steps = Vec::new(); let value = match body { syn::Expr::Block(b) => { - let (last, init) = b.block.stmts.split_last().unwrap_or_else(|| fail(b, "an empty closure")); + let (last, init) = b + .block + .stmts + .split_last() + .unwrap_or_else(|| fail(b, "an empty closure")); init.iter().for_each(|s| self.stmt(s, &mut steps)); match last { syn::Stmt::Expr(e, None) => self.check(e, ok), @@ -937,7 +1015,10 @@ impl Scope<'_> { let owner = unref(&base.ty).base().clone(); match (&f.member, &owner) { (syn::Member::Unnamed(i), Type::Tuple(elements)) => { - let ty = elements.get(i.index as usize).unwrap_or_else(|| fail(f, "no such element")).clone(); + let ty = elements + .get(i.index as usize) + .unwrap_or_else(|| fail(f, "no such element")) + .clone(); Expr::new(Kind::Element(Box::new(base), i.index as usize), ty) } (syn::Member::Named(name), Type::Range(int)) if name == "start" || name == "end" => { @@ -953,7 +1034,8 @@ impl Scope<'_> { return Expr::new(Kind::Field(Box::new(base), i), ty); } // A getter: an object's field, or an opaque value's. - let Some(id) = self.method_of(&owner, &name, |f| matches!(f.access, Access::Field { set: false, .. })) else { + let Some(id) = self.method_of(&owner, &name, |f| matches!(f.access, Access::Field { set: false, .. })) + else { fail(f, format!("no field {name} on {}", self.describe(&owner))) }; let ty = self.t.function(id).ok.clone(); @@ -966,7 +1048,9 @@ impl Scope<'_> { /// The method `name` of `owner`'s type for which `which` holds. fn method_of(&self, owner: &Type, name: &str, which: impl Fn(&Function) -> bool) -> Option { let (owner, methods) = self.methods(owner)?; - let index = methods.iter().position(|f| f.path.last().map(String::as_str) == Some(name) && which(f))?; + let index = methods + .iter() + .position(|f| f.path.last().map(String::as_str) == Some(name) && which(f))?; Some(FnId { owner, index }) } @@ -982,8 +1066,9 @@ impl Scope<'_> { /// A struct literal: a record's, or an enum's struct variant's. fn structure(&mut self, s: &syn::ExprStruct, ty: Option<&Type>) -> Expr { if let Some((e, v)) = self.find_variant(&s.path, None) { - let fields: Vec<(String, Type)> = - (self.t.api.enums[e].variants[v].fields.iter()).map(|f| (f.name.clone(), f.ty.clone())).collect(); + let fields: Vec<(String, Type)> = (self.t.api.enums[e].variants[v].fields.iter()) + .map(|f| (f.name.clone(), f.ty.clone())) + .collect(); let values = self.fields(s, &fields); return Expr::new(Kind::Variant(e, v, values), Type::Enum(e)); } @@ -994,7 +1079,9 @@ impl Scope<'_> { (Some(Type::Record(i)), _) => vec![*i], (_, Some(Type::Record(i))) => { let path = &self.t.api.records[*i].path; - (0..self.t.api.records.len()).filter(|r| self.t.api.records[*r].path == *path).collect() + (0..self.t.api.records.len()) + .filter(|r| self.t.api.records[*r].path == *path) + .collect() } _ => fail(s, "a struct literal of no record"), }; @@ -1009,7 +1096,9 @@ impl Scope<'_> { }) }) .unwrap_or_else(|| fail(s, "a record literal fitting no instance")); - let fields: Vec<(String, Type)> = (self.t.api.records[r].fields.iter()).map(|f| (f.name.clone(), f.ty.clone())).collect(); + let fields: Vec<(String, Type)> = (self.t.api.records[r].fields.iter()) + .map(|f| (f.name.clone(), f.ty.clone())) + .collect(); if fields.len() != s.fields.len() { fail(s, "a record literal without each field"); } @@ -1068,12 +1157,19 @@ impl Scope<'_> { let (variant, enum_path) = names.split_last()?; let enum_path = enum_path.to_vec(); let found = |e: &super::ir::Enum| { - e.path == enum_path || (e.path.last() == enum_path.last() && !enum_path.is_empty()) || e.foreign && ty.is_some() + e.path == enum_path + || (e.path.last() == enum_path.last() && !enum_path.is_empty()) + || e.foreign && ty.is_some() }; let (e, en) = (self.t.api.enums.iter().enumerate()).find(|(i, e)| { - found(e) && ty.is_none_or(|t| matches!(unref(t), Type::Enum(j) if j == i) || matches!(unref(t), Type::Option(inner) if **inner == Type::Enum(*i))) + found(e) + && ty.is_none_or(|t| { + matches!(unref(t), Type::Enum(j) if j == i) + || matches!(unref(t), Type::Option(inner) if **inner == Type::Enum(*i)) + }) })?; - let v = (en.variants.iter()).position(|v| &v.name == variant || (en.foreign && v.name.to_uppercase() == *variant))?; + let v = (en.variants.iter()) + .position(|v| &v.name == variant || (en.foreign && v.name.to_uppercase() == *variant))?; Some((e, v)) } @@ -1086,7 +1182,11 @@ impl Scope<'_> { return Some(Expr::new(Kind::None, ty.unwrap().clone())); } let (e, v) = self.find_variant(path, ty)?; - let fields: Vec = self.t.api.enums[e].variants[v].fields.iter().map(|f| f.ty.clone()).collect(); + let fields: Vec = self.t.api.enums[e].variants[v] + .fields + .iter() + .map(|f| f.ty.clone()) + .collect(); if fields.len() != args.len() { fail(path, "a variant of another arity"); } @@ -1102,22 +1202,40 @@ impl Scope<'_> { /// including methods called by their path with the receiver first. fn functions(&self, path: &syn::Path) -> Vec { let names = self.segments(path); - let Some((name, owner_path)) = names.split_last() else { return Vec::new() }; + let Some((name, owner_path)) = names.split_last() else { + return Vec::new(); + }; let api = &self.t.api; let mut exact = Vec::new(); let mut loose = Vec::new(); for (i, f) in api.functions.iter().enumerate() { if f.path == names { - exact.push(FnId { owner: Owner::Free, index: i }); + exact.push(FnId { + owner: Owner::Free, + index: i, + }); } else if f.path.last() == Some(name) && names.len() == 1 { - loose.push(FnId { owner: Owner::Free, index: i }); + loose.push(FnId { + owner: Owner::Free, + index: i, + }); } } if !owner_path.is_empty() { let owners = (api.records.iter().enumerate()) .map(|(i, r)| (Owner::Record(i), &r.path, &r.methods)) - .chain(api.enums.iter().enumerate().map(|(i, e)| (Owner::Enum(i), &e.path, &e.methods))) - .chain(api.objects.iter().enumerate().map(|(i, o)| (Owner::Object(i), &o.path, &o.methods))); + .chain( + api.enums + .iter() + .enumerate() + .map(|(i, e)| (Owner::Enum(i), &e.path, &e.methods)), + ) + .chain( + api.objects + .iter() + .enumerate() + .map(|(i, o)| (Owner::Object(i), &o.path, &o.methods)), + ); for (owner, path, methods) in owners { let list = match () { _ if *path == owner_path => &mut exact, @@ -1152,7 +1270,13 @@ impl Scope<'_> { } /// The candidate whose parameters `args` fit and whose return `expected` fits. - fn pick(&self, candidates: Vec, args: &[syn::Expr], expected: Option<&Type>, turbofish: &[Type]) -> Option { + fn pick( + &self, + candidates: Vec, + args: &[syn::Expr], + expected: Option<&Type>, + turbofish: &[Type], + ) -> Option { let fitting: Vec = candidates .into_iter() .filter(|id| { @@ -1170,8 +1294,12 @@ impl Scope<'_> { let args: Vec<&syn::Expr> = args.iter().filter(|a| !is_unit(a)).collect(); turbofish.iter().zip(&named).all(|(t, n)| t == n) && args.len() == params.len() + receiver - && args[receiver..].iter().zip(¶ms).all(|(a, ty)| self.fits_expr(a, ty)) - && expected.is_none_or(|e| f.err.is_some() || fits(&f.ok, e) || matches!(unref(e), Type::Result(..))) + && args[receiver..] + .iter() + .zip(¶ms) + .all(|(a, ty)| self.fits_expr(a, ty)) + && expected + .is_none_or(|e| f.err.is_some() || fits(&f.ok, e) || matches!(unref(e), Type::Result(..))) }) .collect(); fitting.first().copied() @@ -1210,7 +1338,13 @@ impl Scope<'_> { } } let Some(id) = self.function(&p.path, &args, expected) else { - fail(call, format!("a call of {}, which the API does not export", self.segments(&p.path).join("::"))) + fail( + call, + format!( + "a call of {}, which the API does not export", + self.segments(&p.path).join("::") + ), + ) }; let args: Vec = args.into_iter().filter(|a| !is_unit(a)).collect(); match self.t.function(id).receiver { @@ -1261,13 +1395,17 @@ impl Scope<'_> { } // `String::from_utf8(..).unwrap()`, of bytes the transcript knows are text. "unwrap" if matches!(&*m.receiver, syn::Expr::Call(c) if path_is(&c.func, "String::from_utf8")) => { - let syn::Expr::Call(c) = &*m.receiver else { unreachable!() }; + let syn::Expr::Call(c) = &*m.receiver else { + unreachable!() + }; let value = self.infer(&c.args[0]); return Expr::new(Kind::Utf8(Box::new(value)), Type::String); } // `.err().unwrap()`, the error of a call that must fail. "unwrap" if matches!(&*m.receiver, syn::Expr::MethodCall(e) if e.method == "err" && e.args.is_empty()) => { - let syn::Expr::MethodCall(e) = &*m.receiver else { unreachable!() }; + let syn::Expr::MethodCall(e) = &*m.receiver else { + unreachable!() + }; let value = self.infer(&e.receiver); let Type::Result(_, err) = &value.ty else { fail(e, "err() of no Result") @@ -1367,9 +1505,12 @@ impl Scope<'_> { /// `items.map(|pat| body).collect::>().join(sep)`. fn join(&mut self, m: &syn::ExprMethodCall) -> Expr { - let [syn::Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(sep), .. - })] = m.args.iter().collect::>()[..] + let [ + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(sep), + .. + }), + ] = m.args.iter().collect::>()[..] else { fail(m, "a join other than on a string literal") }; @@ -1409,9 +1550,13 @@ impl Scope<'_> { } fn methods_named(&self, owner: &Type, name: &str) -> Vec { - let Some((owner, methods)) = self.methods(owner) else { return Vec::new() }; + let Some((owner, methods)) = self.methods(owner) else { + return Vec::new(); + }; (methods.iter().enumerate()) - .filter(|(_, f)| f.path.last().map(String::as_str) == Some(name) && f.receiver.is_some() && f.access == Access::Call) + .filter(|(_, f)| { + f.path.last().map(String::as_str) == Some(name) && f.receiver.is_some() && f.access == Access::Call + }) .map(|(index, _)| FnId { owner, index }) .collect() } @@ -1535,7 +1680,8 @@ fn const_int(expr: &syn::Expr) -> Option { fn const_float(expr: &syn::Expr) -> Option { match expr { syn::Expr::Lit(syn::ExprLit { - lit: syn::Lit::Float(f), .. + lit: syn::Lit::Float(f), + .. }) => f.base10_parse().ok(), syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. @@ -1610,7 +1756,9 @@ fn const_net(expr: &syn::Expr) -> Option { } if path_is(&c.func, "Ipv6Addr::new") { let s: Vec = args.iter().map(|a| int(a).map(|v| v as u16)).collect::>()?; - return Some(Net::Ip(IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7])))); + return Some(Net::Ip(IpAddr::V6(Ipv6Addr::new( + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + )))); } let ip = |e: &syn::Expr| match const_net(e)? { Net::Ip(ip) => Some(ip), diff --git a/ffi/tests/fixtures/transcript/python.rs b/ffi/tests/fixtures/transcript/python.rs index 7451cf90d..c83fd08b1 100644 --- a/ffi/tests/fixtures/transcript/python.rs +++ b/ffi/tests/fixtures/transcript/python.rs @@ -121,18 +121,20 @@ pub(crate) fn emit(t: &Transcript) -> String { /// The locals a call takes `&mut` that are values, not objects: each is an `api.Mut`, /// whose `value` the script reads. fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec) { - let mut visit = |expr: &Expr| walk(expr, &mut |e| { - if let Kind::Call(id, _, args) = &e.kind { - for (arg, param) in args.iter().zip(&t.function(*id).params) { - if let (Kind::Var(name), Type::Ref(Mutability::Mut, inner)) = (&arg.kind, ¶m.ty) - && !matches!(**inner, Type::Object(_) | Type::Reader) - && !out.contains(name) - { - out.push(name.clone()); + let mut visit = |expr: &Expr| { + walk(expr, &mut |e| { + if let Kind::Call(id, _, args) = &e.kind { + for (arg, param) in args.iter().zip(&t.function(*id).params) { + if let (Kind::Var(name), Type::Ref(Mutability::Mut, inner)) = (&arg.kind, ¶m.ty) + && !matches!(**inner, Type::Object(_) | Type::Reader) + && !out.contains(name) + { + out.push(name.clone()); + } } } - } - }); + }) + }; for step in steps { each_expr(step, &mut visit); } @@ -160,9 +162,16 @@ fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { f(expr); let mut inner = |e: &Expr| walk(e, f); match &expr.kind { - Kind::Some(e) | Kind::Field(e, _) | Kind::Element(e, _) | Kind::Clone(e) | Kind::Unwrap(e) | Kind::UnwrapErr(e) => inner(e), + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => es.iter().for_each(inner), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), Kind::Binary(_, a, b) => { inner(a); @@ -201,10 +210,60 @@ struct Emitter<'t> { } /// Python's keywords, which no name may be. -const KEYWORDS: &[&str] = &["from", "in", "is", "not", "and", "or", "None", "True", "False", "lambda", "def", "del", "pass", "with", "yield", "async", "await", "class", "global", "import", "return", "try", "except", "raise", "while", "for", "if", "else", "elif", "break", "continue", "as", "assert", "finally", "nonlocal", "match", "case", "type"]; +const KEYWORDS: &[&str] = &[ + "from", "in", "is", "not", "and", "or", "None", "True", "False", "lambda", "def", "del", "pass", "with", "yield", + "async", "await", "class", "global", "import", "return", "try", "except", "raise", "while", "for", "if", "else", + "elif", "break", "continue", "as", "assert", "finally", "nonlocal", "match", "case", "type", +]; /// What the script itself calls, which no local of its may shadow. -const BUILTINS: &[&str] = &["list", "bytes", "str", "len", "range", "iter", "format", "print", "repr", "copy", "array", "struct", "ipaddress", "api", "local", "id", "hex", "min", "max", "sum", "next", "map", "filter", "bool", "int", "float", "tuple", "set", "dict", "object", "input", "open", "round", "all", "any", "zip", "slice", "vars", "bin", "oct", "ord", "chr", "abs", "hash", "callable"]; +const BUILTINS: &[&str] = &[ + "list", + "bytes", + "str", + "len", + "range", + "iter", + "format", + "print", + "repr", + "copy", + "array", + "struct", + "ipaddress", + "api", + "local", + "id", + "hex", + "min", + "max", + "sum", + "next", + "map", + "filter", + "bool", + "int", + "float", + "tuple", + "set", + "dict", + "object", + "input", + "open", + "round", + "all", + "any", + "zip", + "slice", + "vars", + "bin", + "oct", + "ord", + "chr", + "abs", + "hash", + "callable", +]; /// A local's name in Python. fn ident(name: &str) -> String { @@ -265,7 +324,9 @@ impl Emitter<'_> { } let v = self.expr(value, out); match pat { - Pat::Name(name, _) if self.mutated.contains(name) => self.line(out, &format!("{} = api.Mut({v})", ident(name))), + Pat::Name(name, _) if self.mutated.contains(name) => { + self.line(out, &format!("{} = api.Mut({v})", ident(name))) + } pat => self.bind(pat, &v, &value.ty, out), } } @@ -291,7 +352,9 @@ impl Emitter<'_> { /// A call of a method taking a value's `&mut self` on a local: the local's name, and /// the call, which Python returns the value from as the call left it. fn mut_receiver(&mut self, value: &Expr) -> Option<(String, String)> { - let Kind::Call(id, Some(receiver), args) = &value.kind else { return None }; + let Kind::Call(id, Some(receiver), args) = &value.kind else { + return None; + }; let f = self.t.function(*id); if f.receiver != Some(Receiver::Mut) || !matches!(id.owner, Owner::Record(_)) { return None; @@ -301,7 +364,10 @@ impl Emitter<'_> { }; let mut scratch = String::new(); let call = self.call(*id, Some(receiver), args, &mut scratch); - assert!(scratch.is_empty(), "a value's &mut self method taking a closure of steps"); + assert!( + scratch.is_empty(), + "a value's &mut self method taking a closure of steps" + ); Some((ident(name), call)) } @@ -446,7 +512,13 @@ impl Emitter<'_> { let Type::Object(i) = ty else { return None }; let o = &self.t.api.objects[*i]; let index = o.methods.iter().position(|m| m.access == Access::Text)?; - Some(self.t.name(LANGUAGE, FnId { owner: Owner::Object(*i), index })) + Some(self.t.name( + LANGUAGE, + FnId { + owner: Owner::Object(*i), + index, + }, + )) } /// `v` as Rust's `Debug` prints a value of `ty`. @@ -467,7 +539,9 @@ impl Emitter<'_> { format!("_list({v}, lambda {x}: {show})") } Type::Tuple(elements) => { - let parts: Vec = (0..elements.len()).map(|i| self.debug(&format!("{v}[{i}]"), &elements[i])).collect(); + let parts: Vec = (0..elements.len()) + .map(|i| self.debug(&format!("{v}[{i}]"), &elements[i])) + .collect(); let tail = if parts.len() == 1 { ",)" } else { ")" }; format!("\"(\" + {} + \"{tail}\"", parts.join(" + \", \" + ")) } @@ -487,7 +561,9 @@ impl Emitter<'_> { Kind::Unit => "None".to_string(), Kind::Bool(b) => if *b { "True" } else { "False" }.to_string(), Kind::Int(n) => n.to_string(), - Kind::Float(f) if !f.is_finite() || (*f == 0.0 && f.is_sign_negative()) => format!("_f64({:#x})", f.to_bits()), + Kind::Float(f) if !f.is_finite() || (*f == 0.0 && f.is_sign_negative()) => { + format!("_f64({:#x})", f.to_bits()) + } Kind::Float(f) => format!("{f:?}"), Kind::Char(c) => string(&c.to_string()), Kind::Str(s) => string(s), @@ -515,7 +591,11 @@ impl Emitter<'_> { Kind::Record(r, fields) => { let name = self.t.type_name(LANGUAGE, &Type::Record(*r)).to_string(); let field_types: Vec = self.t.api.records[*r].fields.iter().map(|f| f.ty.clone()).collect(); - let args: Vec = fields.iter().zip(&field_types).map(|(f, ty)| self.value(f, ty, out)).collect(); + let args: Vec = fields + .iter() + .zip(&field_types) + .map(|(f, ty)| self.value(f, ty, out)) + .collect(); format!("api.{name}({})", args.join(", ")) } Kind::Variant(en, v, fields) => { @@ -527,11 +607,17 @@ impl Emitter<'_> { } let field_types: Vec = variant.fields.iter().map(|f| f.ty.clone()).collect(); let variant_name = variant.name.clone(); - let args: Vec = fields.iter().zip(&field_types).map(|(f, ty)| self.value(f, ty, out)).collect(); + let args: Vec = fields + .iter() + .zip(&field_types) + .map(|(f, ty)| self.value(f, ty, out)) + .collect(); format!("api.{name}.{variant_name}({})", args.join(", ")) } Kind::Bound(kind, value) => { - let Type::Bound(int) = unref(&e.ty) else { panic!("a bound of {:?}", e.ty) }; + let Type::Bound(int) = unref(&e.ty) else { + panic!("a bound of {:?}", e.ty) + }; let (kind, v) = match (kind, value) { (BoundKind::Unbounded, _) => ("UNBOUNDED", "0".to_string()), (BoundKind::Included, Some(v)) => ("INCLUDED", self.expr(v, out)), @@ -550,11 +636,17 @@ impl Emitter<'_> { true => format!("{}.value", ident(name)), false => ident(name), }, - Kind::Const(c) => format!("api.{}", self.t.named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::")))), + Kind::Const(c) => format!( + "api.{}", + self.t + .named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::"))) + ), Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args, out), Kind::Field(base, i) => { let b = self.expr(base, out); - let Type::Record(r) = unref(&base.ty).base() else { panic!("a field of {:?}", base.ty) }; + let Type::Record(r) = unref(&base.ty).base() else { + panic!("a field of {:?}", base.ty) + }; format!("{b}.{}", self.t.api.records[*r].fields[*i].name) } Kind::Element(base, i) => { @@ -580,13 +672,17 @@ impl Emitter<'_> { } } Kind::UnwrapErr(inner) => { - let Type::Result(_, err) = &inner.ty else { panic!("unwrap_err of {:?}", inner.ty) }; + let Type::Result(_, err) = &inner.ty else { + panic!("unwrap_err of {:?}", inner.ty) + }; let exception = self.exception(err); let v = self.expr(inner, out); format!("_err(lambda: {v}, api.{exception})") } Kind::IsErr(inner) => { - let Type::Result(_, err) = &inner.ty else { panic!("is_err of {:?}", inner.ty) }; + let Type::Result(_, err) = &inner.ty else { + panic!("is_err of {:?}", inner.ty) + }; let exception = self.exception(err); let v = self.expr(inner, out); format!("_fails(lambda: {v}, api.{exception})") @@ -620,7 +716,12 @@ impl Emitter<'_> { let body = self.expr(body, out); format!("{}.join({body} for {target} in {items})", string(sep)) } - Kind::MapOr { option, none, pat, some } => { + Kind::MapOr { + option, + none, + pat, + some, + } => { let option = self.expr(option, out); let none = self.expr(none, out); let target = self.pat(pat); @@ -647,7 +748,11 @@ impl Emitter<'_> { Type::Tuple(ts) => ts.clone(), _ => elements.iter().map(|e| e.ty.clone()).collect(), }; - let parts: Vec = elements.iter().zip(&wants).map(|(e, t)| self.value(e, t, out)).collect(); + let parts: Vec = elements + .iter() + .zip(&wants) + .map(|(e, t)| self.value(e, t, out)) + .collect(); match parts.len() { 1 => format!("({},)", parts[0]), _ => format!("({})", parts.join(", ")), diff --git a/ffi/tests/fixtures/transcript/swift.rs b/ffi/tests/fixtures/transcript/swift.rs index 3db556e94..87aa33315 100644 --- a/ffi/tests/fixtures/transcript/swift.rs +++ b/ffi/tests/fixtures/transcript/swift.rs @@ -193,7 +193,8 @@ impl Model { /// Whether a parameter of `ty` is `inout`: a value Rust writes back, a reader, or a struct /// borrowed mutably. fn inout(&self, ty: &Type) -> bool { - let written = matches!(ty, Type::Ref(Mutability::Mut, inner) if !matches!(**inner, Type::Object(_) | Type::Reader)); + let written = + matches!(ty, Type::Ref(Mutability::Mut, inner) if !matches!(**inner, Type::Object(_) | Type::Reader)); let reader = matches!(ty, Type::Ref(_, inner) if **inner == Type::Reader); let lent = self.unique(ty) && match ty { @@ -348,10 +349,52 @@ struct Emitter<'t> { /// Swift's keywords, which a local's name is quoted as. const KEYWORDS: &[&str] = &[ - "as", "break", "case", "catch", "class", "continue", "default", "defer", "do", "else", "enum", "extension", "fallthrough", - "false", "for", "func", "guard", "if", "import", "in", "init", "inout", "internal", "is", "let", "nil", "operator", - "private", "protocol", "public", "repeat", "rethrows", "return", "self", "static", "struct", "subscript", "super", - "switch", "throw", "throws", "true", "try", "var", "where", "while", + "as", + "break", + "case", + "catch", + "class", + "continue", + "default", + "defer", + "do", + "else", + "enum", + "extension", + "fallthrough", + "false", + "for", + "func", + "guard", + "if", + "import", + "in", + "init", + "inout", + "internal", + "is", + "let", + "nil", + "operator", + "private", + "protocol", + "public", + "repeat", + "rethrows", + "return", + "self", + "static", + "struct", + "subscript", + "super", + "switch", + "throw", + "throws", + "true", + "try", + "var", + "where", + "while", ]; /// A name as Swift spells it, quoted if a keyword. @@ -382,7 +425,9 @@ impl Emitter<'_> { fn mutations(&mut self, step: &Step) { let visit = |e: &Expr, this: &mut Self| { walk(e, &mut |e| { - let Kind::Call(id, receiver, args) = &e.kind else { return }; + let Kind::Call(id, receiver, args) = &e.kind else { + return; + }; if this.model.mutating(this.t, *id) && let Some(Kind::Var(name)) = receiver.as_ref().map(|r| &r.kind) { @@ -455,7 +500,9 @@ impl Emitter<'_> { } }; find(&self.t.steps); - let ty = types.first().unwrap_or_else(|| panic!("a drop of {name}, which no let binds")); + let ty = types + .first() + .unwrap_or_else(|| panic!("a drop of {name}, which no let binds")); self.model.unique(ty) } @@ -470,7 +517,8 @@ impl Emitter<'_> { fn step(&mut self, step: &Step, out: &mut String) { match step { Step::Let(pat, value) => { - let literal = matches!(&value.kind, Kind::Tuple(_)) && !matches!(unref(&value.ty).base(), Type::Range(_) | Type::Bounds(_)); + let literal = matches!(&value.kind, Kind::Tuple(_)) + && !matches!(unref(&value.ty).base(), Type::Range(_) | Type::Bounds(_)); match (pat, &value.kind) { // A tuple literal binds each element, so each may be its own `let` or `var`. (Pat::Tuple(pats), Kind::Tuple(elements)) if literal => { @@ -617,7 +665,12 @@ impl Emitter<'_> { } /// `write`'s expression, prefixed with `prefix` if it throws. - fn rooted(&mut self, prefix: &str, out: &mut String, write: impl FnOnce(&mut Self, &mut String) -> String) -> String { + fn rooted( + &mut self, + prefix: &str, + out: &mut String, + write: impl FnOnce(&mut Self, &mut String) -> String, + ) -> String { let saved = std::mem::replace(&mut self.threw, false); let v = write(self, out); match std::mem::replace(&mut self.threw, saved) { @@ -850,7 +903,9 @@ impl Emitter<'_> { (spec, ty) => panic!("{spec:?} of {ty:?}"), } match ty { - Type::Bool | Type::Int(_) | Type::U128 | Type::NonZero(_) | Type::String | Type::Str | Type::Char => v.to_string(), + Type::Bool | Type::Int(_) | Type::U128 | Type::NonZero(_) | Type::String | Type::Str | Type::Char => { + v.to_string() + } Type::Object(i) if !self.t.api.objects[*i].traits.display => { let o = &self.t.api.objects[*i]; let Some(index) = o.methods.iter().position(|m| m.access == Access::Text) else { @@ -978,7 +1033,10 @@ impl Emitter<'_> { } Kind::Socket(addr) => { let (v4, v6) = match addr { - std::net::SocketAddr::V4(a) => (Some(format!("SocketAddrV4(ip: {}, port: {})", ipv4(*a.ip()), a.port())), None), + std::net::SocketAddr::V4(a) => ( + Some(format!("SocketAddrV4(ip: {}, port: {})", ipv4(*a.ip()), a.port())), + None, + ), std::net::SocketAddr::V6(a) => ( None, Some(format!( @@ -1066,13 +1124,20 @@ impl Emitter<'_> { Kind::Var(name) => self.var(name), Kind::Const(c) => format!( "Api.{}", - self.t.named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::"))) + self.t + .named(LANGUAGE, &format!("const {}", self.t.api.constants[*c].path.join("::"))) ), Kind::Call(id, receiver, args) => self.call(*id, receiver.as_deref(), args, out), Kind::Field(base, i) => { let b = self.expr(base, out); - let Type::Record(r) = unref(&base.ty).base() else { panic!("a field of {:?}", base.ty) }; - format!("{}.{}", postfix(&b), field_name(&self.t.api.records[*r].fields[*i].name)) + let Type::Record(r) = unref(&base.ty).base() else { + panic!("a field of {:?}", base.ty) + }; + format!( + "{}.{}", + postfix(&b), + field_name(&self.t.api.records[*r].fields[*i].name) + ) } Kind::Element(base, i) => { let b = self.expr(base, out); @@ -1104,7 +1169,9 @@ impl Emitter<'_> { } } Kind::UnwrapErr(inner) => { - let Type::Result(_, err) = &inner.ty else { panic!("unwrap_err of {:?}", inner.ty) }; + let Type::Result(_, err) = &inner.ty else { + panic!("unwrap_err of {:?}", inner.ty) + }; let (exception, wrapped) = self.exception(err); let call = self.attempt(inner); match wrapped { @@ -1113,7 +1180,9 @@ impl Emitter<'_> { } } Kind::IsErr(inner) => { - let Type::Result(_, err) = &inner.ty else { panic!("is_err of {:?}", inner.ty) }; + let Type::Result(_, err) = &inner.ty else { + panic!("is_err of {:?}", inner.ty) + }; let (exception, _) = self.exception(err); let call = self.attempt(inner); format!("_fails({exception}.self) {{ {call} }}") @@ -1160,10 +1229,19 @@ impl Emitter<'_> { let body = self.closure_value(body); match self.model.unique(&item) { true => format!("_each({v}) {{ {x} in {body} }}.joined(separator: \"{}\")", escape(sep)), - false => format!("{}.map {{ {x} in {body} }}.joined(separator: \"{}\")", postfix(&v), escape(sep)), + false => format!( + "{}.map {{ {x} in {body} }}.joined(separator: \"{}\")", + postfix(&v), + escape(sep) + ), } } - Kind::MapOr { option, none, pat, some } => { + Kind::MapOr { + option, + none, + pat, + some, + } => { let option = self.expr(option, out); let none = self.expr(none, out); let x = self.param(pat); @@ -1231,7 +1309,11 @@ impl Emitter<'_> { Type::Tuple(ts) => ts.clone(), _ => elements.iter().map(|e| e.ty.clone()).collect(), }; - let parts: Vec = elements.iter().zip(&wants).map(|(e, t)| self.value(e, t, out)).collect(); + let parts: Vec = elements + .iter() + .zip(&wants) + .map(|(e, t)| self.value(e, t, out)) + .collect(); match parts.len() { 1 => parts.into_iter().next().unwrap(), _ if self.model.unique(&Type::Tuple(wants.clone())) => { @@ -1307,7 +1389,10 @@ impl Emitter<'_> { assert!(!f.future, "a call of the future {key}, which only a hook awaits"); // A fresh implementation of a callback, passed to a call within an expression: the call // is its own statement, so Swift's reference to it goes before the rest runs. - let fresh = args.iter().zip(&f.params).any(|(a, p)| matches!(p.ty.base(), Type::Callback(..)) && matches!(a.kind, Kind::Local(..))); + let fresh = args + .iter() + .zip(&f.params) + .any(|(a, p)| matches!(p.ty.base(), Type::Callback(..)) && matches!(a.kind, Kind::Local(..))); if fresh && !at_root { let call = self.rooted("try! ", out, |this, out| { this.at_root = true; @@ -1483,9 +1568,16 @@ fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { f(expr); let mut inner = |e: &Expr| walk(e, f); match &expr.kind { - Kind::Some(e) | Kind::Field(e, _) | Kind::Element(e, _) | Kind::Clone(e) | Kind::Unwrap(e) | Kind::UnwrapErr(e) => inner(e), + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => es.iter().for_each(inner), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), Kind::Binary(_, a, b) => { inner(a); @@ -1602,7 +1694,11 @@ fn ipv4(ip: std::net::Ipv4Addr) -> String { fn ipv6(ip: std::net::Ipv6Addr) -> String { let bits = u128::from(ip); - format!("Ipv6Addr(bits: U128(high: {:#x}, low: {:#x}))", (bits >> 64) as u64, bits as u64) + format!( + "Ipv6Addr(bits: U128(high: {:#x}, low: {:#x}))", + (bits >> 64) as u64, + bits as u64 + ) } /// Bytes as a Swift array literal. From 42148f892c9a5073a7bb7a322463c8ca77351e0b Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:19:03 -0800 Subject: [PATCH 14/28] style: rustfmt Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 15ad76e45..b24ee456d 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -433,7 +433,11 @@ fn sanitized(sanitizer: &str) { run(Command::new(compiler) .args([std, "-g", "-Wall", "-Wextra", "-Werror", &sanitize, "-I"]) .arg(api.out.join("include")) - .args(scripts.iter().flat_map(|dir| [std::ffi::OsStr::new("-I"), dir.as_os_str()])) + .args( + scripts + .iter() + .flat_map(|dir| [std::ffi::OsStr::new("-I"), dir.as_os_str()]), + ) .arg(tests.join(src)) .arg(&lib) .args(&native) From aa03ac3ed6cdb4940d04223869f72428d0170314 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:24:21 -0800 Subject: [PATCH 15/28] chore: drop unread IR fields, lint, and keep main's formatting Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 34 ++++++++++++++++--------- ffi/src/dart.rs | 6 +++-- ffi/src/go.rs | 3 ++- ffi/src/web.rs | 6 +++-- ffi/tests/fixtures/transcript/go.rs | 2 +- ffi/tests/fixtures/transcript/ir.rs | 10 -------- ffi/tests/fixtures/transcript/kotlin.rs | 5 ++-- ffi/tests/fixtures/transcript/parse.rs | 2 +- 8 files changed, 37 insertions(+), 31 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 6b025440d..b6713dc75 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -2628,7 +2628,8 @@ impl<'tcx> Collector<'tcx> { || (api.records.iter()).any(|r| args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) || (api.enums.iter()).any(|e| { args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) + }) + || (api.objects.iter()).any(|o| args(&o.args) || o.methods.iter().any(signature)) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if !used { self.api.enums.pop(); @@ -2655,10 +2656,12 @@ impl<'tcx> Collector<'tcx> { let used = api.functions.iter().any(signature) || (api.records.iter().enumerate()).any(|(i, r)| { (!value || i != gone) && (args(&r.args) || fields(&r.fields) || r.methods.iter().any(signature)) - }) || (api.enums.iter()).any(|e| { - args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) - }) || (api.objects.iter().enumerate()) - .any(|(i, o)| (value || i != gone) && (args(&o.args) || o.methods.iter().any(signature))) + }) + || (api.enums.iter()).any(|e| { + args(&e.args) || e.variants.iter().any(|v| fields(&v.fields)) || e.methods.iter().any(signature) + }) + || (api.objects.iter().enumerate()) + .any(|(i, o)| (value || i != gone) && (args(&o.args) || o.methods.iter().any(signature))) || (api.callbacks.iter()).any(|c| c.methods.iter().any(signature)); if used { continue; @@ -3354,7 +3357,8 @@ impl<'tcx> Collector<'tcx> { // is, takes it from the future, as it would a parameter. ty::Ref(_, inner, _) if Some(*inner) == self_ty - && polled.is_some() && let Some(kind) = self.task(ty, true) => + && polled.is_some() + && let Some(kind) = self.task(ty, true) => { made = Some(*inner); tasks.push(Task { at: 0, kind }); @@ -4517,7 +4521,8 @@ impl<'tcx> Collector<'tcx> { .inputs() .iter() .filter(|&&input| input == param) - .count() > 1 + .count() + > 1 { return Some(Err(why("closure type taken twice", param.to_string()))); } @@ -4871,11 +4876,16 @@ impl<'tcx> Collector<'tcx> { let plain = matches!( ty.kind(), ty::Adt(..) - | ty::Bool | ty::Char - | ty::Int(_) | ty::Uint(_) - | ty::Float(_) | ty::Str - | ty::Array(..) | ty::Slice(_) - | ty::Ref(..) | ty::Tuple(_) + | ty::Bool + | ty::Char + | ty::Int(_) + | ty::Uint(_) + | ty::Float(_) + | ty::Str + | ty::Array(..) + | ty::Slice(_) + | ty::Ref(..) + | ty::Tuple(_) ); let (method, driven) = match (implements(iterator, ty), implements(into_iterator, ty)) { (true, _) => (next, item), diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 8ec320841..bfd73610f 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -621,11 +621,13 @@ impl<'a> Gen<'a> { !matches!( ty, Ty::Buf - | Ty::U128 | Ty::Duration + | Ty::U128 + | Ty::Duration | Ty::SocketAddr(_) | Ty::IpAddr(_) | Ty::Struct(_) - | Ty::Waker | Ty::ForeignFuture + | Ty::Waker + | Ty::ForeignFuture | Ty::ForeignReader ) } diff --git a/ffi/src/go.rs b/ffi/src/go.rs index e967a9595..7e3f68951 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -2611,7 +2611,8 @@ impl<'a> Gen<'a> { let everywhere = abi.api.everywhere(function.on); let closable = receiver.is_some() && owner_ty.is_some_and(|ty| self.fails(ty)) || function.params.iter().any(|p| self.fails(&p.ty)) - || status || !everywhere; + || status + || !everywhere; if function.err.is_some() || function.future || closable { results.push("error".to_string()); } diff --git a/ffi/src/web.rs b/ffi/src/web.rs index 4a8cdc91c..e3233fc72 100644 --- a/ffi/src/web.rs +++ b/ffi/src/web.rs @@ -674,11 +674,13 @@ impl<'a> Gen<'a> { !matches!( ty, Ty::Buf - | Ty::U128 | Ty::Duration + | Ty::U128 + | Ty::Duration | Ty::SocketAddr(_) | Ty::IpAddr(_) | Ty::Struct(_) - | Ty::Waker | Ty::ForeignFuture + | Ty::Waker + | Ty::ForeignFuture | Ty::ForeignReader ) } diff --git a/ffi/tests/fixtures/transcript/go.rs b/ffi/tests/fixtures/transcript/go.rs index 67ed3630d..5f44a0016 100644 --- a/ffi/tests/fixtures/transcript/go.rs +++ b/ffi/tests/fixtures/transcript/go.rs @@ -1153,7 +1153,7 @@ impl Emitter<'_> { self.lent(&v); let made = self.hoist( &format!("{v}.Clone()"), - &[inner.ty.clone()], + std::slice::from_ref(&inner.ty), true, Failure::Panic, true, diff --git a/ffi/tests/fixtures/transcript/ir.rs b/ffi/tests/fixtures/transcript/ir.rs index cb76f481e..d455b1d76 100644 --- a/ffi/tests/fixtures/transcript/ir.rs +++ b/ffi/tests/fixtures/transcript/ir.rs @@ -112,22 +112,15 @@ pub(crate) struct Object { #[serde(default)] pub(crate) shown: Option>, pub(crate) args: Vec, - #[serde(default = "yes")] - pub(crate) send: bool, pub(crate) sync: bool, pub(crate) copy: bool, pub(crate) shared: bool, pub(crate) methods: Vec, pub(crate) traits: Traits, - pub(crate) foreign: bool, /// The targets it is on. pub(crate) on: u64, } -fn yes() -> bool { - true -} - #[derive(serde::Deserialize)] pub(crate) struct Callback { pub(crate) path: Vec, @@ -138,10 +131,8 @@ pub(crate) struct Callback { #[derive(Clone, Copy, Default, serde::Deserialize)] pub(crate) struct Traits { pub(crate) clone: bool, - pub(crate) eq: bool, pub(crate) display: bool, pub(crate) debug: bool, - pub(crate) default: bool, } #[derive(serde::Deserialize)] @@ -155,7 +146,6 @@ pub(crate) struct Function { pub(crate) ok: Type, pub(crate) err: Option, pub(crate) future: bool, - pub(crate) collect: bool, pub(crate) lends: bool, #[serde(default)] pub(crate) lends_mut: bool, diff --git a/ffi/tests/fixtures/transcript/kotlin.rs b/ffi/tests/fixtures/transcript/kotlin.rs index ad19ab9e6..dd227ddf2 100644 --- a/ffi/tests/fixtures/transcript/kotlin.rs +++ b/ffi/tests/fixtures/transcript/kotlin.rs @@ -99,7 +99,8 @@ fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec, vars: &mut Vec let f = t.function(*id); for (arg, param) in args.iter().zip(params(t, *id)) { if let Kind::Var(name) = &arg.kind - && written(¶m) && !out.contains(name) + && written(¶m) + && !out.contains(name) { out.push(name.clone()); } @@ -941,7 +942,7 @@ impl Emitter<'_> { }; // A handle made for the call is a temporary, which Rust drops once the statement // ends, ending any borrow it holds: Kotlin closes it once the call returns. - let temporary = receiver.is_some_and(|r| temporary(r)) && f.receiver != Some(Receiver::Owned); + let temporary = receiver.is_some_and(temporary) && f.receiver != Some(Receiver::Owned); let (target, close) = match temporary { true => { let tmp = self.fresh("h"); diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index b1673b098..fb5235a02 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -925,7 +925,7 @@ impl Scope<'_> { } Type::Bounds(int) => { let bound = Type::Bound(*int); - let mut end = |s: &mut Self, e: Option<&syn::Expr>, kind: BoundKind| match e { + let end = |s: &mut Self, e: Option<&syn::Expr>, kind: BoundKind| match e { None => Expr::new(Kind::Bound(BoundKind::Unbounded, None), bound.clone()), Some(e) => { let v = s.check(e, &Type::Int(*int)); From 296a992fef48c4999bbbfc5e691da039a6eda2e9 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:30:58 -0800 Subject: [PATCH 16/28] quest: the transcript is generated; follow up on the names table Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-proofs/README.md | 3 +-- quest/m1/ffi-rules/names.md | 25 +++++++++++++++++++++++++ quest/m1/ffi-rules/transcript.md | 19 ------------------- quest/m1/ffi-rules/walker.md | 4 ---- 4 files changed, 26 insertions(+), 25 deletions(-) create mode 100644 quest/m1/ffi-rules/names.md delete mode 100644 quest/m1/ffi-rules/transcript.md diff --git a/quest/m1/ffi-proofs/README.md b/quest/m1/ffi-proofs/README.md index d9f044cb5..4c66dd9da 100644 --- a/quest/m1/ffi-proofs/README.md +++ b/quest/m1/ffi-proofs/README.md @@ -17,5 +17,4 @@ This epic changes no generated API, so it does not hold moq's pin ([the exporter epic](/quest/m1/ffi-export/README.md#plan)). Considered and dropped by the audit: Kani, since the runtime's `unsafe` is FFI and concurrency, where Miri and loom fit better; and mutation testing of the generators until [the shapes](/quest/m1/ffi-proofs/shapes.md) -and [the transcript as data](/quest/m1/ffi-rules/transcript.md) land, since every mutant -reruns eight languages. +land, since every mutant reruns eight languages. diff --git a/quest/m1/ffi-rules/names.md b/quest/m1/ffi-rules/names.md new file mode 100644 index 000000000..8c484f88f --- /dev/null +++ b/quest/m1/ffi-rules/names.md @@ -0,0 +1,25 @@ +# [M] Every binding records each public name in api.json + +## Goal + +`api.json`'s `names` table holds every name each language's binding gives an item: record +fields, enum variants, data-variant payloads, tuple structs, error wrappers, and trait +members such as `clone`, `default`, and `Display`'s, besides the functions, types, and +constants it holds now. The transcript's emitters in `ffi/tests/fixtures/transcript` read +them from the table and drop their copies of each generator's naming rules. + +## Plan + +Found by [#885](https://github.com/kixel-ai/rust2/pull/885), which writes each language's +`tests/api.*` script from the transcript. Each of its eight emitters repeats some of its +generator's naming rules for what the table leaves out: camel or snake case, reserved-word +escapes, numbered duplicates, upper-case enum values, and which `Pair`/`Triple` a tuple +becomes. Go and Dart record variants; C, C++, Kotlin, Python, Swift, and TypeScript do not. +A copy that drifts from its generator fails the api test rather than hiding, so this is +cleanup, not a correctness gap. + +Recommended: record each name where the generator decides it, through `lock::function` and +its siblings, keyed as `field ::`, `variant ::`, and +`trait ::`, so a later rename shows in the lock too. + +Public API: none. diff --git a/quest/m1/ffi-rules/transcript.md b/quest/m1/ffi-rules/transcript.md deleted file mode 100644 index 6fc7fc840..000000000 --- a/quest/m1/ffi-rules/transcript.md +++ /dev/null @@ -1,19 +0,0 @@ -# [L] Generate the differential tests from the transcript - -## Goal - -The differential part of each language's `ffi/tests/api.*`, the script whose output must -match `examples/transcript.rs` line for line, is generated for all eight languages from -the transcript written once as data. What stays hand-written is only what tests a -language's idiom or the protocol: futures and cancel, close and GC, thread checks, and -each broken runtime check. The PR reports the hand-written lines before and after. - -## Plan - -[The epic](/quest/m1/ffi-rules/README.md) holds the measurements and the decision. - -Recommended: a small step language (call, field read, expected value) the shape tests' -driver generator can reuse, rather than a second generator per language; the generated -drivers are written at test time, not committed. - -Public API: none. diff --git a/quest/m1/ffi-rules/walker.md b/quest/m1/ffi-rules/walker.md index b01a91acd..b723d3350 100644 --- a/quest/m1/ffi-rules/walker.md +++ b/quest/m1/ffi-rules/walker.md @@ -17,7 +17,3 @@ several positions (#710 added 130 to 260 lines to each generator), and barely he value type, whose cost is mostly per-language runtime code. Public API: none. - -## Required - -- [The transcript as data](/quest/m1/ffi-rules/transcript.md) - the tests a walker change must pass no longer need porting by hand From 6c712b5623a7c1fa4c2080b23734e06827b69f34 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:43:25 -0800 Subject: [PATCH 17/28] fix(ffi): the transcript folds integers as Rust does and refuses what a writer would re-evaluate Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures/transcript/parse.rs | 175 ++++++++++++++++++++++--- 1 file changed, 157 insertions(+), 18 deletions(-) diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index fb5235a02..4ce8d0cf5 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -171,6 +171,12 @@ impl Scope<'_> { fail(&f.pat, "a for loop binding anything but a name") }; for item in &items.elems { + // Each element is spelled again at each use in the unrolled body, so one + // whose evaluation could be seen, such as a call, would run once per use, + // not once before the loop as Rust runs it. + if !spelled(item) { + fail(item, "a for loop over an element other than a literal, a local, or a value built of them") + } self.vars.push(Var::Alias(name.ident.to_string(), item.clone())); let body = self.block(&f.body.stmts); self.vars.pop(); @@ -1504,7 +1510,13 @@ impl Scope<'_> { let [none, syn::Expr::Closure(c)] = m.args.iter().collect::>()[..] else { fail(m, "a map_or other than of a default and a closure") }; + let none_syn = none; let none = self.infer(none); + // Rust evaluates the default before it looks at the option, which a binding that + // evaluates only the arm taken would skip. + if !pure(&none) { + fail(none_syn, "a map_or default other than a literal, a local, or a value built of them") + } let [p] = c.inputs.iter().collect::>()[..] else { fail(c, "a map_or closure of one parameter") }; @@ -1613,6 +1625,100 @@ fn literalish(expr: &syn::Expr) -> bool { } } +/// Whether evaluating `e` has no effect a script could see, so a writer may evaluate it +/// once per use, or not at all: no call of the API's or a hook's, and no closure. +fn pure(e: &Expr) -> bool { + match &e.kind { + Kind::Unit + | Kind::Bool(_) + | Kind::Int(_) + | Kind::Float(_) + | Kind::Char(_) + | Kind::Str(_) + | Kind::Bytes(_) + | Kind::Duration(..) + | Kind::Socket(_) + | Kind::Ip(_) + | Kind::None + | Kind::Var(_) + | Kind::Const(_) + | Kind::Bound(_, None) => true, + Kind::Some(inner) | Kind::Bound(_, Some(inner)) | Kind::Field(inner, _) | Kind::Element(inner, _) => pure(inner), + Kind::Tuple(items) | Kind::List(items) | Kind::Record(_, items) | Kind::Variant(_, _, items) => items.iter().all(pure), + Kind::Binary(_, a, b) => pure(a) && pure(b), + Kind::Format(pieces) => pieces.iter().all(|p| match p { + Piece::Text(_) => true, + Piece::Value(e, _) => pure(e), + }), + _ => false, + } +} + +/// Whether `expr` is spelled of literals, locals, constants, and constructors alone, as +/// [`pure`] asks of a typed value, without typing it. +fn spelled(expr: &syn::Expr) -> bool { + fn all<'e>(mut items: impl Iterator) -> bool { + items.all(spelled) + } + match expr { + syn::Expr::Lit(_) | syn::Expr::Path(_) => true, + syn::Expr::Paren(p) => spelled(&p.expr), + syn::Expr::Group(g) => spelled(&g.expr), + syn::Expr::Reference(r) => spelled(&r.expr), + syn::Expr::Unary(u) => spelled(&u.expr), + syn::Expr::Index(i) => spelled(&i.expr) && matches!(&*i.index, syn::Expr::Range(r) if r.start.is_none() && r.end.is_none()), + syn::Expr::Array(a) => all(a.elems.iter()), + syn::Expr::Tuple(t) => all(t.elems.iter()), + syn::Expr::Struct(s) => s.rest.is_none() && all(s.fields.iter().map(|f| &f.expr)), + // A variant's or a tuple struct's constructor, which names a type. + syn::Expr::Call(c) => { + let constructor = matches!(&*c.func, syn::Expr::Path(p) + if p.path.segments.last().is_some_and(|s| s.ident.to_string().starts_with(char::is_uppercase))); + constructor && all(c.args.iter()) + } + syn::Expr::MethodCall(m) => CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() && spelled(&m.receiver), + _ => false, + } +} + +/// `n`, negated. +fn negated(n: Num) -> Num { + Num { + negative: !n.negative && n.magnitude != 0, + ..n + } +} + +/// `l + r`, or none past 128 bits of magnitude. +fn sum(l: Num, r: Num) -> Option { + let (negative, magnitude) = match (l.negative == r.negative, l.magnitude >= r.magnitude) { + (true, _) => (l.negative, l.magnitude.checked_add(r.magnitude)?), + (false, true) => (l.negative, l.magnitude - r.magnitude), + (false, false) => (r.negative, r.magnitude - l.magnitude), + }; + Some(Num { + negative: negative && magnitude != 0, + magnitude, + }) +} + +/// `n as` an integer of `bits` bits: its two's complement truncated to them, then read as +/// signed or unsigned. +fn truncated(n: Num, bits: u32, signed: bool) -> Num { + let raw = if n.negative { n.magnitude.wrapping_neg() } else { n.magnitude }; + let raw = if bits == 128 { raw } else { raw & ((1u128 << bits) - 1) }; + match signed && raw >> (bits - 1) & 1 == 1 { + true => Num { + negative: true, + magnitude: if bits == 128 { raw.wrapping_neg() } else { (1u128 << bits) - raw }, + }, + false => Num { + negative: false, + magnitude: raw, + }, + } +} + fn int_named(name: &str) -> Option { Some(match name { "u8" => Int::U8, @@ -1629,8 +1735,9 @@ fn int_named(name: &str) -> Option { }) } -/// An integer spelled by literals, constants such as `u64::MAX`, shifts, sums, and casts, -/// or `NonZero::new(..).unwrap()` of one. +/// An integer spelled by literals, constants such as `u64::MAX`, shifts, sums, +/// differences, and casts, or `NonZero::new(..).unwrap()` of one, folded as Rust folds it: +/// signs kept, and each cast truncating to its type's width. fn const_int(expr: &syn::Expr) -> Option { let num = |v: i128| Some(Num::new(v)); match expr { @@ -1641,26 +1748,28 @@ fn const_int(expr: &syn::Expr) -> Option { magnitude: i.base10_parse().ok()?, }), syn::Expr::Paren(p) => const_int(&p.expr), - syn::Expr::Cast(c) => const_int(&c.expr), - syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => { - let n = const_int(&u.expr)?; - Some(Num { - negative: !n.negative, - ..n - }) + syn::Expr::Cast(c) => { + let n = const_int(&c.expr)?; + let syn::Type::Path(ty) = &*c.ty else { return None }; + match ty.path.get_ident()?.to_string().as_str() { + "u128" => Some(truncated(n, 128, false)), + name => { + let int = int_named(name)?; + Some(truncated(n, int.bits(), int.signed())) + } + } } + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => Some(negated(const_int(&u.expr)?)), syn::Expr::Binary(b) => { let (l, r) = (const_int(&b.left)?, const_int(&b.right)?); - let (l, r) = (l.magnitude, r.magnitude); match b.op { - syn::BinOp::Shl(_) => Some(Num { - negative: false, - magnitude: l << r, - }), - syn::BinOp::Add(_) => Some(Num { - negative: false, - magnitude: l + r, - }), + syn::BinOp::Shl(_) => { + let by = u32::try_from(r.magnitude).ok().filter(|by| !r.negative && *by < 128)?; + let magnitude = l.magnitude << by; + (magnitude >> by == l.magnitude).then_some(Num { magnitude, ..l }) + } + syn::BinOp::Add(_) => sum(l, r), + syn::BinOp::Sub(_) => sum(l, negated(r)), _ => None, } } @@ -1816,3 +1925,33 @@ pub(super) fn fits(have: &Type, want: &Type) -> bool { (a, b) => a == b || (text(a) && text(b)) || (bytes(a) && bytes(b)) || (path(a) && path(b)), } } + +/// Each integer the folder accepts folds to the value rustc gives the same expression. +#[test] +fn folds_like_rust() { + macro_rules! cases { + ($($e:expr),* $(,)?) => { + [$((stringify!($e), $e as i128)),*] + }; + } + #[allow(clippy::identity_op, clippy::cast_lossless, overflowing_literals)] + let cases = cases![ + -1isize + 2, + 256u16 as u8 as u64, + 300 as u8, + -1i64 as u64, + u64::MAX as i64, + u128::MAX as i64, + i8::MIN as u8, + -5 - 3, + 2 - 7, + (1u128 << 127) as i8, + (1i128 << 64) + 1, + -(1i64 << 62) as u32, + u32::MAX as i16 as u64, + ]; + for (text, want) in cases { + let expr: syn::Expr = syn::parse_str(text).unwrap(); + assert_eq!(const_int(&expr), Some(Num::new(want)), "{text}"); + } +} From e38e174998597e3e1c8ca504313081b4106b075d Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:46:56 -0800 Subject: [PATCH 18/28] fix(ffi): lint the folding test Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures/transcript/parse.rs | 45 ++++++++++++++++++++------ 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 4ce8d0cf5..71536add7 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -175,7 +175,10 @@ impl Scope<'_> { // whose evaluation could be seen, such as a call, would run once per use, // not once before the loop as Rust runs it. if !spelled(item) { - fail(item, "a for loop over an element other than a literal, a local, or a value built of them") + fail( + item, + "a for loop over an element other than a literal, a local, or a value built of them", + ) } self.vars.push(Var::Alias(name.ident.to_string(), item.clone())); let body = self.block(&f.body.stmts); @@ -1515,7 +1518,10 @@ impl Scope<'_> { // Rust evaluates the default before it looks at the option, which a binding that // evaluates only the arm taken would skip. if !pure(&none) { - fail(none_syn, "a map_or default other than a literal, a local, or a value built of them") + fail( + none_syn, + "a map_or default other than a literal, a local, or a value built of them", + ) } let [p] = c.inputs.iter().collect::>()[..] else { fail(c, "a map_or closure of one parameter") @@ -1643,8 +1649,12 @@ fn pure(e: &Expr) -> bool { | Kind::Var(_) | Kind::Const(_) | Kind::Bound(_, None) => true, - Kind::Some(inner) | Kind::Bound(_, Some(inner)) | Kind::Field(inner, _) | Kind::Element(inner, _) => pure(inner), - Kind::Tuple(items) | Kind::List(items) | Kind::Record(_, items) | Kind::Variant(_, _, items) => items.iter().all(pure), + Kind::Some(inner) | Kind::Bound(_, Some(inner)) | Kind::Field(inner, _) | Kind::Element(inner, _) => { + pure(inner) + } + Kind::Tuple(items) | Kind::List(items) | Kind::Record(_, items) | Kind::Variant(_, _, items) => { + items.iter().all(pure) + } Kind::Binary(_, a, b) => pure(a) && pure(b), Kind::Format(pieces) => pieces.iter().all(|p| match p { Piece::Text(_) => true, @@ -1666,7 +1676,9 @@ fn spelled(expr: &syn::Expr) -> bool { syn::Expr::Group(g) => spelled(&g.expr), syn::Expr::Reference(r) => spelled(&r.expr), syn::Expr::Unary(u) => spelled(&u.expr), - syn::Expr::Index(i) => spelled(&i.expr) && matches!(&*i.index, syn::Expr::Range(r) if r.start.is_none() && r.end.is_none()), + syn::Expr::Index(i) => { + spelled(&i.expr) && matches!(&*i.index, syn::Expr::Range(r) if r.start.is_none() && r.end.is_none()) + } syn::Expr::Array(a) => all(a.elems.iter()), syn::Expr::Tuple(t) => all(t.elems.iter()), syn::Expr::Struct(s) => s.rest.is_none() && all(s.fields.iter().map(|f| &f.expr)), @@ -1676,7 +1688,9 @@ fn spelled(expr: &syn::Expr) -> bool { if p.path.segments.last().is_some_and(|s| s.ident.to_string().starts_with(char::is_uppercase))); constructor && all(c.args.iter()) } - syn::Expr::MethodCall(m) => CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() && spelled(&m.receiver), + syn::Expr::MethodCall(m) => { + CONVERSIONS.contains(&m.method.to_string().as_str()) && m.args.is_empty() && spelled(&m.receiver) + } _ => false, } } @@ -1705,12 +1719,20 @@ fn sum(l: Num, r: Num) -> Option { /// `n as` an integer of `bits` bits: its two's complement truncated to them, then read as /// signed or unsigned. fn truncated(n: Num, bits: u32, signed: bool) -> Num { - let raw = if n.negative { n.magnitude.wrapping_neg() } else { n.magnitude }; + let raw = if n.negative { + n.magnitude.wrapping_neg() + } else { + n.magnitude + }; let raw = if bits == 128 { raw } else { raw & ((1u128 << bits) - 1) }; match signed && raw >> (bits - 1) & 1 == 1 { true => Num { negative: true, - magnitude: if bits == 128 { raw.wrapping_neg() } else { (1u128 << bits) - raw }, + magnitude: if bits == 128 { + raw.wrapping_neg() + } else { + (1u128 << bits) - raw + }, }, false => Num { negative: false, @@ -1934,11 +1956,14 @@ fn folds_like_rust() { [$((stringify!($e), $e as i128)),*] }; } - #[allow(clippy::identity_op, clippy::cast_lossless, overflowing_literals)] + #[allow( + clippy::unnecessary_cast, + reason = "each case is the expression the folder reads, casts and all" + )] let cases = cases![ -1isize + 2, 256u16 as u8 as u64, - 300 as u8, + 300i32 as u8, -1i64 as u64, u64::MAX as i64, u128::MAX as i64, From 92568ecb729a47b07ae0d2475ece8acc268d06a0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 05:57:42 -0800 Subject: [PATCH 19/28] fix(ffi): the transcript folds at Rust's widths and types aliases in their own scope Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 29 ++++ ffi/tests/fixtures/transcript/parse.rs | 187 +++++++++++++++++-------- 2 files changed, 157 insertions(+), 59 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index b24ee456d..032986f2d 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -3967,3 +3967,32 @@ fn profiled() { "{stderr}" ); } + +/// A loop's element is typed among the locals in scope at the loop, not those its body +/// binds over them, as Rust evaluates it before the body runs. +#[test] +fn transcript_loop_scope() { + let source = scratch().join("api").join("loop-scope.rs"); + std::fs::write( + &source, + "fn main() { let x = 1u8; for n in [x] { let x = 2u8; println!(\"{n} {x}\"); } }", + ) + .unwrap(); + let t = transcript::Transcript::load(&api().out.join("api.json"), &source); + let Some(transcript::Step::Print(pieces)) = t.steps.last() else { + panic!("the loop's body prints last") + }; + let names: Vec<&str> = (pieces.iter()) + .filter_map(|p| match p { + transcript::Piece::Value( + transcript::Expr { + kind: transcript::Kind::Var(name), + .. + }, + _, + ) => Some(name.as_str()), + _ => None, + }) + .collect(); + assert_eq!(names, ["x", "x_2"]); +} diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 71536add7..349024ee1 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -26,8 +26,16 @@ pub(super) fn main(t: &Transcript, source: &str) -> (Vec, BTreeMap scope.import(&u.tree, &mut Vec::new()), syn::Item::Struct(s) if matches!(s.fields, syn::Fields::Unit) => scope.units.push(s.ident.to_string()), - syn::Item::Static(s) => scope.vars.push(Var::Alias(s.ident.to_string(), (*s.expr).clone())), - syn::Item::Const(c) => scope.vars.push(Var::Alias(c.ident.to_string(), (*c.expr).clone())), + syn::Item::Static(s) => { + scope + .vars + .push(Var::Alias(s.ident.to_string(), (*s.expr).clone(), scope.vars.len())) + } + syn::Item::Const(c) => { + scope + .vars + .push(Var::Alias(c.ident.to_string(), (*c.expr).clone(), scope.vars.len())) + } _ => {} } } @@ -56,10 +64,11 @@ fn fail(node: &dyn Spanned, message: impl std::fmt::Display) -> ! { panic!("{}: {message}", at(node.span())) } -/// A local in scope: its unique name and type, or a loop's literal, typed at each use. +/// A local in scope: its unique name and type, or a loop's literal, typed at each use +/// among the locals in scope where it was bound, the first `depth` of the scope's. enum Var { Typed(String, String, Type), - Alias(String, syn::Expr), + Alias(String, syn::Expr, usize), } struct Scope<'t> { @@ -128,9 +137,17 @@ impl Scope<'_> { steps } + /// `f` run among the first `depth` locals alone, as an alias bound there sees them. + fn at(&mut self, depth: usize, f: impl FnOnce(&mut Self) -> R) -> R { + let hidden = self.vars.split_off(depth); + let r = f(self); + self.vars.extend(hidden); + r + } + fn lookup(&self, name: &str) -> Option<&Var> { self.vars.iter().rev().find(|v| match v { - Var::Typed(n, ..) | Var::Alias(n, _) => n == name, + Var::Typed(n, ..) | Var::Alias(n, ..) => n == name, }) } @@ -180,7 +197,8 @@ impl Scope<'_> { "a for loop over an element other than a literal, a local, or a value built of them", ) } - self.vars.push(Var::Alias(name.ident.to_string(), item.clone())); + self.vars + .push(Var::Alias(name.ident.to_string(), item.clone(), self.vars.len())); let body = self.block(&f.body.stmts); self.vars.pop(); steps.extend(body); @@ -527,9 +545,9 @@ impl Scope<'_> { if let Some(name) = p.path.get_ident().map(|i| i.to_string()) { match self.lookup(&name) { Some(Var::Typed(_, unique, ty)) => return Expr::new(Kind::Var(unique.clone()), ty.clone()), - Some(Var::Alias(_, expr)) => { - let expr = expr.clone(); - return self.infer(&expr); + Some(Var::Alias(_, expr, depth)) => { + let (expr, depth) = (expr.clone(), *depth); + return self.at(depth, |s| s.infer(&expr)); } None => {} } @@ -601,9 +619,9 @@ impl Scope<'_> { } syn::Expr::Path(p) if p.path.get_ident().is_some() => { let name = p.path.get_ident().unwrap().to_string(); - if let Some(Var::Alias(_, alias)) = self.lookup(&name) { - let alias = alias.clone(); - return self.check(&alias, ty); + if let Some(Var::Alias(_, alias, depth)) = self.lookup(&name) { + let (alias, depth) = (alias.clone(), *depth); + return self.at(depth, |s| s.check(&alias, ty)); } if self.lookup(&name).is_none() && self.units.contains(&name) { return Expr::new(Kind::Local(name, Vec::new()), ty.clone()); @@ -760,7 +778,13 @@ impl Scope<'_> { match ty { Type::Int(_) | Type::U128 | Type::NonZero(_) => match expr { syn::Expr::Lit(_) => None, - expr => const_int(expr).map(Kind::Int), + expr => { + let width = match ty { + Type::Int(int) | Type::NonZero(int) => (int.bits(), int.signed()), + _ => (128, false), + }; + const_int(expr, Some(width)).map(Kind::Int) + } }, Type::F32 | Type::F64 => const_float(expr).map(Kind::Float), Type::Char if path_is(expr, "char::MAX") => Some(Kind::Char(char::MAX)), @@ -893,7 +917,11 @@ impl Scope<'_> { let depth = self.vars.len(); for (p, value) in pat.elems.iter().zip(&values.elems) { let syn::Pat::Ident(name) = p else { fail(p, "a name") }; - self.vars.push(Var::Alias(name.ident.to_string(), value.clone())); + // Spelled again at each use in the body, as a loop's element is. + if !spelled(value) { + fail(value, "an item other than a literal, a local, or a value built of them") + } + self.vars.push(Var::Alias(name.ident.to_string(), value.clone(), depth)); } let value = self.check(&closure.body, item); self.vars.truncate(depth); @@ -1154,7 +1182,7 @@ impl Scope<'_> { syn::Expr::Paren(p) => return self.fits_expr(&p.expr, ty), syn::Expr::Path(p) => match p.path.get_ident().and_then(|i| self.lookup(&i.to_string())) { Some(Var::Typed(_, _, have)) => return fits(have, ty), - Some(Var::Alias(_, expr)) => return self.fits_expr(&expr.clone(), ty), + Some(Var::Alias(_, expr, _)) => return self.fits_expr(&expr.clone(), ty), None => None, }, syn::Expr::Struct(s) => self.type_of_path(&s.path), @@ -1631,8 +1659,10 @@ fn literalish(expr: &syn::Expr) -> bool { } } -/// Whether evaluating `e` has no effect a script could see, so a writer may evaluate it -/// once per use, or not at all: no call of the API's or a hook's, and no closure. +/// Whether evaluating `e` can neither fail nor have an effect a script could see, so a +/// writer may evaluate it once per use, or not at all: no call of the API's or a hook's, no +/// arithmetic, which may overflow or divide by zero, and no formatting, which may call a +/// type's own `Display`. fn pure(e: &Expr) -> bool { match &e.kind { Kind::Unit @@ -1655,11 +1685,6 @@ fn pure(e: &Expr) -> bool { Kind::Tuple(items) | Kind::List(items) | Kind::Record(_, items) | Kind::Variant(_, _, items) => { items.iter().all(pure) } - Kind::Binary(_, a, b) => pure(a) && pure(b), - Kind::Format(pieces) => pieces.iter().all(|p| match p { - Piece::Text(_) => true, - Piece::Value(e, _) => pure(e), - }), _ => false, } } @@ -1716,14 +1741,19 @@ fn sum(l: Num, r: Num) -> Option { }) } -/// `n as` an integer of `bits` bits: its two's complement truncated to them, then read as -/// signed or unsigned. -fn truncated(n: Num, bits: u32, signed: bool) -> Num { - let raw = if n.negative { +/// `n`'s two's complement in 128 bits. +fn raw(n: Num) -> u128 { + if n.negative { n.magnitude.wrapping_neg() } else { n.magnitude - }; + } +} + +/// `n as` an integer of `bits` bits: its two's complement truncated to them, then read as +/// signed or unsigned. +fn truncated(n: Num, bits: u32, signed: bool) -> Num { + let raw = raw(n); let raw = if bits == 128 { raw } else { raw & ((1u128 << bits) - 1) }; match signed && raw >> (bits - 1) & 1 == 1 { true => Num { @@ -1757,11 +1787,43 @@ fn int_named(name: &str) -> Option { }) } +/// An integer type's width in bits, and whether it is signed. +type Width = (u32, bool); + +/// The width of the integer type `expr`'s own spelling fixes: a literal's suffix, a cast's +/// type, a constant's type, or an operand's. +fn typed_width(expr: &syn::Expr) -> Option { + let named = |name: &str| match name { + "u128" => Some((128, false)), + name => int_named(name).map(|int| (int.bits(), int.signed())), + }; + match expr { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(i), .. + }) => named(i.suffix()), + syn::Expr::Paren(p) => typed_width(&p.expr), + syn::Expr::Unary(u) => typed_width(&u.expr), + syn::Expr::Cast(c) => match &*c.ty { + syn::Type::Path(ty) => named(&ty.path.get_ident()?.to_string()), + _ => None, + }, + syn::Expr::Binary(b) if matches!(b.op, syn::BinOp::Shl(_)) => typed_width(&b.left), + syn::Expr::Binary(b) => typed_width(&b.left).or_else(|| typed_width(&b.right)), + syn::Expr::Path(p) => match &p.path.segments.iter().map(|s| s.ident.to_string()).collect::>()[..] { + [ty, _] => named(ty), + _ => None, + }, + _ => None, + } +} + /// An integer spelled by literals, constants such as `u64::MAX`, shifts, sums, -/// differences, and casts, or `NonZero::new(..).unwrap()` of one, folded as Rust folds it: -/// signs kept, and each cast truncating to its type's width. -fn const_int(expr: &syn::Expr) -> Option { +/// differences, and casts, or `NonZero::new(..).unwrap()` of one, folded as Rust folds it +/// at `width`, the type its context gives it where its spelling does not: signs kept, each +/// shift dropping the bits past its type's width, and each cast truncating to its own. +fn const_int(expr: &syn::Expr, width: Option) -> Option { let num = |v: i128| Some(Num::new(v)); + let width = typed_width(expr).or(width); match expr { syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. @@ -1769,34 +1831,35 @@ fn const_int(expr: &syn::Expr) -> Option { negative: false, magnitude: i.base10_parse().ok()?, }), - syn::Expr::Paren(p) => const_int(&p.expr), + syn::Expr::Paren(p) => const_int(&p.expr, width), syn::Expr::Cast(c) => { - let n = const_int(&c.expr)?; - let syn::Type::Path(ty) = &*c.ty else { return None }; - match ty.path.get_ident()?.to_string().as_str() { - "u128" => Some(truncated(n, 128, false)), - name => { - let int = int_named(name)?; - Some(truncated(n, int.bits(), int.signed())) - } - } + // What is cast has its own type, `i32` where nothing spells one. + let n = const_int(&c.expr, Some(typed_width(&c.expr).unwrap_or((32, true))))?; + let (bits, signed) = width?; + Some(truncated(n, bits, signed)) } - syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => Some(negated(const_int(&u.expr)?)), - syn::Expr::Binary(b) => { - let (l, r) = (const_int(&b.left)?, const_int(&b.right)?); - match b.op { - syn::BinOp::Shl(_) => { - let by = u32::try_from(r.magnitude).ok().filter(|by| !r.negative && *by < 128)?; - let magnitude = l.magnitude << by; - (magnitude >> by == l.magnitude).then_some(Num { magnitude, ..l }) - } - syn::BinOp::Add(_) => sum(l, r), - syn::BinOp::Sub(_) => sum(l, negated(r)), - _ => None, + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => Some(negated(const_int(&u.expr, width)?)), + syn::Expr::Binary(b) => match b.op { + syn::BinOp::Shl(_) => { + let (bits, signed) = width?; + let l = const_int(&b.left, width)?; + let r = const_int(&b.right, typed_width(&b.right))?; + let by = u32::try_from(r.magnitude).ok().filter(|by| !r.negative && *by < bits)?; + Some(truncated( + Num { + negative: false, + magnitude: raw(l) << by, + }, + bits, + signed, + )) } - } + syn::BinOp::Add(_) => sum(const_int(&b.left, width)?, const_int(&b.right, width)?), + syn::BinOp::Sub(_) => sum(const_int(&b.left, width)?, negated(const_int(&b.right, width)?)), + _ => None, + }, syn::Expr::MethodCall(m) if m.method == "unwrap" => match &*m.receiver { - syn::Expr::Call(c) if path_is(&c.func, "NonZero::new") => const_int(&c.args[0]), + syn::Expr::Call(c) if path_is(&c.func, "NonZero::new") => const_int(&c.args[0], width), _ => None, }, syn::Expr::Path(p) => { @@ -1840,7 +1903,9 @@ fn const_float(expr: &syn::Expr) -> Option { }) => i.base10_parse().ok(), syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => const_float(&u.expr).map(|f| -f), syn::Expr::Path(p) if p.path.segments.last()?.ident == "NAN" => Some(f64::NAN), - syn::Expr::Call(c) if path_is(&c.func, "f64::from_bits") => Some(f64::from_bits(const_int(&c.args[0])?.bits())), + syn::Expr::Call(c) if path_is(&c.func, "f64::from_bits") => { + Some(f64::from_bits(const_int(&c.args[0], Some((64, false)))?.bits())) + } _ => None, } } @@ -1854,7 +1919,7 @@ fn const_duration(expr: &syn::Expr) -> Option<(u64, u32)> { _ => None, }, syn::Expr::Call(c) => { - let v = const_int(c.args.first()?)?.magnitude as u64; + let v = const_int(c.args.first()?, Some((64, false)))?.magnitude as u64; let syn::Expr::Path(p) = &*c.func else { return None }; match p.path.segments.last()?.ident.to_string().as_str() { "from_secs" => Some((v, 0)), @@ -1877,7 +1942,7 @@ enum Net { fn const_net(expr: &syn::Expr) -> Option { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6}; - let int = |e: &syn::Expr| const_int(e).map(|n| n.magnitude); + let int = |e: &syn::Expr| const_int(e, None).map(|n| n.magnitude); match expr { syn::Expr::Paren(p) => const_net(&p.expr), syn::Expr::MethodCall(m) if m.method == "into" => const_net(&m.receiver), @@ -1971,12 +2036,16 @@ fn folds_like_rust() { -5 - 3, 2 - 7, (1u128 << 127) as i8, - (1i128 << 64) + 1, + (1u128 << 64) + 1, + 128u8 << 1, + (128u8 << 1) as u64, + 1i8 << 7, + (3u16 << 15) as i64, -(1i64 << 62) as u32, u32::MAX as i16 as u64, ]; for (text, want) in cases { let expr: syn::Expr = syn::parse_str(text).unwrap(); - assert_eq!(const_int(&expr), Some(Num::new(want)), "{text}"); + assert_eq!(const_int(&expr, None), Some(Num::new(want)), "{text}"); } } From d97570b9629002c1fd5bd979ceecda39fa3aa897 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 06:04:23 -0800 Subject: [PATCH 20/28] fix(ffi): aliases resolve in their own scope everywhere, and a map_or default holds no local Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 13 +++++- ffi/tests/fixtures/transcript/parse.rs | 56 +++++++++++++++++++++----- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 032986f2d..be24bd812 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -3972,13 +3972,14 @@ fn profiled() { /// binds over them, as Rust evaluates it before the body runs. #[test] fn transcript_loop_scope() { + let lock = api().out.join("api.json"); let source = scratch().join("api").join("loop-scope.rs"); std::fs::write( &source, "fn main() { let x = 1u8; for n in [x] { let x = 2u8; println!(\"{n} {x}\"); } }", ) .unwrap(); - let t = transcript::Transcript::load(&api().out.join("api.json"), &source); + let t = transcript::Transcript::load(&lock, &source); let Some(transcript::Step::Print(pieces)) = t.steps.last() else { panic!("the loop's body prints last") }; @@ -3995,4 +3996,14 @@ fn transcript_loop_scope() { }) .collect(); assert_eq!(names, ["x", "x_2"]); + + // An element naming the loop's own binding, and a constant naming a later one, resolve + // as Rust resolves them when an overload is picked. + std::fs::write( + &source, + "const A: u64 = B; const B: u64 = 1; \ + fn main() { let x = 1u64; for x in [x] { println!(\"{}\", api::same_u64(x)); } println!(\"{}\", api::same_u64(A)); }", + ) + .unwrap(); + transcript::Transcript::load(&lock, &source); } diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 349024ee1..ee2604d95 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -39,6 +39,13 @@ pub(super) fn main(t: &Transcript, source: &str) -> (Vec, BTreeMap {} } } + // A module's items see each other in any order, as Rust's do. + let module = scope.vars.len(); + for var in &mut scope.vars { + if let Var::Alias(_, _, depth) = var { + *depth = module; + } + } for item in &file.items { if let syn::Item::Fn(f) = item { if f.sig.ident == "main" { @@ -1177,14 +1184,26 @@ impl Scope<'_> { /// Whether `expr` may be of type `ty`, judged by what it plainly is without checking it: /// a local's type, a struct literal's, or a suffixed literal's. What it cannot judge fits. fn fits_expr(&self, expr: &syn::Expr, ty: &Type) -> bool { + self.fits_in(expr, ty, self.vars.len()) + } + + /// [`Self::fits_expr`] among the first `depth` locals alone, as an alias bound there + /// sees them. + fn fits_in(&self, expr: &syn::Expr, ty: &Type, depth: usize) -> bool { let guess = match expr { - syn::Expr::Reference(r) => return self.fits_expr(&r.expr, ty), - syn::Expr::Paren(p) => return self.fits_expr(&p.expr, ty), - syn::Expr::Path(p) => match p.path.get_ident().and_then(|i| self.lookup(&i.to_string())) { - Some(Var::Typed(_, _, have)) => return fits(have, ty), - Some(Var::Alias(_, expr, _)) => return self.fits_expr(&expr.clone(), ty), - None => None, - }, + syn::Expr::Reference(r) => return self.fits_in(&r.expr, ty, depth), + syn::Expr::Paren(p) => return self.fits_in(&p.expr, ty, depth), + syn::Expr::Path(p) => { + let name = p.path.get_ident().map(|i| i.to_string()); + let var = (self.vars[..depth].iter().rev()).find(|v| match v { + Var::Typed(n, ..) | Var::Alias(n, ..) => Some(n) == name.as_ref(), + }); + match var { + Some(Var::Typed(_, _, have)) => return fits(have, ty), + Some(Var::Alias(_, expr, depth)) => return self.fits_in(expr, ty, *depth), + None => None, + } + } syn::Expr::Struct(s) => self.type_of_path(&s.path), syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. @@ -1195,7 +1214,7 @@ impl Scope<'_> { lit: syn::Lit::Str(_), .. }) => Some(Type::Str), expr if const_duration(expr).is_some() => Some(Type::Duration), - syn::Expr::MethodCall(m) if m.method == "unwrap" => return self.fits_expr(&m.receiver, ty), + syn::Expr::MethodCall(m) if m.method == "unwrap" => return self.fits_in(&m.receiver, ty, depth), _ => None, }; match (guess, unref(ty).base()) { @@ -1543,9 +1562,10 @@ impl Scope<'_> { }; let none_syn = none; let none = self.infer(none); - // Rust evaluates the default before it looks at the option, which a binding that - // evaluates only the arm taken would skip. - if !pure(&none) { + // Rust evaluates the default before it looks at the option, and drops it unused, + // which a binding that evaluates only the arm taken would skip: so it holds no local, + // whose move and drop a script could see. + if !pure(&none) || reads_local(&none) { fail( none_syn, "a map_or default other than a literal, a local, or a value built of them", @@ -1689,6 +1709,20 @@ fn pure(e: &Expr) -> bool { } } +/// Whether `e` reads a local. +fn reads_local(e: &Expr) -> bool { + match &e.kind { + Kind::Var(_) => true, + Kind::Some(inner) | Kind::Bound(_, Some(inner)) | Kind::Field(inner, _) | Kind::Element(inner, _) => { + reads_local(inner) + } + Kind::Tuple(items) | Kind::List(items) | Kind::Record(_, items) | Kind::Variant(_, _, items) => { + items.iter().any(reads_local) + } + _ => false, + } +} + /// Whether `expr` is spelled of literals, locals, constants, and constructors alone, as /// [`pure`] asks of a typed value, without typing it. fn spelled(expr: &syn::Expr) -> bool { From b58561350122d22bd69712732f1942629012f87a Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 11:43:18 -0800 Subject: [PATCH 21/28] fix(ffi): the transcript refuses what its steps cannot keep, and TypeScript's script reads each value once The parser refuses a bare block, a let in a loop's body, a local named other than lowercase words, a pointer-sized constant past 32 bits, and a value's &mut self method called inside another expression. Unique local names skip every name taken. TypeScript's script keeps a match scrutinee's temporaries to the match's end, binds a destructured place, evaluates a Debug tuple once, reads an option whose None is rt.None by it, converts a block's wide items at a join, builds a block of non-literal items, and names a closure's ignored parameter. Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 45 ++++- ffi/tests/fixtures/transcript/parse.rs | 102 ++++++++-- ffi/tests/fixtures/transcript/typescript.rs | 204 ++++++++++++++++---- 3 files changed, 295 insertions(+), 56 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index be24bd812..c3ce7a08b 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -3976,12 +3976,16 @@ fn transcript_loop_scope() { let source = scratch().join("api").join("loop-scope.rs"); std::fs::write( &source, - "fn main() { let x = 1u8; for n in [x] { let x = 2u8; println!(\"{n} {x}\"); } }", + "fn main() { let x = 1u8; for n in [x] { match api::divide(7, 2) { \ + Ok((x, _)) => println!(\"{n} {x}\"), Err(e) => println!(\"{e}\") } } }", ) .unwrap(); let t = transcript::Transcript::load(&lock, &source); - let Some(transcript::Step::Print(pieces)) = t.steps.last() else { - panic!("the loop's body prints last") + let Some(transcript::Step::Match { ok, .. }) = t.steps.last() else { + panic!("the loop's body matches last") + }; + let Some(transcript::Step::Print(pieces)) = ok.steps.last() else { + panic!("the arm prints") }; let names: Vec<&str> = (pieces.iter()) .filter_map(|p| match p { @@ -3995,7 +3999,7 @@ fn transcript_loop_scope() { _ => None, }) .collect(); - assert_eq!(names, ["x", "x_2"]); + assert_eq!(names, ["x", "x2"]); // An element naming the loop's own binding, and a constant naming a later one, resolve // as Rust resolves them when an overload is picked. @@ -4007,3 +4011,36 @@ fn transcript_loop_scope() { .unwrap(); transcript::Transcript::load(&lock, &source); } + +/// What no binding's script could say as Rust does fails to parse, naming its line. +#[test] +fn transcript_refusals() { + let lock = api().out.join("api.json"); + let source = scratch().join("api").join("refusals.rs"); + for (body, refusal) in [ + ("{ let x = 1u8; println!(\"{x}\"); }", "a block of its own"), + ( + "for n in [1u8] { let x = n; println!(\"{x}\"); }", + "a let in a for loop's body", + ), + ("let api_ = 1u8; println!(\"{api_}\");", "a local named other than"), + ( + "let n: usize = usize::MAX - 1; println!(\"{n}\");", + "a pointer-sized value past 32 bits", + ), + ( + "let mut s = api::Score::of(2); println!(\"{} {}\", s.take(), s.count());", + "a value's &mut self method", + ), + ] { + std::fs::write(&source, format!("fn main() {{ {body} }}")).unwrap(); + let panic = std::panic::catch_unwind(|| transcript::Transcript::load(&lock, &source)) + .err() + .unwrap_or_else(|| panic!("{body} parsed")); + let message = panic.downcast_ref::().unwrap(); + assert!( + message.starts_with("transcript.rs:1:") && message.contains(refusal), + "{body}: {message}" + ); + } +} diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index ee2604d95..012e2afdc 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -1,11 +1,11 @@ //! `transcript.rs` read into steps: each expression typed against the API, bidirectionally, //! so a literal takes the type of the parameter it is passed to. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use syn::spanned::Spanned; -use super::ir::{Access, Collection, Family, Function, Int, Literal, Mutability, Type}; +use super::ir::{Access, Collection, Family, Function, Int, Literal, Mutability, Receiver, Type}; use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; /// The steps of `source`'s `main`, and the parameters' types of each function it defines @@ -19,7 +19,8 @@ pub(super) fn main(t: &Transcript, source: &str) -> (Vec, BTreeMap { params: BTreeMap>, /// What each name a `use` brings in stands for. uses: BTreeMap>, - /// How many locals took each name, so each binding gets its own. - taken: BTreeMap, + /// The names locals took, so each binding gets its own. + taken: BTreeSet, + /// The method call a statement's value is, alone where a value's `&mut self` method may + /// be called: a binding hands back the receiver it changed beside what Rust returns, + /// which only a statement can store back. + whole: Option<*const syn::ExprMethodCall>, } /// Conversions that leave a value as the binding has it. @@ -167,6 +172,7 @@ impl Scope<'_> { if init.diverge.is_some() { fail(local, "a let-else"); } + self.whole = whole(&init.expr); let value = match &local.pat { syn::Pat::Type(typed) => { let ty = self.ty(&typed.ty); @@ -186,8 +192,13 @@ impl Scope<'_> { fn expr_stmt(&mut self, expr: &syn::Expr, steps: &mut Vec) { match expr { syn::Expr::Macro(m) => steps.push(Step::Print(self.print(&m.mac))), - syn::Expr::Block(b) => steps.extend(self.block(&b.block.stmts)), + // Its locals drop as it ends, a scope the steps do not keep. + syn::Expr::Block(b) => fail(b, "a block of its own"), syn::Expr::ForLoop(f) => { + // Each pass's locals drop as it ends, a scope the unrolled steps do not keep. + if let Some(stmt) = f.body.stmts.iter().find(|s| matches!(s, syn::Stmt::Local(_))) { + fail(stmt, "a let in a for loop's body"); + } let syn::Expr::Array(items) = &*f.expr else { fail(&f.expr, "a for loop over anything but an array literal") }; @@ -223,7 +234,10 @@ impl Scope<'_> { }; steps.push(Step::Drop(unique.clone())); } - expr => steps.push(Step::Do(self.infer(expr))), + expr => { + self.whole = whole(expr); + steps.push(Step::Do(self.infer(expr))) + } } } @@ -246,14 +260,18 @@ impl Scope<'_> { Expr::new(Kind::Call(id, Some(Box::new(receiver)), vec![value]), Type::Unit) } - /// A unique name for a local named `name`. + /// A unique name for a local named `name`: itself, or with a number after it, which + /// leaves it of [`local_name`]'s form. fn unique(&mut self, name: &str) -> String { - let n = self.taken.entry(name.to_string()).or_insert(0); - *n += 1; - match *n { - 1 => name.to_string(), - n => format!("{name}_{n}"), - } + let unique = (1..) + .map(|n| match n { + 1 => name.to_string(), + n => format!("{name}{n}"), + }) + .find(|n| !self.taken.contains(n)) + .unwrap(); + self.taken.insert(unique.clone()); + unique } /// A pattern, binding its names to the parts of `ty`. @@ -262,6 +280,12 @@ impl Scope<'_> { syn::Pat::Type(typed) => self.bind(&typed.pat, ty), syn::Pat::Ident(ident) => { let name = ident.ident.to_string(); + if !local_name(&name) { + fail( + ident, + "a local named other than in lowercase words, each joined by one `_`", + ); + } let unique = self.unique(&name); self.vars.push(Var::Typed(name, unique.clone(), ty.clone())); Pat::Name(unique, ty.clone()) @@ -790,7 +814,17 @@ impl Scope<'_> { Type::Int(int) | Type::NonZero(int) => (int.bits(), int.signed()), _ => (128, false), }; - const_int(expr, Some(width)).map(Kind::Int) + let n = const_int(expr, Some(width))?; + if let Type::Int(int @ (Int::Usize | Int::Isize)) | Type::NonZero(int @ (Int::Usize | Int::Isize)) = + ty + && !wasm32_holds(n, *int) + && !["usize::MAX", "isize::MAX", "isize::MIN"] + .iter() + .any(|p| path_is(expr, p)) + { + fail(expr, "a pointer-sized value past 32 bits, which wasm32 folds otherwise"); + } + Some(Kind::Int(n)) } }, Type::F32 | Type::F64 => const_float(expr).map(Kind::Float), @@ -1455,6 +1489,8 @@ impl Scope<'_> { } fn method(&mut self, m: &syn::ExprMethodCall, expected: Option<&Type>) -> Expr { + // Taken before the receiver and arguments, whose closures' statements are their own. + let whole = self.whole == Some(m as *const syn::ExprMethodCall); let name = m.method.to_string(); let args: Vec = m.args.iter().cloned().collect(); match name.as_str() { @@ -1552,6 +1588,13 @@ impl Scope<'_> { let id = self .pick(api, &with_receiver, expected, &turbofish) .unwrap_or_else(|| fail(m, format!("no instance of {name} on {} fits", self.describe(&rty)))); + let f = self.t.function(id); + if f.receiver == Some(Receiver::Mut) && matches!(id.owner, Owner::Record(_)) && !whole { + fail( + m, + "a value's &mut self method called other than as a statement or a let's value", + ); + } self.apply(m, id, Some(receiver), &args) } @@ -1657,6 +1700,35 @@ impl Scope<'_> { } /// Whether `expr` is `()`, an argument the IR drops. +/// The method call `expr` is, if it is one. +fn whole(expr: &syn::Expr) -> Option<*const syn::ExprMethodCall> { + match expr { + syn::Expr::MethodCall(m) => Some(m), + _ => None, + } +} + +/// Whether `name` is lowercase words joined by single `_`s, each beginning with a letter: +/// a form each language's spelling of a local, such as camel case, keeps apart, and +/// no reserved word's escape or script helper has. +fn local_name(name: &str) -> bool { + name.split('_').all(|word| { + word.starts_with(|c: char| c.is_ascii_lowercase()) + && word.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }) +} + +/// Whether a pointer-sized `n` folds alike on wasm32, whose pointer is 32 bits. +fn wasm32_holds(n: Num, int: Int) -> bool { + match int.signed() { + true => match n.negative { + true => n.magnitude <= 1 << 31, + false => n.magnitude < 1 << 31, + }, + false => !n.negative && n.magnitude <= u128::from(u32::MAX), + } +} + fn is_unit(expr: &syn::Expr) -> bool { matches!(expr, syn::Expr::Tuple(t) if t.elems.is_empty()) } diff --git a/ffi/tests/fixtures/transcript/typescript.rs b/ffi/tests/fixtures/transcript/typescript.rs index 1c3a44c75..0679b88b2 100644 --- a/ffi/tests/fixtures/transcript/typescript.rs +++ b/ffi/tests/fixtures/transcript/typescript.rs @@ -57,6 +57,16 @@ export function _option(value: T | undefined, show: (value: T) => string): st return value === undefined ? "None" : `Some(${show(value)})`; } +/** An option whose `None` is `rt.None`, shown as Debug does. */ +export function _optionN(value: T | rt.None, show: (value: T) => string): string { + return value === rt.None ? "None" : `Some(${show(value as T)})`; +} + +/** `show` of `value`, which it reads more than once, evaluated once. */ +export function _with(value: T, show: (value: T) => string): string { + return show(value); +} + export function _bound( b: { readonly tag: "Included"; readonly _0: T } | { readonly tag: "Excluded"; readonly _0: T } | { readonly tag: "Unbounded" }, show: (value: T) => string, @@ -100,10 +110,20 @@ export function _some(value: T | undefined): T { return value; } +/** The value of an option whose `None` is `rt.None`, which must be `Some`. */ +export function _someN(value: T | rt.None): T { + if (value === rt.None) throw new Error("an unwrap of None"); + return value as T; +} + export function _mapOr(value: T | undefined, none: U, some: (value: T) => U): U { return value === undefined ? none : some(value); } +export function _mapOrN(value: T | rt.None, none: U, some: (value: T) => U): U { + return value === rt.None ? none : some(value as T); +} + /** Its elements as a tuple, not an array. */ export function _tuple(...items: T): T { return items; @@ -123,6 +143,15 @@ export function _f64(bits: bigint): number { return _f64s([bits])[0]!; } +/** The bits of `value`, a float the script holds, which a block of them is built from. */ +export function _f64Bits(value: number): bigint { + return new BigUint64Array(new Float64Array([value]).buffer)[0]!; +} + +export function _f32Bits(value: number): number { + return new Uint32Array(new Float32Array([value]).buffer)[0]!; +} + /** The objects a statement made and lent, which Rust drops as the statement ends. */ const _temps: Disposable[] = []; @@ -132,9 +161,15 @@ export function _tmp(value: T): T { return value; } -/** Dispose the statement's temporaries, the last made first, as Rust drops them. */ -export function _free(): void { - for (let value = _temps.pop(); value !== undefined; value = _temps.pop()) value[Symbol.dispose](); +/** How many temporaries are held: a match's arms free only those made after its scrutinee's. */ +export function _held(): number { + return _temps.length; +} + +/** Dispose the statement's temporaries past the first `kept`, the last made first, as Rust + * drops them. */ +export function _free(kept = 0): void { + while (_temps.length > kept) _temps.pop()![Symbol.dispose](); } "#; @@ -149,6 +184,8 @@ pub(crate) fn emit(t: &Transcript) -> String { modules: BTreeSet::new(), vars: BTreeMap::new(), temps: false, + marks: Vec::new(), + places: Vec::new(), }; mutated(&t.steps, t, &mut e.mutated); let body = e.steps(&t.steps); @@ -264,6 +301,12 @@ struct Emitter<'t> { vars: BTreeMap, /// Whether the statement being written made a temporary to dispose as it ends. temps: bool, + /// For each match being written whose scrutinee made temporaries, the local holding how + /// many were held after it, which its arms' statements leave to the match's end. + marks: Vec<(String, bool)>, + /// The names a pattern being written binds as places: each element's fresh name, the + /// local's, and its type. + places: Vec<(String, String, Type)>, } /// JavaScript's reserved words, and what the script itself names, which no local may be. @@ -399,7 +442,14 @@ impl Emitter<'_> { // A closure's statements leave theirs to the statement that called it, whose own // the closure may still lend. if self.temps && self.closures == 0 { - self.line(&mut out, "_free();"); + let free = match self.marks.last_mut() { + Some((mark, used)) => { + *used = true; + format!("_free({mark});") + } + None => "_free();".to_string(), + }; + self.line(&mut out, &free); self.temps = false; } } @@ -524,13 +574,43 @@ impl Emitter<'_> { pat => { let target = self.pat(pat, ty); self.line(out, &format!("let {target} = {v};")); + for (element, name, ty) in std::mem::take(&mut self.places) { + let ty = self.ts(&ty); + self.line( + out, + &format!("let {}: rt.Place<{ty}> = {{ v: {element} }};", ident(&name)), + ); + } } } } + /// A pattern binding a closure's parameters, of which none is a place. + fn param(&mut self, pat: &Pat, ty: &Type) -> String { + let target = match pat { + // Kept in a parameter list, as an unused name. + Pat::Ignore(_) => { + self.fresh += 1; + format!("_{}", self.fresh) + } + pat => self.pat(pat, ty), + }; + if let Some((_, name, _)) = self.places.first() { + panic!("a closure's parameter {name} passed &mut"); + } + target + } + /// A pattern binding a value of `ty`: a `Bounds`'s by its start and end. fn pat(&mut self, pat: &Pat, ty: &Type) -> String { match pat { + // A place, bound once the pattern has its element. + Pat::Name(name, ty) if self.mutated.contains(name) => { + self.vars.insert(name.clone(), ty.clone()); + let element = self.fresh("e"); + self.places.push((element.clone(), name.clone(), ty.clone())); + element + } Pat::Name(name, ty) => { self.vars.insert(name.clone(), ty.clone()); ident(name) @@ -557,15 +637,14 @@ impl Emitter<'_> { fn matched(&mut self, value: &Expr, ok: &Arm, err: &Arm, out: &mut String) { let v = self.expr(value); + // The scrutinee's temporaries live to the match's end, past its arms' statements. + let held = std::mem::take(&mut self.temps); let (test, ok_value, ok_ty, err_value, err_ty) = match &value.ty { Type::Option(inner) => { - if undefinable(inner) { - panic!("a match on an Option of {inner:?}, whose None is rt.None"); - } let o = self.fresh("o"); self.line(out, &format!("const {o} = {v};")); ( - format!("{o} !== undefined"), + format!("{o} !== {}", none(&value.ty)), o, (**inner).clone(), String::new(), @@ -585,6 +664,11 @@ impl Emitter<'_> { } ty => panic!("a match on {ty:?}"), }; + let at = out.len(); + if held { + let mark = self.fresh("m"); + self.marks.push((mark, false)); + } self.line(out, &format!("if ({test}) {{")); self.depth += 1; if let Some(pat) = &ok.pat { @@ -602,6 +686,13 @@ impl Emitter<'_> { out.push_str(&body); self.depth -= 1; self.line(out, "}"); + if held { + if let Some((mark, true)) = self.marks.pop() { + let held = format!("{}const {mark} = _held();\n", self.indent()); + out.insert_str(at, &held); + } + self.temps = true; + } } /// The TypeScript type of a value of `ty`, as a literal of it takes it. @@ -751,12 +842,14 @@ impl Emitter<'_> { Type::Int(_) | Type::NonZero(_) => format!("`${{{v}}}`"), Type::String | Type::Str => format!("_quoted({v})"), Type::Option(inner) => { - if undefinable(inner) { - panic!("Debug of an Option of {inner:?}, whose None is rt.None"); - } + // Typed, as TypeScript infers no `T` of `T | rt.None` apart from the symbol. + let helper = match undefinable(inner) { + true => format!("_optionN<{}>", self.ts(inner)), + false => "_option".to_string(), + }; let x = self.fresh("x"); let show = self.debug(&x, inner); - format!("_option({v}, ({x}) => {show})") + format!("{helper}({v}, ({x}) => {show})") } Type::Vec | Type::Slice | Type::Bytes | Type::Array(_) => format!("_list({v}, (x) => `${{x}}`)"), Type::List(_, item) => { @@ -764,13 +857,15 @@ impl Emitter<'_> { let show = self.debug(&x, item); format!("_list({v}, ({x}) => {show})") } + // Each element read from the tuple, evaluated once. Type::Tuple(elements) => { + let x = self.fresh("x"); let parts: Vec = (elements.iter().enumerate()) - .map(|(i, e)| self.debug(&format!("{v}[{i}]"), e)) + .map(|(i, e)| self.debug(&format!("{x}[{i}]"), e)) .collect(); let parts: Vec = parts.iter().map(|p| format!("${{{p}}}")).collect(); let tail = if parts.len() == 1 { ",)" } else { ")" }; - format!("`({}{tail}`", parts.join(", ")) + format!("_with({v}, ({x}) => `({}{tail}`)", parts.join(", ")) } Type::Bound(int) => { let x = self.fresh("x"); @@ -960,15 +1055,19 @@ impl Emitter<'_> { } Kind::Unwrap(inner) => { let v = self.expr(inner); - match &inner.ty { + match unref(&inner.ty).base() { Type::Result(..) => format!("_ok({v})"), + Type::Option(some) if undefinable(some) => { + let some = (**some).clone(); + format!("_someN<{}>({v})", self.ts(&some)) + } _ => format!("_some({v})"), } } Kind::UnwrapErr(inner) => format!("_err({})", self.expr(inner)), Kind::IsErr(inner) => format!("!{}.ok", self.expr(inner)), - Kind::IsSome(inner) => format!("({} !== undefined)", self.expr(inner)), - Kind::IsNone(inner) => format!("({} === undefined)", self.expr(inner)), + Kind::IsSome(inner) => format!("({} !== {})", self.expr(inner), none(&inner.ty)), + Kind::IsNone(inner) => format!("({} === {})", self.expr(inner), none(&inner.ty)), Kind::Binary(op, a, b) => self.binary(*op, a, b), Kind::Closure(params, steps, value) => { let Type::Closure(closure) = unref(&e.ty).base() else { @@ -991,8 +1090,13 @@ impl Emitter<'_> { panic!("a join over {:?}", items.ty) }; let item = (**item).clone(); - let items = self.expr(items); - let target = self.pat(pat, &item); + let block = block(unref(&items.ty).base()).is_some(); + let mut items = self.expr(items); + // A block's wide items are `bigint`s, which the body takes as the binding's form. + if let (true, Some(wide)) = (block, wide(&item)) { + items = format!("Array.from({items}, (v) => rt.{wide}FromBig(v))"); + } + let target = self.param(pat, &item); self.closures += 1; let body = self.expr(body); self.closures -= 1; @@ -1010,11 +1114,15 @@ impl Emitter<'_> { let inner = (**inner).clone(); let option = self.expr(option); let none = self.expr(none); - let target = self.pat(pat, &inner); + let target = self.param(pat, &inner); self.closures += 1; let some = self.expr(some); self.closures -= 1; - format!("_mapOr({option}, {none}, ({target}) => {some})") + let helper = match undefinable(&inner) { + true => format!("_mapOrN<{}, {}>", self.ts(&inner), self.ts(&e.ty)), + false => "_mapOr".to_string(), + }; + format!("{helper}({option}, {none}, ({target}) => {some})") } Kind::Utf8(inner) => format!("_text({})", self.expr(inner)), Kind::Len(inner) => { @@ -1109,32 +1217,46 @@ impl Emitter<'_> { let parts: Vec = items.iter().map(|e| self.value(e, &item)).collect(); return format!("[{}]", parts.join(", ")); }; - // A block's items: integers past 32 bits as `bigint`s, and floats as their bits. - let each = |f: &dyn Fn(&Kind) -> Option| -> Vec { + // A block's items: integers past 32 bits as `bigint`s, and floats as their bits, a + // literal's spelled, another's read from the value the script holds. + let mut each = |f: &dyn Fn(&Kind) -> Option, convert: &str| -> Vec { (items.iter()) - .map(|e| f(&e.kind).unwrap_or_else(|| panic!("an item of a block of {element:?} other than a literal"))) + .map(|e| match f(&e.kind) { + Some(literal) => literal, + None => format!("{convert}({})", self.value(e, &item)), + }) .collect() }; match element { Type::Int(int @ (Int::U64 | Int::I64)) => { - let parts = each(&|k| match k { - Kind::Int(n) => Some(format!("{n}n")), - _ => None, - }); + let convert = format!("rt.{}ToBig", wide(element).unwrap()); + let parts = each( + &|k| match k { + Kind::Int(n) => Some(format!("{n}n")), + _ => None, + }, + &convert, + ); format!("new {}([{}])", typed_array(&Type::Int(*int)), parts.join(", ")) } Type::F64 => { - let parts = each(&|k| match k { - Kind::Float(f) => Some(format!("{:#x}n", f.to_bits())), - _ => None, - }); + let parts = each( + &|k| match k { + Kind::Float(f) => Some(format!("{:#x}n", f.to_bits())), + _ => None, + }, + "_f64Bits", + ); format!("_f64s([{}])", parts.join(", ")) } Type::F32 => { - let parts = each(&|k| match k { - Kind::Float(f) => Some(format!("{:#x}", (*f as f32).to_bits())), - _ => None, - }); + let parts = each( + &|k| match k { + Kind::Float(f) => Some(format!("{:#x}", (*f as f32).to_bits())), + _ => None, + }, + "_f32Bits", + ); format!("_f32s([{}])", parts.join(", ")) } element => { @@ -1146,7 +1268,7 @@ impl Emitter<'_> { /// An arrow function: its parameters, of `types`, the steps it runs, and what it returns. fn closure(&mut self, params: &[Pat], types: &[Type], steps: &[Step], value: &Expr) -> String { - let params: Vec = params.iter().zip(types).map(|(p, ty)| self.pat(p, ty)).collect(); + let params: Vec = params.iter().zip(types).map(|(p, ty)| self.param(p, ty)).collect(); let params = params.join(", "); self.closures += 1; let arrow = match steps.is_empty() { @@ -1209,6 +1331,14 @@ fn undefinable(ty: &Type) -> bool { matches!(ty.base(), Type::Unit | Type::Option(_)) } +/// The `None` of the option `ty`: `rt.None` where its `Some` may be `undefined`. +fn none(ty: &Type) -> &'static str { + match unref(ty).base() { + Type::Option(inner) if undefinable(inner) => "rt.None", + _ => "undefined", + } +} + /// The typed array holding a block's elements exactly. fn typed_array(elem: &Type) -> &'static str { match elem { From 78bb5b44b1d6d40b3bcbe1093b2a65d53a25ec24 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 11:57:04 -0800 Subject: [PATCH 22/28] fix(ffi): the transcript refuses what C, C++, and wasm32 would evaluate otherwise Round 5's findings: every pointer-sized part of a constant must fit wasm32, a value's &mut self method called by its path is refused inside another expression too, a loop's element may not read a local its body changes, a match's second arm of one variant is refused, and a call may hold at most one argument with an effect. TypeScript binds a closure parameter passed &mut as a place. The emitters share one expression walker. Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 25 +++ ffi/tests/fixtures/transcript/c.rs | 62 +----- ffi/tests/fixtures/transcript/cpp.rs | 62 +----- ffi/tests/fixtures/transcript/dart.rs | 64 +----- ffi/tests/fixtures/transcript/go.rs | 62 +----- ffi/tests/fixtures/transcript/kotlin.rs | 64 +----- ffi/tests/fixtures/transcript/mod.rs | 60 ++++++ ffi/tests/fixtures/transcript/parse.rs | 223 ++++++++++++++++---- ffi/tests/fixtures/transcript/python.rs | 62 +----- ffi/tests/fixtures/transcript/typescript.rs | 114 ++++------ 10 files changed, 319 insertions(+), 479 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index c3ce7a08b..961553653 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4032,6 +4032,31 @@ fn transcript_refusals() { "let mut s = api::Score::of(2); println!(\"{} {}\", s.take(), s.count());", "a value's &mut self method", ), + ( + "let mut s = api::Score::of(2); println!(\"{} {}\", api::Score::take(&mut s), s.count());", + "a value's &mut self method", + ), + ( + "println!(\"{}\", api::same_u64(usize::MAX as u64));", + "a pointer-sized value past 32 bits", + ), + ( + "match api::divide(7, 2) { Ok(_) if true => println!(\"a\"), Ok(_) => println!(\"b\"), Err(_) => println!(\"c\") }", + "an arm other than Ok, Err, Some, or None", + ), + ( + "match api::divide(7, 2) { Ok(_) => println!(\"a\"), Ok(_) => println!(\"b\"), Err(_) => println!(\"c\") }", + "a second Ok arm", + ), + ( + "let mut s = api::Score::of(2); let t = api::Score::of(3); \ + for n in [s, s] { s.add(t); println!(\"{}\", n.count()); }", + "an element reading a local its body changes", + ), + ( + "let t = api::Tally::new(); println!(\"{}\", api::reach(t.bump(), (), t.bump()));", + "more than one argument with an effect", + ), ] { std::fs::write(&source, format!("fn main() {{ {body} }}")).unwrap(); let panic = std::panic::catch_unwind(|| transcript::Transcript::load(&lock, &source)) diff --git a/ffi/tests/fixtures/transcript/c.rs b/ffi/tests/fixtures/transcript/c.rs index 69da8b158..1472549f2 100644 --- a/ffi/tests/fixtures/transcript/c.rs +++ b/ffi/tests/fixtures/transcript/c.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::fmt::Write; use super::ir::{Access, Closure, Family, Int, Mutability, Receiver, Type}; -use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Pat, Piece, Spec, Step, Transcript, unref}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Pat, Piece, Spec, Step, Transcript, each_expr, unref, walk}; const LANGUAGE: &str = "C"; @@ -2124,66 +2124,6 @@ fn vars(e: &Expr, out: &mut Vec) { } } -/// Each expression a step holds, its arms' and closures' steps included. -fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { - match step { - Step::Let(_, e) | Step::Do(e) => f(e), - Step::Print(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - f(e) - } - }), - Step::Drop(_) => {} - Step::Match { value, ok, err } => { - f(value); - ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); - } - } -} - -/// `f` on `expr` and each expression inside it. -fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { - f(expr); - let mut inner = |e: &Expr| walk(e, f); - match &expr.kind { - Kind::Some(e) - | Kind::Field(e, _) - | Kind::Element(e, _) - | Kind::Clone(e) - | Kind::Unwrap(e) - | Kind::UnwrapErr(e) => inner(e), - Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { - es.iter().for_each(inner) - } - Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), - Kind::Binary(_, a, b) => { - inner(a); - inner(b); - } - Kind::Bound(_, Some(e)) => inner(e), - Kind::Closure(_, steps, value) => { - steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); - walk(value, f); - } - Kind::Format(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - walk(e, f) - } - }), - Kind::Join { items, body, .. } => { - walk(items, f); - walk(body, f); - } - Kind::MapOr { option, none, some, .. } => { - walk(option, f); - walk(none, f); - walk(some, f); - } - _ => {} - } -} - /// `ty` as Rust returns it to C: each borrow a clone, as the C ABI returns one. fn owned(ty: &Type) -> Type { match ty { diff --git a/ffi/tests/fixtures/transcript/cpp.rs b/ffi/tests/fixtures/transcript/cpp.rs index 6f7345e63..0c4e7bff5 100644 --- a/ffi/tests/fixtures/transcript/cpp.rs +++ b/ffi/tests/fixtures/transcript/cpp.rs @@ -10,7 +10,7 @@ use std::collections::BTreeSet; use std::fmt::Write; use super::ir::{Access, Family, Int, Mutability, Receiver, Type}; -use super::{BoundKind, Expr, FnId, Kind, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; +use super::{BoundKind, Expr, FnId, Kind, Op, Owner, Pat, Piece, Spec, Step, Transcript, each_expr, unref, walk}; const LANGUAGE: &str = "C++"; @@ -296,66 +296,6 @@ pub(crate) fn emit(t: &Transcript) -> String { format!("{PRELUDE}\nnamespace transcript {{\n\ninline void script() {{\n{body}}}\n\n}} // namespace transcript\n") } -/// Each expression a step holds, its arms' and closures' steps included. -fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { - match step { - Step::Let(_, e) | Step::Do(e) => f(e), - Step::Print(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - f(e) - } - }), - Step::Drop(_) => {} - Step::Match { value, ok, err } => { - f(value); - ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); - } - } -} - -/// `f` on `expr` and each expression inside it. -fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { - f(expr); - let mut inner = |e: &Expr| walk(e, f); - match &expr.kind { - Kind::Some(e) - | Kind::Field(e, _) - | Kind::Element(e, _) - | Kind::Clone(e) - | Kind::Unwrap(e) - | Kind::UnwrapErr(e) => inner(e), - Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { - es.iter().for_each(inner) - } - Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), - Kind::Binary(_, a, b) => { - inner(a); - inner(b); - } - Kind::Bound(_, Some(e)) => inner(e), - Kind::Closure(_, steps, value) => { - steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); - walk(value, f); - } - Kind::Format(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - walk(e, f) - } - }), - Kind::Join { items, body, .. } => { - walk(items, f); - walk(body, f); - } - Kind::MapOr { option, none, some, .. } => { - walk(option, f); - walk(none, f); - walk(some, f); - } - _ => {} - } -} - /// How a local is used where it appears, marked in the output until the last use of each /// is known. #[derive(Clone, Copy, PartialEq, Eq)] diff --git a/ffi/tests/fixtures/transcript/dart.rs b/ffi/tests/fixtures/transcript/dart.rs index 7ad7d3e9f..bcba5d16b 100644 --- a/ffi/tests/fixtures/transcript/dart.rs +++ b/ffi/tests/fixtures/transcript/dart.rs @@ -4,7 +4,9 @@ use std::fmt::Write; use super::ir::{Access, Collection, Int, Mutability, Receiver, Type}; -use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; +use super::{ + Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, each_expr, unref, walk, +}; const LANGUAGE: &str = "Dart"; @@ -167,66 +169,6 @@ fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec) { } } -/// Each expression a step holds, its arms' and closures' steps included. -fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { - match step { - Step::Let(_, e) | Step::Do(e) => f(e), - Step::Print(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - f(e) - } - }), - Step::Drop(_) => {} - Step::Match { value, ok, err } => { - f(value); - ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); - } - } -} - -/// `f` on `expr` and each expression inside it. -fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { - f(expr); - let mut inner = |e: &Expr| walk(e, f); - match &expr.kind { - Kind::Some(e) - | Kind::Field(e, _) - | Kind::Element(e, _) - | Kind::Clone(e) - | Kind::Unwrap(e) - | Kind::UnwrapErr(e) => inner(e), - Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { - es.iter().for_each(inner) - } - Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), - Kind::Binary(_, a, b) => { - inner(a); - inner(b); - } - Kind::Bound(_, Some(e)) => inner(e), - Kind::Closure(_, steps, value) => { - steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); - walk(value, f); - } - Kind::Format(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - walk(e, f) - } - }), - Kind::Join { items, body, .. } => { - walk(items, f); - walk(body, f); - } - Kind::MapOr { option, none, some, .. } => { - walk(option, f); - walk(none, f); - walk(some, f); - } - _ => {} - } -} - struct Emitter<'t> { t: &'t Transcript, depth: usize, diff --git a/ffi/tests/fixtures/transcript/go.rs b/ffi/tests/fixtures/transcript/go.rs index 5f44a0016..cc80fadef 100644 --- a/ffi/tests/fixtures/transcript/go.rs +++ b/ffi/tests/fixtures/transcript/go.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write; use super::ir::{Access, Family, Int, Mutability, Receiver, Type}; -use super::{Arm, BoundKind, Expr, FnId, Kind, Op, Pat, Piece, Spec, Step, Transcript, unref}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Op, Pat, Piece, Spec, Step, Transcript, each_expr, unref, walk}; const LANGUAGE: &str = "Go"; @@ -312,66 +312,6 @@ fn reads(step: &Step, used: &mut BTreeSet, locals: &mut BTreeSet } } -/// Each expression a step holds, its arms' and closures' steps included. -fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { - match step { - Step::Let(_, e) | Step::Do(e) => f(e), - Step::Print(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - f(e) - } - }), - Step::Drop(_) => {} - Step::Match { value, ok, err } => { - f(value); - ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); - } - } -} - -/// `f` on `expr` and each expression inside it. -fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { - f(expr); - let mut inner = |e: &Expr| walk(e, f); - match &expr.kind { - Kind::Some(e) - | Kind::Field(e, _) - | Kind::Element(e, _) - | Kind::Clone(e) - | Kind::Unwrap(e) - | Kind::UnwrapErr(e) => inner(e), - Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { - es.iter().for_each(inner) - } - Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), - Kind::Binary(_, a, b) => { - inner(a); - inner(b); - } - Kind::Bound(_, Some(e)) => inner(e), - Kind::Closure(_, steps, value) => { - steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); - walk(value, f); - } - Kind::Format(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - walk(e, f) - } - }), - Kind::Join { items, body, .. } => { - walk(items, f); - walk(body, f); - } - Kind::MapOr { option, none, some, .. } => { - walk(option, f); - walk(none, f); - walk(some, f); - } - _ => {} - } -} - /// Go's keywords and the predeclared names the script calls, which no local may take. const RESERVED: &[&str] = &[ "break", diff --git a/ffi/tests/fixtures/transcript/kotlin.rs b/ffi/tests/fixtures/transcript/kotlin.rs index dd227ddf2..6766c333d 100644 --- a/ffi/tests/fixtures/transcript/kotlin.rs +++ b/ffi/tests/fixtures/transcript/kotlin.rs @@ -4,7 +4,9 @@ use std::fmt::Write; use super::ir::{Access, Collection, Int, Mutability, Receiver, Type}; -use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; +use super::{ + Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, each_expr, unref, walk, +}; const LANGUAGE: &str = "Kotlin"; @@ -134,66 +136,6 @@ fn written(ty: &Type) -> bool { matches!(ty, Type::Ref(Mutability::Mut, inner) if !matches!(**inner, Type::Object(_) | Type::Reader)) } -/// Each expression a step holds, its arms' and closures' steps included. -fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { - match step { - Step::Let(_, e) | Step::Do(e) => f(e), - Step::Print(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - f(e) - } - }), - Step::Drop(_) => {} - Step::Match { value, ok, err } => { - f(value); - ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); - } - } -} - -/// `f` on `expr` and each expression inside it. -fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { - f(expr); - let mut inner = |e: &Expr| walk(e, f); - match &expr.kind { - Kind::Some(e) - | Kind::Field(e, _) - | Kind::Element(e, _) - | Kind::Clone(e) - | Kind::Unwrap(e) - | Kind::UnwrapErr(e) => inner(e), - Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { - es.iter().for_each(inner) - } - Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), - Kind::Binary(_, a, b) => { - inner(a); - inner(b); - } - Kind::Bound(_, Some(e)) => inner(e), - Kind::Closure(_, steps, value) => { - steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); - walk(value, f); - } - Kind::Format(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - walk(e, f) - } - }), - Kind::Join { items, body, .. } => { - walk(items, f); - walk(body, f); - } - Kind::MapOr { option, none, some, .. } => { - walk(option, f); - walk(none, f); - walk(some, f); - } - _ => {} - } -} - struct Emitter<'t> { t: &'t Transcript, depth: usize, diff --git a/ffi/tests/fixtures/transcript/mod.rs b/ffi/tests/fixtures/transcript/mod.rs index e4182412c..11b8d425e 100644 --- a/ffi/tests/fixtures/transcript/mod.rs +++ b/ffi/tests/fixtures/transcript/mod.rs @@ -401,3 +401,63 @@ pub(crate) fn bound(pat: &Pat, out: &mut Vec<(String, Type)>) { Pat::Ignore(_) => {} } } + +/// Each expression a step holds, its arms' and closures' steps included. +pub(crate) fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { + match step { + Step::Let(_, e) | Step::Do(e) => f(e), + Step::Print(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + f(e) + } + }), + Step::Drop(_) => {} + Step::Match { value, ok, err } => { + f(value); + ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); + } + } +} + +/// `f` on `expr` and each expression inside it. +pub(crate) fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { + f(expr); + let mut inner = |e: &Expr| walk(e, f); + match &expr.kind { + Kind::Some(e) + | Kind::Field(e, _) + | Kind::Element(e, _) + | Kind::Clone(e) + | Kind::Unwrap(e) + | Kind::UnwrapErr(e) => inner(e), + Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), + Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { + es.iter().for_each(inner) + } + Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), + Kind::Binary(_, a, b) => { + inner(a); + inner(b); + } + Kind::Bound(_, Some(e)) => inner(e), + Kind::Closure(_, steps, value) => { + steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); + walk(value, f); + } + Kind::Format(pieces) => pieces.iter().for_each(|p| { + if let Piece::Value(e, _) = p { + walk(e, f) + } + }), + Kind::Join { items, body, .. } => { + walk(items, f); + walk(body, f); + } + Kind::MapOr { option, none, some, .. } => { + walk(option, f); + walk(none, f); + walk(some, f); + } + _ => {} + } +} diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 012e2afdc..e592f8ffd 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -6,7 +6,9 @@ use std::collections::{BTreeMap, BTreeSet}; use syn::spanned::Spanned; use super::ir::{Access, Collection, Family, Function, Int, Literal, Mutability, Receiver, Type}; -use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; +use super::{ + Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, each_expr, unref, walk, +}; /// The steps of `source`'s `main`, and the parameters' types of each function it defines /// that `main` calls. @@ -97,9 +99,15 @@ struct Scope<'t> { /// The method call a statement's value is, alone where a value's `&mut self` method may /// be called: a binding hands back the receiver it changed beside what Rust returns, /// which only a statement can store back. - whole: Option<*const syn::ExprMethodCall>, + whole: Option<*const ()>, } +/// A pointer-sized value wasm32's 32-bit pointer does not hold, which it folds otherwise. +const PAST_WASM32: &str = "a pointer-sized value past 32 bits, which wasm32 folds otherwise"; + +/// A call whose arguments C and C++ may evaluate in another order than Rust's. +const UNORDERED: &str = "a call of more than one argument with an effect, which C and C++ evaluate in no set order"; + /// Conversions that leave a value as the binding has it. const CONVERSIONS: &[&str] = &[ "to_string", @@ -215,10 +223,17 @@ impl Scope<'_> { "a for loop over an element other than a literal, a local, or a value built of them", ) } + let mut read = Vec::new(); + self.locals_read(item, &mut read); self.vars .push(Var::Alias(name.ident.to_string(), item.clone(), self.vars.len())); let body = self.block(&f.body.stmts); self.vars.pop(); + // Rust evaluates the element once, before the body changes what it reads. + let changed = self.changed(&body); + if read.iter().any(|name| changed.contains(name)) { + fail(item, "a for loop over an element reading a local its body changes"); + } steps.extend(body); } } @@ -241,6 +256,62 @@ impl Scope<'_> { } } + /// The unique names of the locals `expr`, an element [`spelled`] of them, reads. + fn locals_read(&mut self, expr: &syn::Expr, out: &mut Vec) { + let parts: Vec<&syn::Expr> = match expr { + syn::Expr::Path(p) => { + match p.path.get_ident().and_then(|i| self.lookup(&i.to_string())) { + Some(Var::Typed(_, unique, _)) => out.push(unique.clone()), + Some(Var::Alias(_, alias, depth)) => { + let (alias, depth) = (alias.clone(), *depth); + self.at(depth, |s| s.locals_read(&alias, out)); + } + None => {} + } + Vec::new() + } + syn::Expr::Paren(p) => vec![&p.expr], + syn::Expr::Group(g) => vec![&g.expr], + syn::Expr::Reference(r) => vec![&r.expr], + syn::Expr::Unary(u) => vec![&u.expr], + syn::Expr::Index(i) => vec![&i.expr], + syn::Expr::MethodCall(m) => vec![&m.receiver], + syn::Expr::Array(a) => a.elems.iter().collect(), + syn::Expr::Tuple(t) => t.elems.iter().collect(), + syn::Expr::Struct(st) => st.fields.iter().map(|f| &f.expr).collect(), + syn::Expr::Call(c) => c.args.iter().collect(), + _ => Vec::new(), + }; + parts.into_iter().for_each(|e| self.locals_read(e, out)); + } + + /// The locals `steps` change in place: each a value's `&mut self` receiver, a setter's, + /// or an argument passed `&mut`. + fn changed(&self, steps: &[Step]) -> Vec { + let mut out = Vec::new(); + for step in steps { + each_expr(step, &mut |e| { + walk(e, &mut |e| { + let Kind::Call(id, receiver, args) = &e.kind else { + return; + }; + let f = self.t.function(*id); + if let Some(Kind::Var(name)) = receiver.as_ref().map(|r| &r.kind) + && (f.receiver == Some(Receiver::Mut) || matches!(f.access, Access::Field { set: true, .. })) + { + out.push(name.clone()); + } + for (arg, param) in args.iter().zip(&f.params) { + if let (Kind::Var(name), Type::Ref(Mutability::Mut, _)) = (&arg.kind, ¶m.ty) { + out.push(name.clone()); + } + } + }) + }); + } + out + } + /// `place.field = value`: the field's setter, called on the place's receiver. fn assign(&mut self, a: &syn::ExprAssign) -> Expr { let syn::Expr::Field(field) = &*a.left else { @@ -544,6 +615,9 @@ impl Scope<'_> { ("None", true) => (&mut err, None), _ => fail(&arm.pat, format!("{variant} in this match")), }; + if slot.is_some() { + fail(&arm.pat, format!("a second {variant} arm")); + } let pat = inner.map(|p| self.bind(p, ty.as_ref().unwrap())); let mut steps = Vec::new(); match &*arm.body { @@ -815,14 +889,14 @@ impl Scope<'_> { _ => (128, false), }; let n = const_int(expr, Some(width))?; - if let Type::Int(int @ (Int::Usize | Int::Isize)) | Type::NonZero(int @ (Int::Usize | Int::Isize)) = - ty - && !wasm32_holds(n, *int) - && !["usize::MAX", "isize::MAX", "isize::MIN"] - .iter() - .any(|p| path_is(expr, p)) - { - fail(expr, "a pointer-sized value past 32 bits, which wasm32 folds otherwise"); + let pointer = match ty { + Type::Int(int @ (Int::Usize | Int::Isize)) | Type::NonZero(int @ (Int::Usize | Int::Isize)) => { + Some(*int) + } + _ => None, + }; + if let Some(part) = past_wasm32(expr, pointer, true) { + fail(part, PAST_WASM32); } Some(Kind::Int(n)) } @@ -979,7 +1053,17 @@ impl Scope<'_> { (syn::Lit::Byte(b), Type::Int(Int::U8)) => Kind::Int(Num::new(b.value().into())), (syn::Lit::Bool(b), Type::Bool) => Kind::Bool(b.value), (syn::Lit::Char(c), Type::Char) => Kind::Char(c.value()), - (syn::Lit::Int(i), Type::Int(_) | Type::U128 | Type::NonZero(_)) => Kind::Int(Num { + (syn::Lit::Int(i), Type::Int(int) | Type::NonZero(int)) => { + let n = Num { + negative: false, + magnitude: i.base10_parse().unwrap_or_else(|e| fail(i, e)), + }; + if matches!(int, Int::Usize | Int::Isize) && !wasm32_holds(n, *int) { + fail(i, PAST_WASM32); + } + Kind::Int(n) + } + (syn::Lit::Int(i), Type::U128) => Kind::Int(Num { negative: false, magnitude: i.base10_parse().unwrap_or_else(|e| fail(i, e)), }), @@ -1416,6 +1500,7 @@ impl Scope<'_> { /// A call of a path: the API's function, a variant, or a local function. fn call(&mut self, call: &syn::ExprCall, expected: Option<&Type>) -> Expr { + let whole = self.whole == Some(node(call)); let syn::Expr::Path(p) = &*call.func else { fail(call, "a call of anything but a path") }; @@ -1429,7 +1514,10 @@ impl Scope<'_> { syn::ReturnType::Default => Type::Unit, syn::ReturnType::Type(_, ty) => self.ty(&ty), }; - let args = args.iter().map(|a| self.infer(a)).collect(); + let args: Vec = args.iter().map(|a| self.infer(a)).collect(); + if args.iter().filter(|a| effect(a)).count() > 1 { + fail(call, UNORDERED); + } return Expr::new(Kind::Local(name, args), ty); } if path_is(&call.func, "String::from_utf8_lossy") { @@ -1462,20 +1550,31 @@ impl Scope<'_> { // A method called by its path, its receiver first. Some(_) => { let receiver = self.infer(&args[0]); - self.apply(call, id, Some(receiver), &args[1..]) + self.apply(call, id, Some(receiver), &args[1..], whole) } - None => self.apply(call, id, None, &args), + None => self.apply(call, id, None, &args, whole), } } /// The call of `id` on `receiver`, with `args` checked against its parameters. - fn apply(&mut self, at: &dyn Spanned, id: FnId, receiver: Option, args: &[syn::Expr]) -> Expr { - let params: Vec = self.t.function(id).params.iter().map(|p| p.ty.clone()).collect(); + /// A call of `id` at `at`, `whole` when it is its statement's value. + fn apply(&mut self, at: &dyn Spanned, id: FnId, receiver: Option, args: &[syn::Expr], whole: bool) -> Expr { + let f = self.t.function(id); + if f.receiver == Some(Receiver::Mut) && matches!(id.owner, Owner::Record(_)) && !whole { + fail( + at, + "a value's &mut self method called other than as a statement or a let's value", + ); + } + let params: Vec = f.params.iter().map(|p| p.ty.clone()).collect(); let args: Vec<&syn::Expr> = args.iter().filter(|a| !is_unit(a)).collect(); if params.len() != args.len() { fail(at, format!("{} takes {} arguments", self.t.key(id), params.len())); } - let args = args.iter().zip(¶ms).map(|(a, ty)| self.check(a, ty)).collect(); + let args: Vec = args.iter().zip(¶ms).map(|(a, ty)| self.check(a, ty)).collect(); + if receiver.iter().chain(&args).filter(|e| effect(e)).count() > 1 { + fail(at, UNORDERED); + } self.apply_checked(id, receiver, args) } @@ -1490,7 +1589,7 @@ impl Scope<'_> { fn method(&mut self, m: &syn::ExprMethodCall, expected: Option<&Type>) -> Expr { // Taken before the receiver and arguments, whose closures' statements are their own. - let whole = self.whole == Some(m as *const syn::ExprMethodCall); + let whole = self.whole == Some(node(m)); let name = m.method.to_string(); let args: Vec = m.args.iter().cloned().collect(); match name.as_str() { @@ -1588,14 +1687,7 @@ impl Scope<'_> { let id = self .pick(api, &with_receiver, expected, &turbofish) .unwrap_or_else(|| fail(m, format!("no instance of {name} on {} fits", self.describe(&rty)))); - let f = self.t.function(id); - if f.receiver == Some(Receiver::Mut) && matches!(id.owner, Owner::Record(_)) && !whole { - fail( - m, - "a value's &mut self method called other than as a statement or a let's value", - ); - } - self.apply(m, id, Some(receiver), &args) + self.apply(m, id, Some(receiver), &args, whole) } /// `option.map_or(none, |v| some)`. @@ -1700,14 +1792,26 @@ impl Scope<'_> { } /// Whether `expr` is `()`, an argument the IR drops. -/// The method call `expr` is, if it is one. -fn whole(expr: &syn::Expr) -> Option<*const syn::ExprMethodCall> { +/// The call `expr` is, if it is one. +fn whole(expr: &syn::Expr) -> Option<*const ()> { match expr { - syn::Expr::MethodCall(m) => Some(m), + syn::Expr::MethodCall(m) => Some(node(m)), + syn::Expr::Call(c) => Some(node(c)), _ => None, } } +/// A syntax node's identity, which [`Scope::whole`] compares. +fn node(n: &T) -> *const () { + (n as *const T).cast() +} + +/// Whether evaluating `e` has an effect a call's other arguments could see, which C and +/// C++ order no way Rust does: a closure built runs nothing. +fn effect(e: &Expr) -> bool { + !pure(e) && !matches!(e.kind, Kind::Closure(..)) +} + /// Whether `name` is lowercase words joined by single `_`s, each beginning with a letter: /// a form each language's spelling of a local, such as camel case, keeps apart, and /// no reserved word's escape or script helper has. @@ -1899,24 +2003,67 @@ type Width = (u32, bool); /// The width of the integer type `expr`'s own spelling fixes: a literal's suffix, a cast's /// type, a constant's type, or an operand's. fn typed_width(expr: &syn::Expr) -> Option { - let named = |name: &str| match name { + match typed(expr)?.as_str() { "u128" => Some((128, false)), name => int_named(name).map(|int| (int.bits(), int.signed())), - }; + } +} + +/// The name of the type `expr`'s own spelling fixes, as [`typed_width`] reads it. +fn typed(expr: &syn::Expr) -> Option { match expr { syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(i), .. - }) => named(i.suffix()), - syn::Expr::Paren(p) => typed_width(&p.expr), - syn::Expr::Unary(u) => typed_width(&u.expr), + }) => Some(i.suffix().to_string()).filter(|s| !s.is_empty()), + syn::Expr::Paren(p) => typed(&p.expr), + syn::Expr::Unary(u) => typed(&u.expr), syn::Expr::Cast(c) => match &*c.ty { - syn::Type::Path(ty) => named(&ty.path.get_ident()?.to_string()), + syn::Type::Path(ty) => Some(ty.path.get_ident()?.to_string()), _ => None, }, - syn::Expr::Binary(b) if matches!(b.op, syn::BinOp::Shl(_)) => typed_width(&b.left), - syn::Expr::Binary(b) => typed_width(&b.left).or_else(|| typed_width(&b.right)), + syn::Expr::Binary(b) if matches!(b.op, syn::BinOp::Shl(_)) => typed(&b.left), + syn::Expr::Binary(b) => typed(&b.left).or_else(|| typed(&b.right)), syn::Expr::Path(p) => match &p.path.segments.iter().map(|s| s.ident.to_string()).collect::>()[..] { - [ty, _] => named(ty), + [ty, _] => Some(ty.clone()), + _ => None, + }, + _ => None, + } +} + +/// The part of the constant `expr` that is pointer-sized, by its own spelling or, as +/// `pointer` gives, its context's, and folds past what wasm32's 32-bit pointer holds. A +/// `whole` `usize::MAX`, `isize::MAX`, or `isize::MIN` is each target's own bound. +fn past_wasm32(expr: &syn::Expr, pointer: Option, whole: bool) -> Option<&syn::Expr> { + let pointer = match typed(expr).as_deref() { + Some("u128") => None, + Some(name) => match int_named(name) { + Some(int) => Some(int).filter(|int| matches!(int, Int::Usize | Int::Isize)), + None => pointer, + }, + None => pointer, + }; + if let Some(int) = pointer + && !(whole + && ["usize::MAX", "isize::MAX", "isize::MIN"] + .iter() + .any(|p| path_is(expr, p))) + && let Some(n) = const_int(expr, Some((int.bits(), int.signed()))) + && !wasm32_holds(n, int) + { + return Some(expr); + } + match expr { + syn::Expr::Paren(p) => past_wasm32(&p.expr, pointer, whole), + syn::Expr::Unary(u) => past_wasm32(&u.expr, pointer, false), + // What is cast has its own type, `i32` where nothing spells one. + syn::Expr::Cast(c) => past_wasm32(&c.expr, None, false), + syn::Expr::Binary(b) if matches!(b.op, syn::BinOp::Shl(_)) => { + past_wasm32(&b.left, pointer, false).or_else(|| past_wasm32(&b.right, None, false)) + } + syn::Expr::Binary(b) => past_wasm32(&b.left, pointer, false).or_else(|| past_wasm32(&b.right, pointer, false)), + syn::Expr::MethodCall(m) if m.method == "unwrap" => match &*m.receiver { + syn::Expr::Call(c) if path_is(&c.func, "NonZero::new") => past_wasm32(&c.args[0], pointer, false), _ => None, }, _ => None, diff --git a/ffi/tests/fixtures/transcript/python.rs b/ffi/tests/fixtures/transcript/python.rs index c83fd08b1..8b50308e0 100644 --- a/ffi/tests/fixtures/transcript/python.rs +++ b/ffi/tests/fixtures/transcript/python.rs @@ -4,7 +4,7 @@ use std::fmt::Write; use super::ir::{Access, Collection, Int, Mutability, Receiver, Type}; -use super::{Arm, BoundKind, Expr, FnId, Kind, Op, Owner, Pat, Piece, Spec, Step, Transcript, unref}; +use super::{Arm, BoundKind, Expr, FnId, Kind, Op, Owner, Pat, Piece, Spec, Step, Transcript, each_expr, unref, walk}; const LANGUAGE: &str = "Python"; @@ -140,66 +140,6 @@ fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec) { } } -/// Each expression a step holds, its arms' and closures' steps included. -fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { - match step { - Step::Let(_, e) | Step::Do(e) => f(e), - Step::Print(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - f(e) - } - }), - Step::Drop(_) => {} - Step::Match { value, ok, err } => { - f(value); - ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); - } - } -} - -/// `f` on `expr` and each expression inside it. -fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { - f(expr); - let mut inner = |e: &Expr| walk(e, f); - match &expr.kind { - Kind::Some(e) - | Kind::Field(e, _) - | Kind::Element(e, _) - | Kind::Clone(e) - | Kind::Unwrap(e) - | Kind::UnwrapErr(e) => inner(e), - Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { - es.iter().for_each(inner) - } - Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), - Kind::Binary(_, a, b) => { - inner(a); - inner(b); - } - Kind::Bound(_, Some(e)) => inner(e), - Kind::Closure(_, steps, value) => { - steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); - walk(value, f); - } - Kind::Format(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - walk(e, f) - } - }), - Kind::Join { items, body, .. } => { - walk(items, f); - walk(body, f); - } - Kind::MapOr { option, none, some, .. } => { - walk(option, f); - walk(none, f); - walk(some, f); - } - _ => {} - } -} - struct Emitter<'t> { t: &'t Transcript, out: String, diff --git a/ffi/tests/fixtures/transcript/typescript.rs b/ffi/tests/fixtures/transcript/typescript.rs index 0679b88b2..ceb4114c5 100644 --- a/ffi/tests/fixtures/transcript/typescript.rs +++ b/ffi/tests/fixtures/transcript/typescript.rs @@ -5,7 +5,9 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write; use super::ir::{Access, Collection, Family, Int, Mutability, Receiver, Type}; -use super::{Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, bound, unref}; +use super::{ + Arm, BoundKind, Expr, FnId, Kind, Num, Op, Owner, Pat, Piece, Spec, Step, Transcript, bound, each_expr, unref, walk, +}; const LANGUAGE: &str = "TypeScript"; @@ -227,66 +229,6 @@ fn mutated(steps: &[Step], t: &Transcript, out: &mut Vec) { } } -/// Each expression a step holds, its arms' and closures' steps included. -fn each_expr(step: &Step, f: &mut dyn FnMut(&Expr)) { - match step { - Step::Let(_, e) | Step::Do(e) => f(e), - Step::Print(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - f(e) - } - }), - Step::Drop(_) => {} - Step::Match { value, ok, err } => { - f(value); - ok.steps.iter().chain(&err.steps).for_each(|s| each_expr(s, f)); - } - } -} - -/// `f` on `expr` and each expression inside it. -fn walk(expr: &Expr, f: &mut dyn FnMut(&Expr)) { - f(expr); - let mut inner = |e: &Expr| walk(e, f); - match &expr.kind { - Kind::Some(e) - | Kind::Field(e, _) - | Kind::Element(e, _) - | Kind::Clone(e) - | Kind::Unwrap(e) - | Kind::UnwrapErr(e) => inner(e), - Kind::IsSome(e) | Kind::IsNone(e) | Kind::IsErr(e) | Kind::Utf8(e) | Kind::Len(e) => inner(e), - Kind::Tuple(es) | Kind::List(es) | Kind::Record(_, es) | Kind::Variant(_, _, es) | Kind::Local(_, es) => { - es.iter().for_each(inner) - } - Kind::Call(_, r, args) => r.iter().map(|b| &**b).chain(args).for_each(inner), - Kind::Binary(_, a, b) => { - inner(a); - inner(b); - } - Kind::Bound(_, Some(e)) => inner(e), - Kind::Closure(_, steps, value) => { - steps.iter().for_each(|s| each_expr(s, &mut |e| walk(e, f))); - walk(value, f); - } - Kind::Format(pieces) => pieces.iter().for_each(|p| { - if let Piece::Value(e, _) = p { - walk(e, f) - } - }), - Kind::Join { items, body, .. } => { - walk(items, f); - walk(body, f); - } - Kind::MapOr { option, none, some, .. } => { - walk(option, f); - walk(none, f); - walk(some, f); - } - _ => {} - } -} - struct Emitter<'t> { t: &'t Transcript, depth: usize, @@ -585,20 +527,36 @@ impl Emitter<'_> { } } - /// A pattern binding a closure's parameters, of which none is a place. + /// A pattern binding a closure's parameter: an ignored one kept in the list as an + /// unused name, and a place left in [`Emitter::places`] for [`Emitter::arrow`]. fn param(&mut self, pat: &Pat, ty: &Type) -> String { - let target = match pat { - // Kept in a parameter list, as an unused name. + match pat { Pat::Ignore(_) => { self.fresh += 1; format!("_{}", self.fresh) } pat => self.pat(pat, ty), - }; - if let Some((_, name, _)) = self.places.first() { - panic!("a closure's parameter {name} passed &mut"); } - target + } + + /// The statements binding each place a closure's parameters left, as its body begins. + fn places(&mut self) -> Vec { + std::mem::take(&mut self.places) + .into_iter() + .map(|(element, name, ty)| { + let ty = self.ts(&ty); + format!("let {}: rt.Place<{ty}> = {{ v: {element} }};", ident(&name)) + }) + .collect() + } + + /// An arrow function of `params` returning `body`, binding the places they left first. + fn arrow(&mut self, params: &str, places: Vec, body: String) -> String { + match (places.is_empty(), body.starts_with('{')) { + (true, true) => format!("({params}) => ({body})"), + (true, false) => format!("({params}) => {body}"), + (false, _) => format!("({params}) => {{ {} return {body}; }}", places.join(" ")), + } } /// A pattern binding a value of `ty`: a `Bounds`'s by its start and end. @@ -1097,10 +1055,12 @@ impl Emitter<'_> { items = format!("Array.from({items}, (v) => rt.{wide}FromBig(v))"); } let target = self.param(pat, &item); + let places = self.places(); self.closures += 1; let body = self.expr(body); self.closures -= 1; - format!("Array.from({items}, ({target}) => {body}).join({})", string(sep)) + let arrow = self.arrow(&target, places, body); + format!("Array.from({items}, {arrow}).join({})", string(sep)) } Kind::MapOr { option, @@ -1115,14 +1075,16 @@ impl Emitter<'_> { let option = self.expr(option); let none = self.expr(none); let target = self.param(pat, &inner); + let places = self.places(); self.closures += 1; let some = self.expr(some); self.closures -= 1; + let arrow = self.arrow(&target, places, some); let helper = match undefinable(&inner) { true => format!("_mapOrN<{}, {}>", self.ts(&inner), self.ts(&e.ty)), false => "_mapOr".to_string(), }; - format!("{helper}({option}, {none}, ({target}) => {some})") + format!("{helper}({option}, {none}, {arrow})") } Kind::Utf8(inner) => format!("_text({})", self.expr(inner)), Kind::Len(inner) => { @@ -1270,18 +1232,20 @@ impl Emitter<'_> { fn closure(&mut self, params: &[Pat], types: &[Type], steps: &[Step], value: &Expr) -> String { let params: Vec = params.iter().zip(types).map(|(p, ty)| self.param(p, ty)).collect(); let params = params.join(", "); + let places = self.places(); self.closures += 1; let arrow = match steps.is_empty() { true => { let v = self.expr(value); - match v.starts_with('{') { - true => format!("({params}) => ({v})"), - false => format!("({params}) => {v}"), - } + self.arrow(¶ms, places, v) } false => { self.depth += 1; - let mut body = self.steps(steps); + let mut body = String::new(); + for place in &places { + self.line(&mut body, place); + } + body.push_str(&self.steps(steps)); if !matches!(value.kind, Kind::Unit) { let v = self.expr(value); self.line(&mut body, &format!("return {v};")); From bfecc6a39afc62f483c271d7f6514e33c0f197bd Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 12:03:00 -0800 Subject: [PATCH 23/28] fix(ffi): the transcript refuses a change through a field and an argument read across an effect Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 11 +++- ffi/tests/fixtures/transcript/parse.rs | 81 +++++++++++++++++--------- 2 files changed, 65 insertions(+), 27 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 961553653..89e91a2bc 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4055,7 +4055,16 @@ fn transcript_refusals() { ), ( "let t = api::Tally::new(); println!(\"{}\", api::reach(t.bump(), (), t.bump()));", - "more than one argument with an effect", + "two have an effect", + ), + ( + "let mut n = 0u32; println!(\"{}\", api::reach(n, (), api::each(1, |_| { api::Clash::listed(vec![7], &mut n); })));", + "one changes n, which another reads", + ), + ( + "let mut p = api::Packaged { api: 2 }; \ + for n in [p, p] { api::Clash::listed(vec![7], &mut p.api); println!(\"{}\", n.api); }", + "an element reading a local its body changes", ), ] { std::fs::write(&source, format!("fn main() {{ {body} }}")).unwrap(); diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index e592f8ffd..f088e1dc9 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -106,7 +106,7 @@ struct Scope<'t> { const PAST_WASM32: &str = "a pointer-sized value past 32 bits, which wasm32 folds otherwise"; /// A call whose arguments C and C++ may evaluate in another order than Rust's. -const UNORDERED: &str = "a call of more than one argument with an effect, which C and C++ evaluate in no set order"; +const UNORDERED: &str = "a call whose arguments' order matters, which C and C++ do not keep"; /// Conversions that leave a value as the binding has it. const CONVERSIONS: &[&str] = &[ @@ -286,32 +286,35 @@ impl Scope<'_> { } /// The locals `steps` change in place: each a value's `&mut self` receiver, a setter's, - /// or an argument passed `&mut`. + /// or an argument passed `&mut`, or a field or element of one. fn changed(&self, steps: &[Step]) -> Vec { let mut out = Vec::new(); for step in steps { - each_expr(step, &mut |e| { - walk(e, &mut |e| { - let Kind::Call(id, receiver, args) = &e.kind else { - return; - }; - let f = self.t.function(*id); - if let Some(Kind::Var(name)) = receiver.as_ref().map(|r| &r.kind) - && (f.receiver == Some(Receiver::Mut) || matches!(f.access, Access::Field { set: true, .. })) - { - out.push(name.clone()); - } - for (arg, param) in args.iter().zip(&f.params) { - if let (Kind::Var(name), Type::Ref(Mutability::Mut, _)) = (&arg.kind, ¶m.ty) { - out.push(name.clone()); - } - } - }) - }); + each_expr(step, &mut |e| self.changed_in(e, &mut out)); } out } + /// The locals `expr` changes in place, as [`Scope::changed`] reads them. + fn changed_in(&self, expr: &Expr, out: &mut Vec) { + walk(expr, &mut |e| { + let Kind::Call(id, receiver, args) = &e.kind else { + return; + }; + let f = self.t.function(*id); + if let Some(name) = receiver.as_deref().and_then(root) + && (f.receiver == Some(Receiver::Mut) || matches!(f.access, Access::Field { set: true, .. })) + { + out.push(name.to_string()); + } + for (arg, param) in args.iter().zip(&f.params) { + if let (Some(name), Type::Ref(Mutability::Mut, _)) = (root(arg), ¶m.ty) { + out.push(name.to_string()); + } + } + }) + } + /// `place.field = value`: the field's setter, called on the place's receiver. fn assign(&mut self, a: &syn::ExprAssign) -> Expr { let syn::Expr::Field(field) = &*a.left else { @@ -1515,9 +1518,7 @@ impl Scope<'_> { syn::ReturnType::Type(_, ty) => self.ty(&ty), }; let args: Vec = args.iter().map(|a| self.infer(a)).collect(); - if args.iter().filter(|a| effect(a)).count() > 1 { - fail(call, UNORDERED); - } + self.ordered(call, args.iter().collect()); return Expr::new(Kind::Local(name, args), ty); } if path_is(&call.func, "String::from_utf8_lossy") { @@ -1557,6 +1558,27 @@ impl Scope<'_> { } /// The call of `id` on `receiver`, with `args` checked against its parameters. + /// Refuse a call at `at` whose `args` C or C++ could evaluate to other values than Rust, + /// which evaluates them in order: two with an effect, or one changing a local another reads. + fn ordered(&self, at: &dyn Spanned, args: Vec<&Expr>) { + let effects: Vec = (0..args.len()).filter(|i| effect(args[*i])).collect(); + if effects.len() > 1 { + fail(at, format!("{UNORDERED}: two have an effect")); + } + let Some(&i) = effects.first() else { return }; + let mut changed = Vec::new(); + self.changed_in(args[i], &mut changed); + for arg in args.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, a)| a) { + walk(arg, &mut |e| { + if let Kind::Var(name) = &e.kind + && changed.contains(name) + { + fail(at, format!("{UNORDERED}: one changes {name}, which another reads")); + } + }); + } + } + /// A call of `id` at `at`, `whole` when it is its statement's value. fn apply(&mut self, at: &dyn Spanned, id: FnId, receiver: Option, args: &[syn::Expr], whole: bool) -> Expr { let f = self.t.function(id); @@ -1572,9 +1594,7 @@ impl Scope<'_> { fail(at, format!("{} takes {} arguments", self.t.key(id), params.len())); } let args: Vec = args.iter().zip(¶ms).map(|(a, ty)| self.check(a, ty)).collect(); - if receiver.iter().chain(&args).filter(|e| effect(e)).count() > 1 { - fail(at, UNORDERED); - } + self.ordered(at, receiver.iter().chain(&args).collect()); self.apply_checked(id, receiver, args) } @@ -1801,6 +1821,15 @@ fn whole(expr: &syn::Expr) -> Option<*const ()> { } } +/// The local a place is, or is a field or element of. +fn root(e: &Expr) -> Option<&str> { + match &e.kind { + Kind::Var(name) => Some(name), + Kind::Field(base, _) | Kind::Element(base, _) => root(base), + _ => None, + } +} + /// A syntax node's identity, which [`Scope::whole`] compares. fn node(n: &T) -> *const () { (n as *const T).cast() From 7f271c70c9df48acdd00adaf0ed87a13890daada Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 12:15:02 -0800 Subject: [PATCH 24/28] fix(ffi): the transcript's own functions count in its argument-order and loop checks Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 12 +++++++++++- ffi/tests/fixtures/transcript/parse.rs | 13 ++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 89e91a2bc..d469a622e 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4017,7 +4017,17 @@ fn transcript_loop_scope() { fn transcript_refusals() { let lock = api().out.join("api.json"); let source = scratch().join("api").join("refusals.rs"); + // A function `transcript.rs` defines, as each language's hook. + let hooks = "fn set(n: &mut u32) -> u32 { *n = 1; 1 } fn gap(a: u32, b: u32) -> u32 { b - a }"; for (body, refusal) in [ + ( + "let mut n = 0u32; println!(\"{}\", api::reach(n, (), set(&mut n)));", + "one changes n, which another reads", + ), + ( + "let t = api::Tally::new(); let x: u32 = gap(t.bump(), t.bump()); println!(\"{x}\");", + "two have an effect", + ), ("{ let x = 1u8; println!(\"{x}\"); }", "a block of its own"), ( "for n in [1u8] { let x = n; println!(\"{x}\"); }", @@ -4067,7 +4077,7 @@ fn transcript_refusals() { "an element reading a local its body changes", ), ] { - std::fs::write(&source, format!("fn main() {{ {body} }}")).unwrap(); + std::fs::write(&source, format!("{hooks} fn main() {{ {body} }}")).unwrap(); let panic = std::panic::catch_unwind(|| transcript::Transcript::load(&lock, &source)) .err() .unwrap_or_else(|| panic!("{body} parsed")); diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index f088e1dc9..b6e996913 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -298,6 +298,16 @@ impl Scope<'_> { /// The locals `expr` changes in place, as [`Scope::changed`] reads them. fn changed_in(&self, expr: &Expr, out: &mut Vec) { walk(expr, &mut |e| { + // A function `transcript.rs` defines changes what it takes `&mut`. + if let Kind::Local(name, args) = &e.kind + && let Some(params) = self.params.get(name) + { + for (arg, ty) in args.iter().zip(params) { + if let (Some(name), Type::Ref(Mutability::Mut, _)) = (root(arg), ty) { + out.push(name.to_string()); + } + } + } let Kind::Call(id, receiver, args) = &e.kind else { return; }; @@ -798,7 +808,8 @@ impl Scope<'_> { && self.locals.contains_key(&name.to_string()) { self.local_params(&name.to_string()); - let args = call.args.iter().map(|a| self.infer(a)).collect(); + let args: Vec = call.args.iter().map(|a| self.infer(a)).collect(); + self.ordered(call, args.iter().collect()); return Expr::new(Kind::Local(name.to_string(), args), ty.clone()); } if let Some(bound) = self.bound(call, &base) { From 88c01987d8321c01fb557581b05af6cfd3fdfa2f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 13:20:03 -0800 Subject: [PATCH 25/28] fix(ffi): the transcript refuses a captured drop, a handle in a loop's element, and a third option Also a value's &mut self method on anything but a local; a negated literal checks as one pointer-sized value; TypeScript types a Debug tuple it binds once. Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 16 +++++ ffi/tests/fixtures/transcript/parse.rs | 73 ++++++++++++++++++--- ffi/tests/fixtures/transcript/typescript.rs | 4 +- 3 files changed, 84 insertions(+), 9 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index d469a622e..5867e5dc1 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4028,6 +4028,22 @@ fn transcript_refusals() { "let t = api::Tally::new(); let x: u32 = gap(t.bump(), t.bump()); println!(\"{x}\");", "two have an effect", ), + ( + "let n = 7u32; api::each(1, |_| { drop(n); });", + "a drop in a closure of n", + ), + ( + "let t = api::Token::new(7); for item in [t] { println!(\"inside\"); }", + "which holds a handle", + ), + ( + "let mut pair = (api::Score::of(2), 1u8); let n = pair.0.take(); println!(\"{n}\");", + "a value's &mut self method on anything but a local", + ), + ( + "let x: Option>> = None; println!(\"{}\", x.is_none());", + "an option of an option of an option", + ), ("{ let x = 1u8; println!(\"{x}\"); }", "a block of its own"), ( "for n in [1u8] { let x = n; println!(\"{x}\"); }", diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index b6e996913..25a59578c 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -23,6 +23,7 @@ pub(super) fn main(t: &Transcript, source: &str) -> (Vec, BTreeMap { /// be called: a binding hands back the receiver it changed beside what Rust returns, /// which only a statement can store back. whole: Option<*const ()>, + /// How many of `vars` are from outside the closure being read, 0 outside any. + closure: usize, } /// A pointer-sized value wasm32's 32-bit pointer does not hold, which it folds otherwise. @@ -225,6 +228,24 @@ impl Scope<'_> { } let mut read = Vec::new(); self.locals_read(item, &mut read); + // Moved into the array, it would drop as its pass ends, where the unrolled + // steps keep no scope. + for name in &read { + let ty = self.vars.iter().find_map(|v| match v { + Var::Typed(_, unique, ty) if unique == name => Some(ty), + _ => None, + }); + let mut handles = Vec::new(); + if let Some(ty) = ty { + self.t.api.handles(ty, &mut handles, &mut Vec::new()); + } + if !handles.is_empty() { + fail( + item, + format!("a for loop over an element holding {name}, which holds a handle"), + ); + } + } self.vars .push(Var::Alias(name.ident.to_string(), item.clone(), self.vars.len())); let body = self.block(&f.body.stmts); @@ -247,7 +268,16 @@ impl Scope<'_> { let Some(Var::Typed(_, unique, _)) = self.lookup(&name) else { fail(p, format!("drop of {name}, which is no local")) }; - steps.push(Step::Drop(unique.clone())); + let unique = unique.clone(); + // What a closure moves in, a writer captures only by its expressions. + let at = self + .vars + .iter() + .rposition(|v| matches!(v, Var::Typed(n, ..) if *n == name)); + if at.is_some_and(|at| at < self.closure) { + fail(call, format!("a drop in a closure of {name}, a local from outside it")); + } + steps.push(Step::Drop(unique)); } expr => { self.whole = whole(expr); @@ -470,7 +500,14 @@ impl Scope<'_> { "IpAddr" => Type::IpAddr(Family::Any), "Ipv4Addr" => Type::IpAddr(Family::V4), "Ipv6Addr" => Type::IpAddr(Family::V6), - "Option" => Type::Option(Box::new(arg())), + "Option" => match arg() { + // Each `None` but the innermost is the same value in a binding that + // marks one level apart, as the web's `rt.None` does. + Type::Option(inner) if matches!(*inner, Type::Option(_)) => { + fail(ty, "an option of an option of an option") + } + inner => Type::Option(Box::new(inner)), + }, "Box" => Type::Box(Box::new(arg())), "Vec" => match arg() { Type::Int(Int::U8) => Type::Vec, @@ -1133,6 +1170,7 @@ impl Scope<'_> { fail(c, "a closure of another arity"); } let depth = self.vars.len(); + let outside = std::mem::replace(&mut self.closure, depth); let params = c .inputs .iter() @@ -1140,6 +1178,7 @@ impl Scope<'_> { .map(|(p, ty)| self.bind(p, ty)) .collect(); let (steps, value) = self.body(&c.body, &closure.ok); + self.closure = outside; self.vars.truncate(depth); Expr::new(Kind::Closure(params, steps, Box::new(value)), ty.clone()) } @@ -1593,11 +1632,16 @@ impl Scope<'_> { /// A call of `id` at `at`, `whole` when it is its statement's value. fn apply(&mut self, at: &dyn Spanned, id: FnId, receiver: Option, args: &[syn::Expr], whole: bool) -> Expr { let f = self.t.function(id); - if f.receiver == Some(Receiver::Mut) && matches!(id.owner, Owner::Record(_)) && !whole { - fail( - at, - "a value's &mut self method called other than as a statement or a let's value", - ); + if f.receiver == Some(Receiver::Mut) && matches!(id.owner, Owner::Record(_)) { + if !whole { + fail( + at, + "a value's &mut self method called other than as a statement or a let's value", + ); + } + if !matches!(receiver.as_ref().map(|r| &r.kind), Some(Kind::Var(_))) { + fail(at, "a value's &mut self method on anything but a local"); + } } let params: Vec = f.params.iter().map(|p| p.ty.clone()).collect(); let args: Vec<&syn::Expr> = args.iter().filter(|a| !is_unit(a)).collect(); @@ -1822,7 +1866,6 @@ impl Scope<'_> { } } -/// Whether `expr` is `()`, an argument the IR drops. /// The call `expr` is, if it is one. fn whole(expr: &syn::Expr) -> Option<*const ()> { match expr { @@ -1862,6 +1905,17 @@ fn local_name(name: &str) -> bool { }) } +/// Whether `expr` is an integer literal, parenthesized or not. +fn literal_int(expr: &syn::Expr) -> bool { + match expr { + syn::Expr::Paren(p) => literal_int(&p.expr), + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Int(_), .. + }) => true, + _ => false, + } +} + /// Whether a pointer-sized `n` folds alike on wasm32, whose pointer is 32 bits. fn wasm32_holds(n: Num, int: Int) -> bool { match int.signed() { @@ -1873,6 +1927,7 @@ fn wasm32_holds(n: Num, int: Int) -> bool { } } +/// Whether `expr` is `()`, an argument the IR drops. fn is_unit(expr: &syn::Expr) -> bool { matches!(expr, syn::Expr::Tuple(t) if t.elems.is_empty()) } @@ -2095,6 +2150,8 @@ fn past_wasm32(expr: &syn::Expr, pointer: Option, whole: bool) -> Option<&s } match expr { syn::Expr::Paren(p) => past_wasm32(&p.expr, pointer, whole), + // A negated literal is one value, which the check above took whole. + syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) && literal_int(&u.expr) => None, syn::Expr::Unary(u) => past_wasm32(&u.expr, pointer, false), // What is cast has its own type, `i32` where nothing spells one. syn::Expr::Cast(c) => past_wasm32(&c.expr, None, false), diff --git a/ffi/tests/fixtures/transcript/typescript.rs b/ffi/tests/fixtures/transcript/typescript.rs index ceb4114c5..b5bb74265 100644 --- a/ffi/tests/fixtures/transcript/typescript.rs +++ b/ffi/tests/fixtures/transcript/typescript.rs @@ -823,7 +823,9 @@ impl Emitter<'_> { .collect(); let parts: Vec = parts.iter().map(|p| format!("${{{p}}}")).collect(); let tail = if parts.len() == 1 { ",)" } else { ")" }; - format!("_with({v}, ({x}) => `({}{tail}`)", parts.join(", ")) + // Typed, as TypeScript infers an array literal's elements as one union. + let tuple = self.ts(&ty); + format!("_with<{tuple}>({v}, ({x}) => `({}{tail}`)", parts.join(", ")) } Type::Bound(int) => { let x = self.fresh("x"); From 074085792046c4dce6feac5187bdcdc617bb3b46 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 13:27:34 -0800 Subject: [PATCH 26/28] fix(ffi): the transcript counts option levels through a Box or a reference Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 4 ++++ ffi/tests/fixtures/transcript/parse.rs | 14 +++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 5867e5dc1..abd3a5ccf 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4044,6 +4044,10 @@ fn transcript_refusals() { "let x: Option>> = None; println!(\"{}\", x.is_none());", "an option of an option of an option", ), + ( + "let x: Option>>> = None; println!(\"{}\", x.is_some());", + "an option of an option of an option", + ), ("{ let x = 1u8; println!(\"{x}\"); }", "a block of its own"), ( "for n in [1u8] { let x = n; println!(\"{x}\"); }", diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 25a59578c..67503fd0d 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -500,14 +500,18 @@ impl Scope<'_> { "IpAddr" => Type::IpAddr(Family::Any), "Ipv4Addr" => Type::IpAddr(Family::V4), "Ipv6Addr" => Type::IpAddr(Family::V6), - "Option" => match arg() { + "Option" => { // Each `None` but the innermost is the same value in a binding that - // marks one level apart, as the web's `rt.None` does. - Type::Option(inner) if matches!(*inner, Type::Option(_)) => { + // marks one level apart, as the web's `rt.None` does, which no `Box` + // or reference between them keeps apart. + let inner = arg(); + if let Type::Option(middle) = inner.base() + && matches!(middle.base(), Type::Option(_)) + { fail(ty, "an option of an option of an option") } - inner => Type::Option(Box::new(inner)), - }, + Type::Option(Box::new(inner)) + } "Box" => Type::Box(Box::new(arg())), "Vec" => match arg() { Type::Int(Int::U8) => Type::Vec, From 505132566304c451b90dc023336ad94bdd40794f Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 15:38:10 -0800 Subject: [PATCH 27/28] fix(ffi): each Dart program its own package config, and the transcript refuses a mutable loop binding, signed hex, and an unnamed map_or parameter Co-Authored-By: Claude Opus 5.5 --- ffi/tests/fixtures.rs | 17 +++++++++++++--- ffi/tests/fixtures/transcript/parse.rs | 27 ++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index f61334ccf..5df5d3464 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2367,7 +2367,9 @@ fn dart_kernel( .and_then(Path::parent) .expect("dart is in the SDK's bin") .to_path_buf(); - let config = dir.join("package_config.json"); + // Each program's own, as two compiled in one directory at once would race on one. + let stem = main.file_stem().unwrap().to_string_lossy(); + let config = dir.join(format!("{stem}.package_config.json")); let packages: Vec = std::iter::once((name, package)) .chain(others.iter().copied()) .map(|(name, root)| { @@ -2388,7 +2390,7 @@ fn dart_kernel( "aarch64" => "arm64", _ => "x64", }; - let assets = dir.join("native_assets.yaml"); + let assets = dir.join(format!("{stem}.native_assets.yaml")); step::write( &assets, format!( @@ -2396,7 +2398,7 @@ fn dart_kernel( lib.display().to_string() ), ); - let dill = dir.join(format!("{}.dill", main.file_stem().unwrap().to_string_lossy())); + let dill = dir.join(format!("{stem}.dill")); let mut cmd = Command::new(sdk.join("bin").join(format!("dartaotruntime{EXE_SUFFIX}"))); cmd.arg(sdk.join("bin/snapshots/gen_kernel_aot.dart.snapshot")) .arg("--platform") @@ -4760,6 +4762,15 @@ fn transcript_refusals() { "let x: Option> = Some(None); println!(\"{}\", x.is_none());", "an option of an option of an option or of ()", ), + ( + "for mut n in [7u32] { set(&mut n); println!(\"{n}\"); }", + "a for loop binding a mutable name", + ), + ("let n = 7i32; println!(\"{n:x}\");", "hex of Int(I32)"), + ( + "let x: Option = Some(1); println!(\"{}\", x.map_or(0u32, |_| 7));", + "a map_or closure's parameter other than a name", + ), ("{ let x = 1u8; println!(\"{x}\"); }", "a block of its own"), ( "for n in [1u8] { let x = n; println!(\"{x}\"); }", diff --git a/ffi/tests/fixtures/transcript/parse.rs b/ffi/tests/fixtures/transcript/parse.rs index 91ea465cf..ef717dbc4 100644 --- a/ffi/tests/fixtures/transcript/parse.rs +++ b/ffi/tests/fixtures/transcript/parse.rs @@ -216,6 +216,10 @@ impl Scope<'_> { let syn::Pat::Ident(name) = &*f.pat else { fail(&f.pat, "a for loop binding anything but a name") }; + // Each use is the element spelled again, which no write could change. + if name.mutability.is_some() || name.by_ref.is_some() { + fail(&f.pat, "a for loop binding a mutable name"); + } for item in &items.elems { // Each element is spelled again at each use in the unrolled body, so one // whose evaluation could be seen, such as a call, would run once per use, @@ -605,8 +609,14 @@ impl Scope<'_> { "" => Spec::Display, "?" => Spec::Debug, "x" => Spec::Hex(0), - s if s.starts_with('0') && s.ends_with('x') => Spec::Hex(s[1..s.len() - 1].parse().unwrap()), - s if s.starts_with('0') => Spec::Padded(s[1..].parse().unwrap()), + s if s.starts_with('0') && s.ends_with('x') => Spec::Hex( + s[1..s.len() - 1] + .parse() + .unwrap_or_else(|_| fail(&lit, format!("the format {s}"))), + ), + s if s.starts_with('0') => { + Spec::Padded(s[1..].parse().unwrap_or_else(|_| fail(&lit, format!("the format {s}")))) + } s => fail(&lit, format!("the format {s}")), }; let value = if name.is_empty() { @@ -622,6 +632,16 @@ impl Scope<'_> { }); self.infer(&path) }; + // Hex of a signed integer is its two's complement, which no writer spells. + if let Spec::Hex(_) = spec + && !matches!( + unref(&value.ty).base(), + Type::Int(int) | Type::NonZero(int) if !int.signed() + ) + && !matches!(unref(&value.ty).base(), Type::U128) + { + fail(&lit, format!("hex of {}", self.describe(&value.ty))); + } if !literal.is_empty() { pieces.push(Piece::Text(std::mem::take(&mut literal))); } @@ -1788,6 +1808,9 @@ impl Scope<'_> { let [p] = c.inputs.iter().collect::>()[..] else { fail(c, "a map_or closure of one parameter") }; + if !matches!(p, syn::Pat::Ident(_)) { + fail(p, "a map_or closure's parameter other than a name"); + } let depth = self.vars.len(); let pat = self.bind(p, inner); let ty = none.ty.clone(); From 05c82035ee5b95ed3807dae01423dbcc1c46e155 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 16:58:25 -0800 Subject: [PATCH 28/28] quest: record the maintainer's follow-up answers Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-rules/names.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/quest/m1/ffi-rules/names.md b/quest/m1/ffi-rules/names.md index 8c484f88f..e21a1756a 100644 --- a/quest/m1/ffi-rules/names.md +++ b/quest/m1/ffi-rules/names.md @@ -10,6 +10,8 @@ them from the table and drop their copies of each generator's naming rules. ## Plan +Decided with the maintainer on 2026-11-19, in the pick of [#885](https://github.com/kixel-ai/rust2/pull/885): ✅ kept as recommended (rejected: dropping it). + Found by [#885](https://github.com/kixel-ai/rust2/pull/885), which writes each language's `tests/api.*` script from the transcript. Each of its eight emitters repeats some of its generator's naming rules for what the table leaves out: camel or snake case, reserved-word