louise
The Louise language: compiler, runtime, std, tooling
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runÉchoué#94 · main · 15 min 28 s
0Étoiles
0Forks
40Issues
| 1 | //! The distribution wire format's kernel ([ADR 0072], [`docs/wire-format.md`]): |
| 2 | //! type descriptors and the type definitions table, their canonical form |
| 3 | //! and structural hash, and the value encoding's primitives (varints, |
| 4 | //! heads, the message frame's header, node names). |
| 5 | //! |
| 6 | //! Shared by the compiler, which emits descriptors and the table, and the |
| 7 | //! runtime, whose codec walks a value and its descriptor together. The |
| 8 | //! format document is normative; this module implements it, and its tests |
| 9 | //! pin the golden values the document quotes. |
| 10 | //! |
| 11 | //! Nothing here is reachable from a program that does not start |
| 12 | //! distribution: the runtime calls it only from the codec, which only the |
| 13 | //! transport's hooks reach (`--gc-sections` drops the rest). |
| 14 | //! |
| 15 | //! [ADR 0072]: ../../../docs/adr/0072-distribution.md |
| 16 | //! [`docs/wire-format.md`]: ../../../docs/wire-format.md |
| 17 | |
| 18 | use std::collections::{BTreeMap, BTreeSet}; |
| 19 | use std::fmt; |
| 20 | |
| 21 | use num_bigint::{BigInt, BigUint, Sign}; |
| 22 | |
| 23 | use crate::SMALL_INT; |
| 24 | |
| 25 | // ---- limits ---------------------------------------------------------------------- |
| 26 | |
| 27 | /// The longest descriptor or table text accepted, in bytes. |
| 28 | pub const MAX_DESC_LEN: usize = 1 << 16; |
| 29 | pub const MAX_TABLE_LEN: usize = 1 << 24; |
| 30 | /// The deepest nesting of a descriptor (`Subject`, `Array`, tuples, type |
| 31 | /// arguments): parsing recurses on the native stack. |
| 32 | pub const MAX_DESC_DEPTH: usize = 128; |
| 33 | /// The longest name (a qualified type name, a constructor name, a field |
| 34 | /// label), in bytes once unescaped. |
| 35 | pub const MAX_NAME_LEN: usize = 512; |
| 36 | /// A type's parameters, and a tuple's components. |
| 37 | pub const MAX_PARAMS: u32 = 255; |
| 38 | pub const MAX_TUPLE: u32 = 254; |
| 39 | /// A type's constructors: indices below `0xFF00` (runtime kinds start |
| 40 | /// there, `docs/runtime-abi.md`). |
| 41 | pub const MAX_CTORS: u32 = 0xFF00; |
| 42 | /// A constructor's fields: a block holds at most 254 (`0xFF` is |
| 43 | /// `TL_SCAN_LARGE`; codegen refuses wider constructors). |
| 44 | pub const MAX_FIELDS: u32 = 254; |
| 45 | /// The table's definitions. |
| 46 | pub const MAX_DEFS: usize = 1 << 16; |
| 47 | |
| 48 | /// The largest payload of a frame, in bytes. |
| 49 | pub const MAX_PAYLOAD: u32 = 64 << 20; |
| 50 | /// The deepest nesting of a value, counting only nodes whose current |
| 51 | /// child is not their last (a list of any length is depth 1). |
| 52 | pub const MAX_VALUE_DEPTH: u32 = 1 << 16; |
| 53 | /// Pid serials are below 2^46 on the wire (a remote pid's payload, ADR |
| 54 | /// 0072); subject tags are non-negative small `Int`s. |
| 55 | pub const MAX_PID_SERIAL: u64 = 1 << 46; |
| 56 | pub const MAX_TAG: u64 = 1 << 62; |
| 57 | /// A node name is a DNS name. |
| 58 | pub const MAX_NODE_NAME: usize = 253; |
| 59 | |
| 60 | /// The transport's bounds, shared with `[cluster]`'s checks |
| 61 | /// (`louise_package`) so the two cannot drift. The smallest frame limit a |
| 62 | /// node may announce: every handshake frame fits under it, and so does the |
| 63 | /// smallest `max_message_bytes`. |
| 64 | pub const MIN_FRAME: u32 = 1 << 10; |
| 65 | /// The largest useful frame (its length prefix counts the kind byte): a |
| 66 | /// message frame of the largest payload. |
| 67 | pub const MAX_FRAME: u32 = 1 + HEADER_LEN as u32 + MAX_PAYLOAD; |
| 68 | /// The longest delay a configuration may give (a day): deadlines stay far |
| 69 | /// from `Instant`'s range. |
| 70 | pub const MAX_DELAY_MS: u64 = 86_400_000; |
| 71 | /// The most connections past their hello a configuration may allow |
| 72 | /// (`max_peers`), seeds aside. |
| 73 | pub const MAX_PEERS: usize = 4096; |
| 74 | |
| 75 | /// What a malformed descriptor, table or payload is refused with: why, |
| 76 | /// and where: the byte offset where reading stopped; for the checks |
| 77 | /// against a table that follow parsing, the index of the definition at |
| 78 | /// fault ([`Table::new`]), or 0 for a descriptor ([`Table::check`]). |
| 79 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 80 | pub struct WireError { |
| 81 | pub at: usize, |
| 82 | pub what: &'static str, |
| 83 | } |
| 84 | |
| 85 | impl fmt::Display for WireError { |
| 86 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 87 | write!(f, "wire: {} (at byte {})", self.what, self.at) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | impl std::error::Error for WireError {} |
| 92 | |
| 93 | fn err<T>(at: usize, what: &'static str) -> Result<T, WireError> { |
| 94 | Err(WireError { at, what }) |
| 95 | } |
| 96 | |
| 97 | // ---- descriptors ------------------------------------------------------------------- |
| 98 | |
| 99 | /// A type descriptor (`docs/wire-format.md`, *Type descriptors*). |
| 100 | #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 101 | pub enum Desc { |
| 102 | Int, |
| 103 | Float, |
| 104 | String, |
| 105 | Bytes, |
| 106 | U64, |
| 107 | Dec, |
| 108 | Pid, |
| 109 | Unit, |
| 110 | Subject(Box<Desc>), |
| 111 | Array(Box<Desc>), |
| 112 | /// Two to [`MAX_TUPLE`] components. |
| 113 | Tuple(Vec<Desc>), |
| 114 | /// A data type of the table, by qualified name, applied to arguments. |
| 115 | Adt { |
| 116 | name: String, |
| 117 | args: Vec<Desc>, |
| 118 | }, |
| 119 | /// A parameter of the enclosing definition (table field types only). |
| 120 | Param(u32), |
| 121 | } |
| 122 | |
| 123 | /// A literal piece of a descriptor, or a hole the caller fills with a |
| 124 | /// type argument's descriptor ([`Desc::pieces`]). |
| 125 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 126 | pub enum Piece { |
| 127 | Lit(String), |
| 128 | Hole(u32), |
| 129 | } |
| 130 | |
| 131 | impl Desc { |
| 132 | /// A closed descriptor (no parameter). |
| 133 | pub fn parse(text: &str) -> Result<Desc, WireError> { |
| 134 | Self::parse_open(text, 0) |
| 135 | } |
| 136 | |
| 137 | /// A descriptor whose parameters are below `params`. |
| 138 | pub fn parse_open(text: &str, params: u32) -> Result<Desc, WireError> { |
| 139 | if text.len() > MAX_DESC_LEN { |
| 140 | return err(0, "descriptor too long"); |
| 141 | } |
| 142 | let mut p = Parser::new(text.as_bytes())?; |
| 143 | let d = p.desc(params, 0)?; |
| 144 | if p.at != p.s.len() { |
| 145 | return err(p.at, "trailing bytes after the descriptor"); |
| 146 | } |
| 147 | Ok(d) |
| 148 | } |
| 149 | |
| 150 | /// Whether it mentions no parameter. |
| 151 | pub fn is_closed(&self) -> bool { |
| 152 | match self { |
| 153 | Desc::Param(_) => false, |
| 154 | Desc::Subject(d) | Desc::Array(d) => d.is_closed(), |
| 155 | Desc::Tuple(ds) | Desc::Adt { args: ds, .. } => ds.iter().all(Desc::is_closed), |
| 156 | _ => true, |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// The descriptor with each `Param(i)` replaced by `args[i]` (a |
| 161 | /// constructor's field types at an instance). |
| 162 | /// |
| 163 | /// # Panics |
| 164 | /// If a parameter has no argument: the table was checked against it. |
| 165 | pub fn instantiate(&self, args: &[Desc]) -> Desc { |
| 166 | match self { |
| 167 | Desc::Param(i) => args[*i as usize].clone(), |
| 168 | Desc::Subject(d) => Desc::Subject(Box::new(d.instantiate(args))), |
| 169 | Desc::Array(d) => Desc::Array(Box::new(d.instantiate(args))), |
| 170 | Desc::Tuple(ds) => Desc::Tuple(ds.iter().map(|d| d.instantiate(args)).collect()), |
| 171 | Desc::Adt { name, args: a } => Desc::Adt { |
| 172 | name: name.clone(), |
| 173 | args: a.iter().map(|d| d.instantiate(args)).collect(), |
| 174 | }, |
| 175 | leaf => leaf.clone(), |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// The descriptor as literal pieces and holes, `Param(i)` being hole |
| 180 | /// `i`, adjacent literals merged: what the compiler emits for a |
| 181 | /// generic instantiation (a monomorphic type is one literal). |
| 182 | pub fn pieces(&self) -> Vec<Piece> { |
| 183 | fn go(d: &Desc, out: &mut Vec<Piece>) { |
| 184 | let lit = |out: &mut Vec<Piece>, s: &str| match out.last_mut() { |
| 185 | Some(Piece::Lit(l)) => l.push_str(s), |
| 186 | _ => out.push(Piece::Lit(s.to_owned())), |
| 187 | }; |
| 188 | match d { |
| 189 | Desc::Param(i) => out.push(Piece::Hole(*i)), |
| 190 | Desc::Subject(x) => { |
| 191 | lit(out, "S"); |
| 192 | go(x, out); |
| 193 | } |
| 194 | Desc::Array(x) => { |
| 195 | lit(out, "A"); |
| 196 | go(x, out); |
| 197 | } |
| 198 | Desc::Tuple(xs) => { |
| 199 | lit(out, &tuple_prefix(xs.len())); |
| 200 | xs.iter().for_each(|x| go(x, out)); |
| 201 | } |
| 202 | Desc::Adt { name, args } => { |
| 203 | lit(out, &adt_prefix(name, args.len())); |
| 204 | args.iter().for_each(|x| go(x, out)); |
| 205 | } |
| 206 | leaf => lit(out, &leaf.to_string()), |
| 207 | } |
| 208 | } |
| 209 | let mut out = Vec::new(); |
| 210 | go(self, &mut out); |
| 211 | out |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | impl fmt::Display for Desc { |
| 216 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 217 | match self { |
| 218 | Desc::Int => f.write_str("i"), |
| 219 | Desc::Float => f.write_str("f"), |
| 220 | Desc::String => f.write_str("s"), |
| 221 | Desc::Bytes => f.write_str("b"), |
| 222 | Desc::U64 => f.write_str("w"), |
| 223 | Desc::Dec => f.write_str("d"), |
| 224 | Desc::Pid => f.write_str("p"), |
| 225 | Desc::Unit => f.write_str("u"), |
| 226 | Desc::Subject(d) => write!(f, "S{d}"), |
| 227 | Desc::Array(d) => write!(f, "A{d}"), |
| 228 | Desc::Tuple(ds) => { |
| 229 | f.write_str(&tuple_prefix(ds.len()))?; |
| 230 | ds.iter().try_for_each(|d| write!(f, "{d}")) |
| 231 | } |
| 232 | Desc::Adt { name, args } => { |
| 233 | f.write_str(&adt_prefix(name, args.len()))?; |
| 234 | args.iter().try_for_each(|d| write!(f, "{d}")) |
| 235 | } |
| 236 | Desc::Param(i) => write!(f, "${i}"), |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /// The piece a tuple's descriptor starts with; its components follow. |
| 242 | pub fn tuple_prefix(arity: usize) -> String { |
| 243 | format!("T{arity}") |
| 244 | } |
| 245 | |
| 246 | /// The piece an instance of the data type `qualified` starts with; its |
| 247 | /// `args` type arguments' descriptors follow. |
| 248 | pub fn adt_prefix(qualified: &str, args: usize) -> String { |
| 249 | format!("N{};{args}", escape_name(qualified)) |
| 250 | } |
| 251 | |
| 252 | /// Whether `b` stands for itself in a name; every other byte is `%XX`. |
| 253 | fn name_byte(b: u8) -> bool { |
| 254 | b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'/' | b'-') |
| 255 | } |
| 256 | |
| 257 | /// A name in descriptor text: its UTF-8 bytes, those outside |
| 258 | /// `A-Z a-z 0-9 _ . / -` as `%XX` (uppercase hex). |
| 259 | pub fn escape_name(name: &str) -> String { |
| 260 | let mut out = String::with_capacity(name.len()); |
| 261 | for &b in name.as_bytes() { |
| 262 | if name_byte(b) { |
| 263 | out.push(char::from(b)); |
| 264 | } else { |
| 265 | out.push_str(&format!("%{b:02X}")); |
| 266 | } |
| 267 | } |
| 268 | out |
| 269 | } |
| 270 | |
| 271 | struct Parser<'a> { |
| 272 | s: &'a [u8], |
| 273 | at: usize, |
| 274 | } |
| 275 | |
| 276 | impl<'a> Parser<'a> { |
| 277 | fn new(s: &'a [u8]) -> Result<Self, WireError> { |
| 278 | if let Some(i) = s.iter().position(|b| !b.is_ascii()) { |
| 279 | return err(i, "descriptor text is not ASCII"); |
| 280 | } |
| 281 | Ok(Parser { s, at: 0 }) |
| 282 | } |
| 283 | |
| 284 | fn peek(&self) -> Option<u8> { |
| 285 | self.s.get(self.at).copied() |
| 286 | } |
| 287 | |
| 288 | fn expect(&mut self, b: u8, what: &'static str) -> Result<(), WireError> { |
| 289 | if self.peek() != Some(b) { |
| 290 | return err(self.at, what); |
| 291 | } |
| 292 | self.at += 1; |
| 293 | Ok(()) |
| 294 | } |
| 295 | |
| 296 | /// A decimal count: no sign, no leading zero, at most `max`. |
| 297 | fn count(&mut self, max: u32) -> Result<u32, WireError> { |
| 298 | let start = self.at; |
| 299 | while self.peek().is_some_and(|b| b.is_ascii_digit()) { |
| 300 | self.at += 1; |
| 301 | } |
| 302 | let digits = &self.s[start..self.at]; |
| 303 | if digits.is_empty() { |
| 304 | return err(start, "expected a decimal count"); |
| 305 | } |
| 306 | if digits.len() > 1 && digits[0] == b'0' { |
| 307 | return err(start, "a count has no leading zero"); |
| 308 | } |
| 309 | if digits.len() > 9 { |
| 310 | return err(start, "count out of range"); |
| 311 | } |
| 312 | let n = digits |
| 313 | .iter() |
| 314 | .fold(0u32, |n, d| n * 10 + u32::from(d - b'0')); |
| 315 | if n > max { |
| 316 | return err(start, "count out of range"); |
| 317 | } |
| 318 | Ok(n) |
| 319 | } |
| 320 | |
| 321 | /// An escaped name up to its `;` (consumed); empty only if `may_be_empty`. |
| 322 | fn name(&mut self, may_be_empty: bool) -> Result<String, WireError> { |
| 323 | let start = self.at; |
| 324 | let mut out = Vec::new(); |
| 325 | loop { |
| 326 | match self.peek() { |
| 327 | None => return err(self.at, "unterminated name"), |
| 328 | Some(b';') => break, |
| 329 | Some(b'%') => { |
| 330 | let hex = |i: usize| { |
| 331 | self.s |
| 332 | .get(i) |
| 333 | .filter(|b| b.is_ascii_digit() || (b'A'..=b'F').contains(b)) |
| 334 | .map(|b| (*b as char).to_digit(16).expect("hex digit") as u8) |
| 335 | }; |
| 336 | let (Some(h), Some(l)) = (hex(self.at + 1), hex(self.at + 2)) else { |
| 337 | return err(self.at, "bad %XX escape in a name"); |
| 338 | }; |
| 339 | let b = h << 4 | l; |
| 340 | if name_byte(b) { |
| 341 | return err(self.at, "a name escapes a byte that stands for itself"); |
| 342 | } |
| 343 | out.push(b); |
| 344 | self.at += 3; |
| 345 | } |
| 346 | Some(b) if name_byte(b) => { |
| 347 | out.push(b); |
| 348 | self.at += 1; |
| 349 | } |
| 350 | Some(_) => return err(self.at, "unexpected byte in a name"), |
| 351 | } |
| 352 | if out.len() > MAX_NAME_LEN { |
| 353 | return err(start, "name too long"); |
| 354 | } |
| 355 | } |
| 356 | self.at += 1; // `;` |
| 357 | if out.is_empty() && !may_be_empty { |
| 358 | return err(start, "empty name"); |
| 359 | } |
| 360 | String::from_utf8(out).or_else(|_| err(start, "a name is not UTF-8")) |
| 361 | } |
| 362 | |
| 363 | fn desc(&mut self, params: u32, depth: usize) -> Result<Desc, WireError> { |
| 364 | if depth >= MAX_DESC_DEPTH { |
| 365 | return err(self.at, "descriptor nested too deeply"); |
| 366 | } |
| 367 | let at = self.at; |
| 368 | let Some(b) = self.peek() else { |
| 369 | return err(at, "expected a descriptor"); |
| 370 | }; |
| 371 | self.at += 1; |
| 372 | Ok(match b { |
| 373 | b'i' => Desc::Int, |
| 374 | b'f' => Desc::Float, |
| 375 | b's' => Desc::String, |
| 376 | b'b' => Desc::Bytes, |
| 377 | b'w' => Desc::U64, |
| 378 | b'd' => Desc::Dec, |
| 379 | b'p' => Desc::Pid, |
| 380 | b'u' => Desc::Unit, |
| 381 | b'S' => Desc::Subject(Box::new(self.desc(params, depth + 1)?)), |
| 382 | b'A' => Desc::Array(Box::new(self.desc(params, depth + 1)?)), |
| 383 | b'T' => { |
| 384 | let n = self.count(MAX_TUPLE)?; |
| 385 | if n < 2 { |
| 386 | return err(at, "a tuple has two components or more"); |
| 387 | } |
| 388 | let ds = (0..n) |
| 389 | .map(|_| self.desc(params, depth + 1)) |
| 390 | .collect::<Result<_, _>>()?; |
| 391 | Desc::Tuple(ds) |
| 392 | } |
| 393 | b'N' => { |
| 394 | let name = self.name(false)?; |
| 395 | let n = self.count(MAX_PARAMS)?; |
| 396 | let args = (0..n) |
| 397 | .map(|_| self.desc(params, depth + 1)) |
| 398 | .collect::<Result<_, _>>()?; |
| 399 | Desc::Adt { name, args } |
| 400 | } |
| 401 | b'$' => { |
| 402 | let i = self.count(MAX_PARAMS)?; |
| 403 | if i >= params { |
| 404 | return err(at, "parameter out of range"); |
| 405 | } |
| 406 | Desc::Param(i) |
| 407 | } |
| 408 | _ => return err(at, "unknown descriptor"), |
| 409 | }) |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | // ---- the type definitions table ------------------------------------------------------ |
| 414 | |
| 415 | /// A data type of the table: its constructors in runtime index order. |
| 416 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 417 | pub struct TypeDef { |
| 418 | pub name: String, |
| 419 | pub params: u32, |
| 420 | pub ctors: Vec<CtorDef>, |
| 421 | } |
| 422 | |
| 423 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 424 | pub struct CtorDef { |
| 425 | pub name: String, |
| 426 | pub fields: Vec<FieldDef>, |
| 427 | } |
| 428 | |
| 429 | /// A field: its label (empty when positional) and type, which may |
| 430 | /// mention the definition's parameters. |
| 431 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 432 | pub struct FieldDef { |
| 433 | pub label: String, |
| 434 | pub ty: Desc, |
| 435 | } |
| 436 | |
| 437 | /// How a constructor's values are represented at run time |
| 438 | /// (`docs/runtime-abi.md`, *Values*). |
| 439 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 440 | pub enum CtorRepr { |
| 441 | /// A nullary constructor: the small int of its index. |
| 442 | Immediate(u32), |
| 443 | /// A block whose tag is its index and whose fields are its fields, in |
| 444 | /// order. |
| 445 | Block { tag: u32, fields: u32 }, |
| 446 | } |
| 447 | |
| 448 | impl TypeDef { |
| 449 | /// The representation of constructor `index`. |
| 450 | /// |
| 451 | /// # Panics |
| 452 | /// If there is no such constructor. |
| 453 | pub fn repr(&self, index: u32) -> CtorRepr { |
| 454 | let fields = self.ctors[index as usize].fields.len() as u32; |
| 455 | if fields == 0 { |
| 456 | CtorRepr::Immediate(index) |
| 457 | } else { |
| 458 | CtorRepr::Block { tag: index, fields } |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | /// Every data type its field types apply, with the arguments, nested |
| 463 | /// ones included (`List<Option<a>>` gives `List` and `Option`). |
| 464 | fn references(&self) -> impl Iterator<Item = (&str, &[Desc])> { |
| 465 | let mut work: Vec<&Desc> = self |
| 466 | .ctors |
| 467 | .iter() |
| 468 | .flat_map(|c| c.fields.iter().map(|f| &f.ty)) |
| 469 | .collect(); |
| 470 | std::iter::from_fn(move || { |
| 471 | while let Some(ty) = work.pop() { |
| 472 | match ty { |
| 473 | Desc::Subject(x) | Desc::Array(x) => work.push(x), |
| 474 | Desc::Tuple(xs) => work.extend(xs), |
| 475 | Desc::Adt { name, args } => { |
| 476 | work.extend(args); |
| 477 | return Some((name.as_str(), args.as_slice())); |
| 478 | } |
| 479 | _ => {} |
| 480 | } |
| 481 | } |
| 482 | None |
| 483 | }) |
| 484 | } |
| 485 | |
| 486 | /// Its definition text (`docs/wire-format.md`, *The table*). |
| 487 | pub fn write(&self, out: &mut String) { |
| 488 | out.push('D'); |
| 489 | out.push_str(&escape_name(&self.name)); |
| 490 | out.push(';'); |
| 491 | out.push_str(&self.params.to_string()); |
| 492 | for c in &self.ctors { |
| 493 | out.push('C'); |
| 494 | out.push_str(&escape_name(&c.name)); |
| 495 | out.push(';'); |
| 496 | for f in &c.fields { |
| 497 | out.push('F'); |
| 498 | out.push_str(&escape_name(&f.label)); |
| 499 | out.push(';'); |
| 500 | out.push_str(&f.ty.to_string()); |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | /// A program's type definitions table: every data type a `Wire` |
| 507 | /// descriptor of the program reaches. |
| 508 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 509 | pub struct Table { |
| 510 | defs: Vec<TypeDef>, |
| 511 | by_name: BTreeMap<String, usize>, |
| 512 | } |
| 513 | |
| 514 | impl Table { |
| 515 | /// A table of `defs`, checked: unique names, well-formed constructors, |
| 516 | /// every reference to a defined type with as many arguments as it has |
| 517 | /// parameters. |
| 518 | pub fn new(defs: Vec<TypeDef>) -> Result<Table, WireError> { |
| 519 | if defs.len() > MAX_DEFS { |
| 520 | return err(0, "too many definitions"); |
| 521 | } |
| 522 | let mut by_name = BTreeMap::new(); |
| 523 | for (i, d) in defs.iter().enumerate() { |
| 524 | if by_name.insert(d.name.clone(), i).is_some() { |
| 525 | return err(i, "a type is defined twice"); |
| 526 | } |
| 527 | } |
| 528 | let table = Table { defs, by_name }; |
| 529 | for (i, d) in table.defs.iter().enumerate() { |
| 530 | table.check_def(d).map_err(|e| WireError { at: i, ..e })?; |
| 531 | } |
| 532 | table.check_regular()?; |
| 533 | Ok(table) |
| 534 | } |
| 535 | |
| 536 | /// Whether every recursion is regular (`docs/wire-format.md`, *Regular |
| 537 | /// types only*): a reference from a definition to one of its own |
| 538 | /// strongly connected component passes each argument as a bare |
| 539 | /// parameter or a closed type. A closed type then reaches finitely |
| 540 | /// many instances, each no bigger than it and the table's field types; |
| 541 | /// a nested type (`Nest<a> { Nil, Cons(a, Nest<(a, a)>) }`) reaches |
| 542 | /// instances that grow with the value. |
| 543 | fn check_regular(&self) -> Result<(), WireError> { |
| 544 | let component = self.components(); |
| 545 | for (i, d) in self.defs.iter().enumerate() { |
| 546 | let nested = d.references().any(|(name, args)| { |
| 547 | component[self.by_name[name]] == component[i] |
| 548 | && !args |
| 549 | .iter() |
| 550 | .all(|a| matches!(a, Desc::Param(_)) || a.is_closed()) |
| 551 | }); |
| 552 | if nested { |
| 553 | return err(i, "a recursive reference is not regular (a nested type)"); |
| 554 | } |
| 555 | } |
| 556 | Ok(()) |
| 557 | } |
| 558 | |
| 559 | /// The strongly connected component of each definition, in the graph |
| 560 | /// of references between definitions (Tarjan's algorithm, iterative: |
| 561 | /// a chain of definitions does not recurse on the native stack). |
| 562 | fn components(&self) -> Vec<usize> { |
| 563 | let edges: Vec<Vec<usize>> = self |
| 564 | .defs |
| 565 | .iter() |
| 566 | .map(|d| d.references().map(|(name, _)| self.by_name[name]).collect()) |
| 567 | .collect(); |
| 568 | let n = self.defs.len(); |
| 569 | let mut index: Vec<Option<usize>> = vec![None; n]; |
| 570 | let mut low = vec![0; n]; |
| 571 | let mut on_stack = vec![false; n]; |
| 572 | let mut stack = Vec::new(); |
| 573 | let mut component = vec![0; n]; |
| 574 | let (mut next_index, mut next_component) = (0, 0); |
| 575 | for root in 0..n { |
| 576 | if index[root].is_some() { |
| 577 | continue; |
| 578 | } |
| 579 | // (definition, its next edge to visit) |
| 580 | let mut calls = vec![(root, 0)]; |
| 581 | index[root] = Some(next_index); |
| 582 | low[root] = next_index; |
| 583 | next_index += 1; |
| 584 | stack.push(root); |
| 585 | on_stack[root] = true; |
| 586 | while let Some(&(v, e)) = calls.last() { |
| 587 | if let Some(&w) = edges[v].get(e) { |
| 588 | calls.last_mut().expect("a call").1 += 1; |
| 589 | match index[w] { |
| 590 | None => { |
| 591 | index[w] = Some(next_index); |
| 592 | low[w] = next_index; |
| 593 | next_index += 1; |
| 594 | stack.push(w); |
| 595 | on_stack[w] = true; |
| 596 | calls.push((w, 0)); |
| 597 | } |
| 598 | Some(iw) if on_stack[w] => low[v] = low[v].min(iw), |
| 599 | Some(_) => {} |
| 600 | } |
| 601 | continue; |
| 602 | } |
| 603 | calls.pop(); |
| 604 | if let Some(&(u, _)) = calls.last() { |
| 605 | low[u] = low[u].min(low[v]); |
| 606 | } |
| 607 | if Some(low[v]) == index[v] { |
| 608 | loop { |
| 609 | let w = stack.pop().expect("v is on the stack"); |
| 610 | on_stack[w] = false; |
| 611 | component[w] = next_component; |
| 612 | if w == v { |
| 613 | break; |
| 614 | } |
| 615 | } |
| 616 | next_component += 1; |
| 617 | } |
| 618 | } |
| 619 | } |
| 620 | component |
| 621 | } |
| 622 | |
| 623 | fn check_def(&self, d: &TypeDef) -> Result<(), WireError> { |
| 624 | if d.name.is_empty() || d.name.len() > MAX_NAME_LEN { |
| 625 | return err(0, "bad type name"); |
| 626 | } |
| 627 | if d.params > MAX_PARAMS { |
| 628 | return err(0, "too many type parameters"); |
| 629 | } |
| 630 | if d.ctors.len() > MAX_CTORS as usize { |
| 631 | return err(0, "too many constructors"); |
| 632 | } |
| 633 | let mut ctor_names = BTreeSet::new(); |
| 634 | for c in &d.ctors { |
| 635 | if c.name.is_empty() || c.name.len() > MAX_NAME_LEN || !ctor_names.insert(&c.name) { |
| 636 | return err(0, "bad or repeated constructor name"); |
| 637 | } |
| 638 | if c.fields.len() > MAX_FIELDS as usize { |
| 639 | return err(0, "too many fields"); |
| 640 | } |
| 641 | let mut labels = BTreeSet::new(); |
| 642 | for f in &c.fields { |
| 643 | if f.label.len() > MAX_NAME_LEN || (!f.label.is_empty() && !labels.insert(&f.label)) |
| 644 | { |
| 645 | return err(0, "bad or repeated field label"); |
| 646 | } |
| 647 | self.check_desc(&f.ty, d.params, 0)?; |
| 648 | } |
| 649 | } |
| 650 | Ok(()) |
| 651 | } |
| 652 | |
| 653 | /// Whether `ty` is well-formed here: parameters below `params`, every |
| 654 | /// data type defined and fully applied. |
| 655 | fn check_desc(&self, ty: &Desc, params: u32, depth: usize) -> Result<(), WireError> { |
| 656 | if depth >= MAX_DESC_DEPTH { |
| 657 | return err(0, "descriptor nested too deeply"); |
| 658 | } |
| 659 | match ty { |
| 660 | Desc::Param(i) if *i >= params => err(0, "parameter out of range"), |
| 661 | Desc::Subject(d) | Desc::Array(d) => self.check_desc(d, params, depth + 1), |
| 662 | Desc::Tuple(ds) => { |
| 663 | if ds.len() < 2 || ds.len() > MAX_TUPLE as usize { |
| 664 | return err(0, "bad tuple arity"); |
| 665 | } |
| 666 | ds.iter() |
| 667 | .try_for_each(|d| self.check_desc(d, params, depth + 1)) |
| 668 | } |
| 669 | Desc::Adt { name, args } => { |
| 670 | let Some(def) = self.get(name) else { |
| 671 | return err(0, "reference to an undefined type"); |
| 672 | }; |
| 673 | if args.len() != def.params as usize { |
| 674 | return err(0, "wrong number of type arguments"); |
| 675 | } |
| 676 | args.iter() |
| 677 | .try_for_each(|d| self.check_desc(d, params, depth + 1)) |
| 678 | } |
| 679 | _ => Ok(()), |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | /// The table's text (`docs/wire-format.md`, *The table*). |
| 684 | pub fn parse(text: &str) -> Result<Table, WireError> { |
| 685 | if text.len() > MAX_TABLE_LEN { |
| 686 | return err(0, "table too long"); |
| 687 | } |
| 688 | let mut p = Parser::new(text.as_bytes())?; |
| 689 | let mut defs = Vec::new(); |
| 690 | while p.peek().is_some() { |
| 691 | p.expect(b'D', "expected a definition (`D`)")?; |
| 692 | let name = p.name(false)?; |
| 693 | let params = p.count(MAX_PARAMS)?; |
| 694 | let mut ctors = Vec::new(); |
| 695 | while p.peek() == Some(b'C') { |
| 696 | p.at += 1; |
| 697 | let name = p.name(false)?; |
| 698 | let mut fields = Vec::new(); |
| 699 | while p.peek() == Some(b'F') { |
| 700 | p.at += 1; |
| 701 | let label = p.name(true)?; |
| 702 | let ty = p.desc(params, 0)?; |
| 703 | fields.push(FieldDef { label, ty }); |
| 704 | } |
| 705 | ctors.push(CtorDef { name, fields }); |
| 706 | } |
| 707 | defs.push(TypeDef { |
| 708 | name, |
| 709 | params, |
| 710 | ctors, |
| 711 | }); |
| 712 | } |
| 713 | Table::new(defs) |
| 714 | } |
| 715 | |
| 716 | /// Its text: what [`Table::parse`] reads back. |
| 717 | pub fn write(&self) -> String { |
| 718 | let mut out = String::new(); |
| 719 | self.defs.iter().for_each(|d| d.write(&mut out)); |
| 720 | out |
| 721 | } |
| 722 | |
| 723 | /// The definition of the data type `name`. |
| 724 | pub fn get(&self, name: &str) -> Option<&TypeDef> { |
| 725 | self.by_name.get(name).map(|&i| &self.defs[i]) |
| 726 | } |
| 727 | |
| 728 | pub fn defs(&self) -> &[TypeDef] { |
| 729 | &self.defs |
| 730 | } |
| 731 | |
| 732 | /// A closed descriptor read from `text` and checked against the table: |
| 733 | /// what the runtime does with a descriptor a program built. |
| 734 | pub fn parse_desc(&self, text: &str) -> Result<Desc, WireError> { |
| 735 | let d = Desc::parse(text)?; |
| 736 | self.check(&d)?; |
| 737 | Ok(d) |
| 738 | } |
| 739 | |
| 740 | /// Whether a closed descriptor is well-formed against the table. |
| 741 | pub fn check(&self, ty: &Desc) -> Result<(), WireError> { |
| 742 | self.check_desc(ty, 0, 0) |
| 743 | } |
| 744 | |
| 745 | /// The canonical form of a closed type (`docs/wire-format.md`, *The |
| 746 | /// structural type hash*): the version line, its descriptor, then the |
| 747 | /// definition of every data type it reaches, ordered by name, one per |
| 748 | /// line. |
| 749 | pub fn canonical(&self, ty: &Desc) -> Result<String, WireError> { |
| 750 | self.check(ty)?; |
| 751 | let mut reached = BTreeSet::new(); |
| 752 | let mut work = vec![ty]; |
| 753 | while let Some(d) = work.pop() { |
| 754 | match d { |
| 755 | Desc::Subject(x) | Desc::Array(x) => work.push(x), |
| 756 | Desc::Tuple(xs) => work.extend(xs), |
| 757 | Desc::Adt { name, args } => { |
| 758 | work.extend(args); |
| 759 | if reached.insert(name.as_str()) { |
| 760 | let def = self.get(name).expect("checked"); |
| 761 | work.extend( |
| 762 | def.ctors |
| 763 | .iter() |
| 764 | .flat_map(|c| c.fields.iter().map(|f| &f.ty)), |
| 765 | ); |
| 766 | } |
| 767 | } |
| 768 | _ => {} |
| 769 | } |
| 770 | } |
| 771 | let mut out = format!("{CANONICAL_VERSION}\n{ty}\n"); |
| 772 | // Sorted by name (a `BTreeSet<&str>` orders by bytes). |
| 773 | for name in reached { |
| 774 | self.get(name).expect("checked").write(&mut out); |
| 775 | out.push('\n'); |
| 776 | } |
| 777 | Ok(out) |
| 778 | } |
| 779 | |
| 780 | /// The structural hash of a closed type: [`hash_canonical`] of its |
| 781 | /// [canonical form](Table::canonical). |
| 782 | pub fn type_hash(&self, ty: &Desc) -> Result<u64, WireError> { |
| 783 | Ok(hash_canonical(self.canonical(ty)?.as_bytes())) |
| 784 | } |
| 785 | |
| 786 | /// The schema's canonical form (`docs/wire-format.md`, *The schema |
| 787 | /// hash*): [`SCHEMA_LINE`], then every definition, ordered by name, |
| 788 | /// one per line. Independent of the table's order. |
| 789 | pub fn schema(&self) -> String { |
| 790 | let mut out = format!("{SCHEMA_LINE}\n"); |
| 791 | // Sorted by name (a `BTreeMap<String, _>` orders by bytes). |
| 792 | for &i in self.by_name.values() { |
| 793 | self.defs[i].write(&mut out); |
| 794 | out.push('\n'); |
| 795 | } |
| 796 | out |
| 797 | } |
| 798 | |
| 799 | /// The schema hash, which two nodes compare in their handshake: |
| 800 | /// [`hash_canonical`] of the [schema's canonical form](Table::schema). |
| 801 | pub fn schema_hash(&self) -> u64 { |
| 802 | hash_canonical(self.schema().as_bytes()) |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | /// The first line of a schema's canonical form. A type's canonical form |
| 807 | /// starts with [`CANONICAL_VERSION`] alone on its line, so no schema |
| 808 | /// shares a form, or a hash input, with a type. |
| 809 | pub const SCHEMA_LINE: &str = "louise-wire/1 schema"; |
| 810 | |
| 811 | /// The first line of every canonical form. It changes, and with it every |
| 812 | /// hash, whenever the canonical form or the value encoding does. |
| 813 | pub const CANONICAL_VERSION: &str = "louise-wire/1"; |
| 814 | |
| 815 | /// The type hash of a canonical form: the first 8 bytes of its SHA-256, |
| 816 | /// big-endian. |
| 817 | pub fn hash_canonical(canonical: &[u8]) -> u64 { |
| 818 | let digest = sha256(canonical); |
| 819 | u64::from_be_bytes(digest[..8].try_into().expect("8 bytes")) |
| 820 | } |
| 821 | |
| 822 | /// The first line of a `@remote` entry's key input. No canonical form |
| 823 | /// or schema starts with it, so a key never shares a hash input with a |
| 824 | /// type. |
| 825 | pub const REMOTE_LINE: &str = "louise-remote/1"; |
| 826 | |
| 827 | /// The key of the `@remote` function named `qualified` (`module/path.name`, |
| 828 | /// UTF-8): [`hash_canonical`] of [`REMOTE_LINE`], LF, the name, shifted |
| 829 | /// right by 2. Below 2^62, so it is a non-negative small `Int` everywhere |
| 830 | /// and fits a frame's 8 bytes as a tag does (`docs/wire-format.md`, |
| 831 | /// *Remote entries*). |
| 832 | pub fn remote_key(qualified: &str) -> i64 { |
| 833 | let input = format!("{REMOTE_LINE}\n{qualified}"); |
| 834 | (hash_canonical(input.as_bytes()) >> 2) as i64 |
| 835 | } |
| 836 | |
| 837 | // ---- the value encoding's primitives ---------------------------------------------------- |
| 838 | |
| 839 | /// Unsigned LEB128, shortest form. |
| 840 | pub fn write_uvarint(out: &mut Vec<u8>, v: u64) { |
| 841 | write_uvarint128(out, u128::from(v)); |
| 842 | } |
| 843 | |
| 844 | pub fn write_uvarint128(out: &mut Vec<u8>, mut v: u128) { |
| 845 | loop { |
| 846 | let group = (v & 0x7F) as u8; |
| 847 | v >>= 7; |
| 848 | if v == 0 { |
| 849 | out.push(group); |
| 850 | return; |
| 851 | } |
| 852 | out.push(group | 0x80); |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | /// Zigzag: `0, -1, 1, -2, ...` to `0, 1, 2, 3, ...`. |
| 857 | pub fn zigzag(v: i128) -> u128 { |
| 858 | ((v << 1) ^ (v >> 127)) as u128 |
| 859 | } |
| 860 | |
| 861 | pub fn unzigzag(z: u128) -> i128 { |
| 862 | ((z >> 1) as i128) ^ -((z & 1) as i128) |
| 863 | } |
| 864 | |
| 865 | /// A node head: a new node and its kind-specific payload (a constructor |
| 866 | /// index, a length, or 0), or a back-reference to node `n`. |
| 867 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 868 | pub enum Head { |
| 869 | New(u64), |
| 870 | Back(u64), |
| 871 | } |
| 872 | |
| 873 | /// A head; its payload or node index is below 2^63. |
| 874 | pub fn write_head(out: &mut Vec<u8>, head: Head) { |
| 875 | debug_assert!(matches!(head, Head::New(n) | Head::Back(n) if n < 1 << 63)); |
| 876 | let h = match head { |
| 877 | Head::New(p) => u128::from(p) << 1, |
| 878 | Head::Back(n) => u128::from(n) << 1 | 1, |
| 879 | }; |
| 880 | write_uvarint128(out, h); |
| 881 | } |
| 882 | |
| 883 | /// An `Int`'s head: the integer itself, or a back-reference to a node |
| 884 | /// that is a big `Int`. |
| 885 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 886 | pub enum IntHead { |
| 887 | /// In [`SMALL_INT`]: an immediate, never a node. |
| 888 | Small(i64), |
| 889 | /// Outside it: a big integer, a new node. |
| 890 | Big(BigInt), |
| 891 | Back(u64), |
| 892 | } |
| 893 | |
| 894 | /// An `Int` (`docs/wire-format.md`, *Value encoding*): the shortest LEB128 |
| 895 | /// of `zigzag(n) << 1`, of any length. |
| 896 | pub fn write_int(out: &mut Vec<u8>, n: &BigInt) { |
| 897 | if let Ok(v) = i128::try_from(n) |
| 898 | && v.unsigned_abs() < 1 << 125 |
| 899 | { |
| 900 | write_uvarint128(out, zigzag(v) << 1); |
| 901 | return; |
| 902 | } |
| 903 | // zigzag(n) << 1 = 4|n| (n ≥ 0) or 4|n| − 2 (n < 0) |
| 904 | let mag = n.magnitude() << 2u32; |
| 905 | let h = if n.sign() == Sign::Minus { |
| 906 | mag - 2u32 |
| 907 | } else { |
| 908 | mag |
| 909 | }; |
| 910 | let groups = h.to_radix_le(128); |
| 911 | let last = groups.len() - 1; |
| 912 | out.extend( |
| 913 | groups |
| 914 | .iter() |
| 915 | .enumerate() |
| 916 | .map(|(i, g)| if i < last { g | 0x80 } else { *g }), |
| 917 | ); |
| 918 | } |
| 919 | |
| 920 | pub fn write_small_int(out: &mut Vec<u8>, n: i64) { |
| 921 | write_uvarint128(out, zigzag(i128::from(n)) << 1); |
| 922 | } |
| 923 | |
| 924 | pub fn write_float(out: &mut Vec<u8>, x: f64) { |
| 925 | out.extend_from_slice(&x.to_bits().to_le_bytes()); |
| 926 | } |
| 927 | |
| 928 | /// A cursor over a payload: every read checks the bytes left first. |
| 929 | pub struct Reader<'a> { |
| 930 | bytes: &'a [u8], |
| 931 | at: usize, |
| 932 | } |
| 933 | |
| 934 | impl<'a> Reader<'a> { |
| 935 | pub fn new(bytes: &'a [u8]) -> Self { |
| 936 | Reader { bytes, at: 0 } |
| 937 | } |
| 938 | |
| 939 | pub fn at(&self) -> usize { |
| 940 | self.at |
| 941 | } |
| 942 | |
| 943 | pub fn left(&self) -> usize { |
| 944 | self.bytes.len() - self.at |
| 945 | } |
| 946 | |
| 947 | pub fn is_empty(&self) -> bool { |
| 948 | self.left() == 0 |
| 949 | } |
| 950 | |
| 951 | fn fail<T>(&self, what: &'static str) -> Result<T, WireError> { |
| 952 | err(self.at, what) |
| 953 | } |
| 954 | |
| 955 | pub fn byte(&mut self) -> Result<u8, WireError> { |
| 956 | let Some(&b) = self.bytes.get(self.at) else { |
| 957 | return self.fail("payload ends early"); |
| 958 | }; |
| 959 | self.at += 1; |
| 960 | Ok(b) |
| 961 | } |
| 962 | |
| 963 | /// `n` bytes, checked against the bytes left before anything is |
| 964 | /// allocated for them. |
| 965 | pub fn take(&mut self, n: u64) -> Result<&'a [u8], WireError> { |
| 966 | if n > self.left() as u64 { |
| 967 | return self.fail("length past the end of the payload"); |
| 968 | } |
| 969 | let s = &self.bytes[self.at..self.at + n as usize]; |
| 970 | self.at += n as usize; |
| 971 | Ok(s) |
| 972 | } |
| 973 | |
| 974 | pub fn u64_le(&mut self) -> Result<u64, WireError> { |
| 975 | Ok(u64::from_le_bytes( |
| 976 | self.take(8)?.try_into().expect("8 bytes"), |
| 977 | )) |
| 978 | } |
| 979 | |
| 980 | pub fn float(&mut self) -> Result<f64, WireError> { |
| 981 | Ok(f64::from_bits(self.u64_le()?)) |
| 982 | } |
| 983 | |
| 984 | /// The groups of one LEB128 number, its last group not zero unless |
| 985 | /// it is the only one (shortest form). |
| 986 | fn groups(&mut self) -> Result<&'a [u8], WireError> { |
| 987 | let start = self.at; |
| 988 | let rest = &self.bytes[start..]; |
| 989 | let Some(len) = rest.iter().position(|b| b & 0x80 == 0).map(|i| i + 1) else { |
| 990 | return self.fail("payload ends inside a varint"); |
| 991 | }; |
| 992 | if len > 1 && rest[len - 1] == 0 { |
| 993 | return self.fail("varint not in shortest form"); |
| 994 | } |
| 995 | self.at += len; |
| 996 | Ok(&rest[..len]) |
| 997 | } |
| 998 | |
| 999 | /// A LEB128 number below `2^bits` (`bits` ≤ 128). |
| 1000 | fn uvarint_bits(&mut self, bits: u32) -> Result<u128, WireError> { |
| 1001 | let start = self.at; |
| 1002 | let g = self.groups()?; |
| 1003 | let max_groups = bits.div_ceil(7) as usize; |
| 1004 | // The last group of a full-length number holds the top bits only. |
| 1005 | let top_bits = bits - 7 * (max_groups as u32 - 1); |
| 1006 | if g.len() > max_groups || (g.len() == max_groups && g[g.len() - 1] >> top_bits != 0) { |
| 1007 | return err(start, "varint out of range"); |
| 1008 | } |
| 1009 | Ok(g.iter() |
| 1010 | .rev() |
| 1011 | .fold(0u128, |v, b| v << 7 | u128::from(b & 0x7F))) |
| 1012 | } |
| 1013 | |
| 1014 | /// A `U64`, a length, an index or a count. |
| 1015 | pub fn uvarint(&mut self) -> Result<u64, WireError> { |
| 1016 | Ok(self.uvarint_bits(64)? as u64) |
| 1017 | } |
| 1018 | |
| 1019 | /// A `Dec`: zigzag, then LEB128, of its `i128`. |
| 1020 | pub fn dec(&mut self) -> Result<i128, WireError> { |
| 1021 | Ok(unzigzag(self.uvarint_bits(128)?)) |
| 1022 | } |
| 1023 | |
| 1024 | pub fn head(&mut self) -> Result<Head, WireError> { |
| 1025 | let h = self.uvarint()?; |
| 1026 | Ok(if h & 1 == 1 { |
| 1027 | Head::Back(h >> 1) |
| 1028 | } else { |
| 1029 | Head::New(h >> 1) |
| 1030 | }) |
| 1031 | } |
| 1032 | |
| 1033 | /// An `Int`'s head, canonical: small exactly when in [`SMALL_INT`]. |
| 1034 | pub fn int(&mut self) -> Result<IntHead, WireError> { |
| 1035 | let start = self.at; |
| 1036 | let g = self.groups()?; |
| 1037 | let back = g[0] & 1 == 1; |
| 1038 | if g.len() <= 18 { |
| 1039 | // At most 126 bits. |
| 1040 | let h = g |
| 1041 | .iter() |
| 1042 | .rev() |
| 1043 | .fold(0u128, |v, b| v << 7 | u128::from(b & 0x7F)); |
| 1044 | if back { |
| 1045 | return u64::try_from(h >> 1) |
| 1046 | .map(IntHead::Back) |
| 1047 | .or_else(|_| err(start, "back-reference out of range")); |
| 1048 | } |
| 1049 | let v = unzigzag(h >> 1); |
| 1050 | return Ok(match i64::try_from(v) { |
| 1051 | Ok(s) if SMALL_INT.contains(&s) => IntHead::Small(s), |
| 1052 | _ => IntHead::Big(BigInt::from(v)), |
| 1053 | }); |
| 1054 | } |
| 1055 | if back { |
| 1056 | return err(start, "back-reference out of range"); |
| 1057 | } |
| 1058 | let digits: Vec<u8> = g.iter().map(|b| b & 0x7F).collect(); |
| 1059 | let h = BigUint::from_radix_le(&digits, 128).expect("7-bit digits"); |
| 1060 | let z: BigUint = h >> 1u32; |
| 1061 | // Over 126 bits: never small. |
| 1062 | let half = BigInt::from(&z >> 1u32); |
| 1063 | Ok(IntHead::Big(if z.bit(0) { -half - 1 } else { half })) |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | // ---- the message frame --------------------------------------------------------------- |
| 1068 | |
| 1069 | /// The header of a message frame (`docs/wire-format.md`, *Frames*): 36 |
| 1070 | /// bytes, little-endian. |
| 1071 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1072 | pub struct MessageHeader { |
| 1073 | /// The target actor: the receiving node's incarnation as the sender |
| 1074 | /// knows it, and the actor's serial there. |
| 1075 | pub incarnation: u64, |
| 1076 | pub serial: u64, |
| 1077 | /// The target subject's tag. |
| 1078 | pub tag: u64, |
| 1079 | pub type_hash: u64, |
| 1080 | pub payload_len: u32, |
| 1081 | } |
| 1082 | |
| 1083 | pub const HEADER_LEN: usize = 36; |
| 1084 | |
| 1085 | impl MessageHeader { |
| 1086 | pub fn encode(&self) -> [u8; HEADER_LEN] { |
| 1087 | let mut out = [0u8; HEADER_LEN]; |
| 1088 | out[0..8].copy_from_slice(&self.incarnation.to_le_bytes()); |
| 1089 | out[8..16].copy_from_slice(&self.serial.to_le_bytes()); |
| 1090 | out[16..24].copy_from_slice(&self.tag.to_le_bytes()); |
| 1091 | out[24..32].copy_from_slice(&self.type_hash.to_le_bytes()); |
| 1092 | out[32..36].copy_from_slice(&self.payload_len.to_le_bytes()); |
| 1093 | out |
| 1094 | } |
| 1095 | |
| 1096 | /// A header, its fields in range. |
| 1097 | pub fn decode(bytes: &[u8; HEADER_LEN]) -> Result<MessageHeader, WireError> { |
| 1098 | let word = |i: usize| u64::from_le_bytes(bytes[i..i + 8].try_into().expect("8 bytes")); |
| 1099 | let h = MessageHeader { |
| 1100 | incarnation: word(0), |
| 1101 | serial: word(8), |
| 1102 | tag: word(16), |
| 1103 | type_hash: word(24), |
| 1104 | payload_len: u32::from_le_bytes(bytes[32..36].try_into().expect("4 bytes")), |
| 1105 | }; |
| 1106 | if h.serial >= MAX_PID_SERIAL { |
| 1107 | return err(8, "pid serial out of range"); |
| 1108 | } |
| 1109 | if h.tag >= MAX_TAG { |
| 1110 | return err(16, "subject tag out of range"); |
| 1111 | } |
| 1112 | if h.payload_len > MAX_PAYLOAD { |
| 1113 | return err(32, "payload too large"); |
| 1114 | } |
| 1115 | Ok(h) |
| 1116 | } |
| 1117 | } |
| 1118 | |
| 1119 | /// Whether `name` is a node name: a lowercase DNS name (labels of |
| 1120 | /// `a-z 0-9 -`, 1 to 63 bytes, not starting or ending with `-`, |
| 1121 | /// separated by dots, the last not all digits), at most 253 bytes. Byte |
| 1122 | /// equality is then name equality. The last label rules out an IPv4 |
| 1123 | /// address, which a certificate would match against its IP addresses |
| 1124 | /// rather than its DNS names (RFC 1123 host names end with a letter label |
| 1125 | /// for the same reason). |
| 1126 | pub fn check_node_name(name: &[u8]) -> bool { |
| 1127 | let last = name.rsplit(|&b| b == b'.').next().unwrap_or_default(); |
| 1128 | !name.is_empty() |
| 1129 | && name.len() <= MAX_NODE_NAME |
| 1130 | && !last.iter().all(u8::is_ascii_digit) |
| 1131 | && name.split(|&b| b == b'.').all(|label| { |
| 1132 | !label.is_empty() |
| 1133 | && label.len() <= 63 |
| 1134 | && label.first() != Some(&b'-') |
| 1135 | && label.last() != Some(&b'-') |
| 1136 | && label |
| 1137 | .iter() |
| 1138 | .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') |
| 1139 | }) |
| 1140 | } |
| 1141 | |
| 1142 | // ---- SHA-256 (FIPS 180-4) ---------------------------------------------------------------- |
| 1143 | // The compiler and the runtime without its `crypto` feature have no `ring` |
| 1144 | // (Cargo.toml), and the hash must be the same everywhere: this one is |
| 1145 | // checked against `ring`'s and the standard's vectors. |
| 1146 | |
| 1147 | const K: [u32; 64] = [ |
| 1148 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, |
| 1149 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, |
| 1150 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, |
| 1151 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, |
| 1152 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, |
| 1153 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, |
| 1154 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, |
| 1155 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, |
| 1156 | ]; |
| 1157 | |
| 1158 | fn sha256(data: &[u8]) -> [u8; 32] { |
| 1159 | let mut h: [u32; 8] = [ |
| 1160 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, |
| 1161 | 0x5be0cd19, |
| 1162 | ]; |
| 1163 | // The message, a 1 bit, zeros, and its length in bits: whole blocks. |
| 1164 | let mut msg = data.to_vec(); |
| 1165 | msg.push(0x80); |
| 1166 | while msg.len() % 64 != 56 { |
| 1167 | msg.push(0); |
| 1168 | } |
| 1169 | msg.extend_from_slice(&((data.len() as u64).wrapping_mul(8)).to_be_bytes()); |
| 1170 | for block in msg.as_chunks::<64>().0 { |
| 1171 | let mut w = [0u32; 64]; |
| 1172 | for (i, word) in block.as_chunks::<4>().0.iter().enumerate() { |
| 1173 | w[i] = u32::from_be_bytes(*word); |
| 1174 | } |
| 1175 | for i in 16..64 { |
| 1176 | let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); |
| 1177 | let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); |
| 1178 | w[i] = w[i - 16] |
| 1179 | .wrapping_add(s0) |
| 1180 | .wrapping_add(w[i - 7]) |
| 1181 | .wrapping_add(s1); |
| 1182 | } |
| 1183 | let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; |
| 1184 | for i in 0..64 { |
| 1185 | let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); |
| 1186 | let ch = (e & f) ^ (!e & g); |
| 1187 | let t1 = hh |
| 1188 | .wrapping_add(s1) |
| 1189 | .wrapping_add(ch) |
| 1190 | .wrapping_add(K[i]) |
| 1191 | .wrapping_add(w[i]); |
| 1192 | let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); |
| 1193 | let maj = (a & b) ^ (a & c) ^ (b & c); |
| 1194 | let t2 = s0.wrapping_add(maj); |
| 1195 | hh = g; |
| 1196 | g = f; |
| 1197 | f = e; |
| 1198 | e = d.wrapping_add(t1); |
| 1199 | d = c; |
| 1200 | c = b; |
| 1201 | b = a; |
| 1202 | a = t1.wrapping_add(t2); |
| 1203 | } |
| 1204 | for (x, y) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { |
| 1205 | *x = x.wrapping_add(y); |
| 1206 | } |
| 1207 | } |
| 1208 | let mut out = [0u8; 32]; |
| 1209 | for (chunk, word) in out.as_chunks_mut::<4>().0.iter_mut().zip(h) { |
| 1210 | *chunk = word.to_be_bytes(); |
| 1211 | } |
| 1212 | out |
| 1213 | } |
| 1214 | |
| 1215 | #[cfg(test)] |
| 1216 | mod tests { |
| 1217 | use super::*; |
| 1218 | |
| 1219 | fn adt(name: &str, args: Vec<Desc>) -> Desc { |
| 1220 | Desc::Adt { |
| 1221 | name: name.into(), |
| 1222 | args, |
| 1223 | } |
| 1224 | } |
| 1225 | |
| 1226 | /// The prelude's types and `docs/wire-format.md`'s example, as the |
| 1227 | /// compiler would emit them. |
| 1228 | const TABLE: &str = "Dstd/prelude.Bool;0CFalse;CTrue;\ |
| 1229 | Dstd/prelude.List;1CNil;CCons;F;$0F;Nstd/prelude.List;1$0\ |
| 1230 | Dstd/process.ExitReason;0CNormal;CKilled;CCrashed;F;sCShutdown;\ |
| 1231 | Ddemo.Task;1CDone;CStep;Fpayload;$0Freply;SiFnext;Ndemo.Task;1$0\ |
| 1232 | Dstd/prelude.Never;0"; |
| 1233 | |
| 1234 | fn table() -> Table { |
| 1235 | Table::parse(TABLE).unwrap() |
| 1236 | } |
| 1237 | |
| 1238 | #[test] |
| 1239 | fn descriptors_round_trip() { |
| 1240 | for text in [ |
| 1241 | "i", |
| 1242 | "f", |
| 1243 | "s", |
| 1244 | "b", |
| 1245 | "w", |
| 1246 | "d", |
| 1247 | "p", |
| 1248 | "u", |
| 1249 | "Si", |
| 1250 | "AAs", |
| 1251 | "T2is", |
| 1252 | "T3uSpAd", |
| 1253 | "Nstd/prelude.Bool;0", |
| 1254 | "Nstd/prelude.List;1T2iNstd/prelude.List;1s", |
| 1255 | "Napp/donn%C3%A9es.Th%C3%A9;0", |
| 1256 | "Nmy-pkg/x_y.Z;2wS$1", |
| 1257 | ] { |
| 1258 | let params = if text.contains('$') { 2 } else { 0 }; |
| 1259 | let d = Desc::parse_open(text, params).unwrap(); |
| 1260 | assert_eq!(d.to_string(), text); |
| 1261 | assert_eq!(d.is_closed(), params == 0, "{text}"); |
| 1262 | } |
| 1263 | assert_eq!( |
| 1264 | Desc::parse("Nstd/prelude.List;1i").unwrap(), |
| 1265 | adt("std/prelude.List", vec![Desc::Int]) |
| 1266 | ); |
| 1267 | assert_eq!(escape_name("app/données.Thé"), "app/donn%C3%A9es.Th%C3%A9"); |
| 1268 | assert_eq!( |
| 1269 | Desc::parse("Napp/donn%C3%A9es.Th%C3%A9;0").unwrap(), |
| 1270 | adt("app/données.Thé", vec![]) |
| 1271 | ); |
| 1272 | } |
| 1273 | |
| 1274 | #[test] |
| 1275 | fn malformed_descriptors_are_refused() { |
| 1276 | let deep = format!("{}i", "A".repeat(MAX_DESC_DEPTH)); |
| 1277 | let wide = format!("T255{}", "i".repeat(255)); |
| 1278 | for (text, at, what) in [ |
| 1279 | ("", 0, "expected a descriptor"), |
| 1280 | ("x", 0, "unknown descriptor"), |
| 1281 | ("ii", 1, "trailing bytes after the descriptor"), |
| 1282 | ("T1i", 0, "a tuple has two components or more"), |
| 1283 | ("T2i", 3, "expected a descriptor"), |
| 1284 | ("T02ii", 1, "a count has no leading zero"), |
| 1285 | ("T", 1, "expected a decimal count"), |
| 1286 | ("T9999999999i", 1, "count out of range"), |
| 1287 | (wide.as_str(), 1, "count out of range"), |
| 1288 | ("Nfoo", 4, "unterminated name"), |
| 1289 | ("Nfoo;", 5, "expected a decimal count"), |
| 1290 | ("N;0", 1, "empty name"), |
| 1291 | ("Nfoo;1", 6, "expected a descriptor"), |
| 1292 | ("Na b;0", 2, "unexpected byte in a name"), |
| 1293 | ("N%41;0", 1, "a name escapes a byte that stands for itself"), |
| 1294 | ("N%e9;0", 1, "bad %XX escape in a name"), |
| 1295 | ("N%E;0", 1, "bad %XX escape in a name"), |
| 1296 | ("N%FF;0", 1, "a name is not UTF-8"), |
| 1297 | ("$0", 0, "parameter out of range"), |
| 1298 | ("Sé", 1, "descriptor text is not ASCII"), |
| 1299 | ( |
| 1300 | deep.as_str(), |
| 1301 | MAX_DESC_DEPTH, |
| 1302 | "descriptor nested too deeply", |
| 1303 | ), |
| 1304 | ] { |
| 1305 | assert_eq!(Desc::parse(text), Err(WireError { at, what }), "{text:?}"); |
| 1306 | } |
| 1307 | assert!(Desc::parse(&"i".repeat(MAX_DESC_LEN + 1)).is_err()); |
| 1308 | // Nesting just under the limit is fine. |
| 1309 | let ok = format!("{}i", "A".repeat(MAX_DESC_DEPTH - 1)); |
| 1310 | assert!(Desc::parse(&ok).is_ok()); |
| 1311 | } |
| 1312 | |
| 1313 | /// The compiler emits a generic instantiation as these pieces, with |
| 1314 | /// each hole filled by the type argument's descriptor at run time. |
| 1315 | #[test] |
| 1316 | fn pieces_concatenate_to_the_instance() { |
| 1317 | let generic = Desc::parse_open("T2$0SNdemo.Task;1$1", 2).unwrap(); |
| 1318 | assert_eq!( |
| 1319 | generic.pieces(), |
| 1320 | [ |
| 1321 | Piece::Lit("T2".into()), |
| 1322 | Piece::Hole(0), |
| 1323 | Piece::Lit("SNdemo.Task;1".into()), |
| 1324 | Piece::Hole(1), |
| 1325 | ] |
| 1326 | ); |
| 1327 | let args = [Desc::parse("Nstd/prelude.List;1i").unwrap(), Desc::String]; |
| 1328 | let built: String = generic |
| 1329 | .pieces() |
| 1330 | .iter() |
| 1331 | .map(|p| match p { |
| 1332 | Piece::Lit(s) => s.clone(), |
| 1333 | Piece::Hole(i) => args[*i as usize].to_string(), |
| 1334 | }) |
| 1335 | .collect(); |
| 1336 | assert_eq!(built, generic.instantiate(&args).to_string()); |
| 1337 | assert_eq!(built, "T2Nstd/prelude.List;1iSNdemo.Task;1s"); |
| 1338 | // A monomorphic type is one literal. |
| 1339 | let mono = Desc::parse("ANstd/prelude.List;1T2fs").unwrap(); |
| 1340 | assert_eq!( |
| 1341 | mono.pieces(), |
| 1342 | [Piece::Lit("ANstd/prelude.List;1T2fs".into())] |
| 1343 | ); |
| 1344 | assert_eq!(adt_prefix("app/thé.T", 2), "Napp/th%C3%A9.T;2"); |
| 1345 | assert_eq!(tuple_prefix(3), "T3"); |
| 1346 | } |
| 1347 | |
| 1348 | #[test] |
| 1349 | fn tables_round_trip_and_resolve() { |
| 1350 | let t = table(); |
| 1351 | assert_eq!(t.write(), TABLE); |
| 1352 | assert_eq!(t.defs().len(), 5); |
| 1353 | let list = t.get("std/prelude.List").unwrap(); |
| 1354 | assert_eq!(list.params, 1); |
| 1355 | assert_eq!(list.repr(0), CtorRepr::Immediate(0)); |
| 1356 | assert_eq!(list.repr(1), CtorRepr::Block { tag: 1, fields: 2 }); |
| 1357 | // Indices count nullary and boxed constructors alike. |
| 1358 | let reason = t.get("std/process.ExitReason").unwrap(); |
| 1359 | assert_eq!(reason.repr(2), CtorRepr::Block { tag: 2, fields: 1 }); |
| 1360 | assert_eq!(reason.repr(3), CtorRepr::Immediate(3)); |
| 1361 | assert!(t.get("std/prelude.Never").unwrap().ctors.is_empty()); |
| 1362 | let task = t.get("demo.Task").unwrap(); |
| 1363 | assert_eq!( |
| 1364 | task.ctors[1] |
| 1365 | .fields |
| 1366 | .iter() |
| 1367 | .map(|f| f.ty.instantiate(&[Desc::String]).to_string()) |
| 1368 | .collect::<Vec<_>>(), |
| 1369 | ["s", "Si", "Ndemo.Task;1s"] |
| 1370 | ); |
| 1371 | assert_eq!( |
| 1372 | t.parse_desc("Ndemo.Task;1As").unwrap().to_string(), |
| 1373 | "Ndemo.Task;1As" |
| 1374 | ); |
| 1375 | for (text, what) in [ |
| 1376 | ("Nnope;0", "reference to an undefined type"), |
| 1377 | ("Nstd/prelude.List;0", "wrong number of type arguments"), |
| 1378 | ("Nstd/prelude.List;2ii", "wrong number of type arguments"), |
| 1379 | ("ANstd/prelude.Bool;1i", "wrong number of type arguments"), |
| 1380 | ] { |
| 1381 | assert_eq!(t.parse_desc(text).unwrap_err().what, what, "{text}"); |
| 1382 | } |
| 1383 | } |
| 1384 | |
| 1385 | #[test] |
| 1386 | fn malformed_tables_are_refused() { |
| 1387 | for (text, what) in [ |
| 1388 | ("X", "expected a definition (`D`)"), |
| 1389 | ("Da;0Da;0", "a type is defined twice"), |
| 1390 | ("Da;0CX;CX;", "bad or repeated constructor name"), |
| 1391 | ("Da;0C;", "empty name"), |
| 1392 | ("Da;0CX;Fl;iFl;s", "bad or repeated field label"), |
| 1393 | ("Da;1CX;F;$1", "parameter out of range"), |
| 1394 | ("Da;0CX;F;Nb;0", "reference to an undefined type"), |
| 1395 | ("Da;1CX;F;Na;0", "wrong number of type arguments"), |
| 1396 | ("Da;0CX;F;", "expected a descriptor"), |
| 1397 | ("Da;0CX;F;ii", "expected a definition (`D`)"), |
| 1398 | ("Da;256", "count out of range"), |
| 1399 | ] { |
| 1400 | assert_eq!(Table::parse(text).unwrap_err().what, what, "{text}"); |
| 1401 | } |
| 1402 | // Positional fields share the empty label. |
| 1403 | assert!(Table::parse("Da;0CX;F;iF;i").is_ok()); |
| 1404 | let wide = TypeDef { |
| 1405 | name: "a".into(), |
| 1406 | params: 0, |
| 1407 | ctors: vec![CtorDef { |
| 1408 | name: "X".into(), |
| 1409 | fields: vec![ |
| 1410 | FieldDef { |
| 1411 | label: String::new(), |
| 1412 | ty: Desc::Int |
| 1413 | }; |
| 1414 | MAX_FIELDS as usize + 1 |
| 1415 | ], |
| 1416 | }], |
| 1417 | }; |
| 1418 | assert_eq!(Table::new(vec![wide]).unwrap_err().what, "too many fields"); |
| 1419 | } |
| 1420 | |
| 1421 | #[test] |
| 1422 | fn canonical_forms_expand_reachable_definitions_once() { |
| 1423 | let t = table(); |
| 1424 | let ty = Desc::parse("Ndemo.Task;1s").unwrap(); |
| 1425 | assert_eq!( |
| 1426 | t.canonical(&ty).unwrap(), |
| 1427 | "louise-wire/1\n\ |
| 1428 | Ndemo.Task;1s\n\ |
| 1429 | Ddemo.Task;1CDone;CStep;Fpayload;$0Freply;SiFnext;Ndemo.Task;1$0\n" |
| 1430 | ); |
| 1431 | // Definitions sorted by name, each once, whatever the table's order |
| 1432 | // and whatever else it holds. |
| 1433 | let ty = Desc::parse("T2Nstd/prelude.List;1Nstd/prelude.Bool;0Ndemo.Task;1i").unwrap(); |
| 1434 | let canonical = t.canonical(&ty).unwrap(); |
| 1435 | assert_eq!( |
| 1436 | canonical, |
| 1437 | "louise-wire/1\n\ |
| 1438 | T2Nstd/prelude.List;1Nstd/prelude.Bool;0Ndemo.Task;1i\n\ |
| 1439 | Ddemo.Task;1CDone;CStep;Fpayload;$0Freply;SiFnext;Ndemo.Task;1$0\n\ |
| 1440 | Dstd/prelude.Bool;0CFalse;CTrue;\n\ |
| 1441 | Dstd/prelude.List;1CNil;CCons;F;$0F;Nstd/prelude.List;1$0\n" |
| 1442 | ); |
| 1443 | let mut defs = t.defs().to_vec(); |
| 1444 | defs.reverse(); |
| 1445 | defs.retain(|d| d.name != "std/process.ExitReason"); |
| 1446 | assert_eq!(Table::new(defs).unwrap().canonical(&ty).unwrap(), canonical); |
| 1447 | // Leaves reach no definition. |
| 1448 | assert_eq!(t.canonical(&Desc::Int).unwrap(), "louise-wire/1\ni\n"); |
| 1449 | } |
| 1450 | |
| 1451 | #[test] |
| 1452 | fn recursion_terminates() { |
| 1453 | // Mutual recursion, arguments permuted or closed: definitions are |
| 1454 | // expanded, not instances. |
| 1455 | let t = Table::parse( |
| 1456 | "Dm.Even;0CZ;CE;F;Nm.Odd;0\ |
| 1457 | Dm.Odd;0CO;F;Nm.Even;0\ |
| 1458 | Dm.Swap;2CS;F;$0F;Nm.Swap;2$1$0\ |
| 1459 | Dm.Fix;1CX;F;$0F;Nm.Fix;1T2ii", |
| 1460 | ) |
| 1461 | .unwrap(); |
| 1462 | let even = t.canonical(&Desc::parse("Nm.Even;0").unwrap()).unwrap(); |
| 1463 | assert_eq!(even.lines().count(), 4); |
| 1464 | let swap = t.canonical(&Desc::parse("Nm.Swap;2is").unwrap()).unwrap(); |
| 1465 | assert_eq!(swap.lines().count(), 3); |
| 1466 | let fix = t.canonical(&Desc::parse("Nm.Fix;1s").unwrap()).unwrap(); |
| 1467 | assert_eq!(fix.lines().count(), 3); |
| 1468 | } |
| 1469 | |
| 1470 | /// A nested type's instances grow with its values (`Nest`'s n-th cell |
| 1471 | /// is at a type of 2^n leaves): the table refuses it, directly or |
| 1472 | /// through mutual recursion, and only it. |
| 1473 | #[test] |
| 1474 | fn nested_types_are_refused() { |
| 1475 | for (text, at) in [ |
| 1476 | ("Dm.Nest;1CNil;CCons;F;$0F;Nm.Nest;1T2$0$0", 0), |
| 1477 | ("Dm.Nest;1CNil;CCons;F;$0F;ANm.Nest;1A$0", 0), |
| 1478 | ("Dm.A;1CX;F;Nm.B;1$0Dm.B;1CY;F;Nm.A;1S$0", 1), |
| 1479 | ( |
| 1480 | "Dm.Ok;0CO;Dm.A;1CX;F;Nm.A;1Nm.L;1$0Dm.L;1CN;CC;F;$0F;Nm.L;1$0", |
| 1481 | 1, |
| 1482 | ), |
| 1483 | ] { |
| 1484 | assert_eq!( |
| 1485 | Table::parse(text).unwrap_err(), |
| 1486 | WireError { |
| 1487 | at, |
| 1488 | what: "a recursive reference is not regular (a nested type)" |
| 1489 | }, |
| 1490 | "{text}" |
| 1491 | ); |
| 1492 | } |
| 1493 | // Compound arguments to a type outside the recursion are fine. |
| 1494 | Table::parse( |
| 1495 | "Dm.L;1CN;CC;F;$0F;Nm.L;1$0\ |
| 1496 | Dm.T;1CLeaf;CNode;F;Nm.L;1T2$0Nm.T;1$0", |
| 1497 | ) |
| 1498 | .unwrap(); |
| 1499 | } |
| 1500 | |
| 1501 | /// Names, labels and constructor order are part of a type's meaning, |
| 1502 | /// parameter names are not (they are positions). |
| 1503 | #[test] |
| 1504 | fn hashes_follow_meaning() { |
| 1505 | let hash = |table: &str, ty: &str| { |
| 1506 | let t = Table::parse(table).unwrap(); |
| 1507 | t.type_hash(&t.parse_desc(ty).unwrap()).unwrap() |
| 1508 | }; |
| 1509 | let base = hash("Dm.P;0CP;Fx;iFy;i", "Nm.P;0"); |
| 1510 | for (table, ty) in [ |
| 1511 | ("Dm.Q;0CP;Fx;iFy;i", "Nm.Q;0"), // type name |
| 1512 | ("Dm.P;0CQ;Fx;iFy;i", "Nm.P;0"), // constructor name |
| 1513 | ("Dm.P;0CP;Fx;iFz;i", "Nm.P;0"), // label |
| 1514 | ("Dm.P;0CP;Fy;iFx;i", "Nm.P;0"), // field order |
| 1515 | ("Dm.P;0CP;Fx;iFy;f", "Nm.P;0"), // field type |
| 1516 | ("Dm.P;0CP;Fx;iFy;iCR;", "Nm.P;0"), // a new constructor |
| 1517 | ] { |
| 1518 | assert_ne!(hash(table, ty), base, "{table}"); |
| 1519 | } |
| 1520 | // An unrelated definition changes nothing. |
| 1521 | assert_eq!(hash("Dm.P;0CP;Fx;iFy;iDm.U;0CU;", "Nm.P;0"), base); |
| 1522 | let swapped = hash("Dm.E;0CA;CB;", "Nm.E;0"); |
| 1523 | assert_ne!(hash("Dm.E;0CB;CA;", "Nm.E;0"), swapped); |
| 1524 | } |
| 1525 | |
| 1526 | /// Hashes are part of the protocol: these values must never change |
| 1527 | /// without a new `CANONICAL_VERSION`. |
| 1528 | #[test] |
| 1529 | fn hashes_are_stable() { |
| 1530 | let t = table(); |
| 1531 | let h = |ty: &str| t.type_hash(&t.parse_desc(ty).unwrap()).unwrap(); |
| 1532 | // Python's `hashlib.sha256(canonical).digest()[:8].hex()`. |
| 1533 | assert_eq!(h("i"), 0xa1f9_0d70_e682_6ce8); |
| 1534 | assert_eq!(h("Nstd/prelude.List;1i"), 0x75e3_aca9_dd86_7f77); |
| 1535 | assert_eq!(h("Ndemo.Task;1s"), 0x9949_47b8_73cb_1aa7); |
| 1536 | } |
| 1537 | |
| 1538 | /// The schema covers every definition, whatever the table's order; a |
| 1539 | /// golden value pins its form. |
| 1540 | #[test] |
| 1541 | fn schema_hashes_cover_the_whole_table() { |
| 1542 | let t = table(); |
| 1543 | let mut reversed = t.defs().to_vec(); |
| 1544 | reversed.reverse(); |
| 1545 | let r = Table::new(reversed).unwrap(); |
| 1546 | assert_eq!(r.schema(), t.schema()); |
| 1547 | assert_eq!(r.schema_hash(), t.schema_hash()); |
| 1548 | assert!(t.schema().starts_with("louise-wire/1 schema\nDdemo.Task;1")); |
| 1549 | assert_eq!(t.schema().lines().count(), 1 + t.defs().len()); |
| 1550 | let fewer = Table::new(t.defs()[..4].to_vec()).unwrap(); |
| 1551 | assert_ne!(fewer.schema_hash(), t.schema_hash()); |
| 1552 | assert_eq!(Table::default().schema(), "louise-wire/1 schema\n"); |
| 1553 | // Python: `hashlib.sha256(schema).digest()[:8].hex()`. |
| 1554 | assert_eq!(t.schema_hash(), 0x4259_3343_7b01_fc4c); |
| 1555 | } |
| 1556 | |
| 1557 | /// Golden values, from Python: `int.from_bytes(hashlib.sha256( |
| 1558 | /// b"louise-remote/1\n" + name).digest()[:8], "big") >> 2`. |
| 1559 | #[test] |
| 1560 | fn remote_keys_are_small_ints() { |
| 1561 | assert_eq!(remote_key("demo.worker"), 0x0daa_e2c2_50d5_6ded); |
| 1562 | assert_eq!(remote_key("app/données.thé"), 0x019e_5a45_bd38_b345); |
| 1563 | for name in ["a.b", "demo.worker", "x/y.z"] { |
| 1564 | assert!(SMALL_INT.contains(&remote_key(name)) && remote_key(name) >= 0); |
| 1565 | } |
| 1566 | assert_ne!(remote_key("demo.worker"), remote_key("demo.worker2")); |
| 1567 | } |
| 1568 | |
| 1569 | #[test] |
| 1570 | fn sha256_matches_the_standard() { |
| 1571 | let hex = |d: [u8; 32]| d.iter().map(|b| format!("{b:02x}")).collect::<String>(); |
| 1572 | assert_eq!( |
| 1573 | hex(sha256(b"")), |
| 1574 | "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" |
| 1575 | ); |
| 1576 | assert_eq!( |
| 1577 | hex(sha256(b"abc")), |
| 1578 | "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" |
| 1579 | ); |
| 1580 | assert_eq!( |
| 1581 | hex(sha256( |
| 1582 | b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" |
| 1583 | )), |
| 1584 | "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" |
| 1585 | ); |
| 1586 | #[cfg(feature = "crypto")] |
| 1587 | for n in [0, 1, 55, 56, 63, 64, 65, 119, 120, 1000] { |
| 1588 | let data: Vec<u8> = (0..n).map(|i| (i * 7 + 3) as u8).collect(); |
| 1589 | assert_eq!(sha256(&data), crate::crypto::sha256(&data), "{n} bytes"); |
| 1590 | } |
| 1591 | } |
| 1592 | |
| 1593 | #[test] |
| 1594 | fn varints_are_shortest_and_bounded() { |
| 1595 | for v in [0, 1, 127, 128, 300, u64::from(u32::MAX), u64::MAX] { |
| 1596 | let mut out = Vec::new(); |
| 1597 | write_uvarint(&mut out, v); |
| 1598 | let mut r = Reader::new(&out); |
| 1599 | assert_eq!(r.uvarint(), Ok(v)); |
| 1600 | assert!(r.is_empty()); |
| 1601 | } |
| 1602 | let mut out = Vec::new(); |
| 1603 | write_uvarint(&mut out, 300); |
| 1604 | assert_eq!(out, [0xAC, 0x02]); |
| 1605 | let bad = |bytes: &[u8]| Reader::new(bytes).uvarint().unwrap_err().what; |
| 1606 | assert_eq!(bad(&[0x80, 0x00]), "varint not in shortest form"); |
| 1607 | assert_eq!(bad(&[0x80]), "payload ends inside a varint"); |
| 1608 | assert_eq!(bad(&[]), "payload ends inside a varint"); |
| 1609 | // 2^64 needs a 2 in the tenth group. |
| 1610 | let mut over = vec![0x80; 9]; |
| 1611 | over.push(0x02); |
| 1612 | assert_eq!(bad(&over), "varint out of range"); |
| 1613 | assert_eq!(bad(&[0x80; 11]), "payload ends inside a varint"); |
| 1614 | for d in [0, 1, -1, i128::MAX, i128::MIN, 10i128.pow(18)] { |
| 1615 | let mut out = Vec::new(); |
| 1616 | write_uvarint128(&mut out, zigzag(d)); |
| 1617 | assert!(out.len() <= 19); |
| 1618 | assert_eq!(Reader::new(&out).dec(), Ok(d)); |
| 1619 | } |
| 1620 | assert_eq!(zigzag(-1), 1); |
| 1621 | assert_eq!(zigzag(1), 2); |
| 1622 | } |
| 1623 | |
| 1624 | #[test] |
| 1625 | fn ints_are_canonical_whatever_their_size() { |
| 1626 | let encode = |n: &BigInt| { |
| 1627 | let mut out = Vec::new(); |
| 1628 | write_int(&mut out, n); |
| 1629 | out |
| 1630 | }; |
| 1631 | assert_eq!(encode(&BigInt::from(0)), [0x00]); |
| 1632 | assert_eq!(encode(&BigInt::from(-1)), [0x02]); |
| 1633 | assert_eq!(encode(&BigInt::from(1)), [0x04]); |
| 1634 | assert_eq!(encode(&BigInt::from(31)), [0x7C]); |
| 1635 | assert_eq!(encode(&BigInt::from(32)), [0x80, 0x01]); |
| 1636 | let small_max = SMALL_INT.end - 1; |
| 1637 | let big = |s: &str| s.parse::<BigInt>().unwrap(); |
| 1638 | for n in [ |
| 1639 | BigInt::from(0), |
| 1640 | BigInt::from(-7), |
| 1641 | BigInt::from(small_max), |
| 1642 | BigInt::from(SMALL_INT.start), |
| 1643 | BigInt::from(small_max) + 1, |
| 1644 | BigInt::from(SMALL_INT.start) - 1, |
| 1645 | BigInt::from(i64::MAX), |
| 1646 | BigInt::from(i64::MIN), |
| 1647 | BigInt::from(i128::MAX), |
| 1648 | BigInt::from(i128::MIN), |
| 1649 | big("-123456789012345678901234567890123456789012345678901234567890"), |
| 1650 | big("340282366920938463463374607431768211456"), // 2^128 |
| 1651 | BigInt::from(1) << 125u32, |
| 1652 | -(BigInt::from(1) << 125u32), |
| 1653 | ] { |
| 1654 | let bytes = encode(&n); |
| 1655 | let mut r = Reader::new(&bytes); |
| 1656 | let head = r.int().unwrap(); |
| 1657 | assert!(r.is_empty(), "{n}"); |
| 1658 | let small = i64::try_from(&n).ok().filter(|v| SMALL_INT.contains(v)); |
| 1659 | match (small, head) { |
| 1660 | (Some(v), IntHead::Small(w)) => assert_eq!(v, w), |
| 1661 | (None, IntHead::Big(m)) => assert_eq!(m, n), |
| 1662 | (_, other) => panic!("{n} decoded as {other:?}"), |
| 1663 | } |
| 1664 | if let Some(v) = small { |
| 1665 | let mut out = Vec::new(); |
| 1666 | write_small_int(&mut out, v); |
| 1667 | assert_eq!(out, bytes); |
| 1668 | } |
| 1669 | } |
| 1670 | // Back-references share the low bit with the integers. |
| 1671 | let mut out = Vec::new(); |
| 1672 | write_head(&mut out, Head::Back(5)); |
| 1673 | assert_eq!(out, [0x0B]); |
| 1674 | assert_eq!(Reader::new(&out).int(), Ok(IntHead::Back(5))); |
| 1675 | assert_eq!(Reader::new(&out).head(), Ok(Head::Back(5))); |
| 1676 | assert_eq!( |
| 1677 | Reader::new(&[0x80, 0x00]).int().unwrap_err().what, |
| 1678 | "varint not in shortest form" |
| 1679 | ); |
| 1680 | } |
| 1681 | |
| 1682 | #[test] |
| 1683 | fn readers_check_lengths_before_taking() { |
| 1684 | let mut r = Reader::new(&[1, 2, 3]); |
| 1685 | assert_eq!( |
| 1686 | r.take(4).unwrap_err().what, |
| 1687 | "length past the end of the payload" |
| 1688 | ); |
| 1689 | assert_eq!( |
| 1690 | r.take(u64::MAX).unwrap_err().what, |
| 1691 | "length past the end of the payload" |
| 1692 | ); |
| 1693 | assert_eq!(r.take(2), Ok(&[1, 2][..])); |
| 1694 | assert_eq!(r.left(), 1); |
| 1695 | assert_eq!(r.u64_le().unwrap_err().at, 2); |
| 1696 | let nan = f64::from_bits(0x7FF4_0000_0000_0001); |
| 1697 | let mut out = Vec::new(); |
| 1698 | write_float(&mut out, nan); |
| 1699 | assert_eq!(Reader::new(&out).float().unwrap().to_bits(), nan.to_bits()); |
| 1700 | } |
| 1701 | |
| 1702 | #[test] |
| 1703 | fn headers_round_trip_and_are_bounded() { |
| 1704 | let h = MessageHeader { |
| 1705 | incarnation: 0xFEDC_BA98_7654_3210, |
| 1706 | serial: 12, |
| 1707 | tag: 40, |
| 1708 | type_hash: 0x0123_4567_89AB_CDEF, |
| 1709 | payload_len: 23, |
| 1710 | }; |
| 1711 | let bytes = h.encode(); |
| 1712 | assert_eq!(MessageHeader::decode(&bytes), Ok(h)); |
| 1713 | for (field, at) in [ |
| 1714 | (8, "pid serial out of range"), |
| 1715 | (16, "subject tag out of range"), |
| 1716 | ] { |
| 1717 | let mut b = bytes; |
| 1718 | b[field + 7] = 0x40; |
| 1719 | assert_eq!(MessageHeader::decode(&b).unwrap_err().what, at); |
| 1720 | } |
| 1721 | let mut b = bytes; |
| 1722 | b[32..36].copy_from_slice(&(MAX_PAYLOAD + 1).to_le_bytes()); |
| 1723 | assert_eq!( |
| 1724 | MessageHeader::decode(&b).unwrap_err().what, |
| 1725 | "payload too large" |
| 1726 | ); |
| 1727 | } |
| 1728 | |
| 1729 | #[test] |
| 1730 | fn node_names_are_lowercase_dns_names() { |
| 1731 | for good in [ |
| 1732 | "a", |
| 1733 | "a.example", |
| 1734 | "node-1.cluster.local", |
| 1735 | &"a".repeat(63), |
| 1736 | "10.0.0.5a", |
| 1737 | "1.example", |
| 1738 | ] { |
| 1739 | assert!(check_node_name(good.as_bytes()), "{good}"); |
| 1740 | } |
| 1741 | let long = format!("{}.{}", "a".repeat(63), "b".repeat(63)).repeat(2) + ".c"; |
| 1742 | for bad in [ |
| 1743 | "", |
| 1744 | "A.example", |
| 1745 | "a..b", |
| 1746 | ".a", |
| 1747 | "a.", |
| 1748 | "-a", |
| 1749 | "a-", |
| 1750 | "a_b", |
| 1751 | "é", |
| 1752 | &"a".repeat(64), |
| 1753 | &long, |
| 1754 | // An IPv4 address: a certificate's IP addresses would match it |
| 1755 | // (gabla108/louise#404's security review, SEC-10). |
| 1756 | "127.0.0.1", |
| 1757 | "10.0.0.5", |
| 1758 | "node.42", |
| 1759 | "7", |
| 1760 | ] { |
| 1761 | assert!(!check_node_name(bad.as_bytes()), "{bad}"); |
| 1762 | } |
| 1763 | } |
| 1764 | |
| 1765 | /// `docs/wire-format.md`'s worked example, byte for byte. |
| 1766 | #[test] |
| 1767 | fn the_worked_example() { |
| 1768 | let t = table(); |
| 1769 | let ty = t.parse_desc("Ndemo.Task;1s").unwrap(); |
| 1770 | let hash = t.type_hash(&ty).unwrap(); |
| 1771 | // The document quotes these. |
| 1772 | let doc = include_str!("../../../docs/wire-format.md"); |
| 1773 | let entry = t.get("demo.Task").unwrap(); |
| 1774 | let mut text = String::new(); |
| 1775 | entry.write(&mut text); |
| 1776 | assert!(doc.contains(&format!("Table entry: `{text}`"))); |
| 1777 | assert!(doc.contains(&format!("```\n{}```", t.canonical(&ty).unwrap()))); |
| 1778 | assert!(doc.contains(&format!("its hash `{hash:016x}`"))); |
| 1779 | // Step("hi", r, Step("hi", r, Done)), the string and the subject |
| 1780 | // shared; r is tag 3 of actor 7 on node a.example. |
| 1781 | let mut p = Vec::new(); |
| 1782 | write_uvarint(&mut p, 1); // one node entry |
| 1783 | write_uvarint(&mut p, 9); |
| 1784 | p.extend_from_slice(b"a.example"); |
| 1785 | p.extend_from_slice(&0x0123_4567_89AB_CDEFu64.to_le_bytes()); |
| 1786 | write_head(&mut p, Head::New(1)); // node 0: Step |
| 1787 | write_head(&mut p, Head::New(2)); // node 1: "hi" |
| 1788 | p.extend_from_slice(b"hi"); |
| 1789 | write_head(&mut p, Head::New(0)); // node 2: the subject |
| 1790 | write_uvarint(&mut p, 0); // its owner: entry 0, |
| 1791 | write_uvarint(&mut p, 7); // serial 7 |
| 1792 | write_uvarint(&mut p, 3); // its tag |
| 1793 | write_head(&mut p, Head::New(1)); // node 3: Step |
| 1794 | write_head(&mut p, Head::Back(1)); // "hi" |
| 1795 | write_head(&mut p, Head::Back(2)); // the subject |
| 1796 | write_head(&mut p, Head::New(0)); // Done: an immediate |
| 1797 | let header = MessageHeader { |
| 1798 | incarnation: 0xFEDC_BA98_7654_3210, |
| 1799 | serial: 12, |
| 1800 | tag: 40, |
| 1801 | type_hash: hash, |
| 1802 | payload_len: p.len() as u32, |
| 1803 | }; |
| 1804 | let hex = |b: &[u8]| { |
| 1805 | b.chunks(8) |
| 1806 | .map(|c| { |
| 1807 | c.iter() |
| 1808 | .map(|b| format!("{b:02x}")) |
| 1809 | .collect::<Vec<_>>() |
| 1810 | .join(" ") |
| 1811 | }) |
| 1812 | .collect::<Vec<_>>() |
| 1813 | .join("\n") |
| 1814 | }; |
| 1815 | assert_eq!( |
| 1816 | hex(&header.encode()), |
| 1817 | "10 32 54 76 98 ba dc fe\n\ |
| 1818 | 0c 00 00 00 00 00 00 00\n\ |
| 1819 | 28 00 00 00 00 00 00 00\n\ |
| 1820 | a7 1a cb 73 b8 47 49 99\n\ |
| 1821 | 1f 00 00 00" |
| 1822 | ); |
| 1823 | assert_eq!( |
| 1824 | hex(&p), |
| 1825 | "01 09 61 2e 65 78 61 6d\n\ |
| 1826 | 70 6c 65 ef cd ab 89 67\n\ |
| 1827 | 45 23 01 02 04 68 69 00\n\ |
| 1828 | 00 07 03 02 03 05 00" |
| 1829 | ); |
| 1830 | // The document's annotated dump is these bytes: on each line, the |
| 1831 | // two-digit hex tokens before the annotation. |
| 1832 | let dump = doc |
| 1833 | .split("```\nheader") |
| 1834 | .nth(1) |
| 1835 | .and_then(|rest| rest.split("```").next()) |
| 1836 | .expect("the example's dump"); |
| 1837 | let quoted: Vec<u8> = dump |
| 1838 | .lines() |
| 1839 | .flat_map(|line| { |
| 1840 | line.split_whitespace() |
| 1841 | .skip_while(|t| matches!(*t, "header" | "payload")) |
| 1842 | .take_while(|t| t.len() == 2 && t.bytes().all(|b| b.is_ascii_hexdigit())) |
| 1843 | .map(|t| u8::from_str_radix(t, 16).expect("hex")) |
| 1844 | .collect::<Vec<_>>() |
| 1845 | }) |
| 1846 | .collect(); |
| 1847 | let mut frame = header.encode().to_vec(); |
| 1848 | frame.extend_from_slice(&p); |
| 1849 | assert_eq!(quoted, frame); |
| 1850 | } |
| 1851 | } |