diff --git a/pkgs/id/examples/rust-counter/Cargo.lock b/pkgs/id/examples/rust-counter/Cargo.lock new file mode 100644 index 0000000000..d4c1dc4bb6 --- /dev/null +++ b/pkgs/id/examples/rust-counter/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "plaza-sdk" +version = "0.1.0" + +[[package]] +name = "rust-counter" +version = "0.1.0" +dependencies = [ + "plaza-sdk", +] diff --git a/pkgs/id/examples/rust-counter/Cargo.toml b/pkgs/id/examples/rust-counter/Cargo.toml new file mode 100644 index 0000000000..42bcf3621f --- /dev/null +++ b/pkgs/id/examples/rust-counter/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "rust-counter" +version = "0.1.0" +edition = "2021" +description = "Playable Rust Plaza world: the F12.8 (#1065) twin of examples/roc-counter, built on the plaza-sdk crate in ../rust-world." +license = "MIT OR Apache-2.0" + +# Standalone crate: intentionally not a member of the pkgs/id workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +plaza-sdk = { path = "../rust-world" } diff --git a/pkgs/id/examples/rust-counter/README.md b/pkgs/id/examples/rust-counter/README.md new file mode 100644 index 0000000000..d345392435 --- /dev/null +++ b/pkgs/id/examples/rust-counter/README.md @@ -0,0 +1,33 @@ +# Rust counter world + +A tiny pure Rust world program for `id`'s multiplayer service — the +F12.8 (#1065) twin of `../roc-counter`, built on the Rust guest SDK in +`../rust-world`. The host owns the authoritative state; guests send +`inc`, and every participant sees the returned `count=N` presentation. +It demonstrates the SDK's screen helper (the same boxed 20x3 screen +JSON as the Roc program), the `records` export, and snapshot/restore. + +## Build + +Requires the `wasm32-unknown-unknown` Rust target: + +```sh +rustup target add wasm32-unknown-unknown +./build.sh # cargo build --release --target wasm32-unknown-unknown +``` + +`build.sh` refreshes the checked-in `counter.wasm`, which the host's +F12.7 conformance suite (`pkgs/id/src/sandbox.rs`) loads as the +`rust-counter` fixture — no Rust toolchain is needed to run the suite. + +## Run a hosted world + +```sh +id serve --world --world-admin-token "$WORLD_ADMIN" --world-module counter.wasm +``` + +The module has no Wasm imports and exports the full Plaza ABI v1 +surface (see `../roc-world/ABI.md`). The remaining F12.8 scope — the +second SDK (AssemblyScript vs Zig) and the component-model/WIT +direction — stays open on #1065 as Drew-owned decisions; this example +covers the Rust SDK slice only. diff --git a/pkgs/id/examples/rust-counter/build.sh b/pkgs/id/examples/rust-counter/build.sh new file mode 100644 index 0000000000..2fc60fb8ee --- /dev/null +++ b/pkgs/id/examples/rust-counter/build.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Build the Rust counter guest and refresh the checked-in module the +# host conformance suite loads. Requires the wasm32-unknown-unknown +# target (rustup target add wasm32-unknown-unknown). +set -eu +cd "$(dirname "$0")" +cargo build --release --target wasm32-unknown-unknown +cp target/wasm32-unknown-unknown/release/rust_counter.wasm counter.wasm +echo "wrote counter.wasm" diff --git a/pkgs/id/examples/rust-counter/counter.wasm b/pkgs/id/examples/rust-counter/counter.wasm new file mode 100755 index 0000000000..8e61c94402 Binary files /dev/null and b/pkgs/id/examples/rust-counter/counter.wasm differ diff --git a/pkgs/id/examples/rust-counter/src/lib.rs b/pkgs/id/examples/rust-counter/src/lib.rs new file mode 100644 index 0000000000..77b7c309ea --- /dev/null +++ b/pkgs/id/examples/rust-counter/src/lib.rs @@ -0,0 +1,116 @@ +//! Rust counter world — the playable F12.8 example, twin of +//! `examples/roc-counter/main.roc` on the Plaza ABI v1 contract: +//! +//! - `init` ignores the seed; the model is `{ count: i64 }` starting at 0. +//! - `update` increments on a trimmed `inc` event, like the Roc program +//! (events are matched after a text trim, so `" inc "` counts too). +//! - `view` renders the boxed 20x3 screen through the SDK's screen +//! helper; `layout` widens the box to 30 columns at width >= 30. +//! - `records` publishes `{"count":N}`; `wants` is the empty document. +//! - `snapshot` is the decimal count; `restore` parses it back and is +//! total (invalid text restores count 0), so +//! `restore(snapshot(m))` behaves exactly like `m`. + +use plaza_sdk::screen::{Screen, Style}; +use plaza_sdk::{text, World}; + +pub struct Counter { + pub count: i64, +} + +pub struct CounterWorld; + +impl World for CounterWorld { + type Model = Counter; + + fn init(_seed: u64) -> Counter { + Counter { count: 0 } + } + + fn update(model: Counter, _participant: u32, event: &[u8]) -> Counter { + let text_event = String::from_utf8_lossy(event); + if text::trim(&text_event) == "inc" { + Counter { + count: model.count + 1, + } + } else { + model + } + } + + fn view(model: &Counter) -> Vec { + render(model, 20, 3).into_bytes() + } + + fn layout(model: &Counter, width: u64, _height: u64) -> Option> { + let w = if width >= 30 { 30 } else { 20 }; + Some(render(model, w, 3).into_bytes()) + } + + fn records(model: &Counter) -> Option> { + Some(format!("{{\"count\":{}}}", model.count).into_bytes()) + } + + fn wants(_model: &Counter) -> Option> { + Some(b"{}".to_vec()) + } + + fn snapshot(model: &Counter) -> Option> { + Some(model.count.to_string().into_bytes()) + } + + fn restore(snapshot: &[u8]) -> Counter { + let text = String::from_utf8_lossy(snapshot); + Counter { + count: text.trim().parse::().unwrap_or(0), + } + } +} + +fn render(model: &Counter, w: usize, h: usize) -> String { + let mut screen = Screen::new(w, h); + screen.boxed(0, 0, w, h, "counter"); + screen.put_text(2, 1, &format!("count={}", model.count), Style::default()); + screen.render_json() +} + +plaza_sdk::plaza_guest!(CounterWorld); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counter_matches_the_roc_program() { + let m = CounterWorld::init(7); + assert_eq!(m.count, 0); + let m = CounterWorld::update(m, 1, b"inc"); + assert_eq!(m.count, 1); + let m = CounterWorld::update(m, 1, b" inc \n"); + assert_eq!(m.count, 2); + let m = CounterWorld::update(m, 1, b"dec"); + assert_eq!(m.count, 2); + let view = String::from_utf8(CounterWorld::view(&m)).unwrap(); + assert!(view.contains("count=2"), "view: {view}"); + assert_eq!( + CounterWorld::records(&m), + Some(b"{\"count\":2}".to_vec()) + ); + // Snapshot/restore round-trips byte-identically, and restore is + // total on invalid text. + let snap = CounterWorld::snapshot(&m).unwrap(); + assert_eq!(snap, b"2"); + let restored = CounterWorld::restore(&snap); + assert_eq!(CounterWorld::snapshot(&restored).unwrap(), snap); + assert_eq!(CounterWorld::restore(b"junk").count, 0); + } + + #[test] + fn view_is_the_boxed_screen_document() { + let m = Counter { count: 1 }; + assert_eq!( + render(&m, 20, 3), + "{\"kind\":\"screen\",\"version\":1,\"width\":20,\"height\":3,\"rows\":[\"+-counter----------+\",\"| count=1 |\",\"+------------------+\"],\"styles\":[[],[],[]]}" + ); + } +} diff --git a/pkgs/id/examples/rust-world/Cargo.lock b/pkgs/id/examples/rust-world/Cargo.lock new file mode 100644 index 0000000000..856094b5e5 --- /dev/null +++ b/pkgs/id/examples/rust-world/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "plaza-sdk" +version = "0.1.0" diff --git a/pkgs/id/examples/rust-world/Cargo.toml b/pkgs/id/examples/rust-world/Cargo.toml new file mode 100644 index 0000000000..50ecb1005c --- /dev/null +++ b/pkgs/id/examples/rust-world/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "plaza-sdk" +version = "0.1.0" +edition = "2021" +description = "Rust guest SDK for Plaza ABI v1 worlds (F12.8, #1065): screen, json, grid, cap and text helpers equal to the Roc platform libraries, plus the plaza_* export plumbing." +license = "MIT OR Apache-2.0" + +# Standalone crate: intentionally not a member of the pkgs/id workspace, +# like the other example guests. It builds for the host (unit tests) and +# for wasm32-unknown-unknown (the guest module). +[workspace] + +[lib] +crate-type = ["rlib"] diff --git a/pkgs/id/examples/rust-world/README.md b/pkgs/id/examples/rust-world/README.md new file mode 100644 index 0000000000..143e607703 --- /dev/null +++ b/pkgs/id/examples/rust-world/README.md @@ -0,0 +1,29 @@ +# Plaza guest SDK for Rust + +The Rust half of F12.8 (#1065): a guest SDK for `wasm32-unknown-unknown` +with `screen`, `json`, `grid`, `cap` (and `text`) helpers equal to the +Roc platform libraries in `../roc-world`, plus the export plumbing that +turns a pure Rust program into an import-free Plaza ABI v1 world +module (the contract in `../roc-world/ABI.md`). + +A guest is a `cdylib` crate that implements `plaza_sdk::World` +(`init` / `update` / `view`, with optional `layout` / `records` / +`wants` / `snapshot` / `restore`) and invokes `plaza_sdk::plaza_guest!` +once. The macro emits all 14 documented `plaza_*` exports with the +ABI's exact signatures; the model is an opaque pointer the host passes +back, outputs go through the one shared output slot, and host inputs +arrive in `plaza_alloc` memory the host frees with `plaza_free`. + +`../rust-counter` is the playable example built on this SDK — the Rust +twin of `../roc-counter`, with the same events, screen, records, and +snapshot text, and its checked-in module runs in the host's F12.7 +conformance suite (`pkgs/id/src/sandbox.rs`). + +## Component model / WIT + +F12.8 also asks for a Wasm component-model / WIT evaluation. That +decision is **not** taken here: it is a Drew-owned direction for #1065 +(recorded on the issue), and this SDK deliberately targets the landed +ABI v1 module contract so the Rust SDK is usable today. Nothing in the +SDK's helper APIs depends on the raw module boundary, so a future +component-model binding can sit under the same `World` trait. diff --git a/pkgs/id/examples/rust-world/src/cap.rs b/pkgs/id/examples/rust-world/src/cap.rs new file mode 100644 index 0000000000..44c5a7fa15 --- /dev/null +++ b/pkgs/id/examples/rust-world/src/cap.rs @@ -0,0 +1,187 @@ +//! The request side of the capability protocol, mirroring `RocCap.roc`: +//! a session reserves `r0`, `r1`, … ids, records each request's +//! capability, builds the request documents `wants` re-announces after +//! replay, and routes host result events back to the capability that +//! asked. See `examples/roc-world/ABI.md` for the wire protocol. + +use crate::json::{quote, Value}; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CapSession { + next: u64, + pending: Vec<(String, String)>, // (id, cap) +} + +impl CapSession { + pub fn new() -> Self { + Self::default() + } + + /// Rebuild a session from a snapshot's pending list, like + /// `RocCap.from_pending`: ids continue after the highest `r`. + pub fn from_pending(pending: Vec<(String, String)>) -> Self { + let next = pending + .iter() + .filter_map(|(id, _)| id.strip_prefix('r')) + .filter_map(|n| n.parse::().ok()) + .max() + .map(|m| m + 1) + .unwrap_or(0); + CapSession { next, pending } + } + + pub fn pending(&self) -> &[(String, String)] { + &self.pending + } + + /// Reserve the next request id and record its capability, like + /// `RocCap.issue`. Returns the id (`r0`, `r1`, …). + pub fn issue(&mut self, cap: &str) -> String { + let id = format!("r{}", self.next); + self.next += 1; + self.pending.push((id.clone(), cap.to_string())); + id + } + + /// A request document for `wants`: `{"id":..,"cap":..}` plus an + /// `args` object when args JSON is supplied. + pub fn request_doc(&self, id: &str, cap: &str, args_json: Option<&str>) -> String { + match args_json { + Some(args) => format!( + "{{\"id\":{},\"cap\":{},\"args\":{}}}", + quote(id), + quote(cap), + args + ), + None => format!("{{\"id\":{},\"cap\":{}}}", quote(id), quote(cap)), + } + } + + pub fn now_request(&mut self) -> String { + let id = self.issue("time.now"); + self.request_doc(&id, "time.now", None) + } + + pub fn players_request(&mut self) -> String { + let id = self.issue("players.list"); + self.request_doc(&id, "players.list", None) + } + + pub fn world_request(&mut self) -> String { + let id = self.issue("world.info"); + self.request_doc(&id, "world.info", None) + } + + pub fn chat_request(&mut self, text: &str) -> String { + let id = self.issue("chat.say"); + let args = format!("{{\"text\":{}}}", quote(text)); + self.request_doc(&id, "chat.say", Some(&args)) + } + + pub fn history_request(&mut self, count: Option) -> String { + let id = self.issue("chat.history"); + let args = count.map(|c| format!("{{\"count\":{c}}}")); + self.request_doc(&id, "chat.history", args.as_deref()) + } + + pub fn records_request(&mut self, prefix: Option<&str>, after: Option<&str>) -> String { + let id = self.issue("records.read"); + let mut fields = Vec::new(); + if let Some(p) = prefix { + fields.push(format!("\"prefix\":{}", quote(p))); + } + if let Some(a) = after { + fields.push(format!("\"after\":{}", quote(a))); + } + let args = format!("{{{}}}", fields.join(",")); + self.request_doc(&id, "records.read", Some(&args)) + } + + pub fn schedule_at_request(&mut self, schedule_id: &str, at_ms: i64) -> String { + let id = self.issue("schedule.at"); + let args = format!("{{\"id\":{},\"at\":{}}}", quote(schedule_id), at_ms); + self.request_doc(&id, "schedule.at", Some(&args)) + } + + pub fn schedule_cancel_request(&mut self, schedule_id: &str) -> String { + let id = self.issue("schedule.cancel"); + let args = format!("{{\"id\":{}}}", quote(schedule_id)); + self.request_doc(&id, "schedule.cancel", Some(&args)) + } + + /// Route a host result event (`{"cap":"result","id":..,...}`) back + /// to the capability that asked, like `RocCap.answered`. Returns the + /// cap name for a known pending id. + pub fn answered(&self, result: &Value) -> Option { + if result.get("cap").and_then(|c| c.as_str()) != Some("result") { + return None; + } + let id = result.get("id").and_then(|i| i.as_str())?; + self.pending + .iter() + .find(|(pid, _)| pid == id) + .map(|(_, cap)| cap.clone()) + } + + /// Retire a pending request, like `RocCap.done`. + pub fn done(&mut self, id: &str) { + self.pending.retain(|(pid, _)| pid != id); + } + + /// The `wants` document: `{"v":1,"subscribe":[...],"requests":[...]}` + /// with empty parts omitted, as the ABI allows. + pub fn wants_doc(&self, subscribe: &[&str], request_docs: &[String]) -> String { + let mut parts = vec!["\"v\":1".to_string()]; + if !subscribe.is_empty() { + let subs = subscribe + .iter() + .map(|s| quote(s)) + .collect::>() + .join(","); + parts.push(format!("\"subscribe\":[{subs}]")); + } + if !request_docs.is_empty() { + parts.push(format!("\"requests\":[{}]", request_docs.join(","))); + } + format!("{{{}}}", parts.join(",")) + } +} + +/// Rows of a `chat.history` result value: the `lines` array's objects, +/// like `RocCap.history_lines`. +pub fn history_lines(result_value: &Value) -> Vec<&Value> { + result_value + .get("lines") + .and_then(|l| l.as_array()) + .map(|a| a.iter().collect()) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::json::decode; + + #[test] + fn session_issues_routes_and_retires() { + let mut s = CapSession::new(); + let doc = s.now_request(); + assert_eq!(doc, "{\"id\":\"r0\",\"cap\":\"time.now\"}"); + let doc2 = s.chat_request("hi \"there\""); + assert_eq!( + doc2, + "{\"id\":\"r1\",\"cap\":\"chat.say\",\"args\":{\"text\":\"hi \\\"there\\\"\"}}" + ); + let result = decode("{\"cap\":\"result\",\"id\":\"r1\",\"ok\":true,\"value\":{}}").unwrap(); + assert_eq!(s.answered(&result), Some("chat.say".to_string())); + s.done("r1"); + assert_eq!(s.answered(&result), None); + let wants = s.wants_doc(&["players"], &[doc]); + assert_eq!( + wants, + "{\"v\":1,\"subscribe\":[\"players\"],\"requests\":[{\"id\":\"r0\",\"cap\":\"time.now\"}]}" + ); + let mut rebuilt = CapSession::from_pending(s.pending().to_vec()); + assert_eq!(rebuilt.issue("world.info"), "r1"); + } +} diff --git a/pkgs/id/examples/rust-world/src/grid.rs b/pkgs/id/examples/rust-world/src/grid.rs new file mode 100644 index 0000000000..6623c0d45a --- /dev/null +++ b/pkgs/id/examples/rust-world/src/grid.rs @@ -0,0 +1,98 @@ +//! Row-major byte grid mirroring `RocGrid.roc`: bounds-checked and +//! total — a read outside the grid returns a caller-supplied fallback, +//! a write outside it returns the grid unchanged. Never traps. + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Grid { + pub width: usize, + pub height: usize, + cells: Vec, +} + +impl Grid { + pub fn new(width: usize, height: usize, fill: T) -> Self { + Grid { + width, + height, + cells: vec![fill; width.saturating_mul(height)], + } + } + + pub fn in_bounds(&self, x: usize, y: usize) -> bool { + x < self.width && y < self.height + } + + pub fn index(&self, x: usize, y: usize) -> Option { + if self.in_bounds(x, y) { + Some(y * self.width + x) + } else { + None + } + } + + pub fn get(&self, x: usize, y: usize, fallback: T) -> T { + self.index(x, y).map(|i| self.cells[i]).unwrap_or(fallback) + } + + pub fn set(&mut self, x: usize, y: usize, value: T) { + if let Some(i) = self.index(x, y) { + self.cells[i] = value; + } + } + + pub fn count(&self, value: T) -> usize + where + T: PartialEq, + { + self.cells.iter().filter(|c| **c == value).count() + } + + /// The four orthogonal neighbours that are inside the grid, + /// in RocGrid order: up, right, down, left. + pub fn neighbors4(&self, x: usize, y: usize) -> Vec<(usize, usize)> { + let mut out = Vec::with_capacity(4); + if y > 0 && self.in_bounds(x, y - 1) { + out.push((x, y - 1)); + } + if self.in_bounds(x + 1, y) { + out.push((x + 1, y)); + } + if self.in_bounds(x, y + 1) { + out.push((x, y + 1)); + } + if x > 0 && self.in_bounds(x - 1, y) { + out.push((x - 1, y)); + } + out + } + + /// One row as a Vec, or an empty Vec for an out-of-range row. + pub fn row(&self, y: usize) -> Vec { + if y >= self.height { + return Vec::new(); + } + self.cells[y * self.width..(y + 1) * self.width].to_vec() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn grid_is_total_at_the_edges() { + let mut g = Grid::new(3, 2, 0u8); + assert!(g.in_bounds(2, 1)); + assert!(!g.in_bounds(3, 0)); + assert_eq!(g.get(9, 9, 7), 7); + g.set(9, 9, 5); + assert_eq!(g.count(5), 0); + g.set(1, 1, 5); + assert_eq!(g.get(1, 1, 0), 5); + assert_eq!(g.count(5), 1); + assert_eq!(g.row(0), vec![0, 0, 0]); + assert_eq!(g.row(5), Vec::::new()); + assert_eq!(g.neighbors4(0, 0), vec![(1, 0), (0, 1)]); + assert_eq!(g.neighbors4(1, 0), vec![(2, 0), (1, 1), (0, 0)]); + } +} diff --git a/pkgs/id/examples/rust-world/src/json.rs b/pkgs/id/examples/rust-world/src/json.rs new file mode 100644 index 0000000000..5e617b042a --- /dev/null +++ b/pkgs/id/examples/rust-world/src/json.rs @@ -0,0 +1,395 @@ +//! Minimal JSON mirroring `RocJson.roc`: dependency-free decode/encode +//! with the same contract points the examples rely on — number lexemes +//! are preserved as strings (no implicit float conversion), decode is +//! bounded (at most 65,536 bytes and 64 nested arrays/objects), object +//! `get` returns the FIRST matching key, and encoding validates number +//! lexemes instead of emitting malformed JSON. + +pub const MAX_DECODE_BYTES: usize = 65_536; +pub const MAX_DEPTH: usize = 64; + +#[derive(Clone, Debug, PartialEq)] +pub enum Value { + Null, + Bool(bool), + /// The exact source lexeme, e.g. "-12.50e3". + Number(String), + Str(String), + Array(Vec), + /// Insertion-ordered pairs; duplicate keys are preserved. + Object(Vec<(String, Value)>), +} + +impl Value { + pub fn get(&self, key: &str) -> Option<&Value> { + match self { + Value::Object(pairs) => pairs.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + Value::Str(s) => Some(s), + _ => None, + } + } + + pub fn as_i64(&self) -> Option { + match self { + Value::Number(lexeme) => lexeme.parse::().ok(), + _ => None, + } + } + + pub fn as_u64(&self) -> Option { + match self { + Value::Number(lexeme) => lexeme.parse::().ok(), + _ => None, + } + } + + pub fn as_bool(&self) -> Option { + match self { + Value::Bool(b) => Some(*b), + _ => None, + } + } + + pub fn as_array(&self) -> Option<&[Value]> { + match self { + Value::Array(items) => Some(items), + _ => None, + } + } +} + +/// A valid JSON number lexeme: -?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)? +pub fn valid_number_lexeme(text: &str) -> bool { + let b = text.as_bytes(); + let mut i = 0; + if i < b.len() && b[i] == b'-' { + i += 1; + } + if i >= b.len() { + return false; + } + if b[i] == b'0' { + i += 1; + } else if b[i].is_ascii_digit() { + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } else { + return false; + } + if i < b.len() && b[i] == b'.' { + i += 1; + if i >= b.len() || !b[i].is_ascii_digit() { + return false; + } + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + if i < b.len() && (b[i] == b'e' || b[i] == b'E') { + i += 1; + if i < b.len() && (b[i] == b'+' || b[i] == b'-') { + i += 1; + } + if i >= b.len() || !b[i].is_ascii_digit() { + return false; + } + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + i == b.len() +} + +struct Parser<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Parser<'a> { + fn ws(&mut self) { + while self.pos < self.bytes.len() + && matches!(self.bytes[self.pos], b' ' | b'\t' | b'\n' | b'\r') + { + self.pos += 1; + } + } + + fn peek(&self) -> Option { + self.bytes.get(self.pos).copied() + } + + fn value(&mut self, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err("json: nesting deeper than 64".into()); + } + self.ws(); + match self.peek() { + Some(b'n') => self.literal("null", Value::Null), + Some(b't') => self.literal("true", Value::Bool(true)), + Some(b'f') => self.literal("false", Value::Bool(false)), + Some(b'"') => Ok(Value::Str(self.string()?)), + Some(b'[') => { + self.pos += 1; + let mut items = Vec::new(); + self.ws(); + if self.peek() == Some(b']') { + self.pos += 1; + return Ok(Value::Array(items)); + } + loop { + items.push(self.value(depth + 1)?); + self.ws(); + match self.peek() { + Some(b',') => self.pos += 1, + Some(b']') => { + self.pos += 1; + return Ok(Value::Array(items)); + } + _ => return Err("json: expected ',' or ']' in array".into()), + } + } + } + Some(b'{') => { + self.pos += 1; + let mut pairs = Vec::new(); + self.ws(); + if self.peek() == Some(b'}') { + self.pos += 1; + return Ok(Value::Object(pairs)); + } + loop { + self.ws(); + let key = self.string()?; + self.ws(); + if self.peek() != Some(b':') { + return Err("json: expected ':' in object".into()); + } + self.pos += 1; + let val = self.value(depth + 1)?; + pairs.push((key, val)); + self.ws(); + match self.peek() { + Some(b',') => self.pos += 1, + Some(b'}') => { + self.pos += 1; + return Ok(Value::Object(pairs)); + } + _ => return Err("json: expected ',' or '}' in object".into()), + } + } + } + Some(c) if c == b'-' || c.is_ascii_digit() => { + let start = self.pos; + while self.pos < self.bytes.len() + && matches!(self.bytes[self.pos], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') + { + self.pos += 1; + } + let lexeme = std::str::from_utf8(&self.bytes[start..self.pos]) + .map_err(|_| "json: bad number")? + .to_string(); + if !valid_number_lexeme(&lexeme) { + return Err(format!("json: invalid number lexeme {lexeme:?}")); + } + Ok(Value::Number(lexeme)) + } + _ => Err("json: unexpected input".into()), + } + } + + fn literal(&mut self, text: &str, value: Value) -> Result { + if self.bytes[self.pos..].starts_with(text.as_bytes()) { + self.pos += text.len(); + Ok(value) + } else { + Err(format!("json: expected {text}")) + } + } + + fn string(&mut self) -> Result { + if self.peek() != Some(b'"') { + return Err("json: expected string".into()); + } + self.pos += 1; + let mut out = String::new(); + loop { + let c = self.peek().ok_or("json: unterminated string")?; + self.pos += 1; + match c { + b'"' => return Ok(out), + b'\\' => { + let e = self.peek().ok_or("json: bad escape")?; + self.pos += 1; + match e { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push('\u{0008}'), + b'f' => out.push('\u{000C}'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + let hex = self.bytes.get(self.pos..self.pos + 4) + .ok_or("json: bad \\u escape")?; + let text = std::str::from_utf8(hex).map_err(|_| "json: bad \\u")?; + let code = u32::from_str_radix(text, 16) + .map_err(|_| "json: bad \\u escape")?; + self.pos += 4; + out.push(char::from_u32(code).unwrap_or('\u{FFFD}')); + } + _ => return Err("json: bad escape".into()), + } + } + _ => { + // Copy the full UTF-8 sequence for this scalar. + let start = self.pos - 1; + let len = utf8_len(self.bytes[start]); + let end = (start + len).min(self.bytes.len()); + out.push_str( + std::str::from_utf8(&self.bytes[start..end]) + .map_err(|_| "json: invalid utf-8")?, + ); + self.pos = end; + } + } + } + } +} + +fn utf8_len(first: u8) -> usize { + if first < 0x80 { + 1 + } else if first >> 5 == 0b110 { + 2 + } else if first >> 4 == 0b1110 { + 3 + } else if first >> 3 == 0b11110 { + 4 + } else { + 1 + } +} + +/// Decode with RocJson's bounds: > 65,536 bytes or > 64 nesting is an +/// explicit error, never a partial value. +pub fn decode(text: &str) -> Result { + if text.len() > MAX_DECODE_BYTES { + return Err("json: input longer than 65536 bytes".into()); + } + let mut parser = Parser { + bytes: text.as_bytes(), + pos: 0, + }; + let value = parser.value(0)?; + parser.ws(); + if parser.pos != parser.bytes.len() { + return Err("json: trailing input".into()); + } + Ok(value) +} + +/// Encode, validating number lexemes (an invalid one is an error, as in +/// RocJson, rather than malformed output). +pub fn encode(value: &Value) -> Result { + let mut out = String::new(); + encode_into(value, &mut out)?; + Ok(out) +} + +fn encode_into(value: &Value, out: &mut String) -> Result<(), String> { + match value { + Value::Null => out.push_str("null"), + Value::Bool(true) => out.push_str("true"), + Value::Bool(false) => out.push_str("false"), + Value::Number(lexeme) => { + if !valid_number_lexeme(lexeme) { + return Err(format!("json: invalid number lexeme {lexeme:?}")); + } + out.push_str(lexeme); + } + Value::Str(s) => out.push_str("e(s)), + Value::Array(items) => { + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + encode_into(item, out)?; + } + out.push(']'); + } + Value::Object(pairs) => { + out.push('{'); + for (i, (key, val)) in pairs.iter().enumerate() { + if i > 0 { + out.push(','); + } + out.push_str("e(key)); + out.push(':'); + encode_into(val, out)?; + } + out.push('}'); + } + } + Ok(()) +} + +/// JSON string quoting, byte-compatible with `Screen.json_quote` for the +/// escapes the screen document uses. +pub fn quote(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decode_preserves_number_lexemes_and_first_key_wins() { + let v = decode("{\"a\": -12.50e3, \"a\": 2, \"b\": [true, null, \"x\"]}").unwrap(); + assert_eq!(v.get("a"), Some(&Value::Number("-12.50e3".into()))); + assert_eq!(v.get("b").and_then(|b| b.as_array()).map(|a| a.len()), Some(3)); + assert_eq!(v.get("missing"), None); + } + + #[test] + fn encode_validates_numbers_and_round_trips() { + let v = decode("{\"count\": 3}").unwrap(); + assert_eq!(encode(&v).unwrap(), "{\"count\":3}"); + assert!(encode(&Value::Number("01".into())).is_err()); + assert!(encode(&Value::Number("1.5e2".into())).is_ok()); + assert_eq!(quote("a\"\\\n"), "\"a\\\"\\\\\\n\""); + } + + #[test] + fn decode_bounds_are_explicit_errors() { + let big = format!("\"{}\"", "x".repeat(MAX_DECODE_BYTES)); + assert!(decode(&big).is_err()); + let deep = "[".repeat(MAX_DEPTH + 2); + assert!(decode(&deep).is_err()); + assert!(decode("{").is_err()); + assert!(decode("1 2").is_err()); + } +} diff --git a/pkgs/id/examples/rust-world/src/lib.rs b/pkgs/id/examples/rust-world/src/lib.rs new file mode 100644 index 0000000000..96233179df --- /dev/null +++ b/pkgs/id/examples/rust-world/src/lib.rs @@ -0,0 +1,313 @@ +//! Plaza guest SDK for Rust (F12.8, issue #1065). +//! +//! The Roc platform (`examples/roc-world`) turns a pure Roc program into +//! an `id` world module through a Zig host adapter. This crate is the +//! Rust equal: implement the [`World`] trait and invoke +//! [`plaza_guest!`] once, and the crate produces an import-free +//! Wasm32 module exporting the full Plaza ABI v1 surface documented in +//! `examples/roc-world/ABI.md` — memory, alloc/free, init/update, view, +//! layout, records, wants, snapshot/restore, the shared output slot, +//! and the diagnostic pair. +//! +//! Helper modules mirror the Roc platform libraries so a Rust guest +//! reads like its Roc counterpart: +//! +//! - [`screen`] = `Screen.roc` (portable screen JSON + plain text) +//! - [`json`] = `RocJson.roc` (bounded decode, lexeme-preserving numbers) +//! - [`grid`] = `RocGrid.roc` (total, bounds-checked row-major grids) +//! - [`cap`] = `RocCap.roc` (capability request sessions) +//! - [`text`] = `RocText.roc` (total byte-level text helpers) +//! +//! `examples/rust-counter` is the playable example built on this SDK. + +pub mod cap; +pub mod grid; +pub mod json; +pub mod screen; +pub mod text; + +use std::alloc::{alloc, dealloc, Layout}; +use std::cell::UnsafeCell; + +/// A Plaza world program. `Model` is opaque to the host: the ABI hands +/// the host a pointer it passes back to later calls. +/// +/// Only `init`, `update`, and `view` are required; the optional +/// projections default to the Roc platform's absent-export behaviour, +/// except `wants`, which defaults to the empty document `"{}"` that +/// Roc programs return when they want nothing. +pub trait World { + type Model; + + fn init(seed: u64) -> Self::Model; + fn update(model: Self::Model, participant: u32, event: &[u8]) -> Self::Model; + fn view(model: &Self::Model) -> Vec; + + fn layout(model: &Self::Model, _width: u64, _height: u64) -> Option> { + let _ = model; + None + } + + fn records(model: &Self::Model) -> Option> { + let _ = model; + None + } + + fn wants(model: &Self::Model) -> Option> { + let _ = model; + Some(b"{}".to_vec()) + } + + fn snapshot(model: &Self::Model) -> Option> { + let _ = model; + None + } + + /// Reconstruct a model from `snapshot` bytes. Must be total: for + /// malformed or unsupported text return a sensible model rather + /// than trapping (the ABI's restore rule). + fn restore(snapshot: &[u8]) -> Self::Model { + let _ = snapshot; + Self::init(0) + } +} + +// ---- ABI plumbing ------------------------------------------------------- + +struct OutputSlot(UnsafeCell>); +unsafe impl Sync for OutputSlot {} +static OUTPUT: OutputSlot = OutputSlot(UnsafeCell::new(Vec::new())); + +fn set_output(bytes: Vec) -> i32 { + unsafe { + let slot = &mut *OUTPUT.0.get(); + *slot = bytes; + slot.as_ptr() as i32 + } +} + +fn output_len() -> i32 { + unsafe { (&*OUTPUT.0.get()).len() as i32 } +} + +fn output_ptr() -> i32 { + unsafe { (&*OUTPUT.0.get()).as_ptr() as i32 } +} + +fn guest_alloc(len: i32) -> i32 { + let len = usize::try_from(len).unwrap_or(0).max(1); + let layout = Layout::from_size_align(len, 1).unwrap(); + unsafe { alloc(layout) as i32 } +} + +fn guest_free(ptr: i32, len: i32) { + if ptr == 0 { + return; + } + let len = usize::try_from(len).unwrap_or(0).max(1); + let layout = Layout::from_size_align(len, 1).unwrap(); + unsafe { dealloc(ptr as *mut u8, layout) } +} + +fn leak_model(model: M) -> i32 { + Box::into_raw(Box::new(model)) as i32 +} + +unsafe fn take_model(ptr: i32) -> M { + *Box::from_raw(ptr as *mut M) +} + +unsafe fn ref_model<'a, M>(ptr: i32) -> &'a M { + &*(ptr as *const M) +} + +unsafe fn event_bytes<'a>(ptr: i32, len: i32) -> &'a [u8] { + let len = usize::try_from(len).unwrap_or(0); + if len == 0 { + &[] + } else { + std::slice::from_raw_parts(ptr as *const u8, len) + } +} + +/// Generate the 14 documented Plaza ABI v1 exports for a [`World`] +/// implementation. Invoke once at the crate root of a `cdylib` crate: +/// +/// ```ignore +/// struct MyWorld; +/// impl plaza_sdk::World for MyWorld { /* ... */ } +/// plaza_sdk::plaza_guest!(MyWorld); +/// ``` +/// +/// ABI.md makes `plaza_snapshot`/`plaza_restore` an all-or-nothing +/// pair and the conformance suite requires every documented export, +/// so the macro always exports both: a `World` whose `snapshot` +/// returns `None` gets a snapshot of the empty byte string and a +/// restore through `World::restore`, keeping the pair total. +#[macro_export] +macro_rules! plaza_guest { + ($world:ty) => { + #[no_mangle] + pub extern "C" fn plaza_abi_version() -> i32 { + 1 + } + + #[no_mangle] + pub extern "C" fn plaza_alloc(len: i32) -> i32 { + $crate::plaza_alloc_impl(len) + } + + #[no_mangle] + pub extern "C" fn plaza_free(ptr: i32, len: i32) { + $crate::plaza_free_impl(ptr, len) + } + + #[no_mangle] + pub extern "C" fn plaza_init(seed: i64) -> i32 { + $crate::plaza_init_impl::<$world>(seed) + } + + #[no_mangle] + pub extern "C" fn plaza_update( + model: i32, + participant: i32, + event_ptr: i32, + event_len: i32, + ) -> i32 { + $crate::plaza_update_impl::<$world>(model, participant, event_ptr, event_len) + } + + #[no_mangle] + pub extern "C" fn plaza_view(model: i32) -> i32 { + $crate::plaza_view_impl::<$world>(model) + } + + #[no_mangle] + pub extern "C" fn plaza_layout(model: i32, width: i64, height: i64) -> i32 { + $crate::plaza_layout_impl::<$world>(model, width, height) + } + + #[no_mangle] + pub extern "C" fn plaza_records(model: i32) -> i32 { + $crate::plaza_records_impl::<$world>(model) + } + + #[no_mangle] + pub extern "C" fn plaza_wants(model: i32) -> i32 { + $crate::plaza_wants_impl::<$world>(model) + } + + #[no_mangle] + pub extern "C" fn plaza_snapshot(model: i32) -> i32 { + $crate::plaza_snapshot_impl::<$world>(model) + } + + #[no_mangle] + pub extern "C" fn plaza_restore(snapshot_ptr: i32, snapshot_len: i32) -> i32 { + $crate::plaza_restore_impl::<$world>(snapshot_ptr, snapshot_len) + } + + #[no_mangle] + pub extern "C" fn plaza_out_len() -> i32 { + $crate::plaza_out_len_impl() + } + + #[no_mangle] + pub extern "C" fn plaza_error_ptr() -> i32 { + $crate::plaza_error_ptr_impl() + } + + #[no_mangle] + pub extern "C" fn plaza_error_len() -> i32 { + 0 + } + }; +} + +#[doc(hidden)] +pub fn plaza_alloc_impl(len: i32) -> i32 { + guest_alloc(len) +} + +#[doc(hidden)] +pub fn plaza_free_impl(ptr: i32, len: i32) { + guest_free(ptr, len) +} + +#[doc(hidden)] +pub fn plaza_init_impl(seed: i64) -> i32 { + leak_model(W::init(seed as u64)) +} + +#[doc(hidden)] +pub fn plaza_update_impl( + model: i32, + participant: i32, + event_ptr: i32, + event_len: i32, +) -> i32 { + unsafe { + let model = take_model::(model); + let event = event_bytes(event_ptr, event_len).to_vec(); + leak_model(W::update(model, participant as u32, &event)) + } +} + +#[doc(hidden)] +pub fn plaza_view_impl(model: i32) -> i32 { + unsafe { set_output(W::view(ref_model::(model))) } +} + +#[doc(hidden)] +pub fn plaza_layout_impl(model: i32, width: i64, height: i64) -> i32 { + unsafe { + let model_ref = ref_model::(model); + let bytes = W::layout(model_ref, width as u64, height as u64) + .unwrap_or_else(|| W::view(model_ref)); + set_output(bytes) + } +} + +#[doc(hidden)] +pub fn plaza_records_impl(model: i32) -> i32 { + unsafe { + let bytes = W::records(ref_model::(model)).unwrap_or_default(); + set_output(bytes) + } +} + +#[doc(hidden)] +pub fn plaza_wants_impl(model: i32) -> i32 { + unsafe { + let bytes = W::wants(ref_model::(model)).unwrap_or_default(); + set_output(bytes) + } +} + +#[doc(hidden)] +pub fn plaza_snapshot_impl(model: i32) -> i32 { + unsafe { + let bytes = W::snapshot(ref_model::(model)).unwrap_or_default(); + set_output(bytes) + } +} + +#[doc(hidden)] +pub fn plaza_restore_impl(snapshot_ptr: i32, snapshot_len: i32) -> i32 { + unsafe { + let bytes = event_bytes(snapshot_ptr, snapshot_len).to_vec(); + leak_model(W::restore(&bytes)) + } +} + +#[doc(hidden)] +pub fn plaza_out_len_impl() -> i32 { + output_len() +} + +#[doc(hidden)] +pub fn plaza_error_ptr_impl() -> i32 { + // No crash has been captured: the diagnostic pair reads as an + // empty message (length 0), which ABI.md permits at rest. + output_ptr() +} diff --git a/pkgs/id/examples/rust-world/src/screen.rs b/pkgs/id/examples/rust-world/src/screen.rs new file mode 100644 index 0000000000..da125eda11 --- /dev/null +++ b/pkgs/id/examples/rust-world/src/screen.rs @@ -0,0 +1,223 @@ +//! Portable screen mirroring `Screen.roc`: a cell grid with per-cell +//! styles that renders to plain text or to the versioned JSON document +//! (`{"kind":"screen","version":1,...}`) the host validates. A column is +//! one Unicode scalar value. The default style (fg 0, bg 0, not bold) +//! writes no style span, exactly like the Roc renderer. + +use crate::grid::Grid; +use crate::json::quote; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Style { + pub fg: u8, + pub bg: u8, + pub bold: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Cell { + ch: char, + style: Style, +} + +#[derive(Clone, Debug)] +pub struct Screen { + pub width: usize, + pub height: usize, + cells: Grid, +} + +impl Screen { + pub fn new(width: usize, height: usize) -> Self { + Screen { + width, + height, + cells: Grid::new( + width, + height, + Cell { + ch: ' ', + style: Style::default(), + }, + ), + } + } + + pub fn put_text(&mut self, x: usize, y: usize, text: &str, style: Style) { + for (i, ch) in text.chars().enumerate() { + self.cells.set(x + i, y, Cell { ch, style }); + } + } + + pub fn put_grid( + &mut self, + grid: &Grid, + x: usize, + y: usize, + fallback: T, + glyph: impl Fn(T) -> char, + style: Style, + ) { + for gy in 0..grid.height { + for gx in 0..grid.width { + let cell = Cell { + ch: glyph(grid.get(gx, gy, fallback)), + style, + }; + self.cells.set(x + gx, y + gy, cell); + } + } + } + + /// Draw a box: `+---+` edges with the title on the top edge and + /// `|` sides, like `Screen.boxed`. + pub fn boxed(&mut self, x: usize, y: usize, w: usize, h: usize, title: &str) { + if w < 2 || h < 2 { + return; + } + let style = Style::default(); + let top = box_edge(w, title); + let bottom = box_edge(w, ""); + for (i, ch) in top.chars().enumerate() { + self.cells.set(x + i, y, Cell { ch, style }); + } + for row in 1..h - 1 { + self.cells.set(x, y + row, Cell { ch: '|', style }); + self.cells.set(x + w - 1, y + row, Cell { ch: '|', style }); + } + for (i, ch) in bottom.chars().enumerate() { + self.cells.set(x + i, y + h - 1, Cell { ch, style }); + } + } + + fn row_text(&self, row: usize) -> String { + self.cells + .row(row) + .iter() + .map(|c| c.ch) + .collect::() + .trim_end_matches(|c| c == '\u{0}') + .to_string() + } + + pub fn render_plain(&self) -> String { + (0..self.height) + .map(|row| { + let text: String = self.cells.row(row).iter().map(|c| c.ch).collect(); + text + }) + .collect::>() + .join("\n") + } + + fn row_styles_json(&self, row: usize) -> String { + let cells = self.cells.row(row); + let mut spans: Vec = Vec::new(); + let mut run_start = 0usize; + let mut run_len = 0usize; + let mut run_style = Style::default(); + let close = |spans: &mut Vec, start: usize, len: usize, style: Style| { + if len > 0 && style != Style::default() { + spans.push(format!( + "{{\"x\":{},\"length\":{},\"fg\":{},\"bg\":{},\"bold\":{}}}", + start, len, style.fg, style.bg, style.bold + )); + } + }; + for (x, cell) in cells.iter().enumerate() { + if run_len > 0 && cell.style == run_style { + run_len += 1; + } else { + close(&mut spans, run_start, run_len, run_style); + run_start = x; + run_len = 1; + run_style = cell.style; + } + } + close(&mut spans, run_start, run_len, run_style); + format!("[{}]", spans.join(",")) + } + + pub fn render_json(&self) -> String { + let rows = (0..self.height) + .map(|row| quote(&self.row_text(row))) + .collect::>() + .join(","); + let styles = (0..self.height) + .map(|row| self.row_styles_json(row)) + .collect::>() + .join(","); + format!( + "{{\"kind\":\"screen\",\"version\":1,\"width\":{},\"height\":{},\"rows\":[{}],\"styles\":[{}]}}", + self.width, self.height, rows, styles + ) + } +} + +/// One box edge, like `Screen.box_edge`: `+-` + title + `-` fill + `+`, +/// with the title cut so the edge is exactly `width` columns. +pub fn box_edge(width: usize, title: &str) -> String { + if width < 2 { + return "+".repeat(width); + } + let mut edge = String::from("+-"); + let room = width.saturating_sub(3); + for ch in title.chars().take(room) { + edge.push(ch); + } + while edge.chars().count() < width - 1 { + edge.push('-'); + } + edge.push('+'); + edge +} + +/// Quote a string as JSON, exported for parity with `Screen.json_quote`. +pub fn json_quote(s: &str) -> String { + quote(s) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn render_json_matches_roc_screen_expects() { + // Screen.roc `expect` values, byte for byte. + let mut s = Screen::new(2, 1); + s.put_text(0, 0, "ok", Style::default()); + assert_eq!( + s.render_json(), + "{\"kind\":\"screen\",\"version\":1,\"width\":2,\"height\":1,\"rows\":[\"ok\"],\"styles\":[[]]}" + ); + let mut s = Screen::new(3, 1); + s.put_text( + 0, + 0, + "abc", + Style { + fg: 196, + bg: 0, + bold: true, + }, + ); + assert_eq!( + s.render_json(), + "{\"kind\":\"screen\",\"version\":1,\"width\":3,\"height\":1,\"rows\":[\"abc\"],\"styles\":[[{\"x\":0,\"length\":3,\"fg\":196,\"bg\":0,\"bold\":true}]]}" + ); + assert_eq!(json_quote("a\"\\\n"), "\"a\\\"\\\\\\n\""); + } + + #[test] + fn boxed_and_plain_match_roc_screen_expects() { + let mut s = Screen::new(6, 3); + s.boxed(0, 0, 6, 3, "t"); + assert_eq!(s.render_plain(), "+-t--+\n| |\n+----+"); + assert_eq!(box_edge(8, "ti"), "+-ti---+"); + assert_eq!(box_edge(6, "toolong"), "+-too+"); + assert_eq!(box_edge(4, ""), "+--+"); + let mut s = Screen::new(4, 2); + s.put_text(1, 0, "hi", Style::default()); + assert_eq!(s.render_plain(), " hi \n "); + } +} diff --git a/pkgs/id/examples/rust-world/src/text.rs b/pkgs/id/examples/rust-world/src/text.rs new file mode 100644 index 0000000000..98edc276bb --- /dev/null +++ b/pkgs/id/examples/rust-world/src/text.rs @@ -0,0 +1,71 @@ +//! Byte-level text helpers mirroring `RocText.roc`: total functions that +//! never trap. Operations work on UTF-8 bytes where the Roc originals do; +//! `lines` follows `Str.split_on "\n"` semantics used by the examples. + +/// Trim ASCII whitespace (space, tab, newline, carriage return) from +/// both ends, like `RocText.trim`. +pub fn trim(s: &str) -> &str { + s.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r')) +} + +/// ASCII lowercase, like `RocText.lowercase`. +pub fn lowercase(s: &str) -> String { + s.chars().map(|c| c.to_ascii_lowercase()).collect() +} + +pub fn starts_with(s: &str, prefix: &str) -> bool { + s.as_bytes().starts_with(prefix.as_bytes()) +} + +pub fn drop_prefix<'a>(s: &'a str, prefix: &str) -> &'a str { + s.strip_prefix(prefix).unwrap_or(s) +} + +pub fn contains(s: &str, needle: &str) -> bool { + s.as_bytes() + .windows(needle.len().max(1)) + .any(|w| w == needle.as_bytes()) + || needle.is_empty() +} + +/// Split on '\n', like `RocText.lines`. A trailing newline does not +/// produce a trailing empty line beyond what `str::split` yields after +/// the final separator is dropped by the Roc helper's shape; this keeps +/// the exact `split` pieces, matching how the examples consume them. +pub fn lines(s: &str) -> Vec<&str> { + if s.is_empty() { + Vec::new() + } else { + s.split('\n').collect() + } +} + +pub fn join_lines(parts: &[String]) -> String { + parts.join("\n") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_matches_roc_text() { + assert_eq!(trim(" inc \n"), "inc"); + assert_eq!(trim("inc"), "inc"); + assert_eq!(trim(" \t\r\n"), ""); + } + + #[test] + fn helpers_are_total() { + assert_eq!(lowercase("AbC-XYz"), "abc-xyz"); + assert!(starts_with("hello", "he")); + assert!(!starts_with("hi", "hello")); + assert_eq!(drop_prefix("pre:fix", "pre:"), "fix"); + assert_eq!(drop_prefix("fix", "pre:"), "fix"); + assert!(contains("a-b-c", "-b-")); + assert!(!contains("abc", "d")); + assert_eq!(lines("a\nb"), vec!["a", "b"]); + assert_eq!(lines(""), Vec::<&str>::new()); + assert_eq!(join_lines(&["a".into(), "b".into()]), "a\nb"); + } +} diff --git a/pkgs/id/src/sandbox.rs b/pkgs/id/src/sandbox.rs index a800f5cee6..9521b985bb 100644 --- a/pkgs/id/src/sandbox.rs +++ b/pkgs/id/src/sandbox.rs @@ -969,11 +969,15 @@ mod tests { const ABI_MD: &str = include_str!("../examples/roc-world/ABI.md"); - const CONFORMANCE_MODULES: [(&str, &[u8]); 2] = [ + const CONFORMANCE_MODULES: [(&str, &[u8]); 3] = [ ( "roc-counter", include_bytes!("../examples/roc-counter/counter.wasm"), ), + ( + "rust-counter", + include_bytes!("../examples/rust-counter/counter.wasm"), + ), ( "tic-tac-toe", include_bytes!("../apps/tic-tac-toe/program/tic-tac-toe.wasm"),