oxedyne/fe2o3/fe2o3_austenite/tests/eval_styles.rs
32.4 KiB, 37 runs
created by r1870400018:63640, 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 | //! U4: style folding, selectors and realisation, each checked against the `typst` 0.15 oracle run on the |
| 2 | //! synthetic fixtures in `tests/fixtures/eval/styles/`. Until the evaluator (U2) lands, the Austenite side |
| 3 | //! of each case is built directly as content and styles mirroring its fixture. A missing `typst` fails |
| 4 | //! the suite unless `EVAL_ORACLE_SKIP=1` is set. |
| 5 | |
| 6 | use oxedyne_fe2o3_austenite::eval::args::Args; |
| 7 | use oxedyne_fe2o3_austenite::eval::content::{ |
| 8 | Content, |
| 9 | ElemKind, |
| 10 | FieldDefault, |
| 11 | FieldId, |
| 12 | FieldSpec, |
| 13 | FieldType, |
| 14 | Fold, |
| 15 | }; |
| 16 | use oxedyne_fe2o3_austenite::eval::func::{ |
| 17 | Func, |
| 18 | NativeFunc, |
| 19 | }; |
| 20 | use oxedyne_fe2o3_austenite::eval::lib::calc::CalcFn; |
| 21 | use oxedyne_fe2o3_austenite::eval::realise::{ |
| 22 | realise, |
| 23 | Pair, |
| 24 | RealiseMode, |
| 25 | Tag, |
| 26 | }; |
| 27 | use oxedyne_fe2o3_austenite::eval::select::{ |
| 28 | self, |
| 29 | Selector, |
| 30 | StyleFn, |
| 31 | }; |
| 32 | use oxedyne_fe2o3_austenite::eval::styles::{ |
| 33 | fold_all, |
| 34 | set_rule, |
| 35 | Property, |
| 36 | Recipe, |
| 37 | RecipeIndex, |
| 38 | Style, |
| 39 | StyleChain, |
| 40 | Styles, |
| 41 | Transformation, |
| 42 | }; |
| 43 | use oxedyne_fe2o3_austenite::eval::value::{ |
| 44 | Color, |
| 45 | ColorSpace, |
| 46 | Dash, |
| 47 | DashItem, |
| 48 | Dict, |
| 49 | Label, |
| 50 | Length, |
| 51 | Paint, |
| 52 | RegexValue, |
| 53 | Stroke, |
| 54 | Type, |
| 55 | Value, |
| 56 | }; |
| 57 | use oxedyne_fe2o3_austenite::eval::{ |
| 58 | eval_source, |
| 59 | Engine, |
| 60 | World, |
| 61 | }; |
| 62 | use oxedyne_fe2o3_austenite::syntax::{ |
| 63 | FileId, |
| 64 | Span, |
| 65 | }; |
| 66 | |
| 67 | use std::path::{ |
| 68 | Path, |
| 69 | PathBuf, |
| 70 | }; |
| 71 | use std::process::Command; |
| 72 | use std::sync::Arc; |
| 73 | |
| 74 | // Oracle plumbing |
| 75 | |
| 76 | fn fixture(name: &str) -> PathBuf { |
| 77 | Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/eval/styles").join(name) |
| 78 | } |
| 79 | |
| 80 | fn skip() -> bool { std::env::var("EVAL_ORACLE_SKIP").map(|v| v == "1").unwrap_or(false) } |
| 81 | |
| 82 | fn typst(args: &[&str]) -> Option<(String, String)> { |
| 83 | match Command::new("typst").args(args).output() { |
| 84 | Ok(o) => Some((String::from_utf8_lossy(&o.stdout).into_owned(), String::from_utf8_lossy(&o.stderr).into_owned())), |
| 85 | Err(e) => { |
| 86 | assert!(skip(), "the typst oracle could not be run ({}); set EVAL_ORACLE_SKIP=1 to skip", e); |
| 87 | None |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | /// The fixture's `<p>` probes, as the JSON array of strings (or numbers) `typst eval` prints. |
| 93 | fn probes(name: &str) -> Option<Vec<String>> { |
| 94 | let path = fixture(name); |
| 95 | let p = path.to_string_lossy().into_owned(); |
| 96 | let (out, err) = match typst(&["eval", "query(<p>).map(it => it.value)", "--in", &p]) { |
| 97 | Some(r) => r, |
| 98 | None => return None, |
| 99 | }; |
| 100 | assert!(out.trim_start().starts_with('['), "oracle failed on {}: {}", name, err); |
| 101 | Some(json_array(out.trim())) |
| 102 | } |
| 103 | |
| 104 | /// A flat JSON array of strings and numbers. |
| 105 | fn json_array(s: &str) -> Vec<String> { |
| 106 | let mut out = Vec::new(); |
| 107 | let chars: Vec<char> = s.chars().collect(); |
| 108 | let mut i = 1; |
| 109 | while i < chars.len() { |
| 110 | match chars[i] { |
| 111 | '"' => { |
| 112 | let mut v = String::new(); |
| 113 | i += 1; |
| 114 | while i < chars.len() && chars[i] != '"' { |
| 115 | if chars[i] == '\\' && i + 1 < chars.len() { |
| 116 | i += 1; |
| 117 | v.push(match chars[i] { 'n' => '\n', 't' => '\t', c => c }); |
| 118 | } else { |
| 119 | v.push(chars[i]); |
| 120 | } |
| 121 | i += 1; |
| 122 | } |
| 123 | out.push(v); |
| 124 | i += 1; |
| 125 | } |
| 126 | c if c == '-' || c.is_ascii_digit() => { |
| 127 | let mut v = String::new(); |
| 128 | while i < chars.len() && (chars[i] == '-' || chars[i] == '.' || chars[i].is_ascii_digit()) { |
| 129 | v.push(chars[i]); |
| 130 | i += 1; |
| 131 | } |
| 132 | out.push(v); |
| 133 | } |
| 134 | _ => i += 1, |
| 135 | } |
| 136 | } |
| 137 | out |
| 138 | } |
| 139 | |
| 140 | /// The body text of the fixture's HTML export, tags stripped and `<br>` as a newline. |
| 141 | fn html_text(name: &str) -> Option<String> { |
| 142 | let path = fixture(name); |
| 143 | let out = Path::new(env!("CARGO_TARGET_TMPDIR")).join(fmt_name(name, "html")); |
| 144 | let (_, err) = match typst(&["compile", "--features", "html", "--format", "html", |
| 145 | &path.to_string_lossy(), &out.to_string_lossy()]) { |
| 146 | Some(r) => r, |
| 147 | None => return None, |
| 148 | }; |
| 149 | let html = std::fs::read_to_string(&out).unwrap_or_else(|_| panic!("oracle failed on {}: {}", name, err)); |
| 150 | let body = html.split("<body>").nth(1).and_then(|b| b.split("</body>").next()).unwrap_or(""); |
| 151 | let body = body.replace("<br>", "\n"); |
| 152 | let mut text = String::new(); |
| 153 | let mut in_tag = false; |
| 154 | for c in body.chars() { |
| 155 | match c { |
| 156 | '<' => in_tag = true, |
| 157 | '>' => in_tag = false, |
| 158 | _ if !in_tag => text.push(c), |
| 159 | _ => (), |
| 160 | } |
| 161 | } |
| 162 | Some(text) |
| 163 | } |
| 164 | |
| 165 | fn fmt_name(name: &str, ext: &str) -> String { format!("{}.{}", name.trim_end_matches(".typ"), ext) } |
| 166 | |
| 167 | /// The first error of compiling the fixture, and its hints. |
| 168 | fn oracle_error(name: &str) -> Option<(String, Vec<String>)> { |
| 169 | let path = fixture(name); |
| 170 | let out = Path::new(env!("CARGO_TARGET_TMPDIR")).join(fmt_name(name, "pdf")); |
| 171 | let (_, err) = match typst(&["compile", &path.to_string_lossy(), &out.to_string_lossy()]) { |
| 172 | Some(r) => r, |
| 173 | None => return None, |
| 174 | }; |
| 175 | let mut lines = err.lines(); |
| 176 | let msg = lines.find_map(|l| l.strip_prefix("error: ")).unwrap_or_else(|| panic!("no oracle error for {}", name)); |
| 177 | let hints = err.lines().filter_map(|l| l.trim().strip_prefix("= hint: ")).map(|s| s.to_string()).collect(); |
| 178 | Some((msg.to_string(), hints)) |
| 179 | } |
| 180 | |
| 181 | // Rendering Austenite values as Typst's `repr` for the kinds the fold cases produce, then normalising |
| 182 | // both sides: whitespace and `0% + ` (Typst's relative wrapper) dropped, dictionary entries sorted. |
| 183 | |
| 184 | fn num(x: f64) -> String { |
| 185 | let r = (x * 100.0).round() / 100.0; |
| 186 | let s = format!("{:.2}", r); |
| 187 | s.trim_end_matches('0').trim_end_matches('.').to_string() |
| 188 | } |
| 189 | |
| 190 | fn render(v: &Value) -> String { |
| 191 | match v { |
| 192 | Value::None => "none".into(), |
| 193 | Value::Auto => "auto".into(), |
| 194 | Value::Bool(b) => b.to_string(), |
| 195 | Value::Int(i) => i.to_string(), |
| 196 | Value::Float(f) => num(*f), |
| 197 | Value::Str(s) => format!("\"{}\"", s), |
| 198 | Value::Length(l) => match (l.abs, l.em) { |
| 199 | (a, e) if e == 0.0 => format!("{}pt", num(a)), |
| 200 | (a, e) if a == 0.0 => format!("{}em", num(e)), |
| 201 | (a, e) => format!("{}pt + {}em", num(a), num(e)), |
| 202 | }, |
| 203 | Value::Color(c) => color(c), |
| 204 | Value::Stroke(s) => stroke(s), |
| 205 | Value::Dict(d) => { |
| 206 | if d.is_empty() { |
| 207 | return "(:)".into(); |
| 208 | } |
| 209 | let parts: Vec<String> = d.iter().map(|(k, v)| format!("{}: {}", k, render(v))).collect(); |
| 210 | format!("({})", parts.join(", ")) |
| 211 | } |
| 212 | other => format!("<{}>", other.ty().name()), |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | fn color(c: &Color) -> String { |
| 217 | let h = |x: f32| format!("{:02x}", (x * 255.0).round() as u8); |
| 218 | format!("rgb(\"#{}{}{}\")", h(c.c[0]), h(c.c[1]), h(c.c[2])) |
| 219 | } |
| 220 | |
| 221 | fn stroke(s: &Stroke) -> String { |
| 222 | let paint = s.paint.as_ref().map(|p| match p { |
| 223 | Paint::Color(c) => color(c), |
| 224 | _ => "<paint>".to_string(), |
| 225 | }); |
| 226 | let thick = s.thickness.map(|t| render(&Value::Length(t))); |
| 227 | if s.cap.is_none() && s.join.is_none() && s.dash.is_none() && s.miter_limit.is_none() { |
| 228 | match (&thick, &paint) { |
| 229 | (Some(t), Some(p)) => return format!("{} + {}", t, p), |
| 230 | (Some(t), None) => return t.clone(), |
| 231 | (None, Some(p)) => return p.clone(), |
| 232 | (None, None) => (), |
| 233 | } |
| 234 | } |
| 235 | let mut parts = Vec::new(); |
| 236 | if let Some(p) = paint { parts.push(format!("paint: {}", p)); } |
| 237 | if let Some(t) = thick { parts.push(format!("thickness: {}", t)); } |
| 238 | if let Some(c) = s.cap { parts.push(format!("cap: \"{}\"", format!("{:?}", c).to_lowercase())); } |
| 239 | if let Some(j) = s.join { parts.push(format!("join: \"{}\"", format!("{:?}", j).to_lowercase())); } |
| 240 | if let Some(d) = &s.dash { |
| 241 | parts.push(format!("dash: {}", match d { |
| 242 | None => "none".to_string(), |
| 243 | Some(d) => dash(d), |
| 244 | })); |
| 245 | } |
| 246 | if let Some(m) = s.miter_limit { parts.push(format!("miter-limit: {}", num(m))); } |
| 247 | format!("({})", parts.join(", ")) |
| 248 | } |
| 249 | |
| 250 | fn dash(d: &Dash) -> String { |
| 251 | let items: Vec<String> = d.array.iter().map(|i| match i { |
| 252 | DashItem::Dot => "\"dot\"".to_string(), |
| 253 | DashItem::Len(l) => render(&Value::Length(*l)), |
| 254 | }).collect(); |
| 255 | format!("(array: ({}), phase: {})", items.join(", "), render(&Value::Length(d.phase))) |
| 256 | } |
| 257 | |
| 258 | fn normalise(s: &str) -> String { |
| 259 | let mut out = String::new(); |
| 260 | let mut quoted = false; |
| 261 | for c in s.chars() { |
| 262 | if c == '"' { |
| 263 | quoted = !quoted; |
| 264 | } |
| 265 | if quoted || !c.is_whitespace() { |
| 266 | out.push(c); |
| 267 | } |
| 268 | } |
| 269 | let out = out.replace("0%+", "").replace(",)", ")"); |
| 270 | sort_dict(&out) |
| 271 | } |
| 272 | |
| 273 | /// Sorts a dictionary's top-level entries, so key order (which differs between Typst's `Sides` and |
| 274 | /// `Margin` reprs) does not matter. |
| 275 | fn sort_dict(s: &str) -> String { |
| 276 | if !(s.starts_with('(') && s.ends_with(')')) || s == "(:)" { |
| 277 | return s.to_string(); |
| 278 | } |
| 279 | let inner = &s[1..s.len() - 1]; |
| 280 | let mut parts = Vec::new(); |
| 281 | let (mut depth, mut quoted, mut cur) = (0, false, String::new()); |
| 282 | for c in inner.chars() { |
| 283 | match c { |
| 284 | '"' => quoted = !quoted, |
| 285 | '(' if !quoted => depth += 1, |
| 286 | ')' if !quoted => depth -= 1, |
| 287 | ',' if !quoted && depth == 0 => { |
| 288 | parts.push(std::mem::take(&mut cur)); |
| 289 | continue; |
| 290 | } |
| 291 | _ => (), |
| 292 | } |
| 293 | cur.push(c); |
| 294 | } |
| 295 | parts.push(cur); |
| 296 | if !parts.iter().all(|p| p.contains(':')) { |
| 297 | return s.to_string(); |
| 298 | } |
| 299 | parts.sort(); |
| 300 | format!("({})", parts.join(",")) |
| 301 | } |
| 302 | |
| 303 | // Values the fixtures use |
| 304 | |
| 305 | fn rgb(hex: u32) -> Value { |
| 306 | let c = |s: u32| ((hex >> s) & 0xff) as f32 / 255.0; |
| 307 | Value::Color(Color { space: ColorSpace::Rgb, c: [c(16), c(8), c(0), 0.0], alpha: 1.0 }) |
| 308 | } |
| 309 | |
| 310 | fn red() -> Value { rgb(0xff4136) } |
| 311 | fn green() -> Value { rgb(0x2ecc40) } |
| 312 | fn blue() -> Value { rgb(0x0074d9) } |
| 313 | fn pt(x: f64) -> Value { Value::Length(Length::pt(x)) } |
| 314 | fn em(x: f64) -> Value { Value::Length(Length::em(x)) } |
| 315 | fn cm(x: f64) -> Value { pt(x * 72.0 / 2.54) } |
| 316 | |
| 317 | fn dict(entries: &[(&str, Value)]) -> Value { |
| 318 | let mut d = Dict::new(); |
| 319 | for (k, v) in entries { |
| 320 | d.insert(k, v.clone()); |
| 321 | } |
| 322 | Value::dict(d) |
| 323 | } |
| 324 | |
| 325 | // Typst's schema for the fields the fold cases set: name, default and fold rule. |
| 326 | const TEXT_SIZE: FieldSpec = FieldSpec::named("size", FieldType::Of(Type::Length), FieldDefault::Pt(11.0)).fold(Fold::Add); |
| 327 | const TEXT_FEATURES: FieldSpec = FieldSpec::named("features", FieldType::Any, FieldDefault::Computed).fold(Fold::Add); |
| 328 | const LINE_STROKE: FieldSpec = FieldSpec::named("stroke", FieldType::Any, FieldDefault::Computed).fold(Fold::Stroke); |
| 329 | const RECT_INSET: FieldSpec = FieldSpec::named("inset", FieldType::Any, FieldDefault::Pt(5.0)).fold(Fold::Sides); |
| 330 | const RECT_RADIUS: FieldSpec = FieldSpec::named("radius", FieldType::Any, FieldDefault::Computed).fold(Fold::Corners); |
| 331 | const RECT_STROKE: FieldSpec = FieldSpec::named("stroke", FieldType::Any, FieldDefault::Computed).fold(Fold::Sides); |
| 332 | const RECT_FILL: FieldSpec = FieldSpec::named("fill", FieldType::Any, FieldDefault::None); |
| 333 | const BLOCK_STROKE: FieldSpec = FieldSpec::named("stroke", FieldType::Any, FieldDefault::None).fold(Fold::Sides); |
| 334 | const PAR_INDENT: FieldSpec = FieldSpec::named("first-line-indent", FieldType::Any, FieldDefault::Computed).fold(Fold::Keyed("amount")); |
| 335 | const PAGE_MARGIN: FieldSpec = FieldSpec::named("margin", FieldType::Any, FieldDefault::Auto).fold(Fold::Sides); |
| 336 | |
| 337 | /// Sets `values` outer to inner and folds them as the chain would. |
| 338 | fn folded(spec: &FieldSpec, outer_to_inner: &[Value]) -> Value { |
| 339 | let inner_first: Vec<&Value> = outer_to_inner.iter().rev().collect(); |
| 340 | fold_all(spec, &inner_first).unwrap_or(Value::None) |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn folding_matches_the_oracle() { |
| 345 | let expected = match probes("fold.typ") { |
| 346 | Some(p) => p, |
| 347 | None => return, |
| 348 | }; |
| 349 | let dashed = dict(&[("dash", Value::str("dashed"))]); |
| 350 | let ours = vec![ |
| 351 | folded(&TEXT_SIZE, &[em(2.0), em(1.5)]), |
| 352 | folded(&TEXT_SIZE, &[Value::Length(Length { abs: 10.0, em: 1.0 })]), |
| 353 | folded(&LINE_STROKE, &[red(), pt(2.0)]), |
| 354 | folded(&RECT_INSET, &[pt(3.0), dict(&[("left", pt(1.0))])]), |
| 355 | folded(&RECT_INSET, &[dict(&[("x", pt(3.0))]), dict(&[("left", pt(1.0))])]), |
| 356 | folded(&RECT_RADIUS, &[dict(&[("top", pt(3.0))]), dict(&[("left", pt(1.0))])]), |
| 357 | folded(&RECT_RADIUS, &[pt(2.0), dict(&[("top-left", pt(1.0))])]), |
| 358 | folded(&RECT_STROKE, &[dict(&[("left", red())]), pt(2.0)]), |
| 359 | folded(&RECT_STROKE, &[red(), dict(&[("left", pt(2.0))])]), |
| 360 | folded(&RECT_STROKE, &[dict(&[("left", red()), ("rest", blue())]), |
| 361 | dict(&[("paint", green()), ("thickness", pt(3.0))])]), |
| 362 | folded(&BLOCK_STROKE, &[dict(&[("left", red())])]), |
| 363 | folded(&PAR_INDENT, &[em(1.0), dict(&[("all", Value::Bool(true))])]), |
| 364 | folded(&PAR_INDENT, &[dict(&[("amount", em(1.0)), ("all", Value::Bool(true))]), em(2.0)]), |
| 365 | folded(&RECT_INSET, &[dict(&[("rest", pt(3.0))]), dict(&[("left", pt(3.0))])]), |
| 366 | folded(&LINE_STROKE, &[dict(&[("paint", red()), ("dash", Value::str("dashed"))]), dict(&[("dash", Value::None)])]), |
| 367 | folded(&LINE_STROKE, &[red(), dashed]), |
| 368 | folded(&PAGE_MARGIN, &[cm(1.0), dict(&[("left", cm(2.0))])]), |
| 369 | folded(&RECT_FILL, &[red(), Value::None]), |
| 370 | folded(&TEXT_FEATURES, &[dict(&[("smcp", Value::Int(1))]), dict(&[("onum", Value::Int(1))])]), |
| 371 | folded(&LINE_STROKE, &[dict(&[("dash", Value::str("dotted")), ("cap", Value::str("round"))]), |
| 372 | dict(&[("join", Value::str("bevel")), ("miter-limit", Value::Float(2.5))])]), |
| 373 | ]; |
| 374 | assert_eq!(ours.len(), expected.len(), "one Austenite case per oracle probe"); |
| 375 | for (i, (o, e)) in ours.iter().zip(expected.iter()).enumerate() { |
| 376 | assert_eq!(normalise(&render(o)), normalise(e), "fold case {} (oracle {:?})", i + 1, e); |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn chain_get_folds_and_resolve_folds_the_elements_own_value() { |
| 382 | // `text` has only its string in its schema until U6a, so the chain is exercised through a field |
| 383 | // with no schema entry (innermost wins) and the fold path through `fold_all` above. |
| 384 | let id = FieldId(7); |
| 385 | let a = Styles::from_style(Style::Property(Property::new(ElemKind::Text, id, pt(1.0), Span::detached()))); |
| 386 | let b = Styles::from_style(Style::Property(Property::new(ElemKind::Text, id, pt(2.0), Span::detached()))); |
| 387 | let chain = StyleChain::root().chain(&a).chain(&b); |
| 388 | assert!(matches!(chain.get(ElemKind::Text, id), Ok(Some(Value::Length(l))) if l.abs == 2.0)); |
| 389 | assert_eq!(chain.values(ElemKind::Text, id).len(), 2); |
| 390 | assert_eq!(chain.font_size(), 11.0); |
| 391 | } |
| 392 | |
| 393 | // The caches each link keeps, against the plain walk over all of a chain's styles |
| 394 | |
| 395 | /// The recipes in force by the plain walk, innermost first, the way `recipes` computed them before it was |
| 396 | /// cached per link. |
| 397 | fn walked_recipes(chain: &StyleChain) -> Vec<(RecipeIndex, Arc<Recipe>)> { |
| 398 | let all: Vec<&Style> = chain.walk().collect(); |
| 399 | let total = all.iter().filter(|s| matches!(s, Style::Recipe(_))).count(); |
| 400 | let (mut revoked, mut out, mut r) = (Vec::new(), Vec::new(), 0); |
| 401 | for s in all { |
| 402 | match s { |
| 403 | Style::Recipe(recipe) => { |
| 404 | let index = RecipeIndex(total - r); |
| 405 | r += 1; |
| 406 | if !revoked.contains(&index) { |
| 407 | out.push((index, recipe.clone())); |
| 408 | } |
| 409 | } |
| 410 | Style::Revocation(i) => revoked.push(*i), |
| 411 | Style::Property(_) => (), |
| 412 | } |
| 413 | } |
| 414 | out |
| 415 | } |
| 416 | |
| 417 | fn walked_values(chain: &StyleChain, kind: ElemKind, field: FieldId) -> Vec<&Value> { |
| 418 | chain.walk().filter_map(|s| match s { |
| 419 | Style::Property(p) if p.elem == kind && p.field == field => Some(&p.value), |
| 420 | _ => None, |
| 421 | }).collect() |
| 422 | } |
| 423 | |
| 424 | fn check_caches(chain: &StyleChain, keys: &[(ElemKind, FieldId)]) { |
| 425 | let want = walked_recipes(chain); |
| 426 | let got = chain.recipes(); |
| 427 | assert_eq!(got.len(), want.len(), "recipes in force"); |
| 428 | for (g, (index, recipe)) in got.iter().zip(want.iter()) { |
| 429 | assert_eq!(g.index, *index); |
| 430 | assert!(Arc::ptr_eq(&g.recipe, recipe), "recipe {:?}", index); |
| 431 | } |
| 432 | assert!(std::ptr::eq(chain.recipes().as_ptr(), got.as_ptr()), "the list is built once"); |
| 433 | for (kind, field) in keys { |
| 434 | let want = walked_values(chain, *kind, *field); |
| 435 | let got = chain.values(*kind, *field); |
| 436 | assert_eq!(got.len(), want.len(), "values of {:?}.{:?}", kind, field); |
| 437 | for (g, w) in got.iter().zip(want.iter()) { |
| 438 | assert!(std::ptr::eq(*g, *w), "value of {:?}.{:?}", kind, field); |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | #[test] |
| 444 | fn the_per_link_caches_agree_with_the_plain_walk_on_branching_chains() { |
| 445 | // 192 keys against the filter's 128 slots, so some keys must share a slot. |
| 446 | let keys: Vec<(ElemKind, FieldId)> = ElemKind::ALL.iter().take(48) |
| 447 | .flat_map(|k| (0..4u8).map(move |f| (*k, FieldId(f)))).collect(); |
| 448 | let mut seed = 0x2545_F491_4F6C_DD1Du64; |
| 449 | let mut next = move |n: usize| -> usize { |
| 450 | seed ^= seed << 13; |
| 451 | seed ^= seed >> 7; |
| 452 | seed ^= seed << 17; |
| 453 | (seed % n as u64) as usize |
| 454 | }; |
| 455 | let mut chains = vec![StyleChain::root()]; |
| 456 | let mut made = 0; |
| 457 | for _ in 0..120 { |
| 458 | // Chains branch from any earlier one, so siblings share a parent whose lists are already built. |
| 459 | let parent = chains[next(chains.len())].clone(); |
| 460 | check_caches(&parent, &keys); |
| 461 | let mut styles = Styles::new(); |
| 462 | for _ in 0..next(5) { |
| 463 | made += 1; |
| 464 | let style = match next(4) { |
| 465 | 0 => show_text(&format!("r{}", made), "x"), |
| 466 | 1 => Style::Revocation(RecipeIndex(1 + next(8))), |
| 467 | _ => { |
| 468 | let (kind, field) = keys[next(keys.len())]; |
| 469 | Style::Property(Property::new(kind, field, pt(made as f64), Span::detached())) |
| 470 | } |
| 471 | }; |
| 472 | styles.push(style); |
| 473 | } |
| 474 | chains.push(parent.chain(&styles)); |
| 475 | } |
| 476 | // A descendant made after an ancestor was read must not have changed what the ancestor says. |
| 477 | for c in &chains { |
| 478 | check_caches(c, &keys); |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | #[test] |
| 483 | fn a_link_without_recipes_or_revocations_shares_its_parents_recipe_list() { |
| 484 | let ruled = StyleChain::root().chain(&Styles::from_style(show_text("a", "b"))); |
| 485 | let plain = ruled.chain(&set_prop(ElemKind::Text, 1, pt(3.0))); |
| 486 | let deeper = plain.chain(&set_prop(ElemKind::Text, 2, pt(4.0))); |
| 487 | assert_eq!(ruled.recipes().len(), 1); |
| 488 | assert!(std::ptr::eq(ruled.recipes().as_ptr(), plain.recipes().as_ptr())); |
| 489 | assert!(std::ptr::eq(ruled.recipes().as_ptr(), deeper.recipes().as_ptr())); |
| 490 | // A recipe in a branch leaves the shared list alone. |
| 491 | let branch = plain.chain(&Styles::from_style(show_text("c", "d"))); |
| 492 | assert_eq!(branch.recipes().len(), 2); |
| 493 | assert_eq!(branch.recipes()[0].index, RecipeIndex(2)); |
| 494 | assert_eq!(deeper.recipes().len(), 1); |
| 495 | } |
| 496 | |
| 497 | // Realisation through text and regex rules, in paragraph (inline) mode |
| 498 | |
| 499 | fn sp() -> Content { Content::marker(ElemKind::Space, Span::detached()) } |
| 500 | fn t(s: &str) -> Content { Content::text(s) } |
| 501 | |
| 502 | fn show_text(sel: &str, out: &str) -> Style { |
| 503 | Style::Recipe(Arc::new(Recipe { |
| 504 | selector: Some(Selector::Text(sel.into())), |
| 505 | transform: Transformation::Content(t(out)), |
| 506 | span: Span::detached(), |
| 507 | outside: false, |
| 508 | })) |
| 509 | } |
| 510 | |
| 511 | fn show_regex(pat: &str, out: &str) -> Style { |
| 512 | let re = RegexValue::new(pat).unwrap_or_else(|e| panic!("regex {}: {:?}", pat, e)); |
| 513 | Style::Recipe(Arc::new(Recipe { |
| 514 | selector: Some(Selector::Regex(Arc::new(re))), |
| 515 | transform: Transformation::Content(t(out)), |
| 516 | span: Span::detached(), |
| 517 | outside: false, |
| 518 | })) |
| 519 | } |
| 520 | |
| 521 | fn engine() -> Engine { Engine::new(World::new(PathBuf::from("/"))) } |
| 522 | |
| 523 | /// The realised stream as text, tags skipped. |
| 524 | fn plain(pairs: &[Pair]) -> String { |
| 525 | pairs.iter().filter(|p| p.tag.is_none()).map(|p| match p.content.kind() { |
| 526 | Some(ElemKind::Space) => " ".to_string(), |
| 527 | Some(ElemKind::Linebreak) => "\n".to_string(), |
| 528 | _ => p.content.plain_text(), |
| 529 | }).collect() |
| 530 | } |
| 531 | |
| 532 | /// Realises `body` under `styles` (outermost first, one `show` each) as a paragraph's children. |
| 533 | fn inline(body: Vec<Content>, styles: Vec<Style>) -> String { |
| 534 | let mut chain = StyleChain::root(); |
| 535 | for s in styles { |
| 536 | chain = chain.chain(&Styles::from_style(s)); |
| 537 | } |
| 538 | let mut e = engine(); |
| 539 | let pairs = realise(&mut e, &Content::sequence(body), &chain, RealiseMode::Inline) |
| 540 | .unwrap_or_else(|err| panic!("realise: {:?} {:?}", err, e.diags)); |
| 541 | plain(&pairs) |
| 542 | } |
| 543 | |
| 544 | fn check_html(name: &str, ours: String) { |
| 545 | if let Some(expected) = html_text(name) { |
| 546 | assert_eq!(ours, expected, "{}", name); |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | #[test] |
| 551 | fn text_and_regex_rules_match_the_oracle() { |
| 552 | check_html("text_rules.typ", inline( |
| 553 | vec![t("ab"), sp(), t("c"), sp(), t("ab"), sp(), t("abd")], |
| 554 | vec![show_text("ab", "X"), show_regex("b c", "Y")])); |
| 555 | check_html("text_spaces.typ", inline( |
| 556 | vec![t("a"), sp(), t("b"), sp(), t("a"), sp(), t("b")], |
| 557 | vec![show_text("a b", "Z")])); |
| 558 | check_html("text_inner_wins.typ", inline(vec![t("a")], vec![show_text("a", "1"), show_text("a", "2")])); |
| 559 | check_html("text_leftmost.typ", inline(vec![t("abc")], vec![show_text("bc", "1"), show_text("ab", "2")])); |
| 560 | check_html("text_revoked.typ", inline(vec![t("a")], vec![show_text("a", "aa")])); |
| 561 | check_html("text_linebreak.typ", inline( |
| 562 | vec![t("a"), sp(), Content::marker(ElemKind::Linebreak, Span::detached()), sp(), t("b")], |
| 563 | vec![show_text("a\nb", "X")])); |
| 564 | } |
| 565 | |
| 566 | #[test] |
| 567 | fn a_style_change_stops_a_text_rule() { |
| 568 | // `a#text(fill: red)[b]`: the property is a stand-in for `fill`, which U6a's schema will name. |
| 569 | let fill = Styles::from_style(Style::Property(Property::new(ElemKind::Text, FieldId(1), red(), Span::detached()))); |
| 570 | check_html("text_style_break.typ", inline(vec![t("a"), t("b").styled(fill)], vec![show_text("ab", "X")])); |
| 571 | } |
| 572 | |
| 573 | #[test] |
| 574 | fn a_selectorless_show_replaces_the_rest_of_its_scope() { |
| 575 | let rest = Content::sequence(vec![t("b"), sp(), t("c")]); |
| 576 | let recipe = Style::Recipe(Arc::new(Recipe { selector: None, transform: Transformation::Content(t("X")), span: Span::detached(), outside: false, })); |
| 577 | check_html("show_none.typ", inline(vec![t("a"), sp(), rest.styled(Styles::from_style(recipe))], vec![])); |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn an_inline_only_fragment_is_not_made_a_paragraph() { |
| 582 | // Typst makes no `par` for `#block[hello world]`: the fixture counts the paragraphs `show par` sees. |
| 583 | let expected = match probes("fragment_inline.typ") { |
| 584 | Some(p) => p, |
| 585 | None => return, |
| 586 | }; |
| 587 | let mut e = engine(); |
| 588 | let pairs = realise(&mut e, &Content::sequence(vec![t("hello"), sp(), t("world")]), &StyleChain::root(), RealiseMode::Flow) |
| 589 | .unwrap_or_else(|err| panic!("{:?}", err)); |
| 590 | let pars = pairs.iter().filter(|p| p.content.is(ElemKind::Par)).count(); |
| 591 | assert_eq!(pars.to_string(), expected[0]); |
| 592 | assert_eq!(plain(&pairs), "hello world"); |
| 593 | } |
| 594 | |
| 595 | // Diagnostics, message for message |
| 596 | |
| 597 | fn check_error(name: &str, ours: Result<(), String>, diags: &[oxedyne_fe2o3_austenite::diag::Diagnostic]) { |
| 598 | let (msg, hints) = match oracle_error(name) { |
| 599 | Some(e) => e, |
| 600 | None => return, |
| 601 | }; |
| 602 | assert!(ours.is_err(), "{}: Austenite accepted what Typst refuses ({})", name, msg); |
| 603 | let d = diags.iter().find(|d| d.is_error()).unwrap_or_else(|| panic!("{}: no diagnostic recorded", name)); |
| 604 | assert_eq!(d.message, msg, "{}", name); |
| 605 | assert_eq!(d.hints, hints, "{} hints", name); |
| 606 | } |
| 607 | |
| 608 | fn realise_err(content: Content, mode: RealiseMode) -> (Result<(), String>, Engine) { |
| 609 | let mut e = engine(); |
| 610 | let r = realise(&mut e, &content, &StyleChain::root(), mode).map(|_| ()).map_err(|x| format!("{:?}", x)); |
| 611 | (r, e) |
| 612 | } |
| 613 | |
| 614 | #[test] |
| 615 | fn realisation_errors_match_the_oracle() { |
| 616 | let l = Label::new("l"); |
| 617 | let meta = || Content::marker(ElemKind::Metadata, Span::detached()).labelled(l.clone()); |
| 618 | let recipe = Style::Recipe(Arc::new(Recipe { |
| 619 | selector: Some(Selector::Label(l.clone())), |
| 620 | transform: Transformation::Content(meta()), |
| 621 | span: Span::detached(), |
| 622 | outside: false, |
| 623 | })); |
| 624 | let (r, e) = realise_err(meta().styled(Styles::from_style(recipe)), RealiseMode::Document); |
| 625 | check_error("err_depth.typ", r, &e.diags); |
| 626 | |
| 627 | let page = Styles::from_style(Style::Property(Property::new(ElemKind::Page, FieldId(0), pt(85.0), Span::detached()))); |
| 628 | let (r, e) = realise_err(Content::empty().styled(page), RealiseMode::Flow); |
| 629 | check_error("err_page.typ", r, &e.diags); |
| 630 | |
| 631 | let doc = Styles::from_style(Style::Property(Property::new(ElemKind::Document, FieldId(0), Value::str("x"), Span::detached()))); |
| 632 | let (r, e) = realise_err(Content::empty().styled(doc), RealiseMode::Flow); |
| 633 | check_error("err_document.typ", r, &e.diags); |
| 634 | } |
| 635 | |
| 636 | #[test] |
| 637 | fn set_rule_errors_match_the_oracle() { |
| 638 | let mut e = engine(); |
| 639 | let mut args = Args::new(Span::detached()); |
| 640 | args.push_named(Span::detached(), "text", Value::str("a")); |
| 641 | let r = set_rule(&mut e, ElemKind::Text, args).map(|_| ()).map_err(|x| format!("{:?}", x)); |
| 642 | check_error("err_set_text.typ", r, &e.diags); |
| 643 | } |
| 644 | |
| 645 | fn native() -> Value { Value::Func(Func::Native(NativeFunc::Calc(CalcFn::Abs))) } |
| 646 | |
| 647 | fn stringly<T>(r: oxedyne_fe2o3_core::prelude::Outcome<T>) -> Result<T, String> { r.map_err(|x| format!("{:?}", x)) } |
| 648 | |
| 649 | /// Runs one selector case on a fresh engine and compares its diagnostic with the fixture's. |
| 650 | fn selector_case<F: FnOnce(&mut Engine) -> Result<(), String>>(name: &str, f: F) { |
| 651 | let mut e = engine(); |
| 652 | let r = f(&mut e); |
| 653 | check_error(name, r, &e.diags); |
| 654 | } |
| 655 | |
| 656 | fn call_with(e: &mut Engine, f: StyleFn, pos: Vec<Value>, named: Vec<(&str, Value)>) -> Result<Value, String> { |
| 657 | let sp = Span::detached(); |
| 658 | let mut a = Args::new(sp); |
| 659 | for v in pos { |
| 660 | a.push(sp, v); |
| 661 | } |
| 662 | for (n, v) in named { |
| 663 | a.push_named(sp, n, v); |
| 664 | } |
| 665 | stringly(select::call(f, e, a)) |
| 666 | } |
| 667 | |
| 668 | #[test] |
| 669 | fn selector_casts_match_the_oracle() { |
| 670 | let sp = Span::detached(); |
| 671 | let heading = || Value::Func(Func::Element(ElemKind::Heading)); |
| 672 | selector_case("err_show_int.typ", |e| stringly(select::cast_showable(e, sp, Value::Int(1))).map(|_| ())); |
| 673 | selector_case("err_show_empty.typ", |e| stringly(select::cast_showable(e, sp, Value::str(""))).map(|_| ())); |
| 674 | selector_case("err_func.typ", |e| stringly(select::cast_showable(e, sp, native())).map(|_| ())); |
| 675 | selector_case("err_show_before.typ", |e| { |
| 676 | match call_with(e, StyleFn::Before, vec![heading(), Value::Label(Label::new("a"))], vec![]) { |
| 677 | Ok(v) => stringly(select::cast_showable(e, sp, v)).map(|_| ()), |
| 678 | Err(x) => Err(x), |
| 679 | } |
| 680 | }); |
| 681 | selector_case("err_or_int.typ", |e| call_with(e, StyleFn::Or, vec![heading(), Value::Int(1)], vec![]).map(|_| ())); |
| 682 | selector_case("err_where_field.typ", |e| call_with(e, StyleFn::Where, vec![heading()], vec![("foo", Value::Int(1))]).map(|_| ())); |
| 683 | selector_case("err_where_func.typ", |e| call_with(e, StyleFn::Where, vec![native()], vec![("a", Value::Int(1))]).map(|_| ())); |
| 684 | } |
| 685 | |
| 686 | #[test] |
| 687 | fn selector_matching_matches_the_oracle() { |
| 688 | let expected = match probes("matches.typ") { |
| 689 | Some(p) => p, |
| 690 | None => return, |
| 691 | }; |
| 692 | let (a, b) = (Label::new("a"), Label::new("b")); |
| 693 | let m = |l: Option<&Label>| { |
| 694 | let c = Content::marker(ElemKind::Metadata, Span::detached()); |
| 695 | match l { |
| 696 | Some(l) => c.labelled(l.clone()), |
| 697 | None => c, |
| 698 | } |
| 699 | }; |
| 700 | let elems = vec![m(Some(&a)), m(Some(&b)), m(None)]; |
| 701 | let sels = vec![ |
| 702 | Selector::Or(vec![Selector::Label(a.clone()), Selector::Label(b.clone())]), |
| 703 | Selector::And(vec![Selector::Label(a.clone()), Selector::Elem(ElemKind::Metadata, None)]), |
| 704 | Selector::And(vec![Selector::Label(a.clone()), Selector::Label(b.clone())]), |
| 705 | ]; |
| 706 | for (i, s) in sels.iter().enumerate() { |
| 707 | let n = elems.iter().filter(|c| s.matches(c, None).unwrap_or(false)).count(); |
| 708 | assert_eq!(n.to_string(), expected[i], "selector case {}", i + 1); |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | // Mechanisms the oracle shows only through closures and introspection, which need U2 and U8; the |
| 713 | // expected behaviour each asserts is noted from the oracle. |
| 714 | |
| 715 | fn recipe(sel: Selector, transform: Transformation) -> Styles { |
| 716 | Styles::from_style(Style::Recipe(Arc::new(Recipe { selector: Some(sel), transform, span: Span::detached(), outside: false, }))) |
| 717 | } |
| 718 | |
| 719 | fn set_prop(kind: ElemKind, field: u8, v: Value) -> Styles { |
| 720 | Styles::from_style(Style::Property(Property::new(kind, FieldId(field), v, Span::detached()))) |
| 721 | } |
| 722 | |
| 723 | #[test] |
| 724 | fn show_set_rules_collect_whichever_side_of_the_step_they_sit() { |
| 725 | // Oracle: `show heading: set text(red)` reaches a `show heading: it => ..` body whether it was |
| 726 | // written before or after it. Here the step is a content replacement, whose output carries the |
| 727 | // show-set property; the innermost show-set wins. |
| 728 | let l = Label::new("h"); |
| 729 | let target = Content::marker(ElemKind::Metadata, Span::new(FileId(0), 0, 5)).labelled(l.clone()); |
| 730 | for order in 0..2 { |
| 731 | let set_red = recipe(Selector::Label(l.clone()), Transformation::Style(set_prop(ElemKind::Text, 9, red()))); |
| 732 | let set_blue = recipe(Selector::Label(l.clone()), Transformation::Style(set_prop(ElemKind::Text, 9, blue()))); |
| 733 | let step = recipe(Selector::Label(l.clone()), Transformation::Content(t("X"))); |
| 734 | let chain = match order { |
| 735 | 0 => StyleChain::root().chain(&set_red).chain(&set_blue).chain(&step), |
| 736 | _ => StyleChain::root().chain(&step).chain(&set_red).chain(&set_blue), |
| 737 | }; |
| 738 | let mut e = engine(); |
| 739 | let pairs = realise(&mut e, &target, &chain, RealiseMode::Inline).unwrap_or_else(|x| panic!("{:?}", x)); |
| 740 | let text = pairs.iter().find(|p| p.content.is(ElemKind::Text)).unwrap_or_else(|| panic!("no text")); |
| 741 | assert_eq!(plain(&pairs), "X"); |
| 742 | assert!(matches!(text.styles.get(ElemKind::Text, FieldId(9)), Ok(Some(Value::Color(c))) if c.c[2] > 0.8), |
| 743 | "innermost show-set (blue) wins, order {}", order); |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | #[test] |
| 748 | fn a_guarded_element_skips_its_recipe_and_locatable_elements_get_tags() { |
| 749 | let span = Span::new(FileId(0), 3, 9); |
| 750 | let l = Label::new("m"); |
| 751 | let step = recipe(Selector::Elem(ElemKind::Metadata, None), Transformation::Content(t("X"))); |
| 752 | let chain = StyleChain::root().chain(&step); |
| 753 | // Unguarded: replaced, with start and end tags around the output carrying the prepared element. |
| 754 | let mut e = engine(); |
| 755 | let meta = Content::marker(ElemKind::Metadata, span).labelled(l.clone()); |
| 756 | let pairs = realise(&mut e, &meta, &chain, RealiseMode::Inline).unwrap_or_else(|x| panic!("{:?}", x)); |
| 757 | assert_eq!(plain(&pairs), "X"); |
| 758 | let start = match &pairs[0].tag { |
| 759 | Some(Tag::Start(c)) => c.clone(), |
| 760 | other => panic!("expected a start tag, found {:?}", other), |
| 761 | }; |
| 762 | let loc = start.location().unwrap_or_else(|| panic!("the start tag's element has no location")); |
| 763 | assert!(matches!(pairs.last().and_then(|p| p.tag.as_ref()), Some(Tag::End(x)) if *x == loc)); |
| 764 | assert_eq!(start.label(), Some(&l)); |
| 765 | // Guarded against the recipe (index 1, the only one): kept as is, a primitive pushed with its tags. |
| 766 | let mut guarded = meta.clone(); |
| 767 | if let Content::Elem(el) = &mut guarded { |
| 768 | el.edit().guards.push(oxedyne_fe2o3_austenite::eval::styles::RecipeIndex(1)); |
| 769 | } |
| 770 | let mut e = engine(); |
| 771 | let pairs = realise(&mut e, &guarded, &chain, RealiseMode::Inline).unwrap_or_else(|x| panic!("{:?}", x)); |
| 772 | // The recipe is skipped, so the element's own show runs: a metadata element shows as nothing, its |
| 773 | // start tag carrying it. |
| 774 | assert_eq!(plain(&pairs), ""); |
| 775 | assert_eq!(pairs.iter().filter(|p| matches!(&p.tag, Some(Tag::Start(c)) if c.is(ElemKind::Metadata))).count(), 1); |
| 776 | // Plain text is neither locatable nor labelled: no location, no tags. |
| 777 | let mut e = engine(); |
| 778 | let pairs = realise(&mut e, &t("a"), &StyleChain::root(), RealiseMode::Inline).unwrap_or_else(|x| panic!("{:?}", x)); |
| 779 | assert!(pairs.iter().all(|p| p.tag.is_none() && p.content.location().is_none())); |
| 780 | } |
| 781 | |
| 782 | #[test] |
| 783 | fn page_styles_in_the_document_break_pages_around_them() { |
| 784 | let page = set_prop(ElemKind::Page, 0, pt(85.0)); |
| 785 | let body = Content::sequence(vec![ |
| 786 | Content::marker(ElemKind::Metadata, Span::detached()), |
| 787 | Content::marker(ElemKind::Metadata, Span::detached()).styled(page), |
| 788 | ]); |
| 789 | let mut e = engine(); |
| 790 | let pairs = realise(&mut e, &body, &StyleChain::root(), RealiseMode::Document).unwrap_or_else(|x| panic!("{:?}", x)); |
| 791 | // A metadata element shows as nothing, leaving its two tags; the break before the styled one is the |
| 792 | // weak break its page style makes, and the break after is the boundary. |
| 793 | let seq: Vec<String> = pairs.iter().map(|p| match (&p.tag, p.content.kind()) { |
| 794 | (Some(Tag::Start(c)), _) => format!("start {}", c.kind().map(|k| k.name()).unwrap_or("?")), |
| 795 | (Some(Tag::End(_)), _) => "end".to_string(), |
| 796 | (None, Some(k)) => k.name().to_string(), |
| 797 | (None, None) => "?".to_string(), |
| 798 | }).collect(); |
| 799 | assert_eq!(seq, ["start metadata", "end", "pagebreak", "start metadata", "end", "pagebreak"]); |
| 800 | // The page property rides on the second metadata and the leading break, not the trailing one. |
| 801 | let breaks: Vec<&Pair> = pairs.iter().filter(|p| p.content.is(ElemKind::Pagebreak)).collect(); |
| 802 | assert_eq!(breaks[0].styles.values(ElemKind::Page, FieldId(0)).len(), 1); |
| 803 | assert_eq!(breaks[1].styles.values(ElemKind::Page, FieldId(0)).len(), 0); |
| 804 | } |
| 805 | |
| 806 | #[test] |
| 807 | fn selector_functions_build_selectors() { |
| 808 | let sp = Span::detached(); |
| 809 | let mut e = engine(); |
| 810 | let mut a = Args::new(sp); |
| 811 | a.push(sp, Value::Label(Label::new("x"))); |
| 812 | let v = select::call(StyleFn::Selector, &mut e, a).unwrap_or_else(|x| panic!("{:?}", x)); |
| 813 | assert!(matches!(&v, Value::Selector(s) if matches!(**s, Selector::Label(_)))); |
| 814 | let mut a = Args::new(sp); |
| 815 | a.push(sp, v); |
| 816 | a.push(sp, Value::Func(Func::Element(ElemKind::Metadata))); |
| 817 | a.push_named(sp, "inclusive", Value::Bool(false)); |
| 818 | let v = select::call(StyleFn::After, &mut e, a).unwrap_or_else(|x| panic!("{:?}", x)); |
| 819 | assert!(matches!(&v, Value::Selector(s) if matches!(**s, Selector::After { inclusive: false, .. }))); |
| 820 | assert_eq!(select::method("where"), Some(StyleFn::Where)); |
| 821 | assert_eq!(select::method("fields"), None); |
| 822 | } |
| 823 | |
| 824 | // Labelled sequences, evaluated from source |
| 825 | |
| 826 | /// The fixture evaluated by the parser and evaluator, then realised as a paragraph's children. |
| 827 | fn evaluated_inline(name: &str) -> String { |
| 828 | let path = fixture(name); |
| 829 | let root = path.parent().map(|p| p.to_path_buf()).unwrap_or_default(); |
| 830 | let mut world = World::new(root); |
| 831 | let id = world.load(&path).unwrap_or_else(|e| panic!("load {}: {:?}", name, e)); |
| 832 | let mut e = Engine::new(world); |
| 833 | let module = eval_source(&mut e, id).unwrap_or_else(|err| panic!("eval {}: {:?} {:?}", name, err, e.diags)); |
| 834 | let pairs = realise(&mut e, &module.content, &StyleChain::root(), RealiseMode::Inline) |
| 835 | .unwrap_or_else(|err| panic!("realise {}: {:?} {:?}", name, err, e.diags)); |
| 836 | plain(&pairs).trim().to_string() |
| 837 | } |
| 838 | |
| 839 | #[test] |
| 840 | fn a_label_rule_applies_once_to_each_labelled_sequence() { |
| 841 | // Each labelled sequence is its own target, guarded against the rule's output: the outer one's |
| 842 | // output does not hide the inner one from the rule, and neither is transformed twice. |
| 843 | check_html("label_once.typ", evaluated_inline("label_once.typ")); |
| 844 | check_html("label_nested.typ", evaluated_inline("label_nested.typ")); |
| 845 | } |