| @@ -0,0 +1,223 @@ |
| 1 | +//! The runtime's pure kernels and constants, shared by the native runtime |
| 2 | +//! (`tilrt`), the reference interpreter (`tilc_interp`) and the compiler. |
| 3 | +//! |
| 4 | +//! The interpreter is the native backend's test oracle, so it implements |
| 5 | +//! the runtime's semantics a second time on purpose. For leaf functions |
| 6 | +//! over numbers, strings and bytes, a second copy adds nothing to the |
| 7 | +//! oracle and drifts (the interpreter's `random.int` was biased while the |
| 8 | +//! runtime's was not), so both call the one here. Converting values to and |
| 9 | +//! from each back end's representation stays in each. |
| 10 | +//! |
| 11 | +//! No dependencies: `tilrt` links this into every compiled program. |
| 12 | + |
| 13 | +/// The `Int`s held unboxed: 63-bit two's complement, `-2^62 .. 2^62` |
| 14 | +/// (`TL_INT_MIN ..= TL_INT_MAX` in `tilrt.h`). Others are big integers |
| 15 | +/// (ADR 0014). |
| 16 | +pub const SMALL_INT: std::ops::Range<i64> = -(1 << 62)..(1 << 62); |
| 17 | + |
| 18 | +/// The operations of `std/process.proc`, in declaration order: the root |
| 19 | +/// capability the runtime gives every actor holds one clause per |
| 20 | +/// operation, in this order (`tilrt/src/process.rs`). Codegen refuses a |
| 21 | +/// `std/process` whose operations differ. |
| 22 | +pub const PROC_OPS: [&str; 14] = [ |
| 23 | + "spawn", |
| 24 | + "self", |
| 25 | + "subject", |
| 26 | + "send", |
| 27 | + "receive", |
| 28 | + "link", |
| 29 | + "monitor", |
| 30 | + "kill", |
| 31 | + "trap_exits", |
| 32 | + "exits", |
| 33 | + "sleep", |
| 34 | + "receive_any", |
| 35 | + "spawn_link", |
| 36 | + "spawn_monitor", |
| 37 | +]; |
| 38 | + |
| 39 | +// ---- hashing ------------------------------------------------------------------- |
| 40 | + |
| 41 | +const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; |
| 42 | +const FNV_PRIME: u64 = 0x100_0000_01b3; |
| 43 | + |
| 44 | +/// A 64-bit mixer (splitmix64's finalizer), reduced to 62 bits so hashes |
| 45 | +/// are non-negative small `Int`s. |
| 46 | +pub fn mix(mut z: u64) -> i64 { |
| 47 | + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); |
| 48 | + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); |
| 49 | + ((z ^ (z >> 31)) >> 2) as i64 |
| 50 | +} |
| 51 | + |
| 52 | +/// The hash of a string or `Bytes`: FNV-1a, then mixed. |
| 53 | +pub fn hash_bytes(bytes: &[u8]) -> i64 { |
| 54 | + let h = bytes.iter().fold(FNV_OFFSET, |h, b| { |
| 55 | + (h ^ u64::from(*b)).wrapping_mul(FNV_PRIME) |
| 56 | + }); |
| 57 | + mix(h) |
| 58 | +} |
| 59 | + |
| 60 | +/// The hash of a big `Int`, before mixing: FNV-1a over its 64-bit limbs |
| 61 | +/// (least significant first), complemented when it is negative. |
| 62 | +pub fn hash_limbs(negative: bool, limbs: &[u64]) -> u64 { |
| 63 | + let h = limbs |
| 64 | + .iter() |
| 65 | + .fold(FNV_OFFSET, |h, l| (h ^ l).wrapping_mul(FNV_PRIME)); |
| 66 | + if negative { !h } else { h } |
| 67 | +} |
| 68 | + |
| 69 | +/// `hash_combine(a, b)` of two hashes (as saturated `Int`s). |
| 70 | +pub fn hash_combine(a: i64, b: i64) -> i64 { |
| 71 | + let (x, y) = (a as u64, b as u64); |
| 72 | + mix(x.wrapping_mul(31).wrapping_add(y) ^ (x >> 7)) |
| 73 | +} |
| 74 | + |
| 75 | +// ---- strings --------------------------------------------------------------------- |
| 76 | + |
| 77 | +/// The parts of `s` between occurrences of `sep`; all of `s` if `sep` is |
| 78 | +/// empty. |
| 79 | +pub fn split<'a>(s: &'a str, sep: &str) -> Vec<&'a str> { |
| 80 | + if sep.is_empty() { |
| 81 | + vec![s] |
| 82 | + } else { |
| 83 | + s.split(sep).collect() |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +/// `s` with `&`, `<`, `>`, `"` and `'` escaped for HTML text and |
| 88 | +/// attribute values. |
| 89 | +pub fn html_escape(s: &str) -> String { |
| 90 | + let mut out = String::with_capacity(s.len()); |
| 91 | + for c in s.chars() { |
| 92 | + match c { |
| 93 | + '&' => out.push_str("&"), |
| 94 | + '<' => out.push_str("<"), |
| 95 | + '>' => out.push_str(">"), |
| 96 | + '"' => out.push_str("""), |
| 97 | + '\'' => out.push_str("'"), |
| 98 | + c => out.push(c), |
| 99 | + } |
| 100 | + } |
| 101 | + out |
| 102 | +} |
| 103 | + |
| 104 | +/// Decode `%XX` and `+` (URL form encoding); invalid escapes stay, and |
| 105 | +/// invalid UTF-8 becomes U+FFFD. |
| 106 | +pub fn url_decode(s: &str) -> String { |
| 107 | + let bytes = s.as_bytes(); |
| 108 | + let mut out = Vec::with_capacity(bytes.len()); |
| 109 | + let mut i = 0; |
| 110 | + while i < bytes.len() { |
| 111 | + match bytes[i] { |
| 112 | + b'+' => out.push(b' '), |
| 113 | + b'%' if i + 2 < bytes.len() => { |
| 114 | + let hex = |b: u8| (b as char).to_digit(16); |
| 115 | + match (hex(bytes[i + 1]), hex(bytes[i + 2])) { |
| 116 | + (Some(h), Some(l)) => { |
| 117 | + out.push((h * 16 + l) as u8); |
| 118 | + i += 2; |
| 119 | + } |
| 120 | + _ => out.push(b'%'), |
| 121 | + } |
| 122 | + } |
| 123 | + b => out.push(b), |
| 124 | + } |
| 125 | + i += 1; |
| 126 | + } |
| 127 | + String::from_utf8_lossy(&out).into_owned() |
| 128 | +} |
| 129 | + |
| 130 | +// ---- randomness (std/random) --------------------------------------------------------- |
| 131 | + |
| 132 | +/// `n` bytes from the operating system's random source. |
| 133 | +/// |
| 134 | +/// # Panics |
| 135 | +/// If `/dev/urandom` cannot be read. |
| 136 | +pub fn random_bytes(n: usize) -> Vec<u8> { |
| 137 | + use std::io::Read; |
| 138 | + let mut buf = vec![0u8; n]; |
| 139 | + std::fs::File::open("/dev/urandom") |
| 140 | + .and_then(|mut f| f.read_exact(&mut buf)) |
| 141 | + .expect("tilrt: cannot read /dev/urandom"); |
| 142 | + buf |
| 143 | +} |
| 144 | + |
| 145 | +/// A uniformly random number in `0..below` (`below` > 0), from |
| 146 | +/// [`random_bytes`]. |
| 147 | +pub fn random_below(below: u64) -> u64 { |
| 148 | + below_with(below, || { |
| 149 | + u64::from_le_bytes(random_bytes(8).try_into().expect("8 bytes")) |
| 150 | + }) |
| 151 | +} |
| 152 | + |
| 153 | +/// [`random_below`] drawing from `next`. Rejection sampling: a plain |
| 154 | +/// `next() % below` would favour small numbers whenever `below` does not |
| 155 | +/// divide 2^64. |
| 156 | +fn below_with(below: u64, mut next: impl FnMut() -> u64) -> u64 { |
| 157 | + assert!(below > 0, "random_below: the bound must be positive"); |
| 158 | + let zone = u64::MAX - u64::MAX % below; |
| 159 | + loop { |
| 160 | + let x = next(); |
| 161 | + if x < zone { |
| 162 | + return x % below; |
| 163 | + } |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +#[cfg(test)] |
| 168 | +mod tests { |
| 169 | + use super::*; |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn small_ints_are_63_bits() { |
| 173 | + assert_eq!(SMALL_INT.start, -(1 << 62)); |
| 174 | + assert_eq!(SMALL_INT.end - 1, (1 << 62) - 1); |
| 175 | + } |
| 176 | + |
| 177 | + #[test] |
| 178 | + fn url_decoding_keeps_invalid_escapes() { |
| 179 | + assert_eq!(url_decode("a+b%20c"), "a b c"); |
| 180 | + assert_eq!(url_decode("%41%zz%4"), "A%zz%4"); |
| 181 | + assert_eq!(url_decode("%"), "%"); |
| 182 | + assert_eq!(url_decode("%ff"), "\u{fffd}"); |
| 183 | + } |
| 184 | + |
| 185 | + #[test] |
| 186 | + fn html_escaping() { |
| 187 | + assert_eq!( |
| 188 | + html_escape(r#"<a href="x">Tom & 'Jerry'</a>"#), |
| 189 | + "<a href="x">Tom & 'Jerry'</a>" |
| 190 | + ); |
| 191 | + } |
| 192 | + |
| 193 | + #[test] |
| 194 | + fn splitting_on_an_empty_separator_keeps_the_string() { |
| 195 | + assert_eq!(split("a,b,,c", ","), ["a", "b", "", "c"]); |
| 196 | + assert_eq!(split("abc", ""), ["abc"]); |
| 197 | + assert_eq!(split("", ","), [""]); |
| 198 | + } |
| 199 | + |
| 200 | + #[test] |
| 201 | + fn random_numbers_reject_the_biased_zone() { |
| 202 | + // 2^64 = 3 * 6148914691236517205 + 1: the last value of u64 is |
| 203 | + // in the biased zone for 3, and is drawn again. |
| 204 | + let mut draws = [u64::MAX, 7].into_iter(); |
| 205 | + assert_eq!(below_with(3, || draws.next().unwrap()), 1); |
| 206 | + for below in [1, 2, 3, 1000, u64::MAX] { |
| 207 | + assert!(random_below(below) < below); |
| 208 | + } |
| 209 | + } |
| 210 | + |
| 211 | + #[test] |
| 212 | + fn hashes_are_non_negative_small_ints() { |
| 213 | + for h in [ |
| 214 | + hash_bytes(b""), |
| 215 | + hash_bytes(b"tilcayo"), |
| 216 | + mix(u64::MAX), |
| 217 | + hash_combine(-1, i64::MAX), |
| 218 | + ] { |
| 219 | + assert!(SMALL_INT.contains(&h) && h >= 0, "{h}"); |
| 220 | + } |
| 221 | + assert_eq!(hash_limbs(true, &[1, 2]), !hash_limbs(false, &[1, 2])); |
| 222 | + } |
| 223 | +} |