oxedyne/fe2o3/fe2o3_austenite/tests/parmemo.rs
32.3 KiB, 51 runs
created by r1870400018:72659, 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 | //! U9: the paragraph memo. A paragraph whose children are text-like keeps the break that ends each of its lines |
| 2 | //! under a key of the caches' configuration, its `Config`, the region's width and each child's fingerprint; a |
| 3 | //! hit prepares the paragraph again, builds its lines from the kept breaks and commits the same boxes a miss |
| 4 | //! would. |
| 5 | //! |
| 6 | //! - A paragraph set again is a hit and comes out the same; a taller region, which no kept paragraph reads, is |
| 7 | //! a hit too. |
| 8 | //! - Each field of the key, changed alone, is a miss that comes out as a cold layout does: the text, the |
| 9 | //! style chain, the `Config` (through a `par` that no child's chain names), the width and the situation. |
| 10 | //! - U10: a paragraph with an inline box or an equation is kept when laying them out asked the introspector |
| 11 | //! nothing, under a key that adds the region's height and base, and its hit is its miss to the bit; one whose |
| 12 | //! box asks, even a question asked before, is never kept. One that warns is kept, and warns on a hit too. |
| 13 | //! - A hit puts the current source's tag spans in the lines. |
| 14 | //! - A hit is a miss to the bit across the kinds of break: hyphenated, mandatory, right to left, first fit. |
| 15 | //! - The budget: nothing is kept at none, and a small one refuses and changes nothing the compile makes. |
| 16 | //! - In a session: an unchanged recompile hits every paragraph, an edit misses the edited one alone, and warm |
| 17 | //! bytes equal cold bytes with the memo on and off. |
| 18 | |
| 19 | use oxedyne_fe2o3_austenite::caches::{ |
| 20 | Budgets, |
| 21 | Caches, |
| 22 | Counters, |
| 23 | }; |
| 24 | use oxedyne_fe2o3_austenite::compile::Session; |
| 25 | use oxedyne_fe2o3_austenite::emit::sinks::PdfSink; |
| 26 | use oxedyne_fe2o3_austenite::eval::content::ElemKind; |
| 27 | use oxedyne_fe2o3_austenite::eval::realise::{ |
| 28 | realise, |
| 29 | Pair, |
| 30 | RealiseMode, |
| 31 | Tag, |
| 32 | }; |
| 33 | use oxedyne_fe2o3_austenite::eval::styles::StyleChain; |
| 34 | use oxedyne_fe2o3_austenite::eval::{ |
| 35 | eval_source, |
| 36 | Engine, |
| 37 | World, |
| 38 | }; |
| 39 | use oxedyne_fe2o3_austenite::flow::inline::ParSituation; |
| 40 | use oxedyne_fe2o3_austenite::flow::par::layout_par; |
| 41 | use oxedyne_fe2o3_austenite::flow::text::FontStore; |
| 42 | use oxedyne_fe2o3_austenite::flow::Region; |
| 43 | use oxedyne_fe2o3_austenite::ir::{ |
| 44 | LeafKind, |
| 45 | Node, |
| 46 | Sp, |
| 47 | }; |
| 48 | use oxedyne_fe2o3_hash::fingerprint::Fingerprint; |
| 49 | |
| 50 | use oxedyne_fe2o3_core::prelude::*; |
| 51 | |
| 52 | use std::path::{ |
| 53 | Path, |
| 54 | PathBuf, |
| 55 | }; |
| 56 | |
| 57 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 58 | // │ ENGINE LEVEL │ |
| 59 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 60 | |
| 61 | fn work(name: &str) -> Outcome<PathBuf> { |
| 62 | let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("parmemo").join(name); |
| 63 | res!(std::fs::create_dir_all(&dir).map_err(|e| err!(e, "Could not make {:?}.", dir; IO))); |
| 64 | Ok(dir) |
| 65 | } |
| 66 | |
| 67 | // The paragraphs a source realises into, with the engine. |
| 68 | fn paragraphs(src: &str) -> Outcome<(Engine, Vec<Pair>)> { |
| 69 | let root = res!(work("pars")); |
| 70 | let mut world = World::new(root.clone()); |
| 71 | let id = res!(world.add_source(root.join("p.typ"), src.to_string())); |
| 72 | let mut engine = Engine::new(world); |
| 73 | let module = res!(eval_source(&mut engine, id)); |
| 74 | let pairs = res!(realise(&mut engine, &module.content, &StyleChain::root(), RealiseMode::Document)); |
| 75 | Ok((engine, pairs.into_iter().filter(|p| p.content.is(ElemKind::Par)).collect())) |
| 76 | } |
| 77 | |
| 78 | fn region(width: f64, height: f64) -> Region { |
| 79 | Region::new(Sp::from_pt(width), Sp::from_pt(height)) |
| 80 | } |
| 81 | |
| 82 | fn set(engine: &mut Engine, p: &Pair, region: Region, situation: ParSituation) -> Outcome<Vec<Node>> { |
| 83 | layout_par(engine, &p.content, &p.styles, region, situation) |
| 84 | } |
| 85 | |
| 86 | fn counts(engine: &Engine) -> (u64, u64) { |
| 87 | (engine.caches.counters.par_hits, engine.caches.counters.par_misses) |
| 88 | } |
| 89 | |
| 90 | // Everything layout decides about nodes, to the bit, with each tag's span: two equal signatures are two |
| 91 | // identical layouts. |
| 92 | fn signature(nodes: &[Node], out: &mut String) { |
| 93 | for n in nodes { |
| 94 | match n { |
| 95 | Node::HBox(b) | Node::VBox(b) => { |
| 96 | out.push_str(&fmt!("[{} {} {}|", b.dims.width.raw(), b.dims.height.raw(), b.dims.depth.raw())); |
| 97 | signature(&b.list, out); |
| 98 | out.push(']'); |
| 99 | } |
| 100 | Node::Leaf(l) => match &l.kind { |
| 101 | LeafKind::Text(t) => { |
| 102 | out.push_str(&fmt!("(t {:?} {} {}", t.source(), l.dims.width.raw(), l.shift.raw())); |
| 103 | for g in &t.run().glyphs { |
| 104 | out.push_str(&fmt!(" {}:{}:{}:{}", g.id, g.x.to_bits(), g.y.to_bits(), g.adv.to_bits())); |
| 105 | } |
| 106 | out.push(')'); |
| 107 | } |
| 108 | other => out.push_str(&fmt!("(leaf {:?} {})", std::mem::discriminant(other), l.dims.width.raw())), |
| 109 | }, |
| 110 | Node::Glue(g) => out.push_str(&fmt!("(g {} {} {})", g.natural.raw(), g.stretch.raw(), g.shrink.raw())), |
| 111 | Node::Penalty(p) => out.push_str(&fmt!("(p {:?})", p)), |
| 112 | Node::Tag(Tag::Start(c)) => out.push_str(&fmt!("(tag {}-{})", c.span().start, c.span().end)), |
| 113 | Node::Tag(Tag::End(l)) => out.push_str(&fmt!("(end {:?})", l)), |
| 114 | other => out.push_str(&fmt!("({:?})", std::mem::discriminant(other))), |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | fn sig(nodes: &[Node]) -> String { |
| 120 | let mut s = String::new(); |
| 121 | signature(nodes, &mut s); |
| 122 | s |
| 123 | } |
| 124 | |
| 125 | fn tags(nodes: &[Node]) -> Vec<(u32, u32)> { |
| 126 | fn walk(n: &Node, out: &mut Vec<(u32, u32)>) { |
| 127 | match n { |
| 128 | Node::HBox(b) | Node::VBox(b) => for c in &b.list { walk(c, out); }, |
| 129 | Node::Tag(Tag::Start(c)) => out.push((c.span().start, c.span().end)), |
| 130 | _ => (), |
| 131 | } |
| 132 | } |
| 133 | let mut out = Vec::new(); |
| 134 | for n in nodes { |
| 135 | walk(n, &mut out); |
| 136 | } |
| 137 | out |
| 138 | } |
| 139 | |
| 140 | const PROSE: &str = "A paragraph with enough ordinary words in it to run on to a second line of the measure and a third \ |
| 141 | besides, set so that the breaks fall in the middle of it and not at its ends"; |
| 142 | |
| 143 | // The layout of the first paragraph of `src` on a fresh engine: what a miss makes. |
| 144 | fn cold(src: &str, w: f64, situation: ParSituation) -> Outcome<String> { |
| 145 | let (mut engine, pars) = res!(paragraphs(src)); |
| 146 | Ok(sig(&res!(set(&mut engine, &pars[0], region(w, 10_000.0), situation)))) |
| 147 | } |
| 148 | |
| 149 | /// A paragraph set again is a hit and comes out as it did, and what no kept paragraph reads is not in the key: |
| 150 | /// the region's height. |
| 151 | #[test] |
| 152 | fn a_paragraph_set_again_is_a_hit_and_comes_out_the_same() -> Outcome<()> { |
| 153 | let (mut engine, pars) = res!(paragraphs(&fmt!("{} #strong[and a strong word].\n", PROSE))); |
| 154 | let first = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 155 | assert_eq!(counts(&engine), (0, 1), "the first setting is a miss"); |
| 156 | assert_eq!(engine.caches.pars.len(), 1, "and is kept"); |
| 157 | let again = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 158 | assert_eq!(counts(&engine), (1, 1), "the same paragraph, set again, is a hit"); |
| 159 | assert!(sig(&first) == sig(&again), "a hit came out differently from the miss"); |
| 160 | let taller = res!(set(&mut engine, &pars[0], region(150.0, 40.0), ParSituation::First)); |
| 161 | assert_eq!(counts(&engine), (2, 1), "the region's height is not in the key"); |
| 162 | assert!(sig(&first) == sig(&taller), "a shorter region changed the lines"); |
| 163 | assert!(first.len() >= 4, "the paragraph sets in {} lines, too few to test with", first.len()); |
| 164 | Ok(()) |
| 165 | } |
| 166 | |
| 167 | /// Each field of the key, changed alone, is a miss, and the miss comes out as a cold layout does. |
| 168 | #[test] |
| 169 | fn each_field_of_the_key_changed_is_a_miss_that_comes_out_cold() -> Outcome<()> { |
| 170 | let plain = fmt!("{}.\n", PROSE); |
| 171 | let indented = fmt!("#set par(first-line-indent: 1em)\n{}.\n", PROSE); |
| 172 | let first = ParSituation::First; |
| 173 | // (name, the paragraph set first and its situation, the paragraph set next, its width and situation) |
| 174 | let cases: Vec<(&str, &str, ParSituation, String, f64, ParSituation)> = vec![ |
| 175 | ("text", &plain, first, fmt!("{} again.\n", PROSE), 150.0, first), |
| 176 | ("style", &plain, first, fmt!("#set text(size: 11pt)\n{}.\n", PROSE), 150.0, first), |
| 177 | ("justify", &plain, first, fmt!("#set par(justify: true)\n{}.\n", PROSE), 150.0, first), |
| 178 | ("hanging indent", &plain, first, fmt!("#set par(hanging-indent: 1em)\n{}.\n", PROSE), 150.0, first), |
| 179 | ("width", &plain, first, plain.clone(), 151.0, first), |
| 180 | ("situation", &indented, first, indented.clone(), 150.0, ParSituation::Consecutive), |
| 181 | ("smart quote", &plain, first, fmt!("{}.\n", PROSE.replace("ordinary", "\"ordinary\"")), 150.0, first), |
| 182 | ]; |
| 183 | for (name, before, before_at, src, w, situation) in cases { |
| 184 | let (mut engine, pars) = res!(paragraphs(before)); |
| 185 | let _ = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), before_at)); |
| 186 | // The next paragraph is set on an engine that holds the memo the first one made. |
| 187 | let (mut next, next_pars) = res!(paragraphs(&src)); |
| 188 | next.caches = std::mem::take(&mut engine.caches); |
| 189 | let made = res!(set(&mut next, &next_pars[0], region(w, 10_000.0), situation)); |
| 190 | assert_eq!(counts(&next), (0, 2), "{}: a paragraph that differs in this field alone was a hit", name); |
| 191 | let want = res!(cold(&src, w, situation)); |
| 192 | assert!(sig(&made) == want, "{}: the miss came out differently from a cold layout", name); |
| 193 | } |
| 194 | Ok(()) |
| 195 | } |
| 196 | |
| 197 | /// The `Config` a `par` element sets is in the key though no child's chain names it: the same children under |
| 198 | /// `par(justify: true)` are a different paragraph. |
| 199 | #[test] |
| 200 | fn a_par_setting_no_child_names_is_in_the_key() -> Outcome<()> { |
| 201 | let src = fmt!("{}.\n\n#par(justify: true)[{}.]\n", PROSE, PROSE); |
| 202 | let (mut engine, pars) = res!(paragraphs(&src)); |
| 203 | assert_eq!(pars.len(), 2); |
| 204 | let plain = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 205 | let justified = res!(set(&mut engine, &pars[1], region(150.0, 10_000.0), ParSituation::First)); |
| 206 | assert_eq!(counts(&engine), (0, 2), "the justified paragraph took the plain one's lines"); |
| 207 | assert!(sig(&plain) != sig(&justified), "justifying changed nothing, so the case tests nothing"); |
| 208 | let (mut fresh, fresh_pars) = res!(paragraphs(&src)); |
| 209 | let want = res!(set(&mut fresh, &fresh_pars[1], region(150.0, 10_000.0), ParSituation::First)); |
| 210 | assert!(sig(&justified) == sig(&want), "the justified paragraph came out differently from a cold layout"); |
| 211 | Ok(()) |
| 212 | } |
| 213 | |
| 214 | /// A paragraph with an inline box or an equation is never kept. One that warns is kept, and a hit warns as the |
| 215 | /// miss did, because a hit prepares the paragraph again. |
| 216 | #[test] |
| 217 | fn a_paragraph_with_a_box_or_an_equation_is_kept_and_a_hit_is_the_miss() -> Outcome<()> { |
| 218 | let sources = [ |
| 219 | ("box", fmt!("{} #box(width: 20pt, height: 8pt, fill: gray) and on.\n", PROSE)), |
| 220 | ("framed box", fmt!("{} wait #box(stroke: 0.5pt, inset: 1pt)[two] minutes and on.\n", PROSE)), |
| 221 | ("equation", fmt!("{} $x^2 + y$ and on.\n", PROSE)), |
| 222 | ("both", fmt!("{} tilt by $theta = pi/6$, wait #box(stroke: 0.5pt, inset: 1pt)[two] and on.\n", PROSE)), |
| 223 | ]; |
| 224 | for (name, src) in sources { |
| 225 | let (mut engine, pars) = res!(paragraphs(&src)); |
| 226 | assert_eq!(pars.len(), 1, "{}: one paragraph", name); |
| 227 | // A box with a body holds a paragraph of its own, laid out and counted with the outer one. |
| 228 | let one = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 229 | let (_, laid) = counts(&engine); |
| 230 | let two = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 231 | assert_eq!(counts(&engine), (laid, laid), "{}: the paragraph set again was not a hit", name); |
| 232 | assert_eq!(engine.caches.pars.len() as u64, laid, "{}: and was not kept", name); |
| 233 | assert!(sig(&one) == sig(&two), "{}: the hit came out differently from the miss", name); |
| 234 | assert!(sig(&two) == res!(cold(&src, 150.0, ParSituation::First)), "{}: the hit is not a cold layout", name); |
| 235 | assert!(one.len() >= 3, "{}: the paragraph sets in {} lines, too few to test with", name, one.len()); |
| 236 | } |
| 237 | // The warning is the engine's, so a hit on a fresh engine that holds the memo shows it raised again, from |
| 238 | // the paragraph itself and from inside a box. |
| 239 | let sources = [ |
| 240 | ("paragraph", fmt!("{} #link((page: 1, x: 0pt, y: 0pt))[and a link to a position] and on.\n", PROSE)), |
| 241 | ("box", fmt!("{} #box[#link((page: 1, x: 0pt, y: 0pt))[a link to a position]] and on.\n", PROSE)), |
| 242 | ]; |
| 243 | for (name, src) in sources { |
| 244 | let (mut a, pars_a) = res!(paragraphs(&src)); |
| 245 | let miss = res!(set(&mut a, &pars_a[0], region(150.0, 10_000.0), ParSituation::First)); |
| 246 | assert_eq!(a.diags.len(), 1, "{}: the miss warns", name); |
| 247 | let (_, laid) = counts(&a); // with a box's body |
| 248 | let (mut b, pars_b) = res!(paragraphs(&src)); |
| 249 | b.caches = std::mem::take(&mut a.caches); |
| 250 | let hit = res!(set(&mut b, &pars_b[0], region(150.0, 10_000.0), ParSituation::First)); |
| 251 | assert_eq!(counts(&b), (laid, laid), "{}: the warning paragraph was not kept and hit", name); |
| 252 | assert_eq!(b.diags.len(), 1, "{}: the hit did not warn as the miss did", name); |
| 253 | assert!(sig(&hit) == sig(&miss), "{}: the hit came out differently from the miss", name); |
| 254 | } |
| 255 | Ok(()) |
| 256 | } |
| 257 | |
| 258 | /// A box or equation is laid out against the whole region, so a paragraph holding one keys on the region's |
| 259 | /// height and base as well, where a text-like paragraph does not. |
| 260 | #[test] |
| 261 | fn a_paragraph_with_a_box_keys_on_the_region_height_and_base() -> Outcome<()> { |
| 262 | let src = fmt!("{} wait #box(height: 10%, width: 12pt, fill: gray) and on.\n", PROSE); |
| 263 | let (mut engine, pars) = res!(paragraphs(&src)); |
| 264 | let tall = region(150.0, 10_000.0); |
| 265 | let _ = res!(set(&mut engine, &pars[0], tall, ParSituation::First)); |
| 266 | // `Region::new` sets the base from the size, so the shorter region keeps the tall one's base and differs |
| 267 | // in height alone. |
| 268 | let mut low = region(150.0, 300.0); |
| 269 | low.base = tall.base; |
| 270 | let short = res!(set(&mut engine, &pars[0], low, ParSituation::First)); |
| 271 | assert_eq!(counts(&engine), (0, 2), "a shorter region was a hit for a box paragraph"); |
| 272 | let again = res!(set(&mut engine, &pars[0], low, ParSituation::First)); |
| 273 | assert_eq!(counts(&engine), (1, 2), "the same shorter region was not a hit"); |
| 274 | assert!(sig(&short) == sig(&again), "the hit came out differently from the miss"); |
| 275 | let mut based = low; |
| 276 | based.base = (Sp::from_pt(150.0), Sp::from_pt(600.0)); |
| 277 | let _ = res!(set(&mut engine, &pars[0], based, ParSituation::First)); |
| 278 | assert_eq!(counts(&engine), (1, 3), "another base was a hit for a box paragraph"); |
| 279 | Ok(()) |
| 280 | } |
| 281 | |
| 282 | /// A box whose content asks the introspector as it is laid out is never kept: its answers are in no key. The |
| 283 | /// second setting asks the question the first already asked, which the read log keeps once, so only the ask |
| 284 | /// count shows it was asked again. |
| 285 | #[test] |
| 286 | fn a_box_that_asks_the_introspector_is_never_kept_even_asking_again() -> Outcome<()> { |
| 287 | let src = fmt!("= One\n\n{} section #box[#context counter(heading).get().first()] and on.\n", PROSE); |
| 288 | let (mut engine, pars) = res!(paragraphs(&src)); |
| 289 | assert_eq!(pars.len(), 1, "one paragraph"); |
| 290 | let asks = engine.reads.asks(); |
| 291 | let one = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 292 | let reads = engine.reads.all.len(); |
| 293 | assert!(engine.reads.asks() > asks, "laying the box out asked nothing, so the test tests nothing"); |
| 294 | let two = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 295 | assert_eq!(engine.reads.all.len(), reads, "the second setting logged a new read, so it is not a repeat"); |
| 296 | // The box's own body is a paragraph of the answer's text, which asks nothing, so it is kept and hits; the |
| 297 | // outer paragraph misses both times. |
| 298 | assert_eq!(counts(&engine), (1, 3), "a box that asks was kept and hit"); |
| 299 | assert_eq!(engine.caches.pars.len(), 1, "a box that asks was kept"); |
| 300 | assert!(sig(&one) == sig(&two), "laid out twice it came out differently"); |
| 301 | Ok(()) |
| 302 | } |
| 303 | |
| 304 | /// The ask count grows for every question put, where the log of distinct reads does not grow for a repeat. |
| 305 | #[test] |
| 306 | fn the_ask_count_grows_for_a_repeated_question() -> Outcome<()> { |
| 307 | let (once, _) = res!(paragraphs("= One\n\n#context query(heading).len()\n")); |
| 308 | let (twice, _) = res!(paragraphs("= One\n\n#context query(heading).len() #context query(heading).len()\n")); |
| 309 | assert_eq!(twice.reads.all.len(), once.reads.all.len(), "the repeated query logged another read"); |
| 310 | assert_eq!(twice.reads.asks(), once.reads.asks() + 1, "the repeated query was not counted"); |
| 311 | Ok(()) |
| 312 | } |
| 313 | |
| 314 | /// A hit puts the tags of the current source in the lines: a tag holds the span of the element it starts, |
| 315 | /// which the fingerprint leaves out. |
| 316 | #[test] |
| 317 | fn a_hit_takes_its_tags_from_the_current_source() -> Outcome<()> { |
| 318 | let body = fmt!("{} #strong[the strong word] and #emph[a slanted one] to end.\n", PROSE); |
| 319 | let moved = fmt!("\n\n\n\n// A comment above the paragraph moves every span in it.\n\n{}", body); |
| 320 | let (mut a, pars_a) = res!(paragraphs(&body)); |
| 321 | let first = res!(set(&mut a, &pars_a[0], region(150.0, 10_000.0), ParSituation::First)); |
| 322 | let (mut b, pars_b) = res!(paragraphs(&moved)); |
| 323 | b.caches = std::mem::take(&mut a.caches); |
| 324 | let hit = res!(set(&mut b, &pars_b[0], region(150.0, 10_000.0), ParSituation::First)); |
| 325 | assert_eq!(counts(&b), (1, 1), "the edited-above paragraph is a hit"); |
| 326 | let want = res!(cold(&moved, 150.0, ParSituation::First)); |
| 327 | assert_eq!(tags(&hit).len(), 2, "strong and emph each start a tag"); |
| 328 | assert_ne!(tags(&first), tags(&hit), "the spans did not move, so the case tests nothing"); |
| 329 | assert!(sig(&hit) == want, "the hit's lines differ from a cold layout of the same source"); |
| 330 | Ok(()) |
| 331 | } |
| 332 | |
| 333 | /// A hit builds its lines from the kept breaks, and they are the miss's to the bit whatever ends them: a |
| 334 | /// hyphen, a mandatory break, a right-to-left line, and the first-fit breaker's choices as the optimised one's. |
| 335 | #[test] |
| 336 | fn a_hit_is_a_miss_to_the_bit_across_the_kinds_of_break() -> Outcome<()> { |
| 337 | let long = "Incomprehensibilities notwithstanding, extraordinarily uncharacteristically \ |
| 338 | disproportionate counterrevolutionaries institutionalised internationalisation, \ |
| 339 | electroencephalographically misunderstanding indistinguishable phenomenological \ |
| 340 | interdisciplinary considerations"; |
| 341 | // (name, source, width, the source the case must differ from to test anything) |
| 342 | let cases: Vec<(&str, String, f64, Option<String>)> = vec![ |
| 343 | ("hyphen", |
| 344 | fmt!("#set text(hyphenate: true, lang: \"en\")\n#set par(justify: true)\n{}.\n", long), 110.0, |
| 345 | Some(fmt!("#set text(hyphenate: false, lang: \"en\")\n#set par(justify: true)\n{}.\n", long))), |
| 346 | ("mandatory", |
| 347 | fmt!("#set par(justify: true)\nA first short part \\\nthen a second \\\n{}.\n", PROSE), 150.0, |
| 348 | Some(fmt!("#set par(justify: true)\nA first short part then a second {}.\n", PROSE))), |
| 349 | ("right to left", |
| 350 | fmt!("#set par(justify: true, first-line-indent: (amount: 12pt, all: true))\n#set text(dir: rtl)\n{}.\n", PROSE), |
| 351 | 150.0, Some(fmt!("#set par(justify: true, first-line-indent: (amount: 12pt, all: true))\n{}.\n", PROSE))), |
| 352 | ("first fit", |
| 353 | fmt!("#set par(linebreaks: \"simple\", justify: true)\n#set text(hyphenate: true, lang: \"en\")\n{}.\n", long), |
| 354 | 110.0, None), |
| 355 | ]; |
| 356 | for (name, src, w, witness) in cases { |
| 357 | let (mut engine, pars) = res!(paragraphs(&src)); |
| 358 | assert_eq!(pars.len(), 1, "{}: one paragraph", name); |
| 359 | let miss = res!(set(&mut engine, &pars[0], region(w, 10_000.0), ParSituation::First)); |
| 360 | let hit = res!(set(&mut engine, &pars[0], region(w, 10_000.0), ParSituation::First)); |
| 361 | assert_eq!(counts(&engine), (1, 1), "{}: the second setting was not a hit", name); |
| 362 | assert!(sig(&hit) == sig(&miss), "{}: the hit came out differently from the miss", name); |
| 363 | assert!(sig(&hit) == res!(cold(&src, w, ParSituation::First)), "{}: the hit differs from a cold layout", name); |
| 364 | assert!(miss.len() >= 3, "{}: the paragraph sets in {} lines, too few to test with", name, miss.len()); |
| 365 | if let Some(other) = witness { |
| 366 | assert!(sig(&miss) != res!(cold(&other, w, ParSituation::First)), |
| 367 | "{}: the case sets as it would without its kind of break, so it tests nothing", name); |
| 368 | } |
| 369 | } |
| 370 | Ok(()) |
| 371 | } |
| 372 | |
| 373 | /// A budget of none keeps nothing, and a small one refuses what does not fit; neither changes the lines. |
| 374 | #[test] |
| 375 | fn a_small_budget_refuses_and_changes_nothing() -> Outcome<()> { |
| 376 | let src = fmt!("{}.\n\n{} again.\n", PROSE, PROSE); |
| 377 | let (mut engine, pars) = res!(paragraphs(&src)); |
| 378 | let (mut free, free_pars) = res!(paragraphs(&src)); |
| 379 | free.caches.begin(Fingerprint::default()); |
| 380 | let a = res!(set(&mut free, &free_pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 381 | let held = free.caches.pars.bytes(); |
| 382 | assert!(held > 0, "a paragraph's lines are worth some bytes"); |
| 383 | |
| 384 | engine.caches = Caches::new(Budgets { pars: 0, ..Budgets::default() }); |
| 385 | engine.caches.begin(Fingerprint::default()); |
| 386 | let none = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 387 | let none_again = res!(set(&mut engine, &pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 388 | assert_eq!((engine.caches.pars.len(), counts(&engine)), (0, (0, 2)), "a budget of none kept a paragraph"); |
| 389 | assert_eq!(engine.caches.pars.refused(), 0, "a budget of none computes no key, so offers nothing to refuse"); |
| 390 | assert!(sig(&none) == sig(&a) && sig(&none_again) == sig(&a), "a budget changed the lines"); |
| 391 | |
| 392 | // Room for one paragraph and not two. |
| 393 | let (mut small, small_pars) = res!(paragraphs(&src)); |
| 394 | small.caches = Caches::new(Budgets { pars: held + held / 2, ..Budgets::default() }); |
| 395 | small.caches.begin(Fingerprint::default()); |
| 396 | let _ = res!(set(&mut small, &small_pars[0], region(150.0, 10_000.0), ParSituation::First)); |
| 397 | let second = res!(set(&mut small, &small_pars[1], region(150.0, 10_000.0), ParSituation::First)); |
| 398 | assert_eq!(small.caches.pars.len(), 1, "the second paragraph did not fit and was kept"); |
| 399 | assert_eq!(small.caches.pars.refused(), 1); |
| 400 | let (mut fresh, fresh_pars) = res!(paragraphs(&src)); |
| 401 | let want = res!(set(&mut fresh, &fresh_pars[1], region(150.0, 10_000.0), ParSituation::First)); |
| 402 | assert!(sig(&second) == sig(&want), "a refused paragraph came out differently from a cold layout"); |
| 403 | Ok(()) |
| 404 | } |
| 405 | |
| 406 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 407 | // │ SESSION LEVEL │ |
| 408 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 409 | |
| 410 | const HEAD: &str = "#set page(width: 220pt, height: 130pt, margin: 16pt)\n#set text(size: 9pt)\n"; |
| 411 | |
| 412 | const TAILS: [&str; 8] = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel"]; |
| 413 | |
| 414 | // A document of eight paragraphs, each its own, after `extra` settings. |
| 415 | fn doc(extra: &str, edit: Option<usize>) -> String { |
| 416 | let mut s = String::from(HEAD); |
| 417 | s.push_str(extra); |
| 418 | for (i, t) in TAILS.iter().enumerate() { |
| 419 | let more = if edit == Some(i) { " and an edited clause" } else { "" }; |
| 420 | s.push_str(&format!("Paragraph {} has enough ordinary words in it to run on to a second line of the page, \ |
| 421 | and then {}{}.\n\n", i, t, more)); |
| 422 | } |
| 423 | s |
| 424 | } |
| 425 | |
| 426 | fn scratch(name: &str) -> PathBuf { |
| 427 | let d = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("parmemo_session").join(name); |
| 428 | let _ = std::fs::remove_dir_all(&d); |
| 429 | std::fs::create_dir_all(&d).expect("the case's directory"); |
| 430 | std::fs::canonicalize(&d).expect("the case's canonical path") |
| 431 | } |
| 432 | |
| 433 | fn session(budgets: Budgets) -> Session { |
| 434 | let mut s = Session::new(FontStore::default()); |
| 435 | s.set_budgets(budgets); |
| 436 | s |
| 437 | } |
| 438 | |
| 439 | // The PDF and the counters of a compile of `text` under `session`. |
| 440 | fn build(session: &mut Session, dir: &Path, text: &str) -> (Vec<u8>, Counters) { |
| 441 | let main = dir.join("main.typ"); |
| 442 | std::fs::write(&main, text).expect("a project file"); |
| 443 | let mut sink = PdfSink::new().expect("a PDF sink"); |
| 444 | let done = session.compile(&main, dir, &mut sink, None, None, false).expect("the main is readable"); |
| 445 | if let Err(e) = &done.laid { |
| 446 | panic!("the compile failed: {}", e.plain()); |
| 447 | } |
| 448 | (sink.output().expect("a finished PDF").to_vec(), done.counters) |
| 449 | } |
| 450 | |
| 451 | /// An unchanged recompile takes every paragraph from the memo, and makes the same bytes. |
| 452 | #[test] |
| 453 | fn an_unchanged_recompile_hits_every_paragraph() { |
| 454 | let dir = scratch("again"); |
| 455 | let text = doc("", None); |
| 456 | let mut s = session(Budgets::default()); |
| 457 | let (first, c1) = build(&mut s, &dir, &text); |
| 458 | assert!(c1.par_misses >= 8, "a first compile lays the eight paragraphs, {:?}", c1); |
| 459 | let (second, c2) = build(&mut s, &dir, &text); |
| 460 | assert_eq!(c2.par_misses, 0, "a recompile of the same source laid a paragraph afresh: {:?}", c2); |
| 461 | assert!(c2.par_hits >= 8, "and hit {} times for eight paragraphs", c2.par_hits); |
| 462 | assert!(first == second, "the recompile made different bytes"); |
| 463 | assert_eq!(s.caches().pars.len(), 8, "the memo holds the eight paragraphs"); |
| 464 | } |
| 465 | |
| 466 | /// An edit misses the edited paragraph alone, and the bytes are a cold compile's, with the memo on and off. |
| 467 | #[test] |
| 468 | fn an_edit_misses_the_edited_paragraph_alone_and_warm_equals_cold() { |
| 469 | let dir = scratch("edit"); |
| 470 | let mut s = session(Budgets::default()); |
| 471 | let _ = build(&mut s, &dir, &doc("", None)); |
| 472 | let edited = doc("", Some(3)); |
| 473 | let (warm, c) = build(&mut s, &dir, &edited); |
| 474 | assert_eq!(c.par_misses, 1, "the edit laid more than the edited paragraph: {:?}", c); |
| 475 | assert!(c.par_hits >= 7, "the other seven paragraphs were not all hits: {:?}", c); |
| 476 | let (cold_on, _) = build(&mut session(Budgets::default()), &scratch("edit_cold"), &edited); |
| 477 | let off = Budgets { pars: 0, ..Budgets::default() }; |
| 478 | let (cold_off, c_off) = build(&mut session(off), &scratch("edit_off"), &edited); |
| 479 | assert_eq!((c_off.par_hits, c_off.par_misses > 0), (0, true), "a budget of none hit: {:?}", c_off); |
| 480 | assert!(warm == cold_on, "warm bytes differ from cold bytes with the memo on"); |
| 481 | assert!(warm == cold_off, "warm bytes differ from cold bytes with the memo off"); |
| 482 | } |
| 483 | |
| 484 | /// Each field of the key moved by a document-wide setting misses every paragraph the earlier compile kept: |
| 485 | /// the counters are those of a session that kept nothing, and the bytes are a cold compile's. |
| 486 | #[test] |
| 487 | fn a_changed_key_field_leaves_the_earlier_entries_unread() { |
| 488 | let settings = [ |
| 489 | ("style", "#set text(size: 10pt)\n"), |
| 490 | ("justify", "#set par(justify: true)\n"), |
| 491 | ("hanging indent", "#set par(hanging-indent: 1em)\n"), |
| 492 | ("first-line indent", "#set par(first-line-indent: 1em)\n"), |
| 493 | ("width", "#set page(columns: 2)\n"), |
| 494 | ("margin", "#set page(margin: 24pt)\n"), |
| 495 | ]; |
| 496 | for (name, extra) in settings { |
| 497 | let dir = scratch(&format!("key_{}", name.replace(' ', "_"))); |
| 498 | let mut s = session(Budgets::default()); |
| 499 | let _ = build(&mut s, &dir, &doc("", None)); |
| 500 | let changed = doc(extra, None); |
| 501 | let (warm, cw) = build(&mut s, &dir, &changed); |
| 502 | let (cold, cc) = build(&mut session(Budgets::default()), &scratch(&format!("key_cold_{}", name.replace(' ', "_"))), &changed); |
| 503 | assert_eq!((cw.par_hits, cw.par_misses), (cc.par_hits, cc.par_misses), |
| 504 | "{}: the earlier compile's paragraphs were read under a changed key", name); |
| 505 | assert!(warm == cold, "{}: warm bytes differ from cold bytes", name); |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | /// U10: a paragraph with an inline box or an equation is kept like any other, so an unchanged recompile hits |
| 510 | /// it and an edit misses the edited paragraph alone, and the document is the cold bytes with the memo on and |
| 511 | /// off. |
| 512 | #[test] |
| 513 | fn paragraphs_with_boxes_and_equations_are_kept_and_warm_equals_cold() { |
| 514 | let dir = scratch("gate"); |
| 515 | let inline = |edit: bool| { |
| 516 | let mut text = doc("", None); |
| 517 | text.push_str("A paragraph with an inline #box(width: 14pt, height: 7pt, fill: gray) box in it, run on a while.\n\n"); |
| 518 | text.push_str(&format!("A paragraph with an equation $x^2 + y${} in it, run on a while longer to wrap the line.\n\n", |
| 519 | if edit { " edited" } else { "" })); |
| 520 | text.push_str("Tilt by $theta = pi/6$, wait #box(stroke: 0.5pt, inset: 1pt)[two] minutes, and run on to a second line.\n\n"); |
| 521 | text |
| 522 | }; |
| 523 | let mut s = session(Budgets::default()); |
| 524 | let _ = build(&mut s, &dir, &inline(false)); |
| 525 | let (second, c) = build(&mut s, &dir, &inline(false)); |
| 526 | assert_eq!(c.par_misses, 0, "a box or equation paragraph was laid afresh: {:?}", c); |
| 527 | assert!(c.par_hits >= 11, "the eleven paragraphs were not all hits: {:?}", c); |
| 528 | assert_eq!(s.caches().pars.len(), 12, "the memo does not hold the eleven paragraphs and the box's body"); |
| 529 | let (cold, _) = build(&mut session(Budgets::default()), &scratch("gate_cold"), &inline(false)); |
| 530 | assert!(second == cold, "warm bytes differ from cold bytes"); |
| 531 | let (edited, c) = build(&mut s, &dir, &inline(true)); |
| 532 | assert_eq!(c.par_misses, 1, "the edit laid more than the edited paragraph: {:?}", c); |
| 533 | let off = Budgets { pars: 0, ..Budgets::default() }; |
| 534 | let (cold_off, _) = build(&mut session(off), &scratch("gate_off"), &inline(true)); |
| 535 | let (cold_on, _) = build(&mut session(Budgets::default()), &scratch("gate_on"), &inline(true)); |
| 536 | assert!(edited == cold_off, "warm bytes differ from cold bytes with the memo off"); |
| 537 | assert!(edited == cold_on, "warm bytes differ from cold bytes with the memo on"); |
| 538 | } |
| 539 | |
| 540 | /// A box that shows what a `context` reads is laid afresh each compile, so when an edit above changes the |
| 541 | /// answer the document is still the cold bytes. |
| 542 | #[test] |
| 543 | fn a_box_reading_context_is_laid_afresh_and_warm_equals_cold() { |
| 544 | let dir = scratch("box_context"); |
| 545 | let tail = "= Last\n\nThis paragraph holds a box #box(stroke: 0.5pt)[#context counter(heading).get().first()] \ |
| 546 | that counts the headings, and runs on a little to wrap.\n\n"; |
| 547 | let base = format!("{}{}", doc("", None), tail); |
| 548 | let mut s = session(Budgets::default()); |
| 549 | let _ = build(&mut s, &dir, &base); |
| 550 | let edited = format!("{}= Another\n\n{}", doc("", None), tail); |
| 551 | let (warm, c) = build(&mut s, &dir, &edited); |
| 552 | assert!(c.par_misses >= 1, "the box that reads was kept: {:?}", c); |
| 553 | let (cold, _) = build(&mut session(Budgets::default()), &scratch("box_context_cold"), &edited); |
| 554 | assert!(warm == cold, "warm bytes differ from cold bytes after the read changed"); |
| 555 | } |
| 556 | |
| 557 | /// A small budget refuses entries and changes nothing the compile makes; a budget of none keeps none. |
| 558 | #[test] |
| 559 | fn the_budget_bounds_the_memo_and_never_the_bytes() { |
| 560 | let text = doc("", None); |
| 561 | let mut whole = session(Budgets::default()); |
| 562 | let (full, _) = build(&mut whole, &scratch("budget_full"), &text); |
| 563 | let each = whole.caches().pars.bytes() / whole.caches().pars.len().max(1); // a paragraph's bytes, on average |
| 564 | let none = Budgets { pars: 0, ..Budgets::default() }; |
| 565 | let mut s = session(none); |
| 566 | let (a, c) = build(&mut s, &scratch("budget_none"), &text); |
| 567 | let (b, c2) = build(&mut s, &scratch("budget_none"), &text); |
| 568 | assert_eq!((s.caches().pars.len(), c.par_hits, c2.par_hits), (0, 0, 0), "a budget of none kept something"); |
| 569 | assert!(a == full && b == full, "a budget of none changed the bytes"); |
| 570 | let small = Budgets { pars: each * 3, ..Budgets::default() }; // about three of the eight |
| 571 | let mut s = session(small); |
| 572 | let (a, _) = build(&mut s, &scratch("budget_small"), &text); |
| 573 | let (b, c2) = build(&mut s, &scratch("budget_small"), &text); |
| 574 | assert!(s.caches().pars.len() > 0 && s.caches().pars.len() < 8, "a small budget holds {} of eight paragraphs", s.caches().pars.len()); |
| 575 | assert!(s.caches().pars.refused() > 0, "a small budget refused nothing"); |
| 576 | assert!(c2.par_hits > 0 && c2.par_misses > 0, "and the recompile mixed hits and misses: {:?}", c2); |
| 577 | assert!(a == full && b == full, "a small budget changed the bytes"); |
| 578 | } |
| 579 | |
| 580 | /// A paragraph whose text a `context` reads is realised before it is laid, so what was read is in its |
| 581 | /// children and in the key: moved to another page by an edit above, it misses and shows the new page. |
| 582 | #[test] |
| 583 | fn a_paragraph_that_shows_what_a_context_read_misses_when_the_read_changes() { |
| 584 | let dir = scratch("context"); |
| 585 | let tail = "This paragraph is on page #context here().page() of the document, and runs on a little.\n\n"; |
| 586 | let base = format!("{}{}", doc("", None), tail); |
| 587 | let mut s = session(Budgets::default()); |
| 588 | let _ = build(&mut s, &dir, &base); |
| 589 | let edited = format!("{}{}{}", doc("", None), doc("", None).trim_start_matches(HEAD), tail); |
| 590 | let (warm, _) = build(&mut s, &dir, &edited); |
| 591 | let (cold, _) = build(&mut session(Budgets::default()), &scratch("context_cold"), &edited); |
| 592 | assert!(warm == cold, "warm bytes differ from cold bytes after the read changed"); |
| 593 | } |
| 594 | |
| 595 | /// The same paragraphs in a narrower block are the same children under the same chain, so only the region's |
| 596 | /// width tells them apart: the warm compile misses them and makes the cold bytes. |
| 597 | #[test] |
| 598 | fn a_narrower_block_misses_on_the_width_alone() { |
| 599 | let body = doc("", None); |
| 600 | let body = body.trim_start_matches(HEAD); |
| 601 | let wide = format!("{}#block(width: 100%)[\n{}]\n", HEAD, body); |
| 602 | let narrow = format!("{}#block(width: 80%)[\n{}]\n", HEAD, body); |
| 603 | let dir = scratch("block_width"); |
| 604 | let mut s = session(Budgets::default()); |
| 605 | let _ = build(&mut s, &dir, &wide); |
| 606 | let (warm, c) = build(&mut s, &dir, &narrow); |
| 607 | let (cold, _) = build(&mut session(Budgets::default()), &scratch("block_width_cold"), &narrow); |
| 608 | assert!(c.par_misses >= 8, "the narrower paragraphs took the wider ones' lines: {:?}", c); |
| 609 | assert!(warm == cold, "warm bytes differ from cold bytes"); |
| 610 | } |