oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/math.rs
31.6 KiB, 19 runs
created by r1870400018:63244, 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 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Original work copyright (c) the Typst project authors (typst-library `math/` elements, their field names and defaults, version 0.15.1). |
| 3 | // Modified for Austenite: ported to Hematite's types, IR and error handling. |
| 4 | // U7 owns this file. The `math` module: element schemas for `math.*` with Typst 0.15's field names and |
| 5 | // defaults, the style functions (`bold`, `display`, ...), the delimiter and accent functions a symbol |
| 6 | // becomes when called, and `define` binding the module (elements, functions, text operators, spacings |
| 7 | // and the `sym` symbols). Maths-mode syntax becomes these elements in U2's evaluator. |
| 8 | |
| 9 | use crate::diag::DiagnosticKind; |
| 10 | use crate::eval::args::Args; |
| 11 | use crate::eval::content::{ |
| 12 | Content, |
| 13 | ElemKind, |
| 14 | FieldDefault, |
| 15 | FieldSpec, |
| 16 | FieldType, |
| 17 | Fold, |
| 18 | }; |
| 19 | use crate::eval::func::{ |
| 20 | Func, |
| 21 | NativeFunc, |
| 22 | }; |
| 23 | use crate::eval::lib; |
| 24 | use crate::eval::lib::foundations::keyword_message; |
| 25 | use crate::eval::scope::Scope; |
| 26 | use crate::eval::content::display; |
| 27 | use crate::eval::styles::{ |
| 28 | Style, |
| 29 | StyleChain, |
| 30 | Styles, |
| 31 | }; |
| 32 | use crate::eval::value::{ |
| 33 | Dict, |
| 34 | Length, |
| 35 | Module, |
| 36 | Ratio, |
| 37 | Relative, |
| 38 | Type, |
| 39 | Value, |
| 40 | }; |
| 41 | use crate::eval::Engine; |
| 42 | use crate::math::class::MathClass; |
| 43 | use crate::math::props; |
| 44 | use crate::math::resolve::{ |
| 45 | accent_char, |
| 46 | accent_combining, |
| 47 | delim_char, |
| 48 | matching, |
| 49 | }; |
| 50 | use crate::math::style::{ |
| 51 | MathSize, |
| 52 | MathVariant, |
| 53 | }; |
| 54 | use crate::syntax::Span; |
| 55 | |
| 56 | use oxedyne_fe2o3_core::prelude::*; |
| 57 | |
| 58 | use std::sync::Arc; |
| 59 | |
| 60 | native_fns! { |
| 61 | pub enum MathFn { |
| 62 | Display => "display", |
| 63 | Inline => "inline", |
| 64 | Script => "script", |
| 65 | Sscript => "sscript", |
| 66 | Bold => "bold", |
| 67 | Upright => "upright", |
| 68 | Italic => "italic", |
| 69 | Serif => "serif", |
| 70 | Sans => "sans", |
| 71 | Frak => "frak", |
| 72 | Mono => "mono", |
| 73 | Bb => "bb", |
| 74 | Cal => "cal", |
| 75 | Scr => "scr", |
| 76 | Abs => "abs", |
| 77 | Norm => "norm", |
| 78 | Floor => "floor", |
| 79 | Ceil => "ceil", |
| 80 | Round => "round", |
| 81 | Sqrt => "sqrt", |
| 82 | AccentOf => "accent-of", // a combining accent's function, the accent bound first |
| 83 | LrOf => "lr-of", // a delimiter pair's function, both delimiters bound first |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | // Schemas |
| 88 | |
| 89 | const EQUATION: &[FieldSpec] = &[ |
| 90 | FieldSpec::named("block", FieldType::Of(Type::Bool), FieldDefault::Bool(false)), |
| 91 | FieldSpec::named("numbering", FieldType::Any, FieldDefault::None), |
| 92 | FieldSpec::named("number-align", FieldType::Of(Type::Alignment), FieldDefault::Computed), |
| 93 | FieldSpec::named("supplement", FieldType::Any, FieldDefault::Auto), |
| 94 | FieldSpec::named("alt", FieldType::OneOf(&[Type::Str, Type::None]), FieldDefault::None), |
| 95 | FieldSpec::required("body", FieldType::Content), |
| 96 | // Internal, set by the maths functions and layout, never materialised: Typst's ghost fields. |
| 97 | FieldSpec::named("size", FieldType::Of(Type::Str), FieldDefault::Computed).synthesised(), |
| 98 | FieldSpec::named("variant", FieldType::Any, FieldDefault::None).synthesised(), |
| 99 | FieldSpec::named("cramped", FieldType::Of(Type::Bool), FieldDefault::Bool(false)).synthesised(), |
| 100 | FieldSpec::named("bold", FieldType::Of(Type::Bool), FieldDefault::Bool(false)).synthesised(), |
| 101 | FieldSpec::named("italic", FieldType::Any, FieldDefault::None).synthesised(), |
| 102 | FieldSpec::named("script-scale", FieldType::Of(Type::Array), FieldDefault::Computed).synthesised(), |
| 103 | FieldSpec::named("dtls", FieldType::Of(Type::Bool), FieldDefault::Bool(false)).synthesised(), |
| 104 | ]; |
| 105 | |
| 106 | const REL: FieldType = FieldType::OneOf(&[Type::Relative, Type::Length, Type::Ratio]); |
| 107 | |
| 108 | const ALIGN_POINT: &[FieldSpec] = &[]; |
| 109 | |
| 110 | const ATTACH: &[FieldSpec] = &[ |
| 111 | FieldSpec::required("base", FieldType::Content), |
| 112 | FieldSpec::named("t", FieldType::Content, FieldDefault::None), |
| 113 | FieldSpec::named("b", FieldType::Content, FieldDefault::None), |
| 114 | FieldSpec::named("tl", FieldType::Content, FieldDefault::None), |
| 115 | FieldSpec::named("bl", FieldType::Content, FieldDefault::None), |
| 116 | FieldSpec::named("tr", FieldType::Content, FieldDefault::None), |
| 117 | FieldSpec::named("br", FieldType::Content, FieldDefault::None), |
| 118 | ]; |
| 119 | |
| 120 | const BODY: &[FieldSpec] = &[ |
| 121 | FieldSpec::required("body", FieldType::Content), |
| 122 | ]; |
| 123 | |
| 124 | const LIMITS: &[FieldSpec] = &[ |
| 125 | FieldSpec::required("body", FieldType::Content), |
| 126 | FieldSpec::named("inline", FieldType::Of(Type::Bool), FieldDefault::Bool(true)), |
| 127 | ]; |
| 128 | |
| 129 | const PRIMES: &[FieldSpec] = &[ |
| 130 | FieldSpec::required("count", FieldType::Of(Type::Int)), |
| 131 | ]; |
| 132 | |
| 133 | // Keyword choices |
| 134 | const FRAC_STYLE: &str = "\"vertical\", \"skewed\", or \"horizontal\""; |
| 135 | const CLASS_NAME: &str = "\"normal\", \"punctuation\", \"opening\", \"closing\", \"fence\", \"large\", \"relation\", \"unary\", \"binary\", or \"vary\""; |
| 136 | |
| 137 | const FRAC: &[FieldSpec] = &[ |
| 138 | FieldSpec::required("num", FieldType::Content), |
| 139 | FieldSpec::required("denom", FieldType::Content), |
| 140 | FieldSpec::named("style", FieldType::Keyword(&[], FRAC_STYLE), FieldDefault::Str("vertical")), |
| 141 | FieldSpec::named("num-deparenthesized", FieldType::Of(Type::Bool), FieldDefault::Bool(false)).synthesised(), |
| 142 | FieldSpec::named("denom-deparenthesized", FieldType::Of(Type::Bool), FieldDefault::Bool(false)).synthesised(), |
| 143 | ]; |
| 144 | |
| 145 | const BINOM: &[FieldSpec] = &[ |
| 146 | FieldSpec::required("upper", FieldType::Content), |
| 147 | FieldSpec::named("lower", FieldType::Of(Type::Array), FieldDefault::EmptyArray).variadic().unsettable(), |
| 148 | ]; |
| 149 | |
| 150 | const LR: &[FieldSpec] = &[ |
| 151 | FieldSpec::named("size", REL, FieldDefault::Ratio(1.0)), |
| 152 | FieldSpec::required("body", FieldType::Content), |
| 153 | ]; |
| 154 | |
| 155 | const MAT: &[FieldSpec] = &[ |
| 156 | FieldSpec::named("delim", FieldType::Any, FieldDefault::Computed), |
| 157 | FieldSpec::named("align", FieldType::Of(Type::Alignment), FieldDefault::Computed), |
| 158 | FieldSpec::named("augment", FieldType::Any, FieldDefault::None), |
| 159 | FieldSpec::named("row-gap", REL, FieldDefault::Em(0.2)), |
| 160 | FieldSpec::named("column-gap", REL, FieldDefault::Em(0.5)), |
| 161 | FieldSpec::named("rows", FieldType::Of(Type::Array), FieldDefault::EmptyArray).variadic().unsettable(), |
| 162 | ]; |
| 163 | |
| 164 | const VEC: &[FieldSpec] = &[ |
| 165 | FieldSpec::named("delim", FieldType::Any, FieldDefault::Computed), |
| 166 | FieldSpec::named("align", FieldType::Of(Type::Alignment), FieldDefault::Computed), |
| 167 | FieldSpec::named("gap", REL, FieldDefault::Em(0.2)), |
| 168 | FieldSpec::named("children", FieldType::Of(Type::Array), FieldDefault::EmptyArray).variadic().unsettable(), |
| 169 | ]; |
| 170 | |
| 171 | const CASES: &[FieldSpec] = &[ |
| 172 | FieldSpec::named("delim", FieldType::Any, FieldDefault::Computed), |
| 173 | FieldSpec::named("reverse", FieldType::Of(Type::Bool), FieldDefault::Bool(false)), |
| 174 | FieldSpec::named("gap", REL, FieldDefault::Em(0.2)), |
| 175 | FieldSpec::named("children", FieldType::Of(Type::Array), FieldDefault::EmptyArray).variadic().unsettable(), |
| 176 | ]; |
| 177 | |
| 178 | const ROOT: &[FieldSpec] = &[ |
| 179 | FieldSpec::named("index", FieldType::Content, FieldDefault::None).positional(), |
| 180 | FieldSpec::required("radicand", FieldType::Content), |
| 181 | ]; |
| 182 | |
| 183 | const ACCENT: &[FieldSpec] = &[ |
| 184 | FieldSpec::required("base", FieldType::Content), |
| 185 | FieldSpec::required("accent", FieldType::Any), |
| 186 | FieldSpec::named("size", REL, FieldDefault::Ratio(1.0)), |
| 187 | FieldSpec::named("dotless", FieldType::Of(Type::Bool), FieldDefault::Bool(true)), |
| 188 | ]; |
| 189 | |
| 190 | const OP: &[FieldSpec] = &[ |
| 191 | FieldSpec::required("text", FieldType::Content), |
| 192 | FieldSpec::named("limits", FieldType::Of(Type::Bool), FieldDefault::Bool(false)), |
| 193 | ]; |
| 194 | |
| 195 | const CLASS: &[FieldSpec] = &[ |
| 196 | FieldSpec::required("class", FieldType::Keyword(&[], CLASS_NAME)), |
| 197 | FieldSpec::required("body", FieldType::Content), |
| 198 | ]; |
| 199 | |
| 200 | const CANCEL: &[FieldSpec] = &[ |
| 201 | FieldSpec::required("body", FieldType::Content), |
| 202 | FieldSpec::named("length", REL, FieldDefault::Computed), |
| 203 | FieldSpec::named("inverted", FieldType::Of(Type::Bool), FieldDefault::Bool(false)), |
| 204 | FieldSpec::named("cross", FieldType::Of(Type::Bool), FieldDefault::Bool(false)), |
| 205 | FieldSpec::named("angle", FieldType::Any, FieldDefault::Auto), |
| 206 | FieldSpec::named("stroke", FieldType::Any, FieldDefault::Computed).fold(Fold::Stroke), |
| 207 | ]; |
| 208 | |
| 209 | const STRETCH: &[FieldSpec] = &[ |
| 210 | FieldSpec::required("body", FieldType::Content), |
| 211 | FieldSpec::named("size", REL, FieldDefault::Ratio(1.0)), |
| 212 | ]; |
| 213 | |
| 214 | const SPREADER: &[FieldSpec] = &[ |
| 215 | FieldSpec::required("body", FieldType::Content), |
| 216 | FieldSpec::named("annotation", FieldType::Content, FieldDefault::None).positional(), |
| 217 | ]; |
| 218 | |
| 219 | pub fn fields(kind: ElemKind) -> &'static [FieldSpec] { |
| 220 | match kind { |
| 221 | ElemKind::Equation => EQUATION, |
| 222 | ElemKind::MathAlignPoint => ALIGN_POINT, |
| 223 | ElemKind::MathAttach => ATTACH, |
| 224 | ElemKind::MathScripts => BODY, |
| 225 | ElemKind::MathLimits => LIMITS, |
| 226 | ElemKind::MathPrimes => PRIMES, |
| 227 | ElemKind::MathFrac => FRAC, |
| 228 | ElemKind::MathBinom => BINOM, |
| 229 | ElemKind::MathLr => LR, |
| 230 | ElemKind::MathMid => BODY, |
| 231 | ElemKind::MathMat => MAT, |
| 232 | ElemKind::MathVec => VEC, |
| 233 | ElemKind::MathCases => CASES, |
| 234 | ElemKind::MathRoot => ROOT, |
| 235 | ElemKind::MathAccent => ACCENT, |
| 236 | ElemKind::MathOp => OP, |
| 237 | ElemKind::MathClass => CLASS, |
| 238 | ElemKind::MathCancel => CANCEL, |
| 239 | ElemKind::MathStretch => STRETCH, |
| 240 | ElemKind::MathUnderline => BODY, |
| 241 | ElemKind::MathOverline => BODY, |
| 242 | ElemKind::MathUnderbrace | ElemKind::MathOverbrace | ElemKind::MathUnderbracket |
| 243 | | ElemKind::MathOverbracket | ElemKind::MathUnderparen | ElemKind::MathOverparen |
| 244 | | ElemKind::MathUndershell | ElemKind::MathOvershell => SPREADER, |
| 245 | _ => &[], |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // Element construction |
| 250 | |
| 251 | fn elem(kind: ElemKind, fields: Vec<(&str, Value)>, span: Span) -> Outcome<Content> { |
| 252 | let mut fv = Vec::with_capacity(fields.len()); |
| 253 | for (name, v) in fields { |
| 254 | match kind.field_id(name) { |
| 255 | // Built as a constructor argument is cast, so the field holds what Typst's would. |
| 256 | Some(id) => fv.push((id, res!(cast_field(kind, name, v)))), |
| 257 | None => return Err(err!("{} has no field {}", kind.path(), name; Bug)), |
| 258 | } |
| 259 | } |
| 260 | Ok(Content::new(kind, fv, span)) |
| 261 | } |
| 262 | |
| 263 | /// A math field's default where the schema holds none (`Computed`) and Typst gives a value a read can show: where an |
| 264 | /// equation's number sits, the brackets of a matrix, vector or case split and how a matrix or vector aligns, and |
| 265 | /// how far and in what stroke a cancel line is drawn. |
| 266 | pub fn default_value(kind: ElemKind, name: &str) -> Option<Value> { |
| 267 | use crate::eval::value::{Alignment, HAlign, Length, Ratio, Relative, Stroke, VAlign}; |
| 268 | let pair = |a: &str, b: &str| Some(Value::array(vec![Value::str(a), Value::str(b)])); |
| 269 | match (kind, name) { |
| 270 | (ElemKind::Equation, "number-align") |
| 271 | => Some(Value::Alignment(Alignment { x: Some(HAlign::End), y: Some(VAlign::Horizon) })), |
| 272 | (ElemKind::MathMat, "delim") | (ElemKind::MathVec, "delim") => pair("(", ")"), |
| 273 | (ElemKind::MathCases, "delim") => pair("{", "}"), |
| 274 | (ElemKind::MathMat, "align") | (ElemKind::MathVec, "align") |
| 275 | => Some(Value::Alignment(Alignment { x: Some(HAlign::Center), y: None })), |
| 276 | (ElemKind::MathCancel, "length") |
| 277 | => Some(Value::Relative(Relative { rel: Ratio(1.0), abs: Length::em(0.3) })), |
| 278 | (ElemKind::MathCancel, "stroke") |
| 279 | => Some(Value::Stroke(Arc::new(Stroke { thickness: Some(Length::em(0.05)), ..Stroke::default() }))), |
| 280 | _ => kind.field_id(name).and_then(|id| kind.field_spec(id)).and_then(|s| s.default.to_value()), |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /// Casts a field value as Typst's maths element fields do, for constructors and `set` rules alike. |
| 285 | pub fn cast_field(kind: ElemKind, name: &str, v: Value) -> Outcome<Value> { |
| 286 | // A field that holds content keeps content: a string, symbol or number is shown as it would be |
| 287 | // placed in markup, as Typst's content cast does. |
| 288 | let v = match (kind.field_id(name).and_then(|id| kind.fields().get(id.0 as usize)), &v) { |
| 289 | (Some(spec), Value::Str(_) | Value::Symbol(_) | Value::Int(_) | Value::Float(_)) |
| 290 | if matches!(spec.ty, FieldType::Content) => Value::Content(shown(&v)), |
| 291 | // A length or ratio in a relative length's field is stored as the relative length it is. |
| 292 | (Some(spec), Value::Length(l)) if spec.ty == REL => Value::Relative(Relative { rel: Ratio(0.0), abs: *l }), |
| 293 | (Some(spec), Value::Ratio(r)) if spec.ty == REL => Value::Relative(Relative { rel: *r, abs: Length::zero() }), |
| 294 | _ => v, |
| 295 | }; |
| 296 | match (kind, name) { |
| 297 | (ElemKind::MathVec | ElemKind::MathMat | ElemKind::MathCases, "delim") => match delim_error(&v) { |
| 298 | Some(m) => Err(err!("{}", m; Input, Invalid)), |
| 299 | None => Ok(delim_pair(&v)), |
| 300 | }, |
| 301 | (ElemKind::MathClass, "class") => match &v { |
| 302 | Value::Str(s) if MathClass::from_name(s).is_some() => Ok(v), |
| 303 | _ => Err(err!("{}", keyword_message(CLASS_NAME, &v); Input, Invalid)), |
| 304 | }, |
| 305 | (ElemKind::MathMat, "augment") => Ok(augment_value(v)), |
| 306 | // The accent is kept as its combining form, as Typst's cast leaves it. |
| 307 | (ElemKind::MathAccent, "accent") => match accent_char(&v) { |
| 308 | Some(c) => Ok(Value::str(c.to_string())), |
| 309 | None => Err(err!("{}", match v { |
| 310 | Value::Str(_) => "expected exactly one character", |
| 311 | _ => "expected a single-codepoint symbol", |
| 312 | }; Input, Invalid)), |
| 313 | }, |
| 314 | (ElemKind::MathFrac, "style") => match &v { |
| 315 | Value::Str(s) if matches!(s.as_str(), "vertical" | "skewed" | "horizontal") => Ok(v), |
| 316 | _ => Err(err!("{}", keyword_message(FRAC_STYLE, &v); Input, Invalid)), |
| 317 | }, |
| 318 | _ => Ok(v), |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | // Why a `delim` value is not a delimiter pair, or `None` when it is one. |
| 323 | fn delim_error(v: &Value) -> Option<String> { |
| 324 | let one = |v: &Value| -> Option<String> { |
| 325 | match delim_char(v) { |
| 326 | Some(None) => None, |
| 327 | Some(Some(c)) => match crate::math::class::default_math_class(c) { |
| 328 | Some(MathClass::Opening | MathClass::Closing | MathClass::Fence) => None, |
| 329 | _ => Some(fmt!("invalid delimiter: \"{}\"", c)), |
| 330 | }, |
| 331 | None => Some("expected a single-codepoint symbol".to_string()), |
| 332 | } |
| 333 | }; |
| 334 | match v { |
| 335 | Value::Array(a) if a.len() == 2 => one(&a[0]).or_else(|| one(&a[1])), |
| 336 | Value::Array(a) => Some(fmt!("expected 2 delimiters, found {}", a.len())), |
| 337 | other => one(other), |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // An `augment` as Typst stores it: a dictionary of the horizontal and vertical offsets, each an array, |
| 342 | // and the stroke, with an automatic stroke and a single vertical line collapsing to that offset. |
| 343 | fn augment_value(v: Value) -> Value { |
| 344 | let d = match &v { |
| 345 | Value::Dict(d) => d.clone(), |
| 346 | _ => return v, |
| 347 | }; |
| 348 | let offsets = |x: Option<&Value>| -> Vec<Value> { |
| 349 | match x { |
| 350 | Some(Value::Int(i)) => vec![Value::Int(*i)], |
| 351 | Some(Value::Array(a)) => a.iter().cloned().collect(), |
| 352 | _ => Vec::new(), |
| 353 | } |
| 354 | }; |
| 355 | let (hline, vline) = (offsets(d.get("hline")), offsets(d.get("vline"))); |
| 356 | let stroke = d.get("stroke").cloned(); |
| 357 | if stroke.is_none() && hline.is_empty() && vline.len() == 1 { |
| 358 | return vline[0].clone(); |
| 359 | } |
| 360 | let mut out = Dict::new(); |
| 361 | out.insert("hline", Value::array(hline)); |
| 362 | out.insert("vline", Value::array(vline)); |
| 363 | out.insert("stroke", stroke.unwrap_or(Value::Auto)); |
| 364 | Value::dict(out) |
| 365 | } |
| 366 | |
| 367 | // A string, symbol or number as the content it shows as, with no engine in hand. |
| 368 | fn shown(v: &Value) -> Content { |
| 369 | match v { |
| 370 | Value::Str(s) => Content::text(s), |
| 371 | Value::Symbol(s) => Content::symbol(&crate::eval::ops::symbol_text(s)), |
| 372 | other => Content::text(&crate::eval::lib::foundations::display(other).unwrap_or_default()), |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | // A valid `delim` as Typst stores it: the opening and closing delimiters, each a one-character string or |
| 377 | // `none`. One delimiter is the opener, its closer found from it. |
| 378 | fn delim_pair(v: &Value) -> Value { |
| 379 | let one = |c: Option<char>| -> Value { |
| 380 | match c { |
| 381 | Some(c) => Value::str(c.to_string()), |
| 382 | None => Value::None, |
| 383 | } |
| 384 | }; |
| 385 | match v { |
| 386 | Value::Array(a) if a.len() == 2 => { |
| 387 | let o = a.first().and_then(delim_char).flatten(); |
| 388 | let c = a.get(1).and_then(delim_char).flatten(); |
| 389 | Value::array(vec![one(o), one(c)]) |
| 390 | } |
| 391 | other => match delim_char(other) { |
| 392 | Some(Some(c)) => Value::array(vec![one(Some(c)), one(matching(c))]), |
| 393 | _ => Value::array(vec![Value::None, Value::None]), |
| 394 | }, |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | fn check_delim(engine: &mut Engine, span: Span, v: &Value) -> Outcome<()> { |
| 399 | match delim_error(v) { |
| 400 | Some(m) => Err(engine.error(DiagnosticKind::Type, span, m)), |
| 401 | None => Ok(()), |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | /// Builds the elements whose arguments Typst parses specially; `None` for the generic schema walk. |
| 406 | pub fn construct(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Option<Content>> { |
| 407 | let span = args.span; |
| 408 | match kind { |
| 409 | ElemKind::MathMat => { |
| 410 | let gap: Option<Value> = res!(args.named("gap")); |
| 411 | let row_gap = res!(args.named::<Value>("row-gap")).or_else(|| gap.clone()); |
| 412 | let column_gap = res!(args.named::<Value>("column-gap")).or(gap); |
| 413 | let delim: Option<Value> = res!(args.named("delim")); |
| 414 | let align: Option<Value> = res!(args.named("align")); |
| 415 | let augment: Option<Value> = res!(args.named("augment")); |
| 416 | let values: Vec<Value> = res!(args.all::<Value>()); |
| 417 | res!(std::mem::take(args).finish()); |
| 418 | let mut rows: Vec<Vec<Value>> = Vec::new(); |
| 419 | if values.iter().any(|v| matches!(v, Value::Array(_))) { |
| 420 | for v in values { |
| 421 | match v { |
| 422 | Value::Array(a) => { |
| 423 | let mut row = Vec::with_capacity(a.len()); |
| 424 | for x in a.iter() { |
| 425 | row.push(Value::Content(res!(display(engine, x.clone(), span)))); |
| 426 | } |
| 427 | rows.push(row); |
| 428 | } |
| 429 | other => return Err(engine.error(DiagnosticKind::Type, span, fmt!( |
| 430 | "expected array, found {}", other.ty().long_name()))), |
| 431 | } |
| 432 | } |
| 433 | } else if !values.is_empty() { |
| 434 | let mut row = Vec::with_capacity(values.len()); |
| 435 | for x in values { |
| 436 | row.push(Value::Content(res!(display(engine, x, span)))); |
| 437 | } |
| 438 | rows.push(row); |
| 439 | } |
| 440 | let width = rows.iter().map(|r| r.len()).max().unwrap_or(0); |
| 441 | for r in rows.iter_mut() { |
| 442 | while r.len() < width { |
| 443 | r.push(Value::Content(Content::empty())); |
| 444 | } |
| 445 | } |
| 446 | let mut fields = Vec::new(); |
| 447 | if let Some(d) = delim { |
| 448 | match cast_field(kind, "delim", d) { |
| 449 | Ok(d) => fields.push(("delim", d)), |
| 450 | Err(e) => return Err(engine.error(DiagnosticKind::Type, span, crate::diag::message_of(&e))), |
| 451 | } |
| 452 | } |
| 453 | if let Some(a) = align { |
| 454 | fields.push(("align", a)); |
| 455 | } |
| 456 | if let Some(a) = augment { |
| 457 | fields.push(("augment", a)); |
| 458 | } |
| 459 | if let Some(g) = row_gap { |
| 460 | fields.push(("row-gap", g)); |
| 461 | } |
| 462 | if let Some(g) = column_gap { |
| 463 | fields.push(("column-gap", g)); |
| 464 | } |
| 465 | fields.push(("rows", Value::array(rows.into_iter().map(Value::array).collect()))); |
| 466 | Ok(Some(res!(elem(kind, fields, span)))) |
| 467 | } |
| 468 | ElemKind::MathVec | ElemKind::MathCases => { |
| 469 | if let Some(d) = args.items.iter().find(|a| a.name.as_deref() == Some("delim")).map(|a| a.value.clone()) { |
| 470 | res!(check_delim(engine, span, &d)); |
| 471 | } |
| 472 | Ok(None) |
| 473 | } |
| 474 | ElemKind::MathLr => { |
| 475 | let size: Option<Value> = res!(args.named("size")); |
| 476 | let parts: Vec<Value> = res!(args.all::<Value>()); |
| 477 | res!(std::mem::take(args).finish()); |
| 478 | let mut body = Vec::new(); |
| 479 | for (i, p) in parts.into_iter().enumerate() { |
| 480 | if i > 0 { |
| 481 | body.push(Content::symbol(",")); |
| 482 | } |
| 483 | body.push(res!(display(engine, p, span))); |
| 484 | } |
| 485 | let mut fields = Vec::new(); |
| 486 | if let Some(s) = size { |
| 487 | fields.push(("size", s)); |
| 488 | } |
| 489 | fields.push(("body", Value::Content(Content::sequence(body)))); |
| 490 | Ok(Some(res!(elem(kind, fields, span)))) |
| 491 | } |
| 492 | ElemKind::MathBinom => { |
| 493 | let upper: Value = match res!(args.eat::<Value>()) { |
| 494 | Some(v) => v, |
| 495 | None => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: upper")), |
| 496 | }; |
| 497 | let lower: Vec<Value> = res!(args.all::<Value>()); |
| 498 | if lower.is_empty() { |
| 499 | return Err(engine.error(DiagnosticKind::Type, span, "missing argument: lower")); |
| 500 | } |
| 501 | res!(std::mem::take(args).finish()); |
| 502 | let mut lv = Vec::with_capacity(lower.len()); |
| 503 | for v in lower { |
| 504 | lv.push(Value::Content(res!(display(engine, v, span)))); |
| 505 | } |
| 506 | let lower = lv; |
| 507 | Ok(Some(res!(elem(kind, vec![("upper", upper), ("lower", Value::array(lower))], span)))) |
| 508 | } |
| 509 | ElemKind::MathRoot => { |
| 510 | let pos: Vec<Value> = res!(args.all::<Value>()); |
| 511 | res!(std::mem::take(args).finish()); |
| 512 | let (index, radicand) = match pos.len() { |
| 513 | 1 => (None, pos[0].clone()), |
| 514 | 2 => (Some(pos[0].clone()), pos[1].clone()), |
| 515 | 0 => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: radicand")), |
| 516 | _ => return Err(engine.error(DiagnosticKind::Type, span, "unexpected argument")), |
| 517 | }; |
| 518 | let mut fields = Vec::new(); |
| 519 | if let Some(i) = index { |
| 520 | fields.push(("index", i)); |
| 521 | } |
| 522 | fields.push(("radicand", radicand)); |
| 523 | Ok(Some(res!(elem(kind, fields, span)))) |
| 524 | } |
| 525 | ElemKind::MathAccent => { |
| 526 | if let Some(a) = args.items.iter().filter(|a| a.name.is_none()).nth(1).map(|a| a.value.clone()) { |
| 527 | if accent_char(&a).is_none() { |
| 528 | let msg = match a { |
| 529 | Value::Str(_) => "expected exactly one character", |
| 530 | _ => "expected a single-codepoint symbol", |
| 531 | }; |
| 532 | return Err(engine.error(DiagnosticKind::Type, span, msg)); |
| 533 | } |
| 534 | } |
| 535 | Ok(None) |
| 536 | } |
| 537 | ElemKind::MathClass => { |
| 538 | if let Some(Value::Str(s)) = args.items.iter().find(|a| a.name.is_none()).map(|a| a.value.clone()) { |
| 539 | if MathClass::from_name(&s).is_none() { |
| 540 | return Err(engine.error(DiagnosticKind::Type, span, keyword_message(CLASS_NAME, &Value::Str(s)))); |
| 541 | } |
| 542 | } |
| 543 | Ok(None) |
| 544 | } |
| 545 | _ => Ok(None), |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | /// Every maths element is a primitive the maths layout sets. |
| 550 | pub fn show(_engine: &mut Engine, _elem: &Content, _styles: &StyleChain) -> Outcome<Option<Content>> { |
| 551 | Ok(None) |
| 552 | } |
| 553 | |
| 554 | /// The styles an equation sets on itself (Typst's built-in show-set rule): a block equation is centred, |
| 555 | /// unbreakable and in display size, an inline one in text size, and both set in New Computer Modern |
| 556 | /// Math at weight 450. Realisation applies these outside the document's own show-set rules. |
| 557 | pub fn show_set(block: bool) -> Styles { |
| 558 | let mut v: Vec<Option<Style>> = Vec::new(); |
| 559 | if block { |
| 560 | v.push(props::property(ElemKind::Align, "alignment", Value::Alignment(crate::eval::value::Alignment { |
| 561 | x: Some(crate::eval::value::HAlign::Center), y: None }))); |
| 562 | v.push(props::property(ElemKind::Block, "breakable", Value::Bool(false))); |
| 563 | v.push(props::property(ElemKind::ParLine, "numbering", Value::None)); |
| 564 | v.push(props::set_size(MathSize::Display)); |
| 565 | } else { |
| 566 | v.push(props::set_size(MathSize::Text)); |
| 567 | } |
| 568 | v.push(props::property(ElemKind::Text, "weight", Value::Int(450))); |
| 569 | v.push(props::property(ElemKind::Text, "font", Value::str("New Computer Modern Math"))); |
| 570 | Styles::from_vec(v.into_iter().flatten().collect()) |
| 571 | } |
| 572 | |
| 573 | /// The built-in show-set styles of a maths element: an equation's, by whether it is a block. |
| 574 | pub fn show_set_of(elem: &Content, styles: &StyleChain) -> Outcome<Styles> { |
| 575 | if !elem.is(ElemKind::Equation) { |
| 576 | return Ok(Styles::new()); |
| 577 | } |
| 578 | let block = match ElemKind::Equation.field_id("block") { |
| 579 | Some(id) => matches!(res!(styles.resolve(elem, id)), Some(Value::Bool(true))), |
| 580 | None => false, |
| 581 | }; |
| 582 | Ok(show_set(block)) |
| 583 | } |
| 584 | |
| 585 | /// The factor maths scales `text.size` by at the chain's maths size: 1 in display and text size, the |
| 586 | /// font's script percentages below. What a resolved text size multiplies by inside an equation. |
| 587 | pub fn script_factor(styles: &StyleChain) -> f64 { |
| 588 | let base = props::text_size(styles); |
| 589 | if base == 0.0 { 1.0 } else { props::font_size(styles) / base } |
| 590 | } |
| 591 | |
| 592 | /// The function a symbol becomes when called in maths: an accent (`hat(x)`), or a delimiter pair |
| 593 | /// wrapping its argument (`paren.l`, `floor`, ...). `None` for any other symbol. |
| 594 | pub fn symbol_func(text: &str) -> Option<Func> { |
| 595 | if let Some(_) = accent_combining(text) { |
| 596 | let mut a = Args::new(Span::detached()); |
| 597 | a.push(Span::detached(), Value::str(text)); |
| 598 | return Some(Func::Native(NativeFunc::Math(MathFn::AccentOf)).with(a)); |
| 599 | } |
| 600 | let mut it = text.chars(); |
| 601 | let left = match (it.next(), it.next()) { |
| 602 | (Some(c), None) => c, |
| 603 | _ => return None, |
| 604 | }; |
| 605 | match left { |
| 606 | '\u{2308}' => return Some(Func::Native(NativeFunc::Math(MathFn::Ceil))), |
| 607 | '\u{230a}' => return Some(Func::Native(NativeFunc::Math(MathFn::Floor))), |
| 608 | _ => (), |
| 609 | } |
| 610 | let right = DELIMS.iter().find(|(l, _)| *l == left).map(|(_, r)| *r)?; |
| 611 | let mut a = Args::new(Span::detached()); |
| 612 | a.push(Span::detached(), Value::str(left.to_string())); |
| 613 | a.push(Span::detached(), Value::str(right.to_string())); |
| 614 | Some(Func::Native(NativeFunc::Math(MathFn::LrOf)).with(a)) |
| 615 | } |
| 616 | |
| 617 | const DELIMS: &[(char, char)] = &[ |
| 618 | ('(', ')'), ('\u{27ee}', '\u{27ef}'), ('\u{2987}', '\u{2988}'), ('\u{2985}', '\u{2986}'), |
| 619 | ('\u{2993}', '\u{2994}'), ('\u{2995}', '\u{2996}'), ('{', '}'), ('\u{2983}', '\u{2984}'), |
| 620 | ('[', ']'), ('\u{298d}', '\u{2990}'), ('\u{298f}', '\u{298e}'), ('\u{27e6}', '\u{27e7}'), |
| 621 | ('\u{298b}', '\u{298c}'), ('\u{2772}', '\u{2773}'), ('\u{27ec}', '\u{27ed}'), ('\u{2997}', '\u{2998}'), |
| 622 | ('\u{27c5}', '\u{27c6}'), ('\u{23b0}', '\u{23b1}'), ('\u{23b1}', '\u{23b0}'), ('\u{29d8}', '\u{29d9}'), |
| 623 | ('\u{29da}', '\u{29db}'), ('\u{27e8}', '\u{27e9}'), ('\u{29fc}', '\u{29fd}'), ('\u{2991}', '\u{2992}'), |
| 624 | ('\u{2989}', '\u{298a}'), ('\u{27ea}', '\u{27eb}'), ('\u{231c}', '\u{231d}'), ('\u{231e}', '\u{231f}'), |
| 625 | ('|', '|'), ('\u{2016}', '\u{2016}'), ('\u{2980}', '\u{2980}'), ('\u{2999}', '\u{2999}'), |
| 626 | ('\u{299a}', '\u{299a}'), |
| 627 | ]; |
| 628 | |
| 629 | // Functions |
| 630 | |
| 631 | fn styled_body(engine: &mut Engine, args: &mut Args, props: Vec<Option<Style>>) -> Outcome<Value> { |
| 632 | let body: Value = res!(args.expect("body")); |
| 633 | res!(std::mem::take(args).finish()); |
| 634 | let body = res!(display(engine, body, args.span)); |
| 635 | Ok(Value::Content(body.styled(Styles::from_vec(props.into_iter().flatten().collect())))) |
| 636 | } |
| 637 | |
| 638 | fn sized_body(engine: &mut Engine, args: &mut Args, size: MathSize, default_cramped: bool) -> Outcome<Value> { |
| 639 | let cramped: bool = res!(args.named("cramped")).unwrap_or(default_cramped); |
| 640 | styled_body(engine, args, vec![props::set_size(size), props::set_cramped(cramped)]) |
| 641 | } |
| 642 | |
| 643 | fn variant(v: MathVariant) -> Option<Style> { |
| 644 | props::property(ElemKind::Equation, "variant", Value::str(v.name())) |
| 645 | } |
| 646 | |
| 647 | fn delimited(engine: &mut Engine, args: &mut Args, left: &str, right: &str, span: Span) -> Outcome<Value> { |
| 648 | let size: Option<Value> = res!(args.named("size")); |
| 649 | let body: Value = res!(args.expect("body")); |
| 650 | res!(std::mem::take(args).finish()); |
| 651 | let body = res!(display(engine, body, span)); |
| 652 | let bspan = body.span(); |
| 653 | let inner = Content::sequence(vec![Content::symbol(left), body, Content::symbol(right)]); |
| 654 | let mut fields = Vec::new(); |
| 655 | if let Some(s) = size { |
| 656 | fields.push(("size", s)); |
| 657 | } |
| 658 | fields.push(("body", Value::Content(inner))); |
| 659 | let lr = res!(elem(ElemKind::MathLr, fields, span)); |
| 660 | Ok(Value::Content(if bspan.is_detached() { lr } else { lr.with_span(bspan) })) |
| 661 | } |
| 662 | |
| 663 | pub fn call(f: MathFn, engine: &mut Engine, mut args: Args) -> Outcome<Value> { |
| 664 | let span = args.span; |
| 665 | match f { |
| 666 | MathFn::Display => sized_body(engine, &mut args, MathSize::Display, false), |
| 667 | MathFn::Inline => sized_body(engine, &mut args, MathSize::Text, false), |
| 668 | MathFn::Script => sized_body(engine, &mut args, MathSize::Script, true), |
| 669 | MathFn::Sscript => sized_body(engine, &mut args, MathSize::ScriptScript, true), |
| 670 | MathFn::Bold => styled_body(engine, &mut args, vec![props::property(ElemKind::Equation, "bold", Value::Bool(true))]), |
| 671 | MathFn::Upright => styled_body(engine, &mut args, vec![props::property(ElemKind::Equation, "italic", Value::Bool(false))]), |
| 672 | MathFn::Italic => styled_body(engine, &mut args, vec![props::property(ElemKind::Equation, "italic", Value::Bool(true))]), |
| 673 | MathFn::Serif => styled_body(engine, &mut args, vec![variant(MathVariant::Plain)]), |
| 674 | MathFn::Sans => styled_body(engine, &mut args, vec![variant(MathVariant::SansSerif)]), |
| 675 | MathFn::Frak => styled_body(engine, &mut args, vec![variant(MathVariant::Fraktur)]), |
| 676 | MathFn::Mono => styled_body(engine, &mut args, vec![variant(MathVariant::Monospace)]), |
| 677 | MathFn::Bb => styled_body(engine, &mut args, vec![variant(MathVariant::DoubleStruck)]), |
| 678 | MathFn::Cal => styled_body(engine, &mut args, vec![variant(MathVariant::Chancery)]), |
| 679 | MathFn::Scr => styled_body(engine, &mut args, vec![variant(MathVariant::Roundhand)]), |
| 680 | MathFn::Abs => delimited(engine, &mut args, "|", "|", span), |
| 681 | MathFn::Norm => delimited(engine, &mut args, "\u{2016}", "\u{2016}", span), |
| 682 | MathFn::Floor => delimited(engine, &mut args, "\u{230a}", "\u{230b}", span), |
| 683 | MathFn::Ceil => delimited(engine, &mut args, "\u{2308}", "\u{2309}", span), |
| 684 | MathFn::Round => delimited(engine, &mut args, "\u{230a}", "\u{2309}", span), |
| 685 | MathFn::Sqrt => { |
| 686 | let radicand: Value = res!(args.expect("radicand")); |
| 687 | res!(std::mem::take(&mut args).finish()); |
| 688 | elem(ElemKind::MathRoot, vec![("radicand", radicand)], span).map(Value::Content) |
| 689 | } |
| 690 | MathFn::AccentOf => { |
| 691 | let accent: Value = res!(args.expect("accent")); |
| 692 | let accent = res!(cast_field(ElemKind::MathAccent, "accent", accent)); |
| 693 | let base: Value = res!(args.expect("base")); |
| 694 | let size: Option<Value> = res!(args.named("size")); |
| 695 | let dotless: Option<Value> = res!(args.named("dotless")); |
| 696 | res!(std::mem::take(&mut args).finish()); |
| 697 | let mut fields = vec![("base", base), ("accent", accent)]; |
| 698 | if let Some(s) = size { |
| 699 | fields.push(("size", s)); |
| 700 | } |
| 701 | if let Some(d) = dotless { |
| 702 | fields.push(("dotless", d)); |
| 703 | } |
| 704 | elem(ElemKind::MathAccent, fields, span).map(Value::Content) |
| 705 | } |
| 706 | MathFn::LrOf => { |
| 707 | let l: String = res!(args.expect("left")); |
| 708 | let r: String = res!(args.expect("right")); |
| 709 | delimited(engine, &mut args, &l, &r, span) |
| 710 | } |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | // The module |
| 715 | |
| 716 | /// `name` as a horizontal space element of `em` ems, or `None` until the layout schema has `h.amount`. |
| 717 | fn h(em: f64, weak: bool) -> Option<Content> { |
| 718 | let amount = ElemKind::H.field_id("amount")?; |
| 719 | let mut fields = vec![(amount, Value::Length(Length::em(em)))]; |
| 720 | if weak { |
| 721 | if let Some(w) = ElemKind::H.field_id("weak") { |
| 722 | fields.push((w, Value::Bool(true))); |
| 723 | } |
| 724 | } |
| 725 | Some(Content::new(ElemKind::H, fields, Span::detached())) |
| 726 | } |
| 727 | |
| 728 | /// Typst's text operators: `(name, text, limits)`. |
| 729 | const OPS: &[(&str, &str, bool)] = &[ |
| 730 | ("arccos", "arccos", false), ("arcsin", "arcsin", false), ("arctan", "arctan", false), |
| 731 | ("arg", "arg", false), ("cos", "cos", false), ("cosh", "cosh", false), ("cot", "cot", false), |
| 732 | ("coth", "coth", false), ("csc", "csc", false), ("csch", "csch", false), ("ctg", "ctg", false), |
| 733 | ("deg", "deg", false), ("det", "det", true), ("dim", "dim", false), ("exp", "exp", false), |
| 734 | ("gcd", "gcd", true), ("lcm", "lcm", true), ("hom", "hom", false), ("id", "id", false), |
| 735 | ("im", "im", false), ("inf", "inf", true), ("ker", "ker", false), ("lg", "lg", false), |
| 736 | ("lim", "lim", true), ("liminf", "lim inf", true), ("limsup", "lim sup", true), ("ln", "ln", false), |
| 737 | ("log", "log", false), ("max", "max", true), ("min", "min", true), ("mod", "mod", false), |
| 738 | ("Pr", "Pr", true), ("sec", "sec", false), ("sech", "sech", false), ("sin", "sin", false), |
| 739 | ("sinc", "sinc", false), ("sinh", "sinh", false), ("sup", "sup", true), ("tan", "tan", false), |
| 740 | ("tanh", "tanh", false), ("tg", "tg", false), ("tr", "tr", false), |
| 741 | ]; |
| 742 | |
| 743 | fn math_scope(sym: Option<&Scope>) -> Outcome<Scope> { |
| 744 | let mut s = Scope::new(); |
| 745 | // Symbols first, so an element or function of the same name wins. |
| 746 | if let Some(sym) = sym { |
| 747 | for (name, b) in sym.iter() { |
| 748 | s.define(name.clone(), b.value.clone()); |
| 749 | } |
| 750 | } |
| 751 | lib::define_elements(&mut s, "math"); |
| 752 | s.define("text", Value::Func(Func::Element(ElemKind::Text))); |
| 753 | for f in MathFn::ALL { |
| 754 | // Typst's `floor` and `ceil` are symbols (`floor.l`, `floor.r`), called as functions through |
| 755 | // `symbol_func`, so the `sym` symbols stand and these two are not bound as functions. |
| 756 | if matches!(f, MathFn::AccentOf | MathFn::LrOf | MathFn::Floor | MathFn::Ceil) { |
| 757 | continue; |
| 758 | } |
| 759 | s.define(f.name(), Value::Func(Func::Native(NativeFunc::Math(*f)))); |
| 760 | } |
| 761 | for (name, text, limits) in OPS { |
| 762 | let op = res!(elem(ElemKind::MathOp, vec![ |
| 763 | ("text", Value::Content(Content::text(text))), |
| 764 | ("limits", Value::Bool(*limits)), |
| 765 | ], Span::detached())); |
| 766 | s.define(*name, Value::Content(op)); |
| 767 | } |
| 768 | for (name, em) in [("thin", 1.0 / 6.0), ("med", 2.0 / 9.0), ("thick", 5.0 / 18.0), ("quad", 1.0), ("wide", 2.0)] { |
| 769 | if let Some(c) = h(em, false) { |
| 770 | s.define(name, Value::Content(c)); |
| 771 | } |
| 772 | } |
| 773 | for (name, d) in [("dif", "d"), ("Dif", "D")] { |
| 774 | if let Some(space) = h(1.0 / 6.0, true) { |
| 775 | let upright = Content::symbol(d).styled(Styles::from_vec( |
| 776 | props::property(ElemKind::Equation, "italic", Value::Bool(false)).into_iter().collect())); |
| 777 | let class = res!(elem(ElemKind::MathClass, vec![ |
| 778 | ("class", Value::str("unary")), |
| 779 | ("body", Value::Content(upright)), |
| 780 | ], Span::detached())); |
| 781 | s.define(name, Value::Content(Content::sequence(vec![space, class]))); |
| 782 | } |
| 783 | } |
| 784 | Ok(s) |
| 785 | } |
| 786 | |
| 787 | /// Binds `math` in the library, with the `sym` symbols the library already holds. |
| 788 | pub fn define(scope: &mut Scope) { |
| 789 | let sym = match scope.get("sym") { |
| 790 | Some(Value::Module(m)) => Some(m.scope.clone()), |
| 791 | _ => None, |
| 792 | }; |
| 793 | if let Ok(ms) = math_scope(sym.as_ref()) { |
| 794 | scope.define("math", Value::Module(Arc::new(Module::new("math", ms)))); |
| 795 | } |
| 796 | } |