oxedyne/fe2o3/fe2o3_austenite/src/eval/ops.rs
29.3 KiB, 19 runs
created by r1870400018:63504, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | // U2 owns this file: Typst's operators over `Value`, with Typst's own error wording ("cannot add integer |
| 2 | // and string"), which names types by their long names rather than by `repr(type(x))`. |
| 3 | |
| 4 | use crate::eval::args::Args; |
| 5 | use crate::eval::content::{ |
| 6 | Content, |
| 7 | ElemKind, |
| 8 | Sequence, |
| 9 | }; |
| 10 | use crate::eval::fp::Shared; |
| 11 | use crate::eval::func::Func; |
| 12 | use crate::eval::lib::decimal::Decimal; |
| 13 | use crate::eval::lib::foundations::repr; |
| 14 | use crate::eval::value::{ |
| 15 | Alignment, |
| 16 | Angle, |
| 17 | Color, |
| 18 | Datetime, |
| 19 | Dict, |
| 20 | Duration, |
| 21 | Fraction, |
| 22 | Length, |
| 23 | Paint, |
| 24 | Ratio, |
| 25 | Relative, |
| 26 | Stroke, |
| 27 | Symbol, |
| 28 | Value, |
| 29 | }; |
| 30 | |
| 31 | use oxedyne_fe2o3_core::prelude::*; |
| 32 | |
| 33 | use std::cmp::Ordering; |
| 34 | use std::sync::Arc; |
| 35 | |
| 36 | /// The name a Typst diagnostic gives a type: `integer` where `repr(type(1))` is `int`. |
| 37 | fn fail(msg: String) -> Error<ErrTag> { |
| 38 | err!("{}", msg; Input, Invalid) |
| 39 | } |
| 40 | |
| 41 | fn mismatch(verb: &str, a: &Value, joiner: &str, b: &Value) -> Error<ErrTag> { |
| 42 | fail(fmt!("cannot {} {} {} {}", verb, a.ty().long_name(), joiner, b.ty().long_name())) |
| 43 | } |
| 44 | |
| 45 | fn too_large() -> Error<ErrTag> { fail("value is too large".to_string()) } |
| 46 | |
| 47 | // Unary |
| 48 | |
| 49 | pub fn pos(v: Value) -> Outcome<Value> { |
| 50 | match v { |
| 51 | Value::Int(_) | Value::Float(_) | Value::Decimal(_) | Value::Length(_) | Value::Angle(_) |
| 52 | | Value::Ratio(_) | Value::Relative(_) | Value::Fraction(_) => Ok(v), |
| 53 | other => Err(fail(fmt!("cannot apply unary '+' to {}", other.ty().long_name()))), |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub fn neg(v: Value) -> Outcome<Value> { |
| 58 | Ok(match v { |
| 59 | Value::Int(i) => Value::Int(res!(i.checked_neg().ok_or_else(too_large))), |
| 60 | Value::Float(f) => Value::Float(-f), |
| 61 | Value::Decimal(d) => Value::Decimal(d.neg()), |
| 62 | Value::Length(l) => Value::Length(len_neg(l)), |
| 63 | Value::Angle(a) => Value::Angle(Angle(-a.0)), |
| 64 | Value::Ratio(r) => Value::Ratio(Ratio(-r.0)), |
| 65 | Value::Relative(r) => Value::Relative(Relative { rel: Ratio(-r.rel.0), abs: len_neg(r.abs) }), |
| 66 | Value::Fraction(f) => Value::Fraction(Fraction(-f.0)), |
| 67 | Value::Duration(d) => Value::Duration(Duration { secs: -d.secs }), |
| 68 | other => return Err(fail(fmt!("cannot apply '-' to {}", other.ty().long_name()))), |
| 69 | }) |
| 70 | } |
| 71 | |
| 72 | pub fn not(v: Value) -> Outcome<Value> { |
| 73 | match v { |
| 74 | Value::Bool(b) => Ok(Value::Bool(!b)), |
| 75 | other => Err(fail(fmt!("cannot apply 'not' to {}", other.ty().long_name()))), |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// `a and b` once both sides are evaluated; the evaluator short-circuits a `false` left side itself. |
| 80 | pub fn and(a: Value, b: Value) -> Outcome<Value> { |
| 81 | match (&a, &b) { |
| 82 | (Value::Bool(x), Value::Bool(y)) => Ok(Value::Bool(*x && *y)), |
| 83 | _ => Err(mismatch("apply 'and' to", &a, "and", &b)), |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// `a or b` once both sides are evaluated; the evaluator short-circuits a `true` left side itself. |
| 88 | pub fn or(a: Value, b: Value) -> Outcome<Value> { |
| 89 | match (&a, &b) { |
| 90 | (Value::Bool(x), Value::Bool(y)) => Ok(Value::Bool(*x || *y)), |
| 91 | _ => Err(mismatch("apply 'or' to", &a, "and", &b)), |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // Unit arithmetic |
| 96 | |
| 97 | // Typst's `Scalar`: a NaN from `0 * inf` or `inf - inf` becomes zero, so `1pt * float.inf` has no em part. |
| 98 | fn scalar(x: f64) -> f64 { if x.is_nan() { 0.0 } else { x } } |
| 99 | |
| 100 | fn len_add(a: Length, b: Length) -> Length { Length { abs: scalar(a.abs + b.abs), em: scalar(a.em + b.em) } } |
| 101 | fn len_neg(a: Length) -> Length { Length { abs: -a.abs, em: -a.em } } |
| 102 | fn len_scale(a: Length, k: f64) -> Length { Length { abs: scalar(a.abs * k), em: scalar(a.em * k) } } |
| 103 | fn len_is_zero(a: Length) -> bool { a.abs == 0.0 && a.em == 0.0 } |
| 104 | |
| 105 | fn rel(rel: Ratio, abs: Length) -> Value { Value::Relative(Relative { rel, abs }) } |
| 106 | |
| 107 | fn rel_add(a: Relative, b: Relative) -> Relative { |
| 108 | Relative { rel: Ratio(a.rel.0 + b.rel.0), abs: len_add(a.abs, b.abs) } |
| 109 | } |
| 110 | |
| 111 | fn rel_neg(a: Relative) -> Relative { Relative { rel: Ratio(-a.rel.0), abs: len_neg(a.abs) } } |
| 112 | |
| 113 | fn rel_scale(a: Relative, k: f64) -> Relative { Relative { rel: Ratio(scalar(a.rel.0 * k)), abs: len_scale(a.abs, k) } } |
| 114 | |
| 115 | fn as_rel(v: &Value) -> Option<Relative> { |
| 116 | match v { |
| 117 | Value::Length(l) => Some(Relative { rel: Ratio(0.0), abs: *l }), |
| 118 | Value::Ratio(r) => Some(Relative { rel: *r, abs: Length::zero() }), |
| 119 | Value::Relative(r) => Some(*r), |
| 120 | _ => None, |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | fn num(v: &Value) -> Option<f64> { |
| 125 | match v { |
| 126 | Value::Int(i) => Some(*i as f64), |
| 127 | Value::Float(f) => Some(*f), |
| 128 | _ => None, |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | // Binary |
| 133 | |
| 134 | pub fn add(a: Value, b: Value) -> Outcome<Value> { |
| 135 | Ok(match (a, b) { |
| 136 | (a, Value::None) => a, |
| 137 | (Value::None, b) => b, |
| 138 | (Value::Int(x), Value::Int(y)) => Value::Int(res!(x.checked_add(y).ok_or_else(too_large))), |
| 139 | (Value::Int(x), Value::Float(y)) => Value::Float(x as f64 + y), |
| 140 | (Value::Float(x), Value::Int(y)) => Value::Float(x + y as f64), |
| 141 | (Value::Float(x), Value::Float(y)) => Value::Float(x + y), |
| 142 | (a @ (Value::Decimal(_) | Value::Int(_)), b @ Value::Decimal(_)) |
| 143 | | (a @ Value::Decimal(_), b @ Value::Int(_)) => res!(dec_op(&a, &b, Decimal::checked_add)), |
| 144 | (Value::Angle(x), Value::Angle(y)) => Value::Angle(Angle(x.0 + y.0)), |
| 145 | (Value::Length(x), Value::Length(y)) => Value::Length(len_add(x, y)), |
| 146 | (Value::Ratio(x), Value::Ratio(y)) => Value::Ratio(Ratio(x.0 + y.0)), |
| 147 | (Value::Length(x), Value::Ratio(y)) => rel(y, x), |
| 148 | (Value::Ratio(x), Value::Length(y)) => rel(x, y), |
| 149 | (a @ (Value::Length(_) | Value::Ratio(_) | Value::Relative(_)), |
| 150 | b @ (Value::Length(_) | Value::Ratio(_) | Value::Relative(_))) => { |
| 151 | match (as_rel(&a), as_rel(&b)) { |
| 152 | (Some(x), Some(y)) => Value::Relative(rel_add(x, y)), |
| 153 | _ => return Err(mismatch("add", &a, "and", &b)), |
| 154 | } |
| 155 | } |
| 156 | (Value::Fraction(x), Value::Fraction(y)) => Value::Fraction(Fraction(x.0 + y.0)), |
| 157 | (Value::Str(x), Value::Str(y)) => Value::str(fmt!("{}{}", x, y)), |
| 158 | (Value::Str(x), Value::Symbol(y)) => Value::str(fmt!("{}{}", x, symbol_text(&y))), |
| 159 | (Value::Symbol(x), Value::Str(y)) => Value::str(fmt!("{}{}", symbol_text(&x), y)), |
| 160 | (Value::Symbol(x), Value::Symbol(y)) => Value::str(fmt!("{}{}", symbol_text(&x), symbol_text(&y))), |
| 161 | (Value::Bytes(x), Value::Bytes(y)) => { |
| 162 | let mut v = (*x).clone(); |
| 163 | v.extend_from_slice(&y); |
| 164 | Value::Bytes(Arc::new(v)) |
| 165 | } |
| 166 | (Value::Content(x), Value::Content(y)) => Value::Content(content_add(x, y)), |
| 167 | (Value::Content(x), Value::Str(y)) => Value::Content(content_add(x, Content::text(&y))), |
| 168 | (Value::Str(x), Value::Content(y)) => Value::Content(content_add(Content::text(&x), y)), |
| 169 | (Value::Content(x), Value::Symbol(y)) => Value::Content(content_add(x, Content::text(&symbol_text(&y)))), |
| 170 | (Value::Symbol(x), Value::Content(y)) => Value::Content(content_add(Content::text(&symbol_text(&x)), y)), |
| 171 | (Value::Array(x), Value::Array(y)) => { |
| 172 | let mut v = (*x).clone(); |
| 173 | v.extend(y.iter().cloned()); |
| 174 | Value::array(v) |
| 175 | } |
| 176 | (Value::Dict(x), Value::Dict(y)) => Value::dict(dict_add(&x, &y)), |
| 177 | (Value::Args(x), Value::Args(y)) => { |
| 178 | let mut v = (*x).clone(); |
| 179 | v.items.extend(y.items.iter().cloned()); |
| 180 | Value::Args(Arc::new(v)) |
| 181 | } |
| 182 | (Value::Color(c), Value::Length(l)) | (Value::Length(l), Value::Color(c)) |
| 183 | => stroke(Paint::Color(c), l), |
| 184 | (Value::Gradient(g), Value::Length(l)) | (Value::Length(l), Value::Gradient(g)) |
| 185 | => stroke(Paint::Gradient(g), l), |
| 186 | (Value::Tiling(t), Value::Length(l)) | (Value::Length(l), Value::Tiling(t)) |
| 187 | => stroke(Paint::Tiling(t), l), |
| 188 | (Value::Alignment(x), Value::Alignment(y)) => Value::Alignment(res!(align_add(x, y))), |
| 189 | (Value::Duration(x), Value::Duration(y)) => Value::Duration(Duration { secs: x.secs + y.secs }), |
| 190 | (Value::Datetime(x), Value::Duration(y)) => Value::Datetime(res!(datetime_shift(x, y.secs))), |
| 191 | (Value::Duration(x), Value::Datetime(y)) => Value::Datetime(res!(datetime_shift(y, x.secs))), |
| 192 | (a, b) => return Err(mismatch("add", &a, "and", &b)), |
| 193 | }) |
| 194 | } |
| 195 | |
| 196 | pub fn sub(a: Value, b: Value) -> Outcome<Value> { |
| 197 | Ok(match (a, b) { |
| 198 | (Value::Int(x), Value::Int(y)) => Value::Int(res!(x.checked_sub(y).ok_or_else(too_large))), |
| 199 | (Value::Int(x), Value::Float(y)) => Value::Float(x as f64 - y), |
| 200 | (Value::Float(x), Value::Int(y)) => Value::Float(x - y as f64), |
| 201 | (Value::Float(x), Value::Float(y)) => Value::Float(x - y), |
| 202 | (a @ (Value::Decimal(_) | Value::Int(_)), b @ Value::Decimal(_)) |
| 203 | | (a @ Value::Decimal(_), b @ Value::Int(_)) => res!(dec_op(&a, &b, Decimal::checked_sub)), |
| 204 | (Value::Angle(x), Value::Angle(y)) => Value::Angle(Angle(x.0 - y.0)), |
| 205 | (Value::Length(x), Value::Length(y)) => Value::Length(len_add(x, len_neg(y))), |
| 206 | (Value::Ratio(x), Value::Ratio(y)) => Value::Ratio(Ratio(x.0 - y.0)), |
| 207 | (a @ (Value::Length(_) | Value::Ratio(_) | Value::Relative(_)), |
| 208 | b @ (Value::Length(_) | Value::Ratio(_) | Value::Relative(_))) => { |
| 209 | match (as_rel(&a), as_rel(&b)) { |
| 210 | (Some(x), Some(y)) => Value::Relative(rel_add(x, rel_neg(y))), |
| 211 | _ => return Err(mismatch("subtract", &b, "from", &a)), |
| 212 | } |
| 213 | } |
| 214 | (Value::Fraction(x), Value::Fraction(y)) => Value::Fraction(Fraction(x.0 - y.0)), |
| 215 | (Value::Duration(x), Value::Duration(y)) => Value::Duration(Duration { secs: x.secs - y.secs }), |
| 216 | (Value::Datetime(x), Value::Duration(y)) => Value::Datetime(res!(datetime_shift(x, -y.secs))), |
| 217 | (Value::Datetime(x), Value::Datetime(y)) => Value::Duration(res!(datetime_diff(x, y))), |
| 218 | (a, b) => return Err(mismatch("subtract", &b, "from", &a)), |
| 219 | }) |
| 220 | } |
| 221 | |
| 222 | pub fn mul(a: Value, b: Value) -> Outcome<Value> { |
| 223 | Ok(match (a, b) { |
| 224 | (Value::Int(x), Value::Int(y)) => Value::Int(res!(x.checked_mul(y).ok_or_else(too_large))), |
| 225 | (Value::Int(x), Value::Float(y)) => Value::Float(x as f64 * y), |
| 226 | (Value::Float(x), Value::Int(y)) => Value::Float(x * y as f64), |
| 227 | (Value::Float(x), Value::Float(y)) => Value::Float(x * y), |
| 228 | (a @ (Value::Decimal(_) | Value::Int(_)), b @ Value::Decimal(_)) |
| 229 | | (a @ Value::Decimal(_), b @ Value::Int(_)) => res!(dec_op(&a, &b, Decimal::checked_mul)), |
| 230 | (Value::Length(l), k @ (Value::Int(_) | Value::Float(_))) |
| 231 | | (k @ (Value::Int(_) | Value::Float(_)), Value::Length(l)) => Value::Length(len_scale(l, num(&k).unwrap_or(0.0))), |
| 232 | (Value::Length(l), Value::Ratio(r)) | (Value::Ratio(r), Value::Length(l)) |
| 233 | => Value::Length(len_scale(l, r.0)), |
| 234 | (Value::Angle(x), k @ (Value::Int(_) | Value::Float(_))) |
| 235 | | (k @ (Value::Int(_) | Value::Float(_)), Value::Angle(x)) => Value::Angle(Angle(x.0 * num(&k).unwrap_or(0.0))), |
| 236 | (Value::Angle(x), Value::Ratio(r)) | (Value::Ratio(r), Value::Angle(x)) |
| 237 | => Value::Angle(Angle(x.0 * r.0)), |
| 238 | (Value::Ratio(x), Value::Ratio(y)) => Value::Ratio(Ratio(x.0 * y.0)), |
| 239 | (Value::Ratio(x), k @ (Value::Int(_) | Value::Float(_))) |
| 240 | | (k @ (Value::Int(_) | Value::Float(_)), Value::Ratio(x)) => Value::Ratio(Ratio(x.0 * num(&k).unwrap_or(0.0))), |
| 241 | (Value::Relative(x), k @ (Value::Int(_) | Value::Float(_))) |
| 242 | | (k @ (Value::Int(_) | Value::Float(_)), Value::Relative(x)) => Value::Relative(rel_scale(x, num(&k).unwrap_or(0.0))), |
| 243 | (Value::Relative(x), Value::Ratio(r)) | (Value::Ratio(r), Value::Relative(x)) |
| 244 | => Value::Relative(rel_scale(x, r.0)), |
| 245 | (Value::Fraction(x), k @ (Value::Int(_) | Value::Float(_))) |
| 246 | | (k @ (Value::Int(_) | Value::Float(_)), Value::Fraction(x)) => Value::Fraction(Fraction(x.0 * num(&k).unwrap_or(0.0))), |
| 247 | (Value::Fraction(x), Value::Ratio(r)) | (Value::Ratio(r), Value::Fraction(x)) |
| 248 | => Value::Fraction(Fraction(x.0 * r.0)), |
| 249 | (Value::Str(s), Value::Int(n)) | (Value::Int(n), Value::Str(s)) |
| 250 | => Value::str(s.repeat(res!(count(n)))), |
| 251 | (Value::Array(a), Value::Int(n)) | (Value::Int(n), Value::Array(a)) => { |
| 252 | let n = res!(count(n)); |
| 253 | let mut v = Vec::with_capacity(a.len() * n); |
| 254 | for _ in 0..n { |
| 255 | v.extend(a.iter().cloned()); |
| 256 | } |
| 257 | Value::array(v) |
| 258 | } |
| 259 | (Value::Content(c), Value::Int(n)) | (Value::Int(n), Value::Content(c)) => { |
| 260 | let n = res!(count(n)); |
| 261 | Value::Content(Content::sequence(vec![c; n])) |
| 262 | } |
| 263 | (Value::Duration(d), k @ (Value::Int(_) | Value::Float(_))) |
| 264 | | (k @ (Value::Int(_) | Value::Float(_)), Value::Duration(d)) |
| 265 | => Value::Duration(Duration { secs: d.secs * num(&k).unwrap_or(0.0) }), |
| 266 | (a, b) => return Err(mismatch("multiply", &a, "with", &b)), |
| 267 | }) |
| 268 | } |
| 269 | |
| 270 | fn count(n: i64) -> Outcome<usize> { |
| 271 | if n < 0 { |
| 272 | return Err(fail("number must be at least zero".to_string())); |
| 273 | } |
| 274 | Ok(n as usize) |
| 275 | } |
| 276 | |
| 277 | // A decimal operation with an integer operand widened, "value is too large" when it overflows. |
| 278 | fn dec_op(a: &Value, b: &Value, op: fn(Decimal, Decimal) -> Option<Decimal>) -> Outcome<Value> { |
| 279 | let d = |v: &Value| match v { |
| 280 | Value::Decimal(d) => *d, |
| 281 | Value::Int(i) => Decimal::from(*i), |
| 282 | _ => Decimal::ZERO, |
| 283 | }; |
| 284 | match op(d(a), d(b)) { |
| 285 | Some(r) => Ok(Value::Decimal(r)), |
| 286 | None => Err(too_large()), |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | fn is_zero(v: &Value) -> bool { |
| 291 | match v { |
| 292 | Value::Int(i) => *i == 0, |
| 293 | Value::Float(f) => *f == 0.0, |
| 294 | Value::Decimal(d) => d.is_zero(), |
| 295 | Value::Length(l) => len_is_zero(*l), |
| 296 | Value::Angle(a) => a.0 == 0.0, |
| 297 | Value::Ratio(r) => r.0 == 0.0, |
| 298 | Value::Relative(r) => r.rel.0 == 0.0 && len_is_zero(r.abs), |
| 299 | Value::Fraction(f) => f.0 == 0.0, |
| 300 | Value::Duration(d) => d.secs == 0.0, |
| 301 | _ => false, |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // Two lengths divide only when both are absolute or both em. |
| 306 | fn len_div(a: Length, b: Length) -> Outcome<f64> { |
| 307 | if a.em == 0.0 && b.em == 0.0 { |
| 308 | return Ok(a.abs / b.abs); |
| 309 | } |
| 310 | if a.abs == 0.0 && b.abs == 0.0 { |
| 311 | return Ok(a.em / b.em); |
| 312 | } |
| 313 | Err(fail("cannot divide these two lengths".to_string())) |
| 314 | } |
| 315 | |
| 316 | pub fn div(a: Value, b: Value) -> Outcome<Value> { |
| 317 | if is_zero(&b) { |
| 318 | return Err(fail("cannot divide by zero".to_string())); |
| 319 | } |
| 320 | Ok(match (a, b) { |
| 321 | (a @ (Value::Int(_) | Value::Float(_)), b @ (Value::Int(_) | Value::Float(_))) |
| 322 | => Value::Float(num(&a).unwrap_or(0.0) / num(&b).unwrap_or(1.0)), |
| 323 | (a @ (Value::Decimal(_) | Value::Int(_)), b @ Value::Decimal(_)) |
| 324 | | (a @ Value::Decimal(_), b @ Value::Int(_)) => res!(dec_op(&a, &b, Decimal::checked_div)), |
| 325 | (Value::Length(l), k @ (Value::Int(_) | Value::Float(_))) |
| 326 | => Value::Length(len_scale(l, 1.0 / num(&k).unwrap_or(1.0))), |
| 327 | (Value::Length(x), Value::Length(y)) => Value::Float(res!(len_div(x, y))), |
| 328 | (Value::Length(x), Value::Relative(y)) if y.rel.0 == 0.0 => Value::Float(res!(len_div(x, y.abs))), |
| 329 | (Value::Angle(x), k @ (Value::Int(_) | Value::Float(_))) |
| 330 | => Value::Angle(Angle(x.0 / num(&k).unwrap_or(1.0))), |
| 331 | (Value::Angle(x), Value::Angle(y)) => Value::Float(x.0 / y.0), |
| 332 | (Value::Ratio(x), k @ (Value::Int(_) | Value::Float(_))) |
| 333 | => Value::Ratio(Ratio(x.0 / num(&k).unwrap_or(1.0))), |
| 334 | (Value::Ratio(x), Value::Ratio(y)) => Value::Float(x.0 / y.0), |
| 335 | (Value::Ratio(x), Value::Relative(y)) if len_is_zero(y.abs) => Value::Float(x.0 / y.rel.0), |
| 336 | (Value::Relative(x), k @ (Value::Int(_) | Value::Float(_))) |
| 337 | => Value::Relative(rel_scale(x, 1.0 / num(&k).unwrap_or(1.0))), |
| 338 | (Value::Relative(x), Value::Length(y)) if x.rel.0 == 0.0 => Value::Float(res!(len_div(x.abs, y))), |
| 339 | (Value::Relative(x), Value::Ratio(y)) if len_is_zero(x.abs) => Value::Float(x.rel.0 / y.0), |
| 340 | (Value::Relative(x), Value::Relative(y)) => { |
| 341 | if len_is_zero(x.abs) && len_is_zero(y.abs) { |
| 342 | Value::Float(x.rel.0 / y.rel.0) |
| 343 | } else if x.rel.0 == 0.0 && y.rel.0 == 0.0 { |
| 344 | Value::Float(res!(len_div(x.abs, y.abs))) |
| 345 | } else { |
| 346 | return Err(fail("cannot divide these two relative lengths".to_string())); |
| 347 | } |
| 348 | } |
| 349 | (Value::Fraction(x), k @ (Value::Int(_) | Value::Float(_))) |
| 350 | => Value::Fraction(Fraction(x.0 / num(&k).unwrap_or(1.0))), |
| 351 | (Value::Fraction(x), Value::Fraction(y)) => Value::Float(x.0 / y.0), |
| 352 | (Value::Duration(x), k @ (Value::Int(_) | Value::Float(_))) |
| 353 | => Value::Duration(Duration { secs: x.secs / num(&k).unwrap_or(1.0) }), |
| 354 | (Value::Duration(x), Value::Duration(y)) => Value::Float(x.secs / y.secs), |
| 355 | (a, b) => return Err(mismatch("divide", &a, "by", &b)), |
| 356 | }) |
| 357 | } |
| 358 | |
| 359 | /// Joins two values as markup juxtaposition and `+` on content do: strings concatenate, content |
| 360 | /// sequences, `none` is the identity. |
| 361 | pub fn join(a: Value, b: Value) -> Outcome<Value> { |
| 362 | Ok(match (a, b) { |
| 363 | (a, Value::None) => a, |
| 364 | (Value::None, b) => b, |
| 365 | (Value::Symbol(x), Value::Symbol(y)) => Value::str(fmt!("{}{}", symbol_text(&x), symbol_text(&y))), |
| 366 | (Value::Str(x), Value::Str(y)) => Value::str(fmt!("{}{}", x, y)), |
| 367 | (Value::Str(x), Value::Symbol(y)) => Value::str(fmt!("{}{}", x, symbol_text(&y))), |
| 368 | (Value::Symbol(x), Value::Str(y)) => Value::str(fmt!("{}{}", symbol_text(&x), y)), |
| 369 | (Value::Bytes(x), Value::Bytes(y)) => { |
| 370 | let mut v = (*x).clone(); |
| 371 | v.extend_from_slice(&y); |
| 372 | Value::Bytes(Arc::new(v)) |
| 373 | } |
| 374 | (Value::Content(x), Value::Content(y)) => Value::Content(content_add(x, y)), |
| 375 | (Value::Content(x), Value::Symbol(y)) => Value::Content(content_add(x, Content::text(&symbol_text(&y)))), |
| 376 | (Value::Content(x), Value::Str(y)) => Value::Content(content_add(x, Content::text(&y))), |
| 377 | (Value::Str(x), Value::Content(y)) => Value::Content(content_add(Content::text(&x), y)), |
| 378 | (Value::Symbol(x), Value::Content(y)) => Value::Content(content_add(Content::text(&symbol_text(&x)), y)), |
| 379 | (Value::Array(x), Value::Array(y)) => { |
| 380 | let mut v = (*x).clone(); |
| 381 | v.extend(y.iter().cloned()); |
| 382 | Value::array(v) |
| 383 | } |
| 384 | (Value::Dict(x), Value::Dict(y)) => Value::dict(dict_add(&x, &y)), |
| 385 | (Value::Args(x), Value::Args(y)) => { |
| 386 | let mut v = (*x).clone(); |
| 387 | v.items.extend(y.items.iter().cloned()); |
| 388 | Value::Args(Arc::new(v)) |
| 389 | } |
| 390 | (Value::Type(t), Value::Str(s)) => Value::str(fmt!("{}{}", t.name(), s)), |
| 391 | (Value::Str(s), Value::Type(t)) => Value::str(fmt!("{}{}", s, t.name())), |
| 392 | (a, b) => return Err(mismatch("join", &a, "with", &b)), |
| 393 | }) |
| 394 | } |
| 395 | |
| 396 | /// Typst's `+` on content: a sequence absorbs its neighbour rather than nesting. |
| 397 | pub fn content_add(a: Content, b: Content) -> Content { |
| 398 | match (a, b) { |
| 399 | (Content::Sequence(mut x), Content::Sequence(y)) => { |
| 400 | x.edit().children.extend(y.children.iter().cloned()); |
| 401 | Content::Sequence(x) |
| 402 | } |
| 403 | (Content::Sequence(mut x), b) => { |
| 404 | x.edit().children.push(b); |
| 405 | Content::Sequence(x) |
| 406 | } |
| 407 | (a, Content::Sequence(mut y)) => { |
| 408 | y.edit().children.insert(0, a); |
| 409 | Content::Sequence(y) |
| 410 | } |
| 411 | (a, b) => Content::Sequence(Shared::new(Sequence::new(vec![a, b]))), |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | fn dict_add(x: &Dict, y: &Dict) -> Dict { |
| 416 | let mut d = x.clone(); |
| 417 | for (k, v) in y.iter() { |
| 418 | d.insert(k, v.clone()); |
| 419 | } |
| 420 | d |
| 421 | } |
| 422 | |
| 423 | fn stroke(paint: Paint, thickness: Length) -> Value { |
| 424 | Value::Stroke(Arc::new(Stroke { paint: Some(paint), thickness: Some(thickness), ..Stroke::default() })) |
| 425 | } |
| 426 | |
| 427 | fn align_add(a: Alignment, b: Alignment) -> Outcome<Alignment> { |
| 428 | if a.x.is_some() && b.x.is_some() { |
| 429 | return Err(fail("cannot add two horizontal alignments".to_string())); |
| 430 | } |
| 431 | if a.y.is_some() && b.y.is_some() { |
| 432 | return Err(fail("cannot add two vertical alignments".to_string())); |
| 433 | } |
| 434 | Ok(Alignment { x: a.x.or(b.x), y: a.y.or(b.y) }) |
| 435 | } |
| 436 | |
| 437 | // Datetime arithmetic, on the proleptic Gregorian calendar. |
| 438 | |
| 439 | fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { |
| 440 | let y = if m <= 2 { y - 1 } else { y }; |
| 441 | let era = if y >= 0 { y } else { y - 399 } / 400; |
| 442 | let yoe = y - era * 400; |
| 443 | let mp = (m + 9) % 12; |
| 444 | let doy = (153 * mp + 2) / 5 + d - 1; |
| 445 | let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; |
| 446 | era * 146_097 + doe - 719_468 |
| 447 | } |
| 448 | |
| 449 | fn civil_from_days(z: i64) -> (i64, i64, i64) { |
| 450 | let z = z + 719_468; |
| 451 | let era = if z >= 0 { z } else { z - 146_096 } / 146_097; |
| 452 | let doe = z - era * 146_097; |
| 453 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 454 | let y = yoe + era * 400; |
| 455 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 456 | let mp = (5 * doy + 2) / 153; |
| 457 | let d = doy - (153 * mp + 2) / 5 + 1; |
| 458 | let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 459 | (if m <= 2 { y + 1 } else { y }, m, d) |
| 460 | } |
| 461 | |
| 462 | fn has_date(d: &Datetime) -> bool { d.year.is_some() && d.month.is_some() && d.day.is_some() } |
| 463 | fn has_time(d: &Datetime) -> bool { d.hour.is_some() && d.minute.is_some() && d.second.is_some() } |
| 464 | |
| 465 | fn datetime_secs(d: &Datetime) -> i64 { |
| 466 | let mut s = 0; |
| 467 | if has_date(d) { |
| 468 | s += days_from_civil(d.year.unwrap_or(0) as i64, d.month.unwrap_or(1) as i64, d.day.unwrap_or(1) as i64) |
| 469 | * 86_400; |
| 470 | } |
| 471 | if has_time(d) { |
| 472 | s += d.hour.unwrap_or(0) as i64 * 3600 + d.minute.unwrap_or(0) as i64 * 60 + d.second.unwrap_or(0) as i64; |
| 473 | } |
| 474 | s |
| 475 | } |
| 476 | |
| 477 | fn datetime_shift(d: Datetime, secs: f64) -> Outcome<Datetime> { |
| 478 | let total = datetime_secs(&d) + secs.trunc() as i64; |
| 479 | let mut out = d; |
| 480 | if has_time(&d) { |
| 481 | let tod = total.rem_euclid(86_400); |
| 482 | out.hour = Some((tod / 3600) as u8); |
| 483 | out.minute = Some((tod / 60 % 60) as u8); |
| 484 | out.second = Some((tod % 60) as u8); |
| 485 | } |
| 486 | if has_date(&d) { |
| 487 | let (y, m, day) = civil_from_days(total.div_euclid(86_400)); |
| 488 | if y < i32::MIN as i64 || y > i32::MAX as i64 { |
| 489 | return Err(fail("the resulting datetime is out of range".to_string())); |
| 490 | } |
| 491 | out.year = Some(y as i32); |
| 492 | out.month = Some(m as u8); |
| 493 | out.day = Some(day as u8); |
| 494 | } |
| 495 | Ok(out) |
| 496 | } |
| 497 | |
| 498 | fn datetime_diff(a: Datetime, b: Datetime) -> Outcome<Duration> { |
| 499 | if has_date(&a) != has_date(&b) || has_time(&a) != has_time(&b) { |
| 500 | return Err(fail("cannot subtract datetimes of different kinds".to_string())); |
| 501 | } |
| 502 | Ok(Duration { secs: (datetime_secs(&a) - datetime_secs(&b)) as f64 }) |
| 503 | } |
| 504 | |
| 505 | // Symbols |
| 506 | |
| 507 | /// The text of a symbol under its modifiers; the resolution is `lib::sym`'s, the one place it lives. |
| 508 | pub fn symbol_text(s: &Symbol) -> String { crate::eval::lib::sym::text(s).to_string() } |
| 509 | |
| 510 | /// `sym.arrow.r`: the symbol with one more modifier, `None` when no variant carries them all. |
| 511 | pub fn symbol_modified(s: &Symbol, modifier: &str) -> Option<Symbol> { crate::eval::lib::sym::modify(s, modifier) } |
| 512 | |
| 513 | // Comparison |
| 514 | |
| 515 | fn cmp_f64(a: f64, b: f64, ra: &Value, rb: &Value) -> Outcome<Ordering> { |
| 516 | a.partial_cmp(&b).ok_or_else(|| fail(fmt!("cannot compare {} with {}", repr(ra), repr(rb)))) |
| 517 | } |
| 518 | |
| 519 | fn cmp_len(a: Length, b: Length, ra: &Value, rb: &Value) -> Outcome<Ordering> { |
| 520 | if a.em == 0.0 && b.em == 0.0 { |
| 521 | return cmp_f64(a.abs, b.abs, ra, rb); |
| 522 | } |
| 523 | if a.abs == 0.0 && b.abs == 0.0 { |
| 524 | return cmp_f64(a.em, b.em, ra, rb); |
| 525 | } |
| 526 | Err(fail(fmt!("cannot compare {} with {}", repr(ra), repr(rb)))) |
| 527 | } |
| 528 | |
| 529 | /// Typst's `<`, `<=`, `>`, `>=`; comparing incomparable types is an error. |
| 530 | pub fn compare(a: &Value, b: &Value) -> Outcome<Ordering> { |
| 531 | match (a, b) { |
| 532 | (Value::Bool(x), Value::Bool(y)) => Ok(x.cmp(y)), |
| 533 | (Value::Int(x), Value::Int(y)) => Ok(x.cmp(y)), |
| 534 | (Value::Float(x), Value::Float(y)) => cmp_f64(*x, *y, a, b), |
| 535 | (Value::Int(x), Value::Float(y)) => cmp_f64(*x as f64, *y, a, b), |
| 536 | (Value::Float(x), Value::Int(y)) => cmp_f64(*x, *y as f64, a, b), |
| 537 | (Value::Decimal(x), Value::Decimal(y)) => Ok(x.cmp(y)), |
| 538 | (Value::Int(x), Value::Decimal(y)) => Ok(Decimal::from(*x).cmp(y)), |
| 539 | (Value::Decimal(x), Value::Int(y)) => Ok(x.cmp(&Decimal::from(*y))), |
| 540 | (Value::Length(x), Value::Length(y)) => cmp_len(*x, *y, a, b), |
| 541 | (Value::Angle(x), Value::Angle(y)) => cmp_f64(x.0, y.0, a, b), |
| 542 | (Value::Ratio(x), Value::Ratio(y)) => cmp_f64(x.0, y.0, a, b), |
| 543 | (Value::Relative(x), Value::Relative(y)) => { |
| 544 | if x.rel.0 == 0.0 && y.rel.0 == 0.0 { |
| 545 | cmp_len(x.abs, y.abs, a, b) |
| 546 | } else if len_is_zero(x.abs) && len_is_zero(y.abs) { |
| 547 | cmp_f64(x.rel.0, y.rel.0, a, b) |
| 548 | } else { |
| 549 | Err(fail(fmt!("cannot compare {} with {}", repr(a), repr(b)))) |
| 550 | } |
| 551 | } |
| 552 | (Value::Length(x), Value::Relative(y)) if y.rel.0 == 0.0 => cmp_len(*x, y.abs, a, b), |
| 553 | (Value::Relative(x), Value::Length(y)) if x.rel.0 == 0.0 => cmp_len(x.abs, *y, a, b), |
| 554 | (Value::Ratio(x), Value::Relative(y)) if len_is_zero(y.abs) => cmp_f64(x.0, y.rel.0, a, b), |
| 555 | (Value::Relative(x), Value::Ratio(y)) if len_is_zero(x.abs) => cmp_f64(x.rel.0, y.0, a, b), |
| 556 | (Value::Fraction(x), Value::Fraction(y)) => cmp_f64(x.0, y.0, a, b), |
| 557 | (Value::Version(x), Value::Version(y)) => Ok(version_cmp(x, y)), |
| 558 | (Value::Str(x), Value::Str(y)) => Ok(x.cmp(y)), |
| 559 | (Value::Duration(x), Value::Duration(y)) => cmp_f64(x.secs, y.secs, a, b), |
| 560 | (Value::Datetime(x), Value::Datetime(y)) => { |
| 561 | if has_date(x) != has_date(y) || has_time(x) != has_time(y) { |
| 562 | return Err(fail(fmt!("cannot compare {} and {}", repr(a), repr(b)))); |
| 563 | } |
| 564 | Ok(datetime_secs(x).cmp(&datetime_secs(y))) |
| 565 | } |
| 566 | (Value::Array(x), Value::Array(y)) => { |
| 567 | for (p, q) in x.iter().zip(y.iter()) { |
| 568 | match res!(compare(p, q)) { |
| 569 | Ordering::Equal => continue, |
| 570 | o => return Ok(o), |
| 571 | } |
| 572 | } |
| 573 | Ok(x.len().cmp(&y.len())) |
| 574 | } |
| 575 | _ => Err(mismatch("compare", a, "and", b)), |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | // Missing trailing components count as zero, so `version(1) == version(1, 0)`. |
| 580 | fn version_cmp(x: &[u32], y: &[u32]) -> Ordering { |
| 581 | let n = x.len().max(y.len()); |
| 582 | for i in 0..n { |
| 583 | let (p, q) = (x.get(i).copied().unwrap_or(0), y.get(i).copied().unwrap_or(0)); |
| 584 | match p.cmp(&q) { |
| 585 | Ordering::Equal => continue, |
| 586 | o => return o, |
| 587 | } |
| 588 | } |
| 589 | Ordering::Equal |
| 590 | } |
| 591 | |
| 592 | /// Typst's `a in b`. |
| 593 | pub fn contains(a: &Value, b: &Value) -> Outcome<bool> { |
| 594 | match (a, b) { |
| 595 | (Value::Str(x), Value::Str(y)) => Ok(y.contains(x.as_str())), |
| 596 | (Value::Regex(r), Value::Str(y)) => r.re.is_match(y), |
| 597 | (Value::Str(x), Value::Dict(d)) => Ok(d.contains(x)), |
| 598 | (x, Value::Array(arr)) => Ok(arr.iter().any(|v| equal(x, v))), |
| 599 | _ => Err(fail(fmt!("cannot apply 'in' to {} and {}", a.ty().long_name(), b.ty().long_name()))), |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | /// Typst's `==`, which never fails: values of different types are unequal, except int with float, and |
| 604 | /// a length or ratio with the relative length it equals. |
| 605 | pub fn equal(a: &Value, b: &Value) -> bool { |
| 606 | match (a, b) { |
| 607 | (Value::None, Value::None) => true, |
| 608 | (Value::Auto, Value::Auto) => true, |
| 609 | (Value::Bool(x), Value::Bool(y)) => x == y, |
| 610 | (Value::Int(x), Value::Int(y)) => x == y, |
| 611 | (Value::Float(x), Value::Float(y)) => x == y, |
| 612 | (Value::Int(x), Value::Float(y)) => (*x as f64) == *y, |
| 613 | (Value::Float(x), Value::Int(y)) => *x == (*y as f64), |
| 614 | (Value::Decimal(x), Value::Decimal(y)) => x == y, |
| 615 | (Value::Int(i), Value::Decimal(d)) | (Value::Decimal(d), Value::Int(i)) => Decimal::from(*i) == *d, |
| 616 | (Value::Length(x), Value::Length(y)) => x == y, |
| 617 | (Value::Angle(x), Value::Angle(y)) => x == y, |
| 618 | (Value::Ratio(x), Value::Ratio(y)) => x == y, |
| 619 | (Value::Relative(x), Value::Relative(y)) => x == y, |
| 620 | (Value::Length(l), Value::Relative(r)) | (Value::Relative(r), Value::Length(l)) |
| 621 | => r.rel.0 == 0.0 && r.abs == *l, |
| 622 | (Value::Ratio(q), Value::Relative(r)) | (Value::Relative(r), Value::Ratio(q)) |
| 623 | => len_is_zero(r.abs) && r.rel == *q, |
| 624 | (Value::Fraction(x), Value::Fraction(y)) => x == y, |
| 625 | (Value::Color(x), Value::Color(y)) => color_eq(x, y), |
| 626 | (Value::Gradient(x), Value::Gradient(y)) => x == y, |
| 627 | (Value::Tiling(x), Value::Tiling(y)) => Arc::ptr_eq(x, y), |
| 628 | (Value::Stroke(x), Value::Stroke(y)) => stroke_eq(x, y), |
| 629 | (Value::Alignment(x), Value::Alignment(y)) => x == y, |
| 630 | (Value::Direction(x), Value::Direction(y)) => x == y, |
| 631 | (Value::Symbol(x), Value::Symbol(y)) => symbol_text(x) == symbol_text(y) && x.modifiers == y.modifiers, |
| 632 | (Value::Str(x), Value::Str(y)) => x == y, |
| 633 | (Value::Bytes(x), Value::Bytes(y)) => x == y, |
| 634 | (Value::Label(x), Value::Label(y)) => x == y, |
| 635 | (Value::Datetime(x), Value::Datetime(y)) => x == y, |
| 636 | (Value::Duration(x), Value::Duration(y)) => x == y, |
| 637 | (Value::Version(x), Value::Version(y)) => version_cmp(x, y) == Ordering::Equal, |
| 638 | (Value::Regex(x), Value::Regex(y)) => x.pattern == y.pattern, |
| 639 | (Value::Content(x), Value::Content(y)) => content_eq(x, y), |
| 640 | (Value::Array(x), Value::Array(y)) => x.len() == y.len() |
| 641 | && x.iter().zip(y.iter()).all(|(p, q)| equal(p, q)), |
| 642 | (Value::Dict(x), Value::Dict(y)) => x.len() == y.len() |
| 643 | && x.iter().all(|(k, v)| y.get(k).map(|w| equal(v, w)).unwrap_or(false)), |
| 644 | (Value::Func(x), Value::Func(y)) => func_eq(x, y), |
| 645 | (Value::Args(x), Value::Args(y)) => args_eq(x, y), |
| 646 | (Value::Module(x), Value::Module(y)) => Arc::ptr_eq(x, y) || x.name == y.name, |
| 647 | (Value::Type(x), Value::Type(y)) => x == y, |
| 648 | (Value::Styles(x), Value::Styles(y)) => x.ptr_eq(y), |
| 649 | (Value::Selector(x), Value::Selector(y)) => Arc::ptr_eq(x, y), |
| 650 | (Value::Counter(x), Value::Counter(y)) => Arc::ptr_eq(x, y), |
| 651 | (Value::State(x), Value::State(y)) => x.key == y.key && equal(&x.init, &y.init), |
| 652 | (Value::Location(x), Value::Location(y)) => x == y, |
| 653 | _ => false, |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | fn color_eq(x: &Color, y: &Color) -> bool { x == y } |
| 658 | |
| 659 | fn paint_eq(x: &Paint, y: &Paint) -> bool { |
| 660 | match (x, y) { |
| 661 | (Paint::Color(p), Paint::Color(q)) => color_eq(p, q), |
| 662 | (Paint::Gradient(p), Paint::Gradient(q)) => p == q, |
| 663 | (Paint::Tiling(p), Paint::Tiling(q)) => Arc::ptr_eq(p, q), |
| 664 | _ => false, |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | fn stroke_eq(x: &Stroke, y: &Stroke) -> bool { |
| 669 | let paint = match (&x.paint, &y.paint) { |
| 670 | (None, None) => true, |
| 671 | (Some(p), Some(q)) => paint_eq(p, q), |
| 672 | _ => false, |
| 673 | }; |
| 674 | paint && x.thickness == y.thickness && x.cap == y.cap && x.join == y.join && x.dash == y.dash |
| 675 | && x.miter_limit == y.miter_limit |
| 676 | } |
| 677 | |
| 678 | fn func_eq(x: &Func, y: &Func) -> bool { |
| 679 | match (x, y) { |
| 680 | (Func::Native(p), Func::Native(q)) => p == q, |
| 681 | (Func::Element(p), Func::Element(q)) => p == q, |
| 682 | (Func::Closure(p), Func::Closure(q)) => Arc::ptr_eq(p, q), |
| 683 | (Func::With(p), Func::With(q)) => Arc::ptr_eq(p, q), |
| 684 | #[cfg(feature = "plugin")] |
| 685 | (Func::Plugin(p), Func::Plugin(q)) => p == q, |
| 686 | _ => false, |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | fn args_eq(x: &Args, y: &Args) -> bool { |
| 691 | x.items.len() == y.items.len() |
| 692 | && x.items.iter().zip(y.items.iter()).all(|(p, q)| p.name == q.name && equal(&p.value, &q.value)) |
| 693 | } |
| 694 | |
| 695 | /// Structural equality of content: same element, same fields in any order, same label; sequences and |
| 696 | /// styled content child by child. |
| 697 | pub fn content_eq(x: &Content, y: &Content) -> bool { |
| 698 | match (x, y) { |
| 699 | (Content::Elem(p), Content::Elem(q)) => { |
| 700 | if Shared::ptr_eq(p, q) { |
| 701 | return true; |
| 702 | } |
| 703 | p.kind == q.kind && p.label == q.label && p.fields.len() == q.fields.len() |
| 704 | && p.fields.iter().all(|(id, v)| { |
| 705 | q.fields.iter().find(|(j, _)| j == id).map(|(_, w)| equal(v, w)).unwrap_or(false) |
| 706 | }) |
| 707 | } |
| 708 | (Content::Sequence(p), Content::Sequence(q)) => p.label == q.label |
| 709 | && p.children.len() == q.children.len() |
| 710 | && p.children.iter().zip(q.children.iter()).all(|(a, b)| content_eq(a, b)), |
| 711 | (Content::Styled(p), Content::Styled(q)) => p.styles.ptr_eq(&q.styles) |
| 712 | && content_eq(&p.child, &q.child), |
| 713 | _ => false, |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | /// Does realisation leave the element out of label attachment, as Typst's `Unlabellable` does? |
| 718 | pub fn unlabellable(c: &Content) -> bool { |
| 719 | matches!(c.kind(), Some(ElemKind::Space) | Some(ElemKind::Parbreak)) |
| 720 | } |